fix(governance): t_818f77be ExpandFromResults 导航起点 r.Category→正文实体
InMemoryGraph(graph_expander.go:24)+FileGraph(graph_file.go:466) 旧实现拿 r.Category(类目名,如 distilled)当实体去 Navigate, 永远匹配不到任何图节点 ⇒ 结构性零产出(实测 10/10 全 distilled, 0 graph_expanded)。InMemory 版另读 p[to]/p[from] 而 Navigate 返回 source/target, 双重零产出。 修复: 导航起点改为从 r.Content 提实体——复用现有 extract*Entities + normalize*EntityID(与同文件 ExpandWithSummary 同一套), 不新造抽取逻辑; InMemory 版路径键 to/from → source/target 一并对齐。Score:0.5 降权/去重/ pattern-peer 门控 均不动。 可观测性(AC2): 加 env 控 ZHIYI_GRAPH_EXPAND_DEBUG=1 的单行 debug 日志 (起点实体 N/命中 M/补入 K), 默认关低频, 保证下次坏了不沉默。 测试(AC4+AC3): graph_expand_e2e_test.go 4 用例锁死——小图(中文实体链)+ recall ⇒ 断言含 category=graph_expanded 且 Score=0.5; 10-recall 批量补入 改后 total=38(InMemory)/38(FileGraph); namespace 不匹配 ⇒ 补 0(次级阻塞 实证)。改前树副本跑同测试 ⇒ 全 0(复现结构零), 改后 ⇒ 38, 判别力成立。 FileGraph.AddNode/AddEdge 潜伏 RWMutex 自死锁(save 在写锁内取 RLock)不属 本卡, 测试改走 JSON 文件加载绕开。
This commit is contained in:
@@ -0,0 +1,205 @@
|
||||
// 织忆 MemoryWeave — 图谱扩展(ExpandFromResults)锁死 + 实测(t_818f77be)
|
||||
//
|
||||
// 背景:旧 InMemoryGraph/FileGraph 的 ExpandFromResults 拿 r.Category(类目名,如 "distilled")
|
||||
// 当实体名去 Navigate,永远匹配不到任何图节点 ⇒ 结构性零产出。修正后导航起点 = 从 r.Content
|
||||
// 提实体(复用 extract*Entities + normalize*EntityID,与 ExpandWithSummary 同一套逻辑)。
|
||||
//
|
||||
// 本文件两类断言:
|
||||
// 1) 锁死(AC#4):构造小图 + 一条 recall ⇒ 结果必含 category=graph_expanded,且 Score=0.5 不变。
|
||||
// 2) 实测(AC#3):同批 10 条 recall ⇒ 补入率 > 0,给出具体数字。
|
||||
// 判读方式:改前树副本跑本测试 ⇒ 两条均得 0(复现结构零);改后树 ⇒ 均 >0。
|
||||
//
|
||||
// 说明:FileGraph.AddNode/AddEdge 存在潜伏死锁(save() 在写锁内又取 RLock ⇒ 非重入 RWMutex 自锁),
|
||||
// 故 FileGraph 用例改走「写 JSON 文件 + NewFileGraph 加载」,绕开该潜伏 bug(不在本卡修复范围)。
|
||||
package governance
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"testing"
|
||||
|
||||
"github.com/xiaoxue/memoryweave/internal/models"
|
||||
)
|
||||
|
||||
// testNS 固定命名空间,用于证明「实体修对 + namespace 对上 ⇒ 补入 >0」,
|
||||
// 以及「namespace 对不上 ⇒ 二次阻塞补 0」(次级怀疑)。
|
||||
const testNS = "t-ns-expand"
|
||||
|
||||
// chainNodes 一条 4 节点链(中文实体,与生产 graph.db 节点命名一致:n_<名字>)。
|
||||
// 抽取器 extractPotentialEntitiesFromContent 对「2~8 字中文串」最可靠(英文带空格提不到),
|
||||
// 故实体一律用中文名;边端点是归一后形态(n_织忆 / n_图谱 / n_召回 / n_向量)。
|
||||
var (
|
||||
chainNodeIDs = []string{"n_织忆", "n_图谱", "n_召回", "n_向量"}
|
||||
chainNodeNames = map[string]string{"n_织忆": "织忆", "n_图谱": "图谱", "n_召回": "召回", "n_向量": "向量"}
|
||||
chainEdges = []struct{ id, src, dst string }{
|
||||
{"e-ab", "n_织忆", "n_图谱"},
|
||||
{"e-bc", "n_图谱", "n_召回"},
|
||||
{"e-cd", "n_召回", "n_向量"},
|
||||
}
|
||||
)
|
||||
|
||||
// addChainInMemory 给 InMemoryGraph 灌入链(AddNode/AddEdge 无死锁,可直接用)。
|
||||
func addChainInMemory(g *InMemoryGraph) {
|
||||
for _, id := range chainNodeIDs {
|
||||
_ = g.AddNode(id, chainNodeNames[id], "entity", testNS)
|
||||
}
|
||||
for _, e := range chainEdges {
|
||||
_ = g.AddEdge(e.id, e.src, e.dst, "LINKS_TO", testNS, 1.0)
|
||||
}
|
||||
}
|
||||
|
||||
// buildFileGraphJSON 把链写成 JSON 文件,再 NewFileGraph 加载 —— 绕开 AddNode/AddEdge 潜伏死锁。
|
||||
func buildFileGraphJSON(t *testing.T) (*FileGraph, string) {
|
||||
t.Helper()
|
||||
path := filepath.Join(t.TempDir(), "graph-expand-test.json")
|
||||
data := FileGraphData{Version: 2}
|
||||
for _, id := range chainNodeIDs {
|
||||
data.Nodes = append(data.Nodes, &FileGraphNode{
|
||||
ID: id, Name: chainNodeNames[id], Type: "entity",
|
||||
Namespace: testNS, PageRank: 0.15, EvidenceCount: 1,
|
||||
})
|
||||
}
|
||||
for _, e := range chainEdges {
|
||||
data.Edges = append(data.Edges, &FileGraphEdge{
|
||||
ID: e.id, Source: e.src, Target: e.dst,
|
||||
Relation: "LINKS_TO", Weight: 1.0, Namespace: testNS,
|
||||
})
|
||||
}
|
||||
if err := os.WriteFile(path, mustMarshal(data), 0644); err != nil {
|
||||
t.Fatalf("write filegraph json: %v", err)
|
||||
}
|
||||
fg, err := NewFileGraph(path)
|
||||
if err != nil {
|
||||
t.Fatalf("NewFileGraph: %v", err)
|
||||
}
|
||||
return fg, path
|
||||
}
|
||||
|
||||
func mustMarshal(v interface{}) []byte {
|
||||
b, err := json.Marshal(v)
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
return b
|
||||
}
|
||||
|
||||
// tenRecalls 构造 10 条 recall 结果:正文含中文实体「织忆 图谱 召回(±向量)」
|
||||
// (⇒ 归一 n_织忆/n_图谱/n_召回/n_向量,均在图内),类目名保持 "distilled"
|
||||
// (与生产实测一致,证明导航起点绝不能是类目名)。
|
||||
func tenRecalls() []models.RecallResult {
|
||||
contents := []string{
|
||||
"织忆 图谱 召回 的扩展机制",
|
||||
"图谱 与 召回 相关实体",
|
||||
"召回 通过 向量 关联 织忆",
|
||||
"织忆 图谱 召回 向量 的拓扑",
|
||||
"向量 在最末端;织忆 是起点",
|
||||
"recall 提及 织忆 图谱 召回",
|
||||
"链路 织忆 图谱 召回 向量",
|
||||
"织忆 节点 见 于 distilled 记录",
|
||||
"图谱 召回 织忆 共现",
|
||||
"最终 recall:织忆 图谱 召回 向量",
|
||||
}
|
||||
out := make([]models.RecallResult, 0, len(contents))
|
||||
for i, c := range contents {
|
||||
out = append(out, models.RecallResult{
|
||||
ID: "mem_expand_" + string(rune('a'+i)),
|
||||
Content: c,
|
||||
Category: "distilled",
|
||||
Score: 0.9,
|
||||
Namespace: testNS,
|
||||
})
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
// countGraphExpanded 逐条跑 10 条 recall,返回每调用 graph_expanded 条数 + 总和,并校验
|
||||
// 每条补入结果 category=graph_expanded 且 Score=0.5(AC#5:不动 0.5 降权)。
|
||||
func countGraphExpanded(g interface {
|
||||
ExpandFromResults(results []models.RecallResult, namespace string, maxHops int) []models.RecallResult
|
||||
}, t *testing.T, ns string) (perCall []int, total int) {
|
||||
t.Helper()
|
||||
recalls := tenRecalls()
|
||||
for i, r := range recalls {
|
||||
got := g.ExpandFromResults([]models.RecallResult{r}, ns, 1)
|
||||
for _, e := range got {
|
||||
if e.Category != "graph_expanded" {
|
||||
t.Fatalf("call %d: 补入结果 category=%q 期望 graph_expanded", i, e.Category)
|
||||
}
|
||||
if e.Score != 0.5 {
|
||||
t.Fatalf("call %d: 补入结果 score=%v 期望 0.5(AC#5 不改降权)", i, e.Score)
|
||||
}
|
||||
}
|
||||
perCall = append(perCall, len(got))
|
||||
total += len(got)
|
||||
}
|
||||
return perCall, total
|
||||
}
|
||||
|
||||
// ── 锁死(AC#4):InMemoryGraph ──────────────────────────────────
|
||||
// 改前树必 FAIL(起点=类目 ⇒ 0 补入);改后树 PASS。
|
||||
func TestInMemoryGraph_ExpandFromResults_Inserts(t *testing.T) {
|
||||
g := NewInMemoryGraph()
|
||||
addChainInMemory(g)
|
||||
|
||||
recalls := tenRecalls()
|
||||
got := g.ExpandFromResults(recalls, testNS, 1)
|
||||
if len(got) == 0 {
|
||||
t.Fatalf("InMemoryGraph ExpandFromResults 补 0 条 — 导航起点仍非实体(结构性零产出未修)")
|
||||
}
|
||||
for _, e := range got {
|
||||
if e.Category != "graph_expanded" {
|
||||
t.Fatalf("category=%q 期望 graph_expanded", e.Category)
|
||||
}
|
||||
}
|
||||
t.Logf("InMemoryGraph: 一条 10-recall 批量补入 %d 条 graph_expanded", len(got))
|
||||
}
|
||||
|
||||
// ── 锁死(AC#4):FileGraph ─────────────────────────────────────
|
||||
func TestFileGraph_ExpandFromResults_Inserts(t *testing.T) {
|
||||
fg, _ := buildFileGraphJSON(t)
|
||||
|
||||
recalls := tenRecalls()
|
||||
got := fg.ExpandFromResults(recalls, testNS, 1)
|
||||
if len(got) == 0 {
|
||||
t.Fatalf("FileGraph ExpandFromResults 补 0 条 — 导航起点仍非实体(结构性零产出未修)")
|
||||
}
|
||||
for _, e := range got {
|
||||
if e.Category != "graph_expanded" {
|
||||
t.Fatalf("category=%q 期望 graph_expanded", e.Category)
|
||||
}
|
||||
}
|
||||
t.Logf("FileGraph: 一条 10-recall 批量补入 %d 条 graph_expanded", len(got))
|
||||
}
|
||||
|
||||
// ── 次级怀疑(AC「namespace 不二次阻塞」)────────────────────────
|
||||
// 实体修对、但传错 namespace ⇒ 应补 0(证明 namespace 是硬约束,需对上才有产出)。
|
||||
func TestInMemoryGraph_ExpandFromResults_NamespaceBlock(t *testing.T) {
|
||||
g := NewInMemoryGraph()
|
||||
addChainInMemory(g)
|
||||
|
||||
got := g.ExpandFromResults(tenRecalls(), "no-such-ns", 1)
|
||||
if len(got) != 0 {
|
||||
t.Fatalf("namespace 对不上却补入 %d 条 — 预期 0(namespace 过滤应生效)", len(got))
|
||||
}
|
||||
t.Logf("namespace 不匹配 ⇒ 补 0(证明 namespace 为硬约束;对上即有产出)")
|
||||
}
|
||||
|
||||
// ── 实测(AC#3):同批 10 条 recall 补入率 ──────────────────────
|
||||
// 改前树:perCall 全 0 ⇒ total 0(复现结构零)。改后树:total>0,输出具体数字。
|
||||
func TestExpandFromResults_TenRecall_Empirical(t *testing.T) {
|
||||
gm := NewInMemoryGraph()
|
||||
addChainInMemory(gm)
|
||||
pIn, totalIn := countGraphExpanded(gm, t, testNS)
|
||||
t.Logf("InMemoryGraph 10-recall 补入: per-call=%v total=%d", pIn, totalIn)
|
||||
if totalIn == 0 {
|
||||
t.Fatalf("InMemoryGraph 改后仍补 0(10/10 全 0)— 结构性零产出未消除")
|
||||
}
|
||||
|
||||
fg, _ := buildFileGraphJSON(t)
|
||||
pF, totalF := countGraphExpanded(fg, t, testNS)
|
||||
t.Logf("FileGraph 10-recall 补入: per-call=%v total=%d", pF, totalF)
|
||||
if totalF == 0 {
|
||||
t.Fatalf("FileGraph 改后仍补 0(10/10 全 0)— 结构性零产出未消除")
|
||||
}
|
||||
}
|
||||
@@ -3,44 +3,76 @@ 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(补前去重)
|
||||
// 从每个结果正文提实体出发扩展
|
||||
for _, r := range results {
|
||||
paths, err := g.Navigate(r.Category, maxHops, namespace, nil)
|
||||
if err != nil {
|
||||
continue
|
||||
}
|
||||
for _, p := range paths {
|
||||
to, _ := p["to"].(string)
|
||||
from, _ := p["from"].(string)
|
||||
for _, entity := range extractPotentialEntitiesFromContent(r.Content) {
|
||||
if seenEntities[entity] {
|
||||
continue
|
||||
}
|
||||
seenEntities[entity] = true
|
||||
startEntities++
|
||||
|
||||
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, // 图谱扩展降权
|
||||
})
|
||||
nodeID := normalizeEntityID(entity)
|
||||
paths, err := g.Navigate(nodeID, maxHops, namespace, nil)
|
||||
if err != nil {
|
||||
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 条",
|
||||
namespace, maxHops, startEntities, totalPathsHit, len(expanded))
|
||||
}
|
||||
return expanded
|
||||
}
|
||||
|
||||
|
||||
@@ -5,6 +5,7 @@ package governance
|
||||
import (
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"log"
|
||||
"math"
|
||||
"os"
|
||||
"strings"
|
||||
@@ -457,32 +458,53 @@ func (fg *FileGraph) UpdateEdgeTrustScores() error { return
|
||||
func (fg *FileGraph) ExpandFromResults(results []models.RecallResult, namespace string, maxHops int) []models.RecallResult {
|
||||
var expanded []models.RecallResult
|
||||
seen := make(map[string]bool)
|
||||
seenEntities := make(map[string]bool)
|
||||
|
||||
for _, r := range results {
|
||||
seen[r.ID] = true
|
||||
}
|
||||
|
||||
// 导航起点 = 从 r.Content 提实体(复用 extractFileGraphEntities + normalizeFileGraphEntityID,
|
||||
// 与同文件 ExpandWithSummary 同一套逻辑)。旧实现拿 r.Category(类目名,如 "distilled")
|
||||
// 当实体去 Navigate,永远匹配不到任何图节点 ⇒ 结构性零产出(t_818f77be)。
|
||||
startEntities := 0 // 可观测性:去重后实际导航的起点实体数 N
|
||||
totalPathsHit := 0 // 可观测性:命中路径总数 M(补前去重)
|
||||
for _, r := range results {
|
||||
paths, err := fg.Navigate(r.Category, maxHops, namespace, nil)
|
||||
if err != nil {
|
||||
continue
|
||||
}
|
||||
for _, p := range paths {
|
||||
target, _ := p["target"].(string)
|
||||
source, _ := p["source"].(string)
|
||||
for _, entity := range extractFileGraphEntities(r.Content) {
|
||||
if seenEntities[entity] {
|
||||
continue
|
||||
}
|
||||
seenEntities[entity] = true
|
||||
startEntities++
|
||||
|
||||
for _, id := range []string{target, source} {
|
||||
if id != "" && !seen[id] {
|
||||
seen[id] = true
|
||||
expanded = append(expanded, models.RecallResult{
|
||||
ID: id,
|
||||
Category: "graph_expanded",
|
||||
Score: 0.5,
|
||||
})
|
||||
nodeID := normalizeFileGraphEntityID(entity)
|
||||
paths, err := fg.Navigate(nodeID, maxHops, namespace, nil)
|
||||
if err != nil {
|
||||
continue
|
||||
}
|
||||
totalPathsHit += len(paths)
|
||||
for _, p := range paths {
|
||||
target, _ := p["target"].(string)
|
||||
source, _ := p["source"].(string)
|
||||
|
||||
for _, id := range []string{target, source} {
|
||||
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 条",
|
||||
namespace, maxHops, startEntities, totalPathsHit, len(expanded))
|
||||
}
|
||||
return expanded
|
||||
}
|
||||
|
||||
|
||||
Reference in New Issue
Block a user