fix(distill): semantic near-dedup gate on distill write path

Previously distill's direct-write path only skipped facts whose exact
content already existed (sim[0].Content == fact). This let semantically
equivalent facts - e.g. "牧尘在招商局工作" vs "牧尘在招商局工作。"
(trailing period) - slip through as separate memories, accounting for
most of the 404 redundant entries found by a full-vector cosine scan.

Now distill encodes each fact, searches 5 nearest neighbors in the same
namespace, and skips insertion if any neighbor has either identical
content OR cosine similarity >= 0.98. The same threshold is shared by
the commit path (routes/core.go), via a new api-level cosineSimilarity
helper.

This is preventative only: it does NOT merge existing duplicates.
Existing 404 redundant entries remain; they will be cleaned up by a
separate manual dedup run after the gate is live.
This commit is contained in:
小唯
2026-09-20 00:37:25 +08:00
parent 0d4add1fb2
commit 69602ddd08
2 changed files with 38 additions and 3 deletions
+23
View File
@@ -0,0 +1,23 @@
package api
import "math"
// cosineSimilarity 计算两个向量的余弦相似度。
// 放在 api 包根目录,让 server(蒸馏写入路径)和 routes(commit 路径)
// 共享同一套近重复判据(>=0.98),避免两套逻辑各自漂移。
func cosineSimilarity(a, b []float32) float64 {
var dot, normA, normB float64
n := len(a)
if len(b) < n {
n = len(b)
}
for i := 0; i < n; i++ {
dot += float64(a[i]) * float64(b[i])
normA += float64(a[i]) * float64(a[i])
normB += float64(b[i]) * float64(b[i])
}
if normA == 0 || normB == 0 {
return 0
}
return dot / math.Sqrt(normA*normB)
}
+15 -3
View File
@@ -168,12 +168,24 @@ func NewServer() http.Handler {
if !distill.IsQualityFact(fact) {
continue // 碎片/噪声过滤
}
// 查重: 同 namespace 已存在完全相同 content → 跳过
// 查重: 同 namespace 已存在**语义等价**记忆 → 跳过
// 必须用 cosine 近重复判据(≥0.98),不能只比字符串相等——
// 否则 "牧尘在招商局工作" 与 "牧尘在招商局工作。"(多一个句号)
// 会被判为两条不同事实双双入库,造成近重复堆积。
var skip bool
if qvec, eErr := emb.EncodeSingle(fact); eErr == nil {
if sim, _ := ldb.Search("memories", qvec, 1, input.Namespace); len(sim) > 0 && sim[0].Content == fact {
continue
if sim, _ := ldb.Search("memories", qvec, 5, input.Namespace); len(sim) > 0 {
for _, ex := range sim {
if ex.Content == fact || cosineSimilarity(qvec, ex.Vector) >= 0.98 {
skip = true
break
}
}
}
}
if skip {
continue
}
mem := models.MemoryRecord{
ID: fmt.Sprintf("mem_%d", time.Now().UnixNano()),
AgentID: input.AgentID,