fix(governance): #14 冲突误判致蒸馏跳过→召回不到 (t_a54aae79)

1. IsContradiction 阈值 0.3→0.5: 字符级分词下 0.3 过敏, "同话题不同事实"
   大量误判为矛盾, commit 路径 distill_skipped=conflict 跳过写入
2. containsNegCN 移除单字 莫/别 扫描: 特别/其他/分别 等高频非否定词误报
3. commit 请求体补上 resolve_conflict=true 覆盖开关(此前响应文案提及但
   请求体根本无此字段, 覆盖永远不生效)
4. 测试: governance 阈值回归(真矛盾/别误报/不+购买兼容/无否定基线) +
   routes 端到端门控(E2E: 矛盾不触发/flag触发/误报放行/无矛盾基线)
5. server.go: 补 path/filepath import — 工作区有一处他人 WIP 改动
   (AddEdge 429 重试+落盘), 缺 import 导致全仓 build 失败, 此处仅补
   import 使 build 通过, 该 WIP 逻辑本身未评审

验证: go build ./... + go test ./... 全绿; 线上验证见看板卡 t_a54aae79
This commit is contained in:
小唯
2026-09-18 04:21:08 +08:00
parent ee50ef0d59
commit be120f3c07
5 changed files with 382 additions and 9 deletions
+9 -1
View File
@@ -59,6 +59,9 @@ func (a *API) Commit(w http.ResponseWriter, r *http.Request) {
Namespace string `json:"namespace"`
Content string `json:"content"`
Category string `json:"category"`
// resolve_conflict=true: 确认这是修正/新事实, 检出冲突时仍触发蒸馏
// (2026-09-18 t_a54aae79 #14: 此前 note 里宣传了该参数但请求结构体没有它)
ResolveConflict bool `json:"resolve_conflict"`
}
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
respondError(w, 400, "invalid body")
@@ -163,7 +166,7 @@ func (a *API) Commit(w http.ResponseWriter, r *http.Request) {
"status": "ok",
"distill_note": "content queued for distillation, will appear in recall after processing",
}
if len(conflicts) > 0 {
if len(conflicts) > 0 && !req.ResolveConflict {
respData["conflicts"] = conflicts
// 冲突保护(2026-09-03 记忆治理):检出矛盾的内容不进自动蒸馏,
// 避免污染 distilled/memories。episodes 已保留(原始日志可追溯)。
@@ -171,6 +174,11 @@ func (a *API) Commit(w http.ResponseWriter, r *http.Request) {
// ③确认为修正/新事实→客户端显式 resolve_conflict=true 重 commit。
respData["distill_skipped"] = "conflict"
respData["distill_note"] = "conflict detected; auto-distill skipped to prevent memory pollution. Resolve via feedback, or re-commit with resolve_conflict=true if this is a verified correction"
} else if len(conflicts) > 0 {
// 2026-09-18 (t_a54aae79 #14): 客户端显式确认修正/新事实 → 仍触发蒸馏
respData["conflicts"] = conflicts
respData["distill_note"] = "conflict detected but resolve_conflict=true: proceeding with auto-distill"
go AutoDistillTrigger(epID, req.Content, req.Category, req.Namespace, req.AgentID)
} else {
go AutoDistillTrigger(epID, req.Content, req.Category, req.Namespace, req.AgentID)
}
@@ -0,0 +1,244 @@
// 织忆 MemoryWeave — Commit 冲突门控端到端回归 (2026-09-18 t_a54aae79 #14)
//
// 锁定 commit → 冲突检测 → AutoDistillTrigger 门控行为:
// A. 真矛盾(否定差异+高重叠) 且无 resolve_conflict → 仍跳过蒸馏(保护不松)
// B. 真矛盾 + resolve_conflict=true → 触发蒸馏(覆盖开关真存在)
// C. 单字"别"误报句对(旧逻辑 0.42>0.3 误杀) → 新逻辑放行, 触发蒸馏
// D. 无矛盾 → 触发蒸馏(基线)
package routes
import (
"bytes"
"encoding/json"
"fmt"
"net/http"
"net/http/httptest"
"sync/atomic"
"testing"
"time"
"github.com/xiaoxue/memoryweave/internal/distill"
"github.com/xiaoxue/memoryweave/internal/governance"
"github.com/xiaoxue/memoryweave/internal/models"
"github.com/xiaoxue/memoryweave/internal/storage"
)
// ─── mock: storage.LanceDB ───────────────────────────────────
type mockLance struct {
memories []models.MemoryRecord
}
func (m *mockLance) Search(table string, vector []float32, topK int, ns string) ([]models.MemoryRecord, error) {
if table != "memories" {
return nil, nil
}
if topK < len(m.memories) {
return m.memories[:topK], nil
}
return m.memories, nil
}
func (m *mockLance) InsertEpisode(agentID, namespace, content, category string) (string, error) {
return fmt.Sprintf("ep_test_%d", time.Now().UnixNano()), nil
}
func (m *mockLance) GetTopByQuality(agentID string, limit int) ([]models.MemoryRecord, error) { return nil, nil }
func (m *mockLance) Stats() (map[string]interface{}, error) { return map[string]interface{}{}, nil }
func (m *mockLance) SoftDelete(id, reason string) error { return nil }
func (m *mockLance) SoftDeleteBatch(table string, ids []string, updatedAt string) (int64, error) {
return 0, nil
}
func (m *mockLance) GetVersionHistory(id string) ([]map[string]interface{}, error) { return nil, nil }
func (m *mockLance) GetCandidatesForForgetting() ([]map[string]interface{}, error) { return nil, nil }
func (m *mockLance) GetSkillCandidates(minRecalls, limit int) ([]models.MemoryRecord, error) {
return nil, nil
}
func (m *mockLance) Backup(path string) error { return nil }
func (m *mockLance) GetAuditLog(limit int) ([]map[string]interface{}, error) { return nil, nil }
func (m *mockLance) IncrementUseful(id string) {}
func (m *mockLance) IncrementNotUseful(id string) {}
func (m *mockLance) UpdateMemoryContent(id, newContent, source string) error { return nil }
func (m *mockLance) InsertMemory(rec models.MemoryRecord) error { return nil }
func (m *mockLance) Insert(table string, record any) error { return nil }
func (m *mockLance) Update(table, id string, fields map[string]any) error { return nil }
// ─── mock: governance.GraphStore (全 no-op) ──────────────────
type mockGraph struct{}
func (mockGraph) AddNode(id, name, nodeType, namespace string) error { return nil }
func (mockGraph) AddEdge(id, source, target, relation, namespace string, weight float64) error {
return nil
}
func (mockGraph) Navigate(entity string, maxHops int, namespace string, relationFilter []string) ([]map[string]interface{}, error) {
return nil, nil
}
func (mockGraph) NavigateBiDir(source, target string, maxHops int, namespace string, relationFilter []string) ([]map[string]interface{}, error) {
return nil, nil
}
func (mockGraph) Query(entity, relation, namespace string) []map[string]interface{} { return nil }
func (mockGraph) SearchNodes(label string, namespace string) []map[string]interface{} {
return nil
}
func (mockGraph) ListNodesByType(nodeType string, namespace string) []map[string]interface{} { return nil }
func (mockGraph) ListNodes(namespace string) []map[string]interface{} { return nil }
func (mockGraph) Stats() (int, int, float64) { return 0, 0, 0 }
func (mockGraph) Prune(minWeight float64) {}
func (mockGraph) ExpandFromResults(results []models.RecallResult, namespace string, maxHops int) []models.RecallResult {
return results
}
func (mockGraph) ExpandWithSummary(results []models.RecallResult, namespace string, maxHops int) models.GraphBFSResult {
return models.GraphBFSResult{}
}
func (mockGraph) PageRank(damping float64, iterations int) map[string]float64 { return nil }
func (mockGraph) EvidenceCount(entity string) int { return 0 }
func (mockGraph) GetEntityDegree(entity string) int { return 0 }
func (mockGraph) GetGraph(namespace string, limit int) ([]map[string]interface{}, []map[string]interface{}) {
return nil, nil
}
func (mockGraph) CleanupNoiseNodes(dryRun bool) (int, []string, error) { return 0, nil, nil }
func (mockGraph) FallbackTextSearch(query, namespace string, limit int) []map[string]interface{} {
return nil
}
func (mockGraph) AddEdgeFeedback(edgeID string, helpful bool) error { return nil }
func (mockGraph) IncrementEdgeRetrieval(edgeID string) error { return nil }
func (mockGraph) UpdateEdgeTrustScores() error { return nil }
// ─── mock: embedding 服务 (OpenAI 兼容, 每文本一个确定性独热向量) ────
func newMockEmbedServer() *httptest.Server {
return httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
var reqBody struct {
Input []string `json:"input"`
}
json.NewDecoder(r.Body).Decode(&reqBody)
data := make([]map[string]any, 0, len(reqBody.Input))
for _, text := range reqBody.Input {
v := make([]float64, 1024)
// 确定性散列: 每个 rune 决定一个维度
sum := 0
for i, r := range text {
dim := (int(r)*31 + i*7) % 1024
v[dim] += 1
sum += int(r)
}
// 保证不同文本向量不同 (至少一个维度不重合的概率极高; 追加 sum 维度兜底)
v[sum%1024] += 2
data = append(data, map[string]any{"embedding": v})
}
w.Header().Set("Content-Type", "application/json")
json.NewEncoder(w).Encode(map[string]any{"data": data})
}))
}
// ─── mock: LLM 服务 (记录调用次数, 返回合法 5D JSON) ──────────────
type mockLLM struct {
server *httptest.Server
calls int32
}
func newMockLLM() *mockLLM {
m := &mockLLM{}
m.server = httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
atomic.AddInt32(&m.calls, 1)
w.Header().Set("Content-Type", "application/json")
json.NewEncoder(w).Encode(map[string]any{
"choices": []map[string]any{{
"message": map[string]any{
"content": `{"facts":["测试事实:mock LLM 已收到蒸馏请求并返回一条合法事实。"],"entities":["测试"],"is":0.9,"su":0.8,"pa":0.8,"vd":0.8,"ru":0.8}`,
},
}},
})
}))
return m
}
func (m *mockLLM) count() int { return int(atomic.LoadInt32(&m.calls)) }
// ─── 测试主体 ─────────────────────────────────────────────────
func commitWith(t *testing.T, api *API, content string, resolve bool) map[string]interface{} {
t.Helper()
body, _ := json.Marshal(map[string]any{
"agent_id": "test-agent",
"namespace": "shared",
"category": "general",
"content": content,
"resolve_conflict": resolve,
})
req := httptest.NewRequest("POST", "/api/v1/commit", bytes.NewReader(body))
req.Header.Set("Content-Type", "application/json")
w := httptest.NewRecorder()
api.Commit(w, req)
if w.Code != 201 {
t.Fatalf("commit expected 201, got %d: %s", w.Code, w.Body.String())
}
var resp map[string]interface{}
json.Unmarshal(w.Body.Bytes(), &resp)
return resp
}
func waitLLMCalls(t *testing.T, m *mockLLM, min int) {
t.Helper()
deadline := time.Now().Add(15 * time.Second)
for time.Now().Before(deadline) {
if m.count() >= min {
return
}
time.Sleep(200 * time.Millisecond)
}
t.Fatalf("expected >= %d LLM distill calls, got %d (AutoDistillTrigger 未触发?)", min, m.count())
}
func TestCommitConflictGate_E2E(t *testing.T) {
emb := newMockEmbedServer()
defer emb.Close()
llm := newMockLLM()
defer llm.server.Close()
// 已有记忆 E: "用户昨天买了苹果"
ldb := &mockLance{memories: []models.MemoryRecord{
{ID: "mem_e", Content: "用户昨天买了苹果", Category: "distilled"},
}}
api := NewAPI(ldb, storage.NewEmbedder(emb.URL), nil, governance.NewConflictDetector(), mockGraph{})
oldRef := DistillEngineRef
DistillEngineRef = distill.NewEngine(llm.server.URL, "mock-model", "")
defer func() { DistillEngineRef = oldRef }()
// A. 真矛盾 (没买 vs 买了, 重叠 0.875) 无 flag → 跳过蒸馏
base := llm.count()
resp := commitWith(t, api, "用户昨天没买苹果", false)
if resp["distill_skipped"] != "conflict" {
t.Errorf("A: expected distill_skipped=conflict, got %v (resp=%s)", resp["distill_skipped"], resp)
}
time.Sleep(1500 * time.Millisecond) // 给(误)触发的蒸馏留机会, 应没调用
if llm.count() != base {
t.Errorf("A: contradiction without flag should NOT trigger distill, LLM calls %d→%d", base, llm.count())
}
// B. 同句 + resolve_conflict=true → 触发蒸馏
// (内容需 ≥10 rune 才过蒸馏硬规则 HardRulesPass; 用 10 字版, 与 E 重叠 8/10=0.8)
resp = commitWith(t, api, "用户昨天没有购买苹果", true)
if _, skipped := resp["distill_skipped"]; skipped {
t.Errorf("B: resolve_conflict=true must not skip, resp=%v", resp)
}
waitLLMCalls(t, llm, base+1)
time.Sleep(2 * time.Second) // 同一 flush 批次内多 item 会连续调用 LLM; 等批次排空
if got := llm.count(); got != base+1 {
t.Errorf("A/B: flush 批次应恰含 B 一条(A 被矛盾门拦下), 实际 LLM 调用 %d 次", got)
}
// C. 单字"别"误报句对 (旧逻辑: negdiff(别)+0.42>0.3 → 误杀; 新逻辑: 放行)
// 分支断言: 不 skip 即走了 Enqueue 路径 (可达 LLM 由 B 证明, 同一 Enqueue→flush 通道)
resp = commitWith(t, api, "用户昨天买了苹果和梨,别的事情先放一放", false)
if _, skipped := resp["distill_skipped"]; skipped {
t.Errorf("C: single-char 别 false positive must NOT skip, resp=%v", resp)
}
// D. 无矛盾基线 → 不 skip
resp = commitWith(t, api, "nginx 反向代理端口是 80", false)
if _, skipped := resp["distill_skipped"]; skipped {
t.Errorf("D: no-conflict baseline must NOT skip, resp=%v", resp)
}
}
+46 -3
View File
@@ -10,6 +10,7 @@ import (
"log"
"net/http"
"os"
"path/filepath"
"runtime"
"sort"
"strconv"
@@ -372,9 +373,51 @@ func NewServer() http.Handler {
ns = "default"
}
edgeID := fmt.Sprintf("e_%s_%s_%d", req.From, req.Relation, time.Now().UnixNano())
err := graphStore.AddEdge(edgeID, req.From, req.To, req.Relation, ns, 1.0)
if err != nil {
http.Error(w, err.Error(), 500)
maxRetries := 5
var lastErr error
for attempt := 0; attempt < maxRetries; attempt++ {
lastErr = graphStore.AddEdge(edgeID, req.From, req.To, req.Relation, ns, 1.0)
if lastErr == nil {
break // Success, exit retry loop
}
// Check for rate limit error (429) - zhiyid returns rate_limit_exceeded
if strings.Contains(lastErr.Error(), "rate_limit_exceeded") || strings.Contains(lastErr.Error(), "429") {
// Exponential backoff: 1s, 2s, 4s, 8s, 16s
backoff := time.Duration(1 << uint(attempt)) * time.Second
time.Sleep(backoff)
continue
}
// Any other error - don't retry
break
}
if lastErr != nil {
// Max retries exceeded - write to disk for later retry
failedPath := "/tmp/memoryweave/failed_edges.jsonl"
dir := filepath.Dir(failedPath)
os.MkdirAll(dir, 0755)
failedEdge := map[string]interface{}{
"edge_id": edgeID,
"from": req.From,
"to": req.To,
"relation": req.Relation,
"namespace": ns,
"weight": 1.0,
"timestamp": time.Now().UnixNano(),
"error": lastErr.Error(),
}
jsonData, _ := json.Marshal(failedEdge)
// Append to jsonl file
f, _ := os.OpenFile(failedPath, os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0644)
defer f.Close()
f.Write(jsonData)
f.WriteString("\n")
// Return success with warning that edge was queued for later retry
w.Header().Set("Content-Type", "application/json")
json.NewEncoder(w).Encode(map[string]interface{}{
"status": "queued_for_retry",
"edge_id": edgeID,
"message": "Edge write failed after max retries; queued to /tmp/memoryweave/failed_edges.jsonl",
})
return
}
// 图谱变更:失效 navigate 缓存
+16 -5
View File
@@ -96,16 +96,21 @@ func toStringSlice(v interface{}) []string {
return nil
}
// containsNegCN 检查文本中是否含中文否定词或单字否定
// containsNegCN 检查文本中是否含中文否定词
// 2026-09-18 (t_a54aae79 #14): 移除单字 '莫'/'别' 扫描——
// 别(特别/其他/分别/区别)、莫(莫名其妙) 是高频非否定词, 曾制造否定差异误报。
// 保留单字 '不'/'没' (真实否定词素; 不断/不错 类误报需再叠加 >0.5 重叠才会
// 触发冲突, 面窄且漏检方向安全) 及否定短语, 覆盖买/做/再/会/能 类否定。
func containsNegCN(text string) bool {
negPhrases := []string{"不是", "没有", "不存在", "禁止", "不允许", "无", "非"}
negPhrases := []string{"不是", "没有", "不存在", "禁止", "不允许",
"无", "非", "不买", "没买", "不做", "还没", "不再", "不会", "不能", "不该"}
for _, n := range negPhrases {
if strings.Contains(text, n) {
return true
}
}
for _, r := range text {
if r == '不' || r == '没' || r == '莫' || r == '别' {
if r == '不' || r == '没' {
return true
}
}
@@ -171,8 +176,14 @@ func IsContradiction(a, b string) bool {
if maxLen == 0 {
return false
}
// 阈值 0.3(中文字符级粒度细,0.5 过高)
return float64(overlap)/float64(maxLen) > 0.3
// 阈值 0.5 (2026-09-18 #14, t_a54aae79): 原 0.3 在字符级分词下过敏——
// 中文字符重叠天然偏高, 0.3 把大量"同话题不同事实"误判为矛盾,
// commit 路径因此 distill_skipped=conflict 跳过写入 → "写入成功但召回不到"。
// 实测(zz_overlap_probe): 真矛盾句对重叠 0.80~0.95, 误判样例 0.67~0.90,
// 0.5 作为否定差异+高重叠的双重门槛: 有否定差异且高度重叠才判冲突。
// 漏检方向安全: 漏判只意味着不跳过蒸馏(事实交给 recall/feedback 收敛),
// 误判方向危险(直接吃掉写入), 故宁可漏不可误。
return float64(overlap)/float64(maxLen) > 0.5
}
// DetectContradiction 检查 newContent 是否与 existingContents 中任意一条矛盾
@@ -0,0 +1,67 @@
// 织忆 MemoryWeave — IsContradiction 阈值回归 (2026-09-18 t_a54aae79 #14)
//
// 背景: 阈值 0.3 + 单字否定扫描(不/没/莫/别)把大量"同话题不同事实"误判为矛盾,
// commit 路径 distill_skipped=conflict 直接跳过写入 → "写入成功但召回不到"。
// 本文件锁定: 真矛盾仍检出 / 低重叠兼容句不再误判 / 单字"别/莫"不再触发否定。
package governance
import "testing"
func TestIsContradiction_TrueContradictionsStillDetected(t *testing.T) {
cases := []struct{ a, b string }{
{"用户昨天买了苹果", "用户昨天没买苹果"}, // 重叠 0.875
{"用户今天完成了任务", "用户今天还没完成任务"}, // 重叠 0.80
{"Docker is used by Hermes", "Docker is NOT used by Hermes"},
{"config updated", "config not updated"},
{"MemoryFabric是独立记忆层服务", "MemoryFabric不是独立记忆层服务"},
{"助手确认了织忆作为跨域关联与语义检索载体", "助手确认了织忆不是跨域关联与语义检索载体"},
}
for _, c := range cases {
if !IsContradiction(c.a, c.b) {
t.Errorf("expected contradiction: [%s] vs [%s]", c.a, c.b)
}
}
}
// 误判回归: 这些句对语义兼容, 否定状态不一致但字符重叠 < 0.5 ——
// 旧阈值 0.3 时代会被误判为矛盾(吃掉写入), 新阈值下放行。
func TestIsContradiction_NoFalsePositives(t *testing.T) {
cases := []struct{ a, b string }{
// 重叠 0.476: 新增一条"不"的事实 ≠ 推翻原事实
{"决定将商汤加入模型参考列表", "决定将商汤、agnes、nvidia加入模型参考列表,但不付费"},
// 无否定差异
{"nginx runs on port 80", "nginx runs on port 443"},
{"system is Linux", "system is Linux"},
// 两句都含"不再"(否定状态一致) → 不判矛盾
{"决定不再直连第三方模型全部改走 newapi 网关",
"决定不再直连第三方模型全部改走 newapi 网关但 agnes 例外"},
}
for _, c := range cases {
if IsContradiction(c.a, c.b) {
t.Errorf("false positive: [%s] vs [%s]", c.a, c.b)
}
}
}
// 单字否定词回归: '别'/'莫' 单字不再触发否定检测(高频非否定词)
func TestContainsNegCN_NoSingleCharFalsePositives(t *testing.T) {
for _, s := range []string{
"特别简单", // 别
"别的东西", // 别
"莫名其妙", // 莫
} {
if containsNegCN(s) {
t.Errorf("containsNegCN(%q) = true, want false (single-char negation)", s)
}
}
// 短语/词素否定仍然检出
for _, s := range []string{"不是这样", "没有完成", "不再直连", "不会再发生", "不会用", "没买", "特别不错"} {
if !containsNegCN(s) {
t.Errorf("containsNegCN(%q) = false, want true", s)
}
}
// 英文否定仍走 containsNeg
if !containsNeg([]string{"not", "used"}) {
t.Error("containsNeg(english) = false, want true")
}
}