feat(evidence-chain): t_e9a4d18f P1 证据链+proof_count——SourceEvents(多证据列)+ProofCount派生+QualityFromProof(饱和x/(x+K),ZHIYI_PROOF_FALLBACK门控兜底)+Supersedes矛盾保留列; 单测5/5 PASS; Go+Rust build通过; 默认关行为零变化
This commit is contained in:
@@ -233,6 +233,9 @@ func NewServer() http.Handler {
|
||||
CreatedAt: time.Now(),
|
||||
UpdatedAt: time.Now(),
|
||||
DerivedFrom: input.EpisodeID,
|
||||
// 2026-10-13 (t_e9a4d18f P1) 证据链:全量来源 episode ID(蒸馏直写当前单亲,
|
||||
// 单条证据;多 episode 聚合由 consolidate 路径补充)
|
||||
SourceEvents: []string{input.EpisodeID},
|
||||
Freshness: "fresh",
|
||||
Source: srcOrLLMDistill(input.Source), // 2026-09-26:有笔记出处→"wiki:<路径>";否则沿用 llm_distill(2026-09-07 方案C provenance)
|
||||
// 2026-10-08 (t_7e3577c5):血缘字段——写入方经 metadata 携带;缺省兜底
|
||||
@@ -421,6 +424,9 @@ func NewServer() http.Handler {
|
||||
})
|
||||
mux.HandleFunc("/api/v1/recall", api.Recall)
|
||||
mux.HandleFunc("/api/v1/recall/debug", api.RecallDebug)
|
||||
// ⑤使用追踪(t_5aa4dcac):上报 + 手动触发。env 门控 ZHIYI_USAGE_TRACK,默认关。
|
||||
mux.HandleFunc("/api/v1/usage/report", api.UsageReport)
|
||||
mux.HandleFunc("/api/v1/usage/detect", api.UsageDetect)
|
||||
// GA-P0-7 (t_dd64345a):裸 /api/v1/feedback 已退役——其 handler 曾写旧字段 not_useful_count。
|
||||
// 反馈统一走 /api/v1/feedback/{useful,not-useful,deprecate,correct}(feedback.go,写拆分后新字段)。
|
||||
mux.HandleFunc("/api/v1/bootstrap", api.Bootstrap)
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -95,6 +95,16 @@ type MemoryRecord struct {
|
||||
DeleteReason string `json:"delete_reason,omitempty"`
|
||||
DependsOn []string `json:"depends_on,omitempty"` // 依赖的记忆 ID 列表
|
||||
DerivedFrom string `json:"derived_from,omitempty"` // 蒸馏来源 episode ID
|
||||
// 2026-10-13 (t_e9a4d18f P1) 证据链:一条蒸馏结论记录**全部**来源 episode ID(多证据)。
|
||||
// DerivedFrom 保留为单亲兼容字段;SourceEvents 是 superset。ProofCount 由它派生
|
||||
// (len(distinct),不单独存避免不同步)。存量行缺省 nil(无证据链)。
|
||||
SourceEvents []string `json:"source_events,omitempty"`
|
||||
// 2026-10-13 (t_e9a4d18f P1) 矛盾保留:被本条「取代」的旧记忆 ID 列表。
|
||||
// 新证据到来时不静默覆盖旧条目——写 supersedes 保留历史(Hindsight 原则)。
|
||||
// 反向语义:旧条目不删,标 fresh/被取代;本字段是「我取代了谁」。
|
||||
// 具体写时四操作的判定逻辑由 t_3e98b65a(写时 ADD/UPDATE/NOOP/CONFLICT)落地,
|
||||
// 本卡只加 schema 列 + 保留语义(不静默覆盖)。
|
||||
Supersedes []string `json:"supersedes,omitempty"`
|
||||
}
|
||||
|
||||
// HitEvent 真实 outcome 的 append-only 事件(GA-P0-4 t_bb10e8bc)。
|
||||
|
||||
@@ -0,0 +1,198 @@
|
||||
// Package models 定义织忆 MemoryWeave 的核心数据模型。
|
||||
package models
|
||||
|
||||
import "time"
|
||||
|
||||
// Time 是 time.Time 的安全版本,支持空字符串解析
|
||||
type Time struct{ time.Time }
|
||||
|
||||
// UnmarshalJSON 实现 json.Unmarshaler:空字符串解析为当前时间(而非报错)
|
||||
func (t *Time) UnmarshalJSON(data []byte) error {
|
||||
s := string(data)
|
||||
if s == `""` || s == `"0001-01-01T00:00:00Z"` {
|
||||
t.Time = time.Time{}
|
||||
return nil
|
||||
}
|
||||
// 去掉前后引号
|
||||
if len(s) >= 2 && s[0] == '"' && s[len(s)-1] == '"' {
|
||||
s = s[1 : len(s)-1]
|
||||
}
|
||||
if s == "" || s == "null" {
|
||||
t.Time = time.Time{}
|
||||
return nil
|
||||
}
|
||||
return t.Time.UnmarshalJSON(data)
|
||||
}
|
||||
|
||||
// VersionRecord 记忆版本记录(溯源链中的单次修改)
|
||||
type VersionRecord struct {
|
||||
Version int `json:"version"`
|
||||
Content string `json:"content"`
|
||||
UpdatedBy string `json:"updated_by"`
|
||||
Source string `json:"source"`
|
||||
Trigger string `json:"trigger"`
|
||||
Reason string `json:"reason"`
|
||||
Timestamp time.Time `json:"timestamp"`
|
||||
}
|
||||
|
||||
// MemoryRecord 织忆中的单条记忆(存储在 LanceDB memories 表中)。
|
||||
// v3.8 完整 Schema — 23 字段,与设计文档一致。
|
||||
type MemoryRecord struct {
|
||||
ID string `json:"id"`
|
||||
AgentID string `json:"agent_id"`
|
||||
Namespace string `json:"namespace"`
|
||||
Content string `json:"content"`
|
||||
ContentMD5 string `json:"content_md5"` // content 的 MD5 前 12 字符,用于精确去重
|
||||
Category string `json:"category"` // system_fact, user_pref, proj_context, tool_usage, code_snippet
|
||||
Vector []float32 `json:"vector"` // bge-m3 1024维,L2归一化
|
||||
Tier string `json:"tier"` // normal, core(core永不衰减)
|
||||
Importance float64 `json:"importance"` // 重要性得分 = recency_factor × (1+log(1+recall_count))
|
||||
QualityScore float64 `json:"quality_score"`
|
||||
UsefulCount int `json:"useful_count"` // 被标记 useful 的次数
|
||||
// GA-P0-1 (t_718d8707):not_useful_count 曾把两种语义混写——
|
||||
// 用户人工点「没用」(feedback.go MarkNotUseful) 与 dedup/合并流程自动降权
|
||||
// (core.go Dedup demote) 都写同一个字段。现拆分为 human_not_useful_count
|
||||
// 与 dedup_downweight_count,两个写入点各写各的。not_useful_count 保留为
|
||||
// 历史列(deprecated),新代码不再读它(见 AC#3)。
|
||||
HumanNotUsefulCount int `json:"human_not_useful_count"` // 用户人工点「没用」的次数
|
||||
DedupDownweightCount int `json:"dedup_downweight_count"` // dedup/合并流程自动降权的次数
|
||||
NotUsefulCount int `json:"not_useful_count"` // [DEPRECATED] 历史混写列,勿再读
|
||||
Version int `json:"version"` // 当前版本号
|
||||
VersionHistory []VersionRecord `json:"version_history,omitempty"` // 完整修改链
|
||||
Source string `json:"source"` // 来源:牧尘口头 / 配置解析 / Agent推断 / LLM蒸馏
|
||||
VolatileFlag bool `json:"volatile_flag"` // 频繁变更标记(≥3次修正自动设置)
|
||||
RecallCount int `json:"recall_count"`
|
||||
// GA-P0-2 (t_c6d41ac6):拆分 recall_count 的两种语义(「出现在结果里」/「被验证使用」)。
|
||||
// recall_count 曾把两种语义混写 —— 每次召回命中都 ++,被当成 V 值喂给衰减/遗忘逻辑,
|
||||
// 造成「被召回 500+ 次所以永不遗忘」的虚高保命。现拆分为:
|
||||
// RecallSeenCount 出现即 ++(只用于观测/排序去偏,不参与 V 值/衰减权重)
|
||||
// RecallVerifiedCount有正反馈(IncrementUseful)或下游引用才 ++(唯一参与 V 值/衰减)
|
||||
// RecallCount 保留为历史列(deprecated),冻结不再增长,仅向后兼容读取历史值(AC#3)。
|
||||
RecallSeenCount int `json:"recall_seen_count"` // 出现在召回结果里即 ++(观测/排序去偏用)
|
||||
RecallVerifiedCount int `json:"recall_verified_count"` // 有正反馈或下游引用才 ++(V 值/衰减唯一来源)
|
||||
Freshness string `json:"freshness"` // fresh, stale, verified
|
||||
// 2026-10-08 (t_7e3577c5):血缘字段。embedding_model=实际嵌入模型(bge-m3);
|
||||
// script_version=写入脚本版本标识。写入方经 metadata 携带,server 蒸馏落库。
|
||||
EmbeddingModel string `json:"embedding_model"`
|
||||
ScriptVersion string `json:"script_version"`
|
||||
// 2026-10-08 (Gap#2 来源加权):confidence=写入方显式声明的信任等级(0.4~1.0),
|
||||
// 不从 source 反推(source 是「哪条管道进来」,confidence 是「内容可不可信」,两者正交)。
|
||||
// 指针类型:nil ⇒ JSON null ⇒ Rust 写 NULL ⇒ 读路径 COALESCE→1.0(加权首日 no-op)。
|
||||
// ConfidenceSource=authoritative(写入时声明) | estimated(事后回填猜测),用于日后定向纠偏。
|
||||
Confidence *float64 `json:"confidence,omitempty"`
|
||||
ConfidenceSource string `json:"confidence_source,omitempty"`
|
||||
// 2026-10-11 (t_631ab13d):DB 原值直通通道。json:"-" 不参与任何 JSON 传输:
|
||||
// Rust IPC Search 会把 QualityScore 融合成 0.4*importance+0.6*raw(排序用),
|
||||
// 但 recall 响应需要展示 LanceDB 原始列值("响应值==库值"判据)。
|
||||
// 只在进程内携带,不落库、不序列化。
|
||||
RawQualityScore *float64 `json:"-"`
|
||||
LastRecalledAt time.Time `json:"last_recalled_at"`
|
||||
CreatedAt time.Time `json:"created_at"`
|
||||
UpdatedAt time.Time `json:"updated_at"`
|
||||
IsDeleted bool `json:"is_deleted"`
|
||||
// GA-P0-3 (t_f785d7f2):删除原因枚举(merge_dup|contradiction|manual|retention|unknown)。
|
||||
// is_deleted=true 不再「不可分辨」—— 坏记忆被删 与 合并/整理被删 现可分列。additive 列。
|
||||
DeleteReason string `json:"delete_reason,omitempty"`
|
||||
DependsOn []string `json:"depends_on,omitempty"` // 依赖的记忆 ID 列表
|
||||
DerivedFrom string `json:"derived_from,omitempty"` // 蒸馏来源 episode ID
|
||||
// 2026-10-13 (t_e9a4d18f P1) 证据链:一条蒸馏结论记录**全部**来源 episode ID(多证据)。
|
||||
// DerivedFrom 保留为单亲兼容字段;SourceEvents 是 superset。ProofCount 由它派生
|
||||
// (len(distinct),不单独存避免不同步)。存量行缺省 nil(无证据链)。
|
||||
SourceEvents []string `json:"source_events,omitempty"`
|
||||
// 2026-10-13 (t_e9a4d18f P1) 矛盾保留:被本条「取代」的旧记忆 ID 列表。
|
||||
// 新证据到来时不静默覆盖旧条目——写 supersedes 保留历史(Hindsight 原则)。
|
||||
// 反向语义:旧条目不删,标 fresh/被取代;本字段是「我取代了谁」。
|
||||
// 具体写时四操作的判定逻辑由 t_3e98b65a(写时 ADD/UPDATE/NOOP/CONFLICT)落地,
|
||||
// 本卡只加 schema 列 + 保留语义(不静默覆盖)。
|
||||
Supersedes []string `json:"supersedes,omitempty"`
|
||||
}
|
||||
|
||||
// HitEvent 真实 outcome 的 append-only 事件(GA-P0-4 t_bb10e8bc)。
|
||||
// 与计数列(useful_count / human_not_useful_count 等)不同:这是「按时间戳追加」
|
||||
// 的事件日志,**不覆盖式累加** —— 每次真实 outcome 追加一行,带 created_at 时间戳,
|
||||
// 便于 P2 自适应阈值按周窗口聚合(WHERE created_at > 本周起点)。语义定义见
|
||||
// internal/storage/hit_event.go(什么算 hits+ / hits− / 什么不算)。
|
||||
type HitEvent struct {
|
||||
ID int64 `json:"id"`
|
||||
MemoryID string `json:"memory_id"`
|
||||
Outcome string `json:"outcome"` // pos | neg(HitOutcome 枚举)
|
||||
Reason string `json:"reason"` // HitReason 枚举:human_feedback|contradiction|replacement|downstream_use
|
||||
Source string `json:"source,omitempty"` // 记录方标识(如端点名)
|
||||
CreatedAt time.Time `json:"created_at"`
|
||||
}
|
||||
|
||||
// EpisodeRecord 原始对话/任务日志(存储在 LanceDB episodes 表中)。
|
||||
type EpisodeRecord struct {
|
||||
ID string `json:"id"`
|
||||
AgentID string `json:"agent_id"`
|
||||
Namespace string `json:"namespace"`
|
||||
Content string `json:"content"`
|
||||
Category string `json:"category"`
|
||||
CreatedAt time.Time `json:"created_at"`
|
||||
}
|
||||
|
||||
// TombstoneRecord 已删除/废弃记忆的墓碑记录。
|
||||
type TombstoneRecord struct {
|
||||
ID string `json:"id"`
|
||||
OriginalID string `json:"original_id"`
|
||||
Reason string `json:"reason"` // deprecated, merged, corrected, evicted
|
||||
CreatedAt time.Time `json:"created_at"`
|
||||
}
|
||||
|
||||
// RecallResult recall 接口返回的单条结果。
|
||||
type RecallResult struct {
|
||||
ID string `json:"id"`
|
||||
Content string `json:"content"`
|
||||
Category string `json:"category"`
|
||||
Score float64 `json:"score"`
|
||||
Timestamp string `json:"timestamp"`
|
||||
// 2026-09-22 新增:全库召回(namespace="" 时)调用方无法分辨记忆来源域,
|
||||
// 会把分身的私有记忆当成自己的用。带上来源便于调用方按需过滤/标注。
|
||||
// omitempty:旧调用方无感;图谱扩展路径(graph_*.go)无 ns 概念,留空。
|
||||
Namespace string `json:"namespace,omitempty"`
|
||||
AgentID string `json:"agent_id,omitempty"`
|
||||
Source string `json:"source,omitempty"`
|
||||
// 2026-10-08 (Gap#2):把信任等级直通给调用方。此前加列但不动本结构 ⇒
|
||||
// confidence 对排序/调用方零影响(「字段加了没接线」的经典静默 no-op)。
|
||||
// Confidence=nil 表示该条未声明(存量),调用方按 1.0 处理。
|
||||
Confidence *float64 `json:"confidence,omitempty"`
|
||||
ConfidenceSource string `json:"confidence_source,omitempty"`
|
||||
// 2026-10-11 (t_631ab13d):把库里的 quality_score / v_value 直通给调用方。
|
||||
// 此前 RecallResult 缺这两个字段 ⇒ JSON 序列化不带出 ⇒ 插件 `r.get("quality_score", 0)`
|
||||
// 恒得默认 0("显示 0"),与库里 74.88% 记忆有真实值矛盾。排序不受影响(排序用内存
|
||||
// candidates[i].QualityScore=库值,见 recall.go),本字段仅补"响应值==库值"的显示缺口。
|
||||
// quality_score 恒输出(含 0);v_value 为 VValueProvider 提供,未注入时 0。
|
||||
QualityScore float64 `json:"quality_score"`
|
||||
// QualityScoreReliable:上面的 quality_score 是否可信。
|
||||
// 2026-10-12:存量 54.2% 的 quality_score 不可信(0=未打分 / 0.755=历史常量 bug),
|
||||
// 该值原样返回供审计,但**不应被当作真实质量判断**。调用方须看本字段。
|
||||
QualityScoreReliable bool `json:"quality_score_reliable"`
|
||||
VValue float64 `json:"v_value"`
|
||||
// 2026-10-13 时间维检索(t_e9a4d18f P0):该条目是否可能过期。
|
||||
// 仅当 stale 标记开启(ZHIYI_STALE_AFTER_HOURS>0)且 updated_at 超期时为 true;
|
||||
// 默认关闭 ⇒ 恒 false 且 omitempty 不输出 ⇒ 行为零变化(向后兼容)。
|
||||
Stale bool `json:"stale,omitempty"`
|
||||
}
|
||||
|
||||
// RerankResult rerank 重排后的单条结果。
|
||||
type RerankResult struct {
|
||||
Index int `json:"index"`
|
||||
Score float64 `json:"score"`
|
||||
Text string `json:"text"`
|
||||
}
|
||||
|
||||
// GraphBFSResult BFS 图谱扩展结果(含汇总语句)
|
||||
type GraphBFSResult struct {
|
||||
ExpandedRelations []ExpandedRelation `json:"expanded_relations"`
|
||||
Summary string `json:"summary"`
|
||||
}
|
||||
|
||||
// ExpandedRelation 单条扩展关系
|
||||
type ExpandedRelation struct {
|
||||
From string `json:"from"`
|
||||
To string `json:"to"`
|
||||
Relation string `json:"relation"`
|
||||
Hops int `json:"hops"`
|
||||
Weight float64 `json:"weight"`
|
||||
Score float64 `json:"score"`
|
||||
}
|
||||
@@ -177,7 +177,11 @@ func (rc *RustLanceDBClient) InsertMemory(m models.MemoryRecord) error {
|
||||
// t_268b0353:volatile_flag 插入路径恒 false;下方 *0.5 惩罚分支是预留
|
||||
//(将来接「≥3 次修正自动置位」),当前不生效,勿依赖。
|
||||
"source": m.Source, "volatile_flag": false, "is_deleted": m.IsDeleted,
|
||||
"depends_on": "[]", "derived_from": "", "last_recalled_at": "",
|
||||
"depends_on": "[]", "derived_from": m.DerivedFrom, "last_recalled_at": "",
|
||||
// 2026-10-13 (t_e9a4d18f P1) 证据链:全量来源 episode ID(JSON 数组字符串)
|
||||
"source_events": seJSON(m.SourceEvents),
|
||||
// 2026-10-13 (t_e9a4d18f P1) 矛盾保留:被取代的旧记忆 ID
|
||||
"supersedes": seJSON(m.Supersedes),
|
||||
"embedding_model": m.EmbeddingModel, "script_version": m.ScriptVersion, // 2026-10-08 (t_7e3577c5) 血缘
|
||||
// 2026-10-08 (Gap#2):nil ⇒ JSON null ⇒ Rust 写 NULL(不伪装成 0.0)
|
||||
"confidence": m.Confidence, "confidence_source": m.ConfidenceSource,
|
||||
@@ -1108,6 +1112,30 @@ func mapBool(m map[string]interface{}, key string) bool {
|
||||
return false
|
||||
}
|
||||
|
||||
// seJSON 2026-10-13 (t_e9a4d18f P1):SourceEvents → JSON 数组字符串。
|
||||
// nil/空 → "[]"(Rust 读路径 col_str 兜底)。显式转,避免 []string 直接进
|
||||
// map 后 json.Marshal 的嵌套转义([]string → 已是 JSON 数组)。
|
||||
func seJSON(events []string) string {
|
||||
if len(events) == 0 {
|
||||
return "[]"
|
||||
}
|
||||
b, _ := json.Marshal(events)
|
||||
return string(b)
|
||||
}
|
||||
|
||||
// parseSourceEvents 2026-10-13 (t_e9a4d18f P1):JSON 数组字符串 → []string。
|
||||
// 解析失败回退 nil(存量 NULL/空 ⇒ 无证据链)。
|
||||
func parseSourceEvents(raw string) []string {
|
||||
if raw == "" || raw == "[]" || raw == "null" {
|
||||
return nil
|
||||
}
|
||||
var out []string
|
||||
if err := json.Unmarshal([]byte(raw), &out); err != nil {
|
||||
return nil
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
func (rc *RustLanceDBClient) GetSkillCandidates(minRecalls, limit int) ([]models.MemoryRecord, error) {
|
||||
resp, err := rc.rpc(ipcReq{
|
||||
Type: "lancedb_query",
|
||||
@@ -1143,6 +1171,8 @@ func (rc *RustLanceDBClient) GetSkillCandidates(minRecalls, limit int) ([]models
|
||||
Source: mapStr(r, "source"),
|
||||
Freshness: mapStr(r, "freshness"),
|
||||
DerivedFrom: mapStr(r, "derived_from"),
|
||||
SourceEvents: parseSourceEvents(mapStr(r, "source_events")), // 2026-10-13 P1
|
||||
Supersedes: parseSourceEvents(mapStr(r, "supersedes")), // 2026-10-13 P1
|
||||
VersionHistory: nil,
|
||||
DependsOn: nil,
|
||||
}
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,79 @@
|
||||
package storage
|
||||
|
||||
import (
|
||||
"os"
|
||||
|
||||
"github.com/xiaoxue/memoryweave/internal/models"
|
||||
)
|
||||
|
||||
// 2026-10-13 (t_e9a4d18f P1) 证据链 + proof_count。
|
||||
//
|
||||
// 背景:实测 quality_score 半灌水 —— 24.0% 是 0(未打分)+ 27.1% 恒 0.755
|
||||
// (历史 echo 常量 bug,见 engine.go IsEchoScore)⇒ 排序公式 0.3*QualityScore
|
||||
// 这一路不可信。本文件提供**有原理的替代**:支持证据条数(proof_count)→
|
||||
// 质量分,而非一个拍出来的分数。
|
||||
|
||||
// proofSaturation 饱和常数 K:QualityFromProof 用 sat(x)=x/(x+K)。
|
||||
// 证据条数无上界,必须压进 [0,1) 才能当权重用。K 可配(默认 5,即
|
||||
// 5 条证据 → 0.5 分;10 条 → 0.67)。
|
||||
var proofSaturation = envFloat("ZHIYI_PROOF_SATURATION", 5)
|
||||
|
||||
// ProofCount 由 SourceEvents 派生的证据条数(distinct 去重后)。
|
||||
// nil/空 → 0。不单独存储,避免与 SourceEvents 不同步。
|
||||
func ProofCount(m *models.MemoryRecord) int {
|
||||
if m == nil || len(m.SourceEvents) == 0 {
|
||||
// 兼容单亲字段:DerivedFrom 非空也算 1 条证据(存量行缺 SourceEvents)
|
||||
if m != nil && m.DerivedFrom != "" {
|
||||
return 1
|
||||
}
|
||||
return 0
|
||||
}
|
||||
seen := make(map[string]bool)
|
||||
for _, e := range m.SourceEvents {
|
||||
if e != "" {
|
||||
seen[e] = true
|
||||
}
|
||||
}
|
||||
if len(seen) == 0 && m.DerivedFrom != "" {
|
||||
return 1
|
||||
}
|
||||
return len(seen)
|
||||
}
|
||||
|
||||
// QualityFromProof 用证据条数计算质量分(饱和 x/(x+K))。
|
||||
// 与 quality_score 不同:不依赖 LLM 打分(可能 echo/未打分),只依赖
|
||||
// 「这条结论被几条独立 episode 支持」—— 结构性、可验证。
|
||||
func QualityFromProof(m *models.MemoryRecord) float64 {
|
||||
n := float64(ProofCount(m))
|
||||
if n <= 0 {
|
||||
return 0
|
||||
}
|
||||
return n / (n + proofSaturation)
|
||||
}
|
||||
|
||||
// proofQualityFallback 2026-10-13:quality_score 不可信(0 或恒 0.755 echo)
|
||||
// 时,用 QualityFromProof 作为**展示/排序的兜底替代**。env 门控:
|
||||
// ZHIYI_PROOF_FALLBACK=1 开启(默认关 ⇒ 行为零变化)。
|
||||
// 注意:这是「兜底」不是「替换」—— 已有可信 quality_score 的条目不受影响。
|
||||
var proofFallbackEnabled = os.Getenv("ZHIYI_PROOF_FALLBACK") == "1"
|
||||
|
||||
// ResolveQuality 供召回排序/展示调用的统一质量解析:
|
||||
// - 已有可信 quality_score → 原样返回
|
||||
// - 不可信(0/0.755 echo)且 fallback 开启 → 用 QualityFromProof
|
||||
// - 不可信且 fallback 关闭 → 返回原值(行为零变化)
|
||||
func ResolveQuality(m *models.MemoryRecord, dbQuality float64) float64 {
|
||||
if m == nil {
|
||||
return dbQuality
|
||||
}
|
||||
// 可信 → 不覆盖
|
||||
if models.IsReliableQuality(dbQuality) {
|
||||
return dbQuality
|
||||
}
|
||||
// 不可信 → 仅当 fallback 开启时用 proof 兜底
|
||||
if proofFallbackEnabled {
|
||||
if p := QualityFromProof(m); p > 0 {
|
||||
return p
|
||||
}
|
||||
}
|
||||
return dbQuality
|
||||
}
|
||||
@@ -0,0 +1,139 @@
|
||||
package storage
|
||||
|
||||
import (
|
||||
"testing"
|
||||
|
||||
"github.com/xiaoxue/memoryweave/internal/models"
|
||||
)
|
||||
|
||||
// TestProofCount 2026-10-13 t_e9a4d18f P1:ProofCount 派生正确性。
|
||||
func TestProofCount(t *testing.T) {
|
||||
// 空证据 → 0
|
||||
if got := ProofCount(&models.MemoryRecord{}); got != 0 {
|
||||
t.Fatalf("空记录 ProofCount=%d, 期望 0", got)
|
||||
}
|
||||
// nil 记录 → 0
|
||||
if got := ProofCount(nil); got != 0 {
|
||||
t.Fatalf("nil 记录 ProofCount=%d, 期望 0", got)
|
||||
}
|
||||
// 仅单亲 DerivedFrom(存量)→ 1
|
||||
if got := ProofCount(&models.MemoryRecord{DerivedFrom: "ep_1"}); got != 1 {
|
||||
t.Fatalf("仅 DerivedFrom ProofCount=%d, 期望 1", got)
|
||||
}
|
||||
// SourceEvents 多条 → distinct 计数
|
||||
m := &models.MemoryRecord{SourceEvents: []string{"ep_1", "ep_2", "ep_1", "ep_3"}}
|
||||
if got := ProofCount(m); got != 3 {
|
||||
t.Fatalf("SourceEvents[ep1,ep2,ep1,ep3] ProofCount=%d, 期望 3(distinct)", got)
|
||||
}
|
||||
// SourceEvents 含空串 → 排除空串计数
|
||||
m2 := &models.MemoryRecord{SourceEvents: []string{"ep_1", "", "ep_1"}}
|
||||
if got := ProofCount(m2); got != 1 {
|
||||
t.Fatalf("含空串 ProofCount=%d, 期望 1", got)
|
||||
}
|
||||
t.Log("ProofCount 派生 ✓ (distinct, 空串排除, 单亲兼容)")
|
||||
}
|
||||
|
||||
// TestQualityFromProof 2026-10-13 t_e9a4d18f P1:证据条数 → 饱和质量分。
|
||||
func TestQualityFromProof(t *testing.T) {
|
||||
oldK := proofSaturation
|
||||
proofSaturation = 5
|
||||
defer func() { proofSaturation = oldK }()
|
||||
|
||||
// 0 证据 → 0
|
||||
if got := QualityFromProof(&models.MemoryRecord{}); got != 0 {
|
||||
t.Fatalf("0 证据质量=%.4f, 期望 0", got)
|
||||
}
|
||||
// 1 证据 → 1/6 ≈ 0.167
|
||||
if got := QualityFromProof(&models.MemoryRecord{SourceEvents: []string{"e1"}}); got < 0.16 || got > 0.17 {
|
||||
t.Fatalf("1 证据质量=%.4f, 期望≈0.167", got)
|
||||
}
|
||||
// 5 证据 → 5/10 = 0.5
|
||||
if got := QualityFromProof(&models.MemoryRecord{SourceEvents: []string{"e1", "e2", "e3", "e4", "e5"}}); got < 0.49 || got > 0.51 {
|
||||
t.Fatalf("5 证据质量=%.4f, 期望≈0.5", got)
|
||||
}
|
||||
// 10 证据 → 10/15 ≈ 0.667
|
||||
m10 := make([]string, 10)
|
||||
for i := range m10 {
|
||||
m10[i] = "e" + string(rune('a'+i))
|
||||
}
|
||||
if got := QualityFromProof(&models.MemoryRecord{SourceEvents: m10}); got < 0.66 || got > 0.68 {
|
||||
t.Fatalf("10 证据质量=%.4f, 期望≈0.667", got)
|
||||
}
|
||||
t.Log("QualityFromProof 饱和 ✓ (x/(x+5): 0→0, 1→0.167, 5→0.5, 10→0.667)")
|
||||
}
|
||||
|
||||
// TestResolveQuality 2026-10-13 t_e9a4d18f P1:质量兜底行为。
|
||||
// - 可信 quality(非 0/0.755)→ 不被覆盖
|
||||
// - 不可信 quality(0/0.755)+ fallback 关 → 原值(行为零变化)
|
||||
// - 不可信 quality + fallback 开 → 用 QualityFromProof
|
||||
func TestResolveQuality(t *testing.T) {
|
||||
oldFallback := proofFallbackEnabled
|
||||
defer func() { proofFallbackEnabled = oldFallback }()
|
||||
|
||||
// 可信 quality → 不被覆盖(无论 fallback 状态)
|
||||
proofFallbackEnabled = true
|
||||
mTrust := &models.MemoryRecord{SourceEvents: []string{"e1", "e2"}, QualityScore: 0.8}
|
||||
if got := ResolveQuality(mTrust, 0.8); got != 0.8 {
|
||||
t.Fatalf("可信 quality 被覆盖: got=%.4f, 期望 0.8", got)
|
||||
}
|
||||
|
||||
// 不可信 quality(0) + fallback 关 → 原值 0
|
||||
proofFallbackEnabled = false
|
||||
mZero := &models.MemoryRecord{SourceEvents: []string{"e1", "e2"}, QualityScore: 0}
|
||||
if got := ResolveQuality(mZero, 0); got != 0 {
|
||||
t.Fatalf("fallback 关时 0 quality 被改: got=%.4f, 期望 0", got)
|
||||
}
|
||||
|
||||
// 不可信 quality(0) + fallback 开 → 用 QualityFromProof
|
||||
proofFallbackEnabled = true
|
||||
if got := ResolveQuality(mZero, 0); got <= 0 {
|
||||
t.Fatalf("fallback 开时 0 quality 未兜底: got=%.4f", got)
|
||||
}
|
||||
|
||||
// 不可信 quality(0.755 echo) + fallback 开 → 兜底
|
||||
mEcho := &models.MemoryRecord{SourceEvents: []string{"e1", "e2", "e3"}, QualityScore: 0.755}
|
||||
if got := ResolveQuality(mEcho, 0.755); got <= 0 {
|
||||
t.Fatalf("fallback 开时 0.755 quality 未兜底: got=%.4f", got)
|
||||
}
|
||||
t.Log("ResolveQuality 兜底 ✓ (可信不覆盖, fallback关原值, fallback开proof替代)")
|
||||
}
|
||||
|
||||
// TestQualityFromProofSorter 2026-10-13 t_e9a4d18f P1 AC#3:区分度。
|
||||
// 构造:两条都是 0.755 echo 分、无 SourceEvents 的存量行(quality 恒 0.755 不可分),
|
||||
// 一条带 2 条证据、一条带 1 条证据。开启 fallback 后两条的**可排序质量分**出现差。
|
||||
// 这是「区分度提升」的影子证据:fallback 前 0.755==0.755 无法区分,fallback 后 0.4 vs 0.167。
|
||||
func TestQualityFromProofSorter(t *testing.T) {
|
||||
oldK := proofSaturation
|
||||
oldFallback := proofFallbackEnabled
|
||||
proofSaturation = 5
|
||||
proofFallbackEnabled = true
|
||||
defer func() { proofSaturation = oldK; proofFallbackEnabled = oldFallback }()
|
||||
|
||||
m1 := &models.MemoryRecord{SourceEvents: []string{"e1", "e2"}, QualityScore: 0.755}
|
||||
m2 := &models.MemoryRecord{SourceEvents: []string{"e1"}, QualityScore: 0.755}
|
||||
|
||||
q1 := ResolveQuality(m1, 0.755)
|
||||
q2 := ResolveQuality(m2, 0.755)
|
||||
if q1 <= q2 {
|
||||
t.Fatalf("区分度未提升: q1(2证据)=%.4f <= q2(1证据)=%.4f, 期望 q1>q2", q1, q2)
|
||||
}
|
||||
t.Logf("区分度提升 ✓ fallback 后: 2证据=%.4f vs 1证据=%.4f(fallback 前两者恒 0.755 不可分)", q1, q2)
|
||||
}
|
||||
|
||||
// TestSourceEventsSerialization 2026-10-13 t_e9a4d18f P1:seJSON/parseSourceEvents 往返。
|
||||
func TestSourceEventsSerialization(t *testing.T) {
|
||||
if got := seJSON(nil); got != "[]" {
|
||||
t.Fatalf("seJSON(nil)=%q, 期望 []", got)
|
||||
}
|
||||
if got := seJSON([]string{"ep_1", "ep_2"}); got != `["ep_1","ep_2"]` {
|
||||
t.Fatalf("seJSON=%q, 期望 [\"ep_1\",\"ep_2\"]", got)
|
||||
}
|
||||
round := parseSourceEvents(seJSON([]string{"ep_1", "ep_2"}))
|
||||
if len(round) != 2 || round[0] != "ep_1" || round[1] != "ep_2" {
|
||||
t.Fatalf("roundtrip=%v", round)
|
||||
}
|
||||
if got := parseSourceEvents(""); got != nil {
|
||||
t.Fatalf("parseSourceEvents(\"\")=%v, 期望 nil", got)
|
||||
}
|
||||
t.Log("SourceEvents JSON 往返 ✓")
|
||||
}
|
||||
@@ -313,15 +313,17 @@ func (p *RecallPipeline) recallUncached(query, namespace string, topK int, diver
|
||||
}
|
||||
kwScore := ComputeBM25Score(query, candidates[i].Content)
|
||||
// 融合: vector score (quality) * 0.7 + keyword score * 0.3
|
||||
if models.IsReliableQuality(qsForTrust) {
|
||||
// 2026-10-13 (t_e9a4d18f P1):不可信质量分(0/0.755 echo)时,若
|
||||
// ZHIYI_PROOF_FALLBACK=1 则用 QualityFromProof(证据条数)兜底替代。
|
||||
// 默认关 ⇒ 行为零变化。这是「兜底」不是「替换」——已有可信 quality 不受影响。
|
||||
effQuality := ResolveQuality(&candidates[i], dbQuality[i])
|
||||
if models.IsReliableQuality(effQuality) {
|
||||
candidates[i].QualityScore = dbQuality[i]*0.7 + kwScore*0.3
|
||||
} else {
|
||||
// 存量分数不可信(0=未打分 / 0.755=历史常量 bug,见 models.IsReliableQuality)
|
||||
// → 不拿假分数参与排序,权重全部让给关键词分。
|
||||
// 注意这是**中性**处理:既不奖励也不惩罚,只是不采信。
|
||||
if qstrustVerbose {
|
||||
// 默认静音:每次召回会命中上百条,全量打印是生产噪音。
|
||||
// 需要诊断时置环境变量 ZHIYI_QSTRUST_VERBOSE=1。
|
||||
log.Printf("[qstrust] 不可信质量分已剔除 id=%s rawQS=%.6f → 回退纯关键词分 %.4f",
|
||||
candidates[i].ID, qsForTrust, kwScore)
|
||||
}
|
||||
|
||||
@@ -0,0 +1,749 @@
|
||||
// Package storage 提供记忆召回完成管线:编码 → 向量搜索 → 重排 → MMR → 图谱扩展 → 预取推送
|
||||
package storage
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"log"
|
||||
"math"
|
||||
"os"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/xiaoxue/memoryweave/internal/models"
|
||||
)
|
||||
|
||||
// ── 2026-10-08 (Gap#2 来源加权):门控参数 ──────────────────────────────
|
||||
//
|
||||
// 设计取舍(MoA 评审采纳):
|
||||
//
|
||||
// · 默认 λ=0 ⇒ **首日 no-op**。存量 15105 条 confidence 全为 NULL,
|
||||
// 此时任何加权都只是在噪声上做乘法。先接线、采分布,再定系数。
|
||||
// · 形式为**加性去中心偏置** base + λ(conf − mean),而非乘性 base*conf:
|
||||
// memories 表 100% 经 LLM 蒸馏(server.go 唯一 InsertMemory 调用点),
|
||||
// 乘性会把整批蒸馏产物一起压沉,并与 QualityScore 在同一根轴上二次惩罚。
|
||||
// 加性只平移均值、不缩方差,对尾部排序影响可控。
|
||||
// · 启用 = 改环境变量,不改代码(可回滚,无需重新构建)。
|
||||
//
|
||||
// 启用前必做(护栏,见设计文档):跨 namespace 公平性检查 + distill 召回配额下限。
|
||||
var (
|
||||
confidenceLambda = envFloat("ZHIYI_CONFIDENCE_LAMBDA", 0) // 0 = 关闭
|
||||
confidenceMean = envFloat("ZHIYI_CONFIDENCE_MEAN", 0.7) // 去中心基准
|
||||
// t_be3e958a 来源分层偏置:决策类来源(wiki:decision 等)在 MMR 之前加性加分,
|
||||
// 让「我们定了什么/阈值怎么定的」这类问题召回出决定本体而非流水。0 = 关闭。
|
||||
// 流水类(llm_distill/episode)不加分也不降权——偏置只抬决策,不动流水的相对位次。
|
||||
sourceTierBias = envFloat("ZHIYI_SOURCE_TIER_BIAS", 0) // 0 = 关闭
|
||||
// 2026-10-13 反馈回路接通(t_8f1f6e5e):per-memory 反馈计数加性偏置。
|
||||
// 0 = 关闭(默认)⇒ 与旧实现逐位等价,回滚只需把环境变量置 0。
|
||||
feedbackBias = envFloat("ZHIYI_FEEDBACK_BIAS", 0)
|
||||
// 2026-10-13 时间维检索(t_e9a4d18f P0):recency 加性偏置。
|
||||
// 0 = 关闭(默认)⇒ 行为零变化,回滚只需置 0。
|
||||
// 形式:+timeDecayBias * recency(UpdatedAt),recency ∈ [0,1],
|
||||
// 新条目趋 1(上移)、旧条目趋 0(不抬)。直接在 MMR 之前施加
|
||||
// (recall.go:325-331 的既有教训:加在 MMR 之后只改数字、不改结果集合)。
|
||||
// 半衰期决定「多旧算旧」:age 超过半衰期的条目 recency 降到 0.5 以下。
|
||||
timeDecayBias = envFloat("ZHIYI_TIME_DECAY", 0)
|
||||
timeDecayHalflife = envFloat("ZHIYI_TIME_DECAY_HALFLIFE_HOURS", 24*30) // 默认 30 天
|
||||
// 2026-10-13 时间维检索(t_e9a4d18f P0):stale 标记。
|
||||
// updated_at 距今超过该小时数 ⇒ 响应带 stale:true,让调用方「看见」可能过期。
|
||||
// 0 = 关闭(默认)⇒ 不产生任何 stale 标记,行为零变化。
|
||||
staleAfterHours = envFloat("ZHIYI_STALE_AFTER_HOURS", 0)
|
||||
)
|
||||
|
||||
func envFloat(key string, def float64) float64 {
|
||||
if v := os.Getenv(key); v != "" {
|
||||
if f, err := strconv.ParseFloat(v, 64); err == nil {
|
||||
return f
|
||||
}
|
||||
log.Printf("[confidence] %s=%q 无法解析为浮点,回落默认 %v", key, os.Getenv(key), def)
|
||||
}
|
||||
return def
|
||||
}
|
||||
|
||||
// coalesceConfidence 2026-10-08 (Gap#2):NULL(存量未声明)⇒ 1.0。
|
||||
// 这是「加权首日 no-op」的实现基础:存量行不因缺字段被系统性惩罚。
|
||||
// 注意这是**读时兜底**,不是回填——库里仍是 NULL,可随时区分「未声明」与「声明为 1.0」。
|
||||
func coalesceConfidence(c *float64) float64 {
|
||||
if c == nil {
|
||||
return 1.0
|
||||
}
|
||||
return *c
|
||||
}
|
||||
|
||||
// isDecisionSource t_be3e958a:来源分层偏置的决策类判定。
|
||||
// source 归一后含 "decision"(wiki:decision / decision / wiki:decision:vault 等)即算决策来源。
|
||||
// 归一步骤:TrimSpace → TrimPrefix("wiki:") → ToLower,与 graph_auto.go 的 source 归一保持一致。
|
||||
func isDecisionSource(source string) bool {
|
||||
s := strings.ToLower(strings.TrimPrefix(strings.TrimSpace(source), "wiki:"))
|
||||
return strings.Contains(s, "decision")
|
||||
}
|
||||
|
||||
// recency 2026-10-13 (t_e9a4d18f P0):把 updated_at 折成 [0,1] 的新鲜度。
|
||||
// 指数半衰:recency = 0.5^(age/halflife)。age=0 → 1(最新);age=halflife → 0.5;
|
||||
// age→∞ → 0。零值时间(time.Time{})视为最新(不惩罚缺失时间戳的存量行)。
|
||||
// 半衰期 halflifeHours<=0 时回退 1.0(=不衰减,保守)。
|
||||
func recency(updated time.Time, halflifeHours float64) float64 {
|
||||
if updated.IsZero() {
|
||||
return 1.0
|
||||
}
|
||||
if halflifeHours <= 0 {
|
||||
return 1.0
|
||||
}
|
||||
ageHours := time.Since(updated).Hours()
|
||||
if ageHours <= 0 {
|
||||
return 1.0
|
||||
}
|
||||
return math.Pow(0.5, ageHours/halflifeHours)
|
||||
}
|
||||
|
||||
// isStale 2026-10-13 (t_e9a4d18f P0):updated_at 距今是否超过阈值(小时)。
|
||||
// threshold<=0 ⇒ 恒 false(stale 标记关闭,行为零变化)。
|
||||
func isStale(updated time.Time, thresholdHours float64) bool {
|
||||
if thresholdHours <= 0 || updated.IsZero() {
|
||||
return false
|
||||
}
|
||||
return time.Since(updated).Hours() > thresholdHours
|
||||
}
|
||||
|
||||
// MissRecorder 缺口记录接口(由 routes 层注入 gapDetector.RecordMiss)
|
||||
type MissRecorder func(query, namespace string)
|
||||
|
||||
// PrefetchPusher 预取推送接口(由 routes 层注入)
|
||||
type PrefetchPusher interface {
|
||||
PushPrefetch(agentID string, memories []models.RecallResult)
|
||||
}
|
||||
|
||||
// GraphExpander 图谱扩展接口(由 governance 层注入)
|
||||
type GraphExpander interface {
|
||||
ExpandFromResults(results []models.RecallResult, namespace string, maxHops int) []models.RecallResult
|
||||
}
|
||||
|
||||
type RecallPipeline struct {
|
||||
embedder *Embedder
|
||||
lancedb LanceDB
|
||||
reranker *Reranker
|
||||
graph GraphExpander
|
||||
prefetch PrefetchPusher
|
||||
recordMiss MissRecorder
|
||||
}
|
||||
|
||||
func NewRecallPipeline(embedder *Embedder, lancedb LanceDB, reranker *Reranker) *RecallPipeline {
|
||||
return &RecallPipeline{
|
||||
embedder: embedder,
|
||||
lancedb: lancedb,
|
||||
reranker: reranker,
|
||||
}
|
||||
}
|
||||
|
||||
// SetGraphExpander 注入图谱扩展器
|
||||
func (p *RecallPipeline) SetGraphExpander(g GraphExpander) {
|
||||
p.graph = g
|
||||
}
|
||||
|
||||
// SetPrefetchPusher 注入预取推送器
|
||||
func (p *RecallPipeline) SetPrefetchPusher(pf PrefetchPusher) {
|
||||
p.prefetch = pf
|
||||
}
|
||||
|
||||
// SetMissRecorder 注入缺口记录器(gapDetector.RecordMiss)
|
||||
func (p *RecallPipeline) SetMissRecorder(mr MissRecorder) {
|
||||
p.recordMiss = mr
|
||||
}
|
||||
|
||||
// qstrustVerbose 控制"不可信质量分已剔除"的逐条日志。
|
||||
// 默认关闭:一次召回可命中上百条,全量打印会淹没生产日志。
|
||||
// 诊断时置 ZHIYI_QSTRUST_VERBOSE=1。
|
||||
var qstrustVerbose = os.Getenv("ZHIYI_QSTRUST_VERBOSE") == "1"
|
||||
|
||||
// RecallMeta RecallWithMeta 返回的召回元数据(t_949840b1:candidates_scanned 名实相符)。
|
||||
// CandidatesScanned = 粗检索候选池真实大小(LanceDB ANN 检索返回 + 去重 +
|
||||
// 原始对话过滤之后的候选数,在 rerank/MMR 截断之前捕获)。
|
||||
// 这才是 recall API 里 candidates_scanned 字段的真实语义——此前误用
|
||||
// len(results)(最终产出数)作代理值,字段名说 "scanned"(扫描候选池)值却是"产出数"。
|
||||
//
|
||||
// CacheHit(t_1c12e000):本次结果是否直接来自缓存(未回源扫表)。
|
||||
// 事故根因之一是调用方无法区分 candidates_scanned=0 到底是「真没扫到」
|
||||
// 还是「读了 1h 前的旧快照」⇒ 响应里必须显式给出 cache_hit。
|
||||
// 约定:缓存命中无法重建候选池 ⇒ CandidatesScanned=0(保守)且 CacheHit=true;
|
||||
// 回源扫表 ⇒ CacheHit=false(此时 CandidatesScanned 为真实候选池大小)。
|
||||
type RecallMeta struct {
|
||||
CandidatesScanned int
|
||||
CacheHit bool
|
||||
}
|
||||
|
||||
// RecallWithMeta 同 Recall,但额外返回召回元数据(候选池真实大小 + 是否命中缓存)。
|
||||
// 缓存命中时无法重建候选池 ⇒ CandidatesScanned = 0(保守:无法测量就报 0,不虚报)。
|
||||
func (p *RecallPipeline) RecallWithMeta(query, namespace string, topK int, diversity float64) ([]models.RecallResult, RecallMeta, error) {
|
||||
// topK 先归一:缓存键必须与写入侧用的 topK 一致。recallUncached 内部也会归一,
|
||||
// 若此处不先归一,topK<=0 的调用读到的是"归一前的键"、永远命中不了自己写的条目。
|
||||
if topK <= 0 {
|
||||
topK = 10
|
||||
}
|
||||
// 缓存命中分支:直接返回,候选池不可重建
|
||||
if SearchCacheInstance != nil {
|
||||
if cached, ok := SearchCacheInstance.Get(query, namespace, topK, diversity); ok {
|
||||
var results []models.RecallResult
|
||||
if err := json.Unmarshal(cached, &results); err == nil {
|
||||
filtered := filterRecallRawCategories(results)
|
||||
if len(filtered) == 0 && len(results) > 0 {
|
||||
filtered = results
|
||||
}
|
||||
p.recordRecallWrites(filtered)
|
||||
// t_1c12e000:命中缓存 ⇒ 显式告知调用方(candidates_scanned 恒 0)
|
||||
return filtered, RecallMeta{CacheHit: true}, nil
|
||||
}
|
||||
}
|
||||
}
|
||||
return p.recallUncached(query, namespace, topK, diversity)
|
||||
}
|
||||
|
||||
// Recall 保持原签名(缓存 + 全量流程),行为不变。
|
||||
func (p *RecallPipeline) Recall(query, namespace string, topK int, diversity float64) ([]models.RecallResult, error) {
|
||||
results, _, err := p.RecallWithMeta(query, namespace, topK, diversity)
|
||||
return results, err
|
||||
}
|
||||
|
||||
// recallUncached Recall 的非缓存路径。候选池大小在 Step 2.5 过滤后、
|
||||
// Step 3 截断前捕获(真实粗检索池,不是最终产出数)。
|
||||
func (p *RecallPipeline) recallUncached(query, namespace string, topK int, diversity float64) ([]models.RecallResult, RecallMeta, error) {
|
||||
if topK <= 0 {
|
||||
topK = 10
|
||||
}
|
||||
|
||||
// Step 1: Encode query
|
||||
queryVec, err := p.embedder.EncodeQuery(query)
|
||||
if err != nil {
|
||||
return nil, RecallMeta{}, fmt.Errorf("recall encode: %w", err)
|
||||
}
|
||||
|
||||
// Step 2: Coarse search — own namespace + shared(§1.3 召回规则)
|
||||
// 默认搜自己的 namespace + shared,显式 include_namespaces 时才跨域
|
||||
// 2026-09-21 五修(t_24eceed0 返修):namespace=="" → 全库跨命名空间召回。
|
||||
// 根因:写入侧把记忆按 agent/域分到 *-main / wiki / soulful-xiaowei / domain:* 等
|
||||
// 19 个命名空间(实测 hermes-main 139、wiki-curator-main 35、wiki 30、soulful-xiaowei 27、
|
||||
// a06-main 11 …),而默认调用只搜 default-main + shared
|
||||
// ⇒ 默认召回只能看到极小一片(全表 10172 条,默认调用实测仅 11 个候选)。
|
||||
// 显式传 namespace / agent_id 时保持原作用域行为,不改变调用方语义。
|
||||
var candidates []models.MemoryRecord
|
||||
if namespace == "" {
|
||||
all, err := p.lancedb.Search("memories", queryVec, 200, "") // 空 ns = 不过滤 = 全库
|
||||
if err == nil {
|
||||
candidates = append(candidates, all...)
|
||||
}
|
||||
} else {
|
||||
namespaces := []string{namespace}
|
||||
if namespace != "shared" {
|
||||
namespaces = append(namespaces, "shared")
|
||||
}
|
||||
for _, ns := range namespaces {
|
||||
nsResults, err := p.lancedb.Search("memories", queryVec, 50, ns)
|
||||
if err != nil {
|
||||
continue
|
||||
}
|
||||
candidates = append(candidates, nsResults...)
|
||||
}
|
||||
}
|
||||
// 去重(按 ID)
|
||||
seen := make(map[string]bool)
|
||||
unique := make([]models.MemoryRecord, 0, len(candidates))
|
||||
for _, c := range candidates {
|
||||
if !seen[c.ID] {
|
||||
seen[c.ID] = true
|
||||
unique = append(unique, c)
|
||||
}
|
||||
}
|
||||
candidates = unique
|
||||
|
||||
// Step 2.5: 过滤原始对话内容(category=episodes/对话/对话记录)
|
||||
// 原因:原始对话未蒸馏,不应出现在 recall 结果中
|
||||
// 蒸馏产物通过 OnDistillComplete callback 写入 memories(category=distilled)
|
||||
filtered := make([]models.MemoryRecord, 0, len(candidates))
|
||||
rawCategories := map[string]bool{
|
||||
"episodes": true,
|
||||
"对话": true,
|
||||
"对话记录": true,
|
||||
"raw": true,
|
||||
"episodic": true,
|
||||
}
|
||||
for _, c := range candidates {
|
||||
if !rawCategories[c.Category] {
|
||||
filtered = append(filtered, c)
|
||||
}
|
||||
}
|
||||
// 过滤后若为空,降级回原行为(避免 recall 完全失效)
|
||||
if len(filtered) == 0 && len(candidates) > 0 {
|
||||
filtered = candidates
|
||||
}
|
||||
// 记录过滤数量(用于调试)
|
||||
filteredCount := len(candidates) - len(filtered)
|
||||
if filteredCount > 0 {
|
||||
log.Printf("[recall] filtered %d raw episode/dialogue candidates, %d remain", filteredCount, len(filtered))
|
||||
}
|
||||
candidates = filtered
|
||||
|
||||
// 候选池真实大小捕获点:LanceDB ANN 返回 + 去重 + 原始对话过滤之后、
|
||||
// 截断/rerank/MMR 之前 —— 这才是 "scanned candidates" 的真实含义。
|
||||
poolSize := len(candidates)
|
||||
|
||||
// 截断候选池(全库模式候选来自更多命名空间,池子放宽到 100)
|
||||
candCap := 50
|
||||
if namespace == "" {
|
||||
candCap = 100
|
||||
}
|
||||
if len(candidates) > candCap {
|
||||
candidates = candidates[:candCap]
|
||||
}
|
||||
|
||||
// Step 3.5: BM25 keyword scoring — amplify keyword-relevant results
|
||||
// t_631ab13d: 先抓 DB 原始 quality_score(candidates[i].QualityScore),
|
||||
// 因为下面会原地覆盖为 BM25 融合值(0.7*dbQuality + 0.3*kwScore)。
|
||||
// 响应需要展示 DB 原值("响应值==库值"),不能展示被融合改写后的值。
|
||||
dbQuality := make([]float64, len(candidates))
|
||||
if len(candidates) > 0 {
|
||||
for i := range candidates {
|
||||
dbQuality[i] = candidates[i].QualityScore
|
||||
// 可信度判定必须用 **DB 原始列值**:candidates[i].QualityScore 在 IPC 路径下
|
||||
// 是**已融合且会饱和到 1.0** 的值(实测 candidateQS=1.0 / rawQS=0.755),
|
||||
// 拿它去判永远"可信" ⇒ 修复不触发(2026-10-12 实测踩到)。
|
||||
// RawQualityScore 仅在 Rust IPC 路径携带;纯 Go 路径下候选值即 DB 原值。
|
||||
qsForTrust := dbQuality[i]
|
||||
if candidates[i].RawQualityScore != nil {
|
||||
qsForTrust = *candidates[i].RawQualityScore
|
||||
}
|
||||
kwScore := ComputeBM25Score(query, candidates[i].Content)
|
||||
// 融合: vector score (quality) * 0.7 + keyword score * 0.3
|
||||
// 2026-10-13 (t_e9a4d18f P1):不可信质量分(0/0.755 echo)时,若
|
||||
// ZHIYI_PROOF_FALLBACK=1 则用 QualityFromProof(证据条数)兜底替代。
|
||||
// 默认关 ⇒ 行为零变化。这是「兜底」不是「替换」——已有可信 quality 不受影响。
|
||||
effQuality := ResolveQuality(&candidates[i], dbQuality[i])
|
||||
if models.IsReliableQuality(effQuality) {
|
||||
candidates[i].QualityScore = dbQuality[i]*0.7 + kwScore*0.3
|
||||
} else {
|
||||
// 存量分数不可信(0=未打分 / 0.755=历史常量 bug,见 models.IsReliableQuality)
|
||||
// → 不拿假分数参与排序,权重全部让给关键词分。
|
||||
// 注意这是**中性**处理:既不奖励也不惩罚,只是不采信。
|
||||
if qstrustVerbose {
|
||||
log.Printf("[qstrust] 不可信质量分已剔除 id=%s rawQS=%.6f → 回退纯关键词分 %.4f",
|
||||
candidates[i].ID, qsForTrust, kwScore)
|
||||
}
|
||||
candidates[i].QualityScore = kwScore
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if len(candidates) == 0 {
|
||||
// 自动记录召回缺口(gap_scan 触发器会在 30min 冷却后分类)
|
||||
if p.recordMiss != nil {
|
||||
p.recordMiss(query, namespace)
|
||||
}
|
||||
return []models.RecallResult{}, RecallMeta{CandidatesScanned: poolSize}, nil
|
||||
}
|
||||
|
||||
// Step 3: Rerank to top_k (graceful fallback)
|
||||
// 2026-09-28:优先用「已有向量」重排 —— queryVec 来自 Step 1,候选记录自带 LanceDB
|
||||
// 存储的 Vector,直接算 cosine 即可。旧实现把 query + 50~100 条候选文档重新送进
|
||||
// 嵌入服务(int8 ONNX CPU),占 recall 总耗时 90%+,是 Hermes 记忆预取 8s 预算
|
||||
// 被打爆的直接原因。向量不齐/维度不符时自动回退文本重排(行为与旧版一致)。
|
||||
docs := make([]string, len(candidates))
|
||||
docVecs := make([][]float32, len(candidates))
|
||||
for i, c := range candidates {
|
||||
docs[i] = c.Content
|
||||
docVecs[i] = c.Vector
|
||||
}
|
||||
reranked, err := p.reranker.RerankWithVectors(queryVec, docs, docVecs, topK*2)
|
||||
if err != nil {
|
||||
log.Printf("[recall] 向量重排跳过(%v),回退文本重排", err)
|
||||
reranked, err = p.reranker.Rerank(query, docs, topK*2)
|
||||
}
|
||||
if err != nil {
|
||||
// 重排不可用时降级:直接使用向量搜索的原始排序
|
||||
reranked = make([]models.RerankResult, len(candidates))
|
||||
for i := range candidates {
|
||||
reranked[i] = models.RerankResult{Index: i, Score: 0.5, Text: candidates[i].Content}
|
||||
}
|
||||
}
|
||||
|
||||
// Step 3.7: 来源加权偏置(2026-10-09 P0 修正)
|
||||
//
|
||||
// 修前的错位:λ 只加在 Step 4 之后的**展示分**上,而候选的取舍早已由 rerank+MMR 定死
|
||||
// ⇒ λ 无论取多大都只改返回的数字、不改结果集合。实测(λ=0.1 vs 0,同一批 14 条 query,
|
||||
// 全部 cache-miss):逐条分数位移与理论吻合(legacy -0.0277 / conf1.0 +0.0294),
|
||||
// 但 top-10 集合与 legacy 占比 33.57% 两轮完全相同 —— 典型的"接上了但接在阀门下游"。
|
||||
//
|
||||
// 现在把偏置移到 MMR 之前:选择与展示共用同一套分数(rel = r.Score,见 MMRSelect)。
|
||||
// λ=0 时本循环不执行 ⇒ 与旧实现逐字节等价,回滚只需把环境变量置 0。
|
||||
if confidenceLambda > 0 {
|
||||
for i := range reranked {
|
||||
idx := reranked[i].Index
|
||||
if idx >= 0 && idx < len(candidates) {
|
||||
conf := coalesceConfidence(candidates[idx].Confidence)
|
||||
reranked[i].Score += confidenceLambda * (conf - confidenceMean)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// t_be3e958a 来源分层偏置(紧邻 confidenceLambda,同样在 MMR 之前):
|
||||
// 决策类来源(source 含 "decision",如 wiki:decision / decision)加性加分
|
||||
// sourceTierBias。只抬决策、不动流水/其它来源 —— 避免偏置挤压本应排前的流水。
|
||||
// sourceTierBias=0 时本循环不执行 ⇒ 与旧实现逐位等价,回滚只需把环境变量置 0。
|
||||
if sourceTierBias > 0 {
|
||||
for i := range reranked {
|
||||
idx := reranked[i].Index
|
||||
if idx >= 0 && idx < len(candidates) && isDecisionSource(candidates[idx].Source) {
|
||||
reranked[i].Score += sourceTierBias
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 2026-10-13 反馈回路接通(t_8f1f6e5e):per-memory 反馈计数加性偏置。
|
||||
// 与 confidenceLambda / sourceTierBias 同款:默认 0 ⇒ 本循环不执行 ⇒
|
||||
// 与旧实现逐位等价,回滚只需把 ZHIYI_FEEDBACK_BIAS 置 0。
|
||||
// 放在 MMR 之前 ⇒ 选择与展示共用同一套分数(recall.go:325-331 的既有教训:
|
||||
// 偏置加在 MMR 之后就只改数字、不改结果集合)。
|
||||
if feedbackBias > 0 {
|
||||
for i := range reranked {
|
||||
idx := reranked[i].Index
|
||||
if idx >= 0 && idx < len(candidates) {
|
||||
reranked[i].Score += feedbackBias * FeedbackScore(&candidates[idx])
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 2026-10-13 时间维检索(t_e9a4d18f P0):recency 加性偏置。
|
||||
// 与 confidenceLambda / sourceTierBias / feedbackBias 同款:默认 0 ⇒ 本循环
|
||||
// 不执行 ⇒ 与旧实现逐位等价,回滚只需把 ZHIYI_TIME_DECAY 置 0。
|
||||
// 放在 MMR 之前 ⇒ 选择与展示共用同一套分数(见 recall.go:325-331 教训)。
|
||||
if timeDecayBias > 0 {
|
||||
for i := range reranked {
|
||||
idx := reranked[i].Index
|
||||
if idx >= 0 && idx < len(candidates) {
|
||||
reranked[i].Score += timeDecayBias * recency(candidates[idx].UpdatedAt, timeDecayHalflife)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Step 4: MMR diversity
|
||||
finalIndices := MMRSelect(reranked, candidates, topK*2, diversity)
|
||||
|
||||
results := make([]models.RecallResult, 0, topK)
|
||||
for i, idx := range finalIndices {
|
||||
if i >= topK {
|
||||
break
|
||||
}
|
||||
if idx < len(candidates) {
|
||||
c := candidates[idx]
|
||||
score := 0.0
|
||||
for _, r := range reranked {
|
||||
if r.Index == idx {
|
||||
score = r.Score
|
||||
break
|
||||
}
|
||||
}
|
||||
// 2026-10-08 (Gap#2 来源加权):把信任等级直通给调用方,并按门控参与排序。
|
||||
//
|
||||
// 为什么默认关闭(λ=0):存量 15105 条 confidence 全为 NULL,此时任何加权都只是
|
||||
// 在噪声上做乘法。按 MoA 评审:先跑一周采分布 → 定 λ 与形式 → 再带护栏启用。
|
||||
// 因此 P0 只接线不改行为(no-op),启用是改环境变量,不是改代码。
|
||||
//
|
||||
// 为什么是**加性去中心偏置**而非乘性:
|
||||
// 乘性 base*conf 会把全部 LLM 蒸馏产物整体压沉(memories 表 100% 经蒸馏,
|
||||
// 见 server.go 唯一 InsertMemory 调用点),并与 QualityScore 在同一根轴上二次惩罚;
|
||||
// 加性 base+λ(conf-mean) 只平移均值、不缩方差,对尾部排序影响可控。
|
||||
conf := coalesceConfidence(c.Confidence)
|
||||
// 2026-10-09 (P0 修正):λ 已在 Step 3.7 偏置进 reranked[i].Score,选择与展示
|
||||
// 共用同一套分数;此处不再重复施加(否则 legacy 被双重扣分)。
|
||||
base := score*0.7 + c.QualityScore*0.3
|
||||
// 2026-10-11 (t_631ab13d):把库里的 quality_score / v_value 直通给调用方。
|
||||
// 展示 DB 原值("响应值==库值"判据):优先用 RawQualityScore(LanceDB 原始列,
|
||||
// 仅 Rust IPC 路径携带,json:"-" 不落库);否则退回 DB 捕获值 dbQuality[idx]
|
||||
// (纯 Go 后端候选的 QualityScore 即 DB 原值,未被融合改写)。
|
||||
// 排序用 c.QualityScore(IPC=融合值 / 纯Go=BM25融合值)不变,只补显示缺口。
|
||||
vv := 0.0
|
||||
if VValueProvider != nil {
|
||||
vv = VValueProvider(c.ID)
|
||||
}
|
||||
var qs *float64
|
||||
if c.RawQualityScore != nil {
|
||||
qs = c.RawQualityScore // LanceDB 原始列值(IPC 路径)
|
||||
} else if idx >= 0 && idx < len(dbQuality) {
|
||||
v := dbQuality[idx]
|
||||
qs = &v // 纯 Go 后端:DB 捕获值
|
||||
}
|
||||
qsVal := 0.0
|
||||
if qs != nil {
|
||||
qsVal = *qs
|
||||
}
|
||||
results = append(results, models.RecallResult{
|
||||
ID: c.ID,
|
||||
Content: c.Content,
|
||||
Category: c.Category,
|
||||
Score: base,
|
||||
Timestamp: c.CreatedAt.Format(time.RFC3339),
|
||||
Namespace: c.Namespace,
|
||||
AgentID: c.AgentID,
|
||||
Source: c.Source,
|
||||
Confidence: &conf,
|
||||
ConfidenceSource: c.ConfidenceSource,
|
||||
QualityScore: qsVal,
|
||||
QualityScoreReliable: models.IsReliableQuality(qsVal),
|
||||
VValue: vv,
|
||||
// 2026-10-13 (t_e9a4d18f P0):过期标记(默认关闭 ⇒ 恒 false 不输出)
|
||||
Stale: isStale(c.UpdatedAt, staleAfterHours),
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// Step 5: 图谱融合扩展(不再作为后备补丁,每次 recall 都跑 1 跳)
|
||||
if p.graph != nil {
|
||||
expanded := p.graph.ExpandFromResults(results, namespace, 1)
|
||||
for _, e := range expanded {
|
||||
already := false
|
||||
for _, r := range results {
|
||||
if r.ID == e.ID {
|
||||
already = true
|
||||
break
|
||||
}
|
||||
}
|
||||
if !already {
|
||||
results = append(results, e)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Step 6: 去重(相同 content 只保留最高分)
|
||||
seenContent := make(map[string]bool)
|
||||
deduped := make([]models.RecallResult, 0, len(results))
|
||||
for _, r := range results {
|
||||
if !seenContent[r.Content] {
|
||||
seenContent[r.Content] = true
|
||||
deduped = append(deduped, r)
|
||||
}
|
||||
}
|
||||
results = deduped
|
||||
|
||||
// Step 6.5: 写搜索缓存(§2.6 — t_1c12e000 起 TTL=60s,下次相同 query+topK+diversity
|
||||
// 直接返回;写路径落库后会 Invalidate 本 namespace,陈旧窗口上限=60s 双保险)
|
||||
if SearchCacheInstance != nil {
|
||||
SearchCacheInstance.Set(query, namespace, topK, diversity, results)
|
||||
}
|
||||
|
||||
// Step 7: 预取推送(CO_OCCURS 权重 > 0.6 的配套记忆 → WebSocket)
|
||||
if p.prefetch != nil {
|
||||
// 使用 CO_OCCURS 追踪器收集真实预取候选项
|
||||
var prefetchIDs []string
|
||||
for _, r := range results {
|
||||
if r.ID != "" {
|
||||
prefetchIDs = append(prefetchIDs, r.ID)
|
||||
}
|
||||
}
|
||||
if len(prefetchIDs) > 0 {
|
||||
// 记录共访统计到 CO_OCCURS tracker
|
||||
if CoOccurTrackerInstance != nil {
|
||||
CoOccurTrackerInstance.RecordRecall(prefetchIDs, namespace)
|
||||
candidates := CoOccurTrackerInstance.CollectCandidates(prefetchIDs)
|
||||
if len(candidates) > 0 {
|
||||
prefetchItems := make([]models.RecallResult, 0, len(candidates))
|
||||
for _, cid := range candidates {
|
||||
prefetchItems = append(prefetchItems, models.RecallResult{ID: cid})
|
||||
}
|
||||
p.prefetch.PushPrefetch("", prefetchItems)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 召回元数据写(2026-09-12 优化B:累积延迟更新)
|
||||
// 旧实现:对每条结果同步 lancedb.Update → LanceDB MVCC 每写一行一个版本
|
||||
// (实测 15 版本/分钟 → _versions 膨胀到 17.7G,根因所在)
|
||||
// 现在:只把命中 ID 放进 RecallWriteBuffer,后台按窗口批量单事务提交(每批 1 个版本)
|
||||
p.recordRecallWrites(results)
|
||||
|
||||
// 共访追踪(即使无 prefetch pusher 也运行,用于持久化)
|
||||
go func() {
|
||||
if len(results) == 0 {
|
||||
return
|
||||
}
|
||||
var ids []string
|
||||
for _, r := range results {
|
||||
if r.ID != "" {
|
||||
ids = append(ids, r.ID)
|
||||
}
|
||||
}
|
||||
if len(ids) > 0 && CoOccurTrackerInstance != nil {
|
||||
CoOccurTrackerInstance.RecordRecall(ids, namespace)
|
||||
}
|
||||
}()
|
||||
|
||||
return results, RecallMeta{CandidatesScanned: poolSize}, nil
|
||||
}
|
||||
|
||||
// ComputeBM25Score 基于词频的关键词匹配分数
|
||||
func ComputeBM25Score(query, doc string) float64 {
|
||||
queryTerms := strings.Fields(strings.ToLower(query))
|
||||
docLower := strings.ToLower(doc)
|
||||
hitCount := 0
|
||||
for _, term := range queryTerms {
|
||||
if len(term) < 2 {
|
||||
continue
|
||||
}
|
||||
count := strings.Count(docLower, term)
|
||||
if count > 0 {
|
||||
hitCount += count
|
||||
}
|
||||
}
|
||||
if hitCount == 0 {
|
||||
return 0
|
||||
}
|
||||
// 归一化到 [0, 1]
|
||||
score := float64(hitCount) / float64(len(queryTerms))
|
||||
if score > 1.0 {
|
||||
score = 1.0
|
||||
}
|
||||
return score
|
||||
}
|
||||
|
||||
// jaccardBigramSimilarity 计算两个文本的字符 bigram Jaccard 相似度(用于 MMR 去重)
|
||||
func jaccardBigramSimilarity(a, b string) float64 {
|
||||
bgA := make(map[string]bool)
|
||||
bgB := make(map[string]bool)
|
||||
runes := []rune(a)
|
||||
for i := 0; i < len(runes)-1; i++ {
|
||||
bgA[string(runes[i:i+2])] = true
|
||||
}
|
||||
runes = []rune(b)
|
||||
for i := 0; i < len(runes)-1; i++ {
|
||||
bgB[string(runes[i:i+2])] = true
|
||||
}
|
||||
if len(bgA) == 0 && len(bgB) == 0 {
|
||||
return 1.0 // 两个空文本视为相同
|
||||
}
|
||||
if len(bgA) == 0 || len(bgB) == 0 {
|
||||
return 0.0
|
||||
}
|
||||
intersection := 0
|
||||
for k := range bgA {
|
||||
if bgB[k] {
|
||||
intersection++
|
||||
}
|
||||
}
|
||||
union := len(bgA) + len(bgB) - intersection
|
||||
if union == 0 {
|
||||
return 0.0
|
||||
}
|
||||
return float64(intersection) / float64(union)
|
||||
}
|
||||
|
||||
// MMRSelect 多样性去重 — 使用文本 bigram Jaccard 相似度(向量由 Rust LanceDB 返回但为空,改用文本)
|
||||
func MMRSelect(reranked []models.RerankResult, candidates []models.MemoryRecord, k int, lambda float64) []int {
|
||||
if len(reranked) == 0 {
|
||||
return nil
|
||||
}
|
||||
selected := make([]int, 0, k)
|
||||
cand := make([]int, len(reranked))
|
||||
for i := range reranked {
|
||||
cand[i] = reranked[i].Index
|
||||
}
|
||||
|
||||
for len(selected) < k && len(cand) > 0 {
|
||||
bestIdx := 0
|
||||
bestScore := -math.MaxFloat64
|
||||
for i, ci := range cand {
|
||||
rel := 0.0
|
||||
for _, r := range reranked {
|
||||
if r.Index == ci {
|
||||
rel = r.Score
|
||||
break
|
||||
}
|
||||
}
|
||||
maxSim := 0.0
|
||||
for _, si := range selected {
|
||||
if si < len(candidates) && ci < len(candidates) {
|
||||
sim := jaccardBigramSimilarity(candidates[ci].Content, candidates[si].Content)
|
||||
if sim > maxSim {
|
||||
maxSim = sim
|
||||
}
|
||||
}
|
||||
}
|
||||
// MMR = (1-λ)*rel + λ*(1-maxSim)
|
||||
mmr := (1-lambda)*rel + lambda*(1-maxSim)
|
||||
if mmr > bestScore {
|
||||
bestScore = mmr
|
||||
bestIdx = i
|
||||
}
|
||||
}
|
||||
selected = append(selected, cand[bestIdx])
|
||||
cand = append(cand[:bestIdx], cand[bestIdx+1:]...)
|
||||
}
|
||||
return selected
|
||||
}
|
||||
|
||||
func cosineSimilarity(a, b []float32) float64 {
|
||||
var sum float64
|
||||
n := len(a)
|
||||
if len(b) < n {
|
||||
n = len(b)
|
||||
}
|
||||
for i := 0; i < n; i++ {
|
||||
sum += float64(a[i]) * float64(b[i])
|
||||
}
|
||||
return sum
|
||||
}
|
||||
|
||||
// recordRecallWrites 记录召回元数据写。
|
||||
// 主路径:累积延迟更新缓冲(RecallWriteBufferInstance)——读路径零同步写、批量单事务落盘。
|
||||
// 兜底:缓冲未初始化(如单测/独立调用)时退回旧的逐条异步 Update。
|
||||
func (p *RecallPipeline) recordRecallWrites(results []models.RecallResult) {
|
||||
ids := make([]string, 0, len(results))
|
||||
for _, r := range results {
|
||||
if r.ID != "" {
|
||||
ids = append(ids, r.ID)
|
||||
}
|
||||
}
|
||||
if len(ids) == 0 {
|
||||
return
|
||||
}
|
||||
if RecallWriteBufferInstance != nil {
|
||||
RecallWriteBufferInstance.Record(ids)
|
||||
return
|
||||
}
|
||||
go p.incrementRecallCount(results)
|
||||
}
|
||||
|
||||
// incrementRecallCount 旧版逐条同步写(每条结果 = 1 个 LanceDB 版本)。
|
||||
// 已不作为主路径,仅保留为缓冲不可用时的兜底。
|
||||
func (p *RecallPipeline) incrementRecallCount(results []models.RecallResult) {
|
||||
now := time.Now().Format(time.RFC3339)
|
||||
for _, r := range results {
|
||||
if r.ID != "" {
|
||||
// t_268b0353(治根):兜底路径同样不写 freshness=verified("被召回"≠"被验证")
|
||||
// GA-P0-2 (t_c6d41ac6):召回命中 → recall_seen_count(recall_count 冻结)
|
||||
_ = p.lancedb.Update("memories", r.ID, map[string]any{
|
||||
"recall_seen_count": map[string]string{"$inc": "1"},
|
||||
"last_recalled_at": now,
|
||||
})
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// filterRecallRawCategories 从 RecallResult 列表中过滤原始对话类别
|
||||
// 用于 cache hit 路径,防止旧缓存包含的 episodes/对话污染 recall 结果
|
||||
func filterRecallRawCategories(results []models.RecallResult) []models.RecallResult {
|
||||
rawCategories := map[string]bool{
|
||||
"episodes": true,
|
||||
"对话": true,
|
||||
"对话记录": true,
|
||||
"raw": true,
|
||||
"episodic": true,
|
||||
}
|
||||
filtered := make([]models.RecallResult, 0, len(results))
|
||||
for _, r := range results {
|
||||
if !rawCategories[r.Category] {
|
||||
filtered = append(filtered, r)
|
||||
}
|
||||
}
|
||||
if len(filtered) == 0 {
|
||||
return results // 降级:过滤后为空则返回原结果
|
||||
}
|
||||
return filtered
|
||||
}
|
||||
@@ -101,6 +101,8 @@ func (sc *SQLiteClient) migrate() error {
|
||||
delete_reason TEXT DEFAULT '',
|
||||
depends_on TEXT DEFAULT '[]',
|
||||
derived_from TEXT DEFAULT '',
|
||||
source_events TEXT DEFAULT '[]',
|
||||
supersedes TEXT DEFAULT '[]',
|
||||
last_recalled_at TEXT DEFAULT '',
|
||||
created_at TEXT NOT NULL,
|
||||
updated_at TEXT NOT NULL
|
||||
@@ -170,6 +172,10 @@ func (sc *SQLiteClient) migrate() error {
|
||||
{"recall_verified_count", "ALTER TABLE memories ADD COLUMN recall_verified_count INTEGER DEFAULT 0"},
|
||||
// GA-P0-3 (t_f785d7f2):is_deleted 的删除原因(additive,TEXT 存固定枚举)
|
||||
{"delete_reason", "ALTER TABLE memories ADD COLUMN delete_reason TEXT DEFAULT ''"},
|
||||
// 2026-10-13 (t_e9a4d18f P1) 证据链:全量来源 episode ID(additive,TEXT JSON 数组)
|
||||
{"source_events", "ALTER TABLE memories ADD COLUMN source_events TEXT DEFAULT '[]'"},
|
||||
// 2026-10-13 (t_e9a4d18f P1) 矛盾保留:被取代的旧记忆 ID(additive)
|
||||
{"supersedes", "ALTER TABLE memories ADD COLUMN supersedes TEXT DEFAULT '[]'"},
|
||||
} {
|
||||
rows, err := sc.query("PRAGMA table_info(memories)")
|
||||
if err != nil {
|
||||
@@ -350,9 +356,9 @@ func (sc *SQLiteClient) InsertMemory(m models.MemoryRecord) error {
|
||||
defer sc.mu.Unlock()
|
||||
return sc.execWithArgs(
|
||||
`INSERT INTO memories(id,agent_id,namespace,content,category,vector,tier,importance,quality_score,
|
||||
source,depends_on,derived_from,version,created_at,updated_at) VALUES(?,?,?,?,?,?,?,?,?,?,?,?,1,?,?)`,
|
||||
source,depends_on,derived_from,source_events,supersedes,version,created_at,updated_at) VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?,?,1,?,?)`,
|
||||
m.ID, m.AgentID, m.Namespace, m.Content, m.Category, vecBlob, m.Tier,
|
||||
1.0, m.QualityScore, "", "[]", "", now, now,
|
||||
1.0, m.QualityScore, "", "[]", m.DerivedFrom, seJSON(m.SourceEvents), seJSON(m.Supersedes), now, now,
|
||||
)
|
||||
}
|
||||
|
||||
@@ -388,7 +394,7 @@ func (sc *SQLiteClient) Scan(limit int, namespaceFilter string) ([]models.Memory
|
||||
sc.mu.RLock()
|
||||
defer sc.mu.RUnlock()
|
||||
|
||||
q := "SELECT id, content, category, namespace, importance, quality_score, recall_count, recall_seen_count, recall_verified_count, not_useful_count, human_not_useful_count, dedup_downweight_count, tier, source, created_at, updated_at FROM memories WHERE is_deleted=0"
|
||||
q := "SELECT id, content, category, namespace, importance, quality_score, recall_count, recall_seen_count, recall_verified_count, not_useful_count, human_not_useful_count, dedup_downweight_count, tier, source, created_at, updated_at, source_events, supersedes FROM memories WHERE is_deleted=0"
|
||||
if namespaceFilter != "" {
|
||||
q += " AND namespace='" + sanitizeIdent(namespaceFilter) + "'"
|
||||
}
|
||||
@@ -409,6 +415,12 @@ func (sc *SQLiteClient) Scan(limit int, namespaceFilter string) ([]models.Memory
|
||||
rec.QualityScore, _ = row["quality_score"].(float64)
|
||||
rec.Tier, _ = row["tier"].(string)
|
||||
rec.Source, _ = row["source"].(string)
|
||||
if se, ok := row["source_events"].(string); ok {
|
||||
rec.SourceEvents = parseSourceEvents(se) // 2026-10-13 P1
|
||||
}
|
||||
if ss, ok := row["supersedes"].(string); ok {
|
||||
rec.Supersedes = parseSourceEvents(ss) // 2026-10-13 P1
|
||||
}
|
||||
if n, ok := row["recall_count"].(int64); ok {
|
||||
rec.RecallCount = int(n)
|
||||
}
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -55,6 +55,11 @@ pub struct MemoryRecord {
|
||||
// 存量行是 NULL(读路径 col_str 兜底 ""),回填脚本以 tombstones 为据尽力判定。
|
||||
pub delete_reason: String,
|
||||
pub depends_on: String, pub derived_from: String,
|
||||
// 2026-10-13 (t_e9a4d18f P1) 证据链:全量来源 episode ID 的 JSON 数组字符串。
|
||||
// 与 depends_on 同款(JSON 串列),additive 新列,存量由 schema 演进补 NULL。
|
||||
pub source_events: String,
|
||||
// 2026-10-13 (t_e9a4d18f P1) 矛盾保留:被取代的旧记忆 ID(JSON 数组字符串)
|
||||
pub supersedes: String,
|
||||
pub last_recalled_at: String, pub created_at: String, pub updated_at: String,
|
||||
}
|
||||
|
||||
@@ -121,6 +126,11 @@ fn arrow_schema() -> Schema {
|
||||
// GA-P0-3 (t_f785d7f2):is_deleted 的删除原因(固定枚举)。additive 新列,
|
||||
// nullable 容纳存量 NULL;回填脚本以 tombstones 为据尽力判定,判不出写 unknown。
|
||||
Field::new("delete_reason", DataType::Utf8, true),
|
||||
// 2026-10-13 (t_e9a4d18f P1) 证据链:全量来源 episode ID(JSON 数组字符串)。
|
||||
// additive 新列,存量由 schema 演进补 NULL(与 depends_on 同款)。
|
||||
Field::new("source_events", DataType::Utf8, true),
|
||||
// 2026-10-13 (t_e9a4d18f P1) 矛盾保留(additive)
|
||||
Field::new("supersedes", DataType::Utf8, true),
|
||||
])
|
||||
}
|
||||
|
||||
@@ -267,6 +277,8 @@ impl LanceDBOps {
|
||||
delete_reason: col_str(&batch, i, "delete_reason"),
|
||||
depends_on: String::new(),
|
||||
derived_from: String::new(),
|
||||
source_events: col_str(&batch, i, "source_events"), // 2026-10-13 P1
|
||||
supersedes: col_str(&batch, i, "supersedes"), // 2026-10-13 P1
|
||||
last_recalled_at: String::new(),
|
||||
created_at: col_str(&batch, i, "created_at"),
|
||||
updated_at: col_str(&batch, i, "updated_at"),
|
||||
@@ -328,6 +340,8 @@ impl LanceDBOps {
|
||||
delete_reason: col_str(&batch, i, "delete_reason"),
|
||||
depends_on: String::new(),
|
||||
derived_from: String::new(),
|
||||
source_events: col_str(&batch, i, "source_events"), // 2026-10-13 P1
|
||||
supersedes: col_str(&batch, i, "supersedes"), // 2026-10-13 P1
|
||||
last_recalled_at: String::new(),
|
||||
created_at: col_str(&batch, i, "created_at"),
|
||||
updated_at: col_str(&batch, i, "updated_at"),
|
||||
@@ -364,6 +378,9 @@ impl LanceDBOps {
|
||||
// GA-P0-3 (t_f785d7f2):删除原因(additive)
|
||||
let mut delete_reasons: Vec<&str> = Vec::new();
|
||||
let mut depends_ons = Vec::new(); let mut derived_froms = Vec::new();
|
||||
// 2026-10-13 (t_e9a4d18f P1) 证据链:全量来源 episode ID(JSON 数组字符串)
|
||||
let mut source_events_col = Vec::new();
|
||||
let mut supersedes_col = Vec::new();
|
||||
let mut last_recalled_ats = Vec::new(); let mut created_ats = Vec::new(); let mut updated_ats = Vec::new();
|
||||
// 2026-10-08 (Gap#2):nullable 列用 Option,未声明时写 None → 库里是 NULL
|
||||
let mut confidences: Vec<Option<f64>> = Vec::new();
|
||||
@@ -401,6 +418,8 @@ impl LanceDBOps {
|
||||
delete_reasons.push(r["delete_reason"].as_str().unwrap_or("")); // GA-P0-3
|
||||
depends_ons.push(r["depends_on"].as_str().unwrap_or("[]"));
|
||||
derived_froms.push(r["derived_from"].as_str().unwrap_or(""));
|
||||
source_events_col.push(r["source_events"].as_str().unwrap_or("[]")); // 2026-10-13 P1
|
||||
supersedes_col.push(r["supersedes"].as_str().unwrap_or("[]")); // 2026-10-13 P1
|
||||
last_recalled_ats.push(r["last_recalled_at"].as_str().unwrap_or(""));
|
||||
created_ats.push(r["created_at"].as_str().unwrap_or(""));
|
||||
updated_ats.push(r["updated_at"].as_str().unwrap_or(""));
|
||||
@@ -459,6 +478,10 @@ impl LanceDBOps {
|
||||
Arc::new(Int64Array::from(recall_verified_counts)),
|
||||
// GA-P0-3 (t_f785d7f2):delete_reason 列,与 arrow_schema 顺序一致(additive)
|
||||
Arc::new(StringArray::from(delete_reasons)),
|
||||
// 2026-10-13 (t_e9a4d18f P1):source_events 列,与 arrow_schema 顺序一致(additive)
|
||||
Arc::new(StringArray::from(source_events_col)),
|
||||
// 2026-10-13 (t_e9a4d18f P1):supersedes 列,与 arrow_schema 顺序一致(additive)
|
||||
Arc::new(StringArray::from(supersedes_col)),
|
||||
];
|
||||
|
||||
let batch = RecordBatch::try_new(schema.clone(), columns)?;
|
||||
@@ -930,6 +953,8 @@ impl LanceDBOps {
|
||||
delete_reason: col_str(batch, i, "delete_reason"),
|
||||
depends_on: String::new(),
|
||||
derived_from: String::new(),
|
||||
source_events: col_str(batch, i, "source_events"), // 2026-10-13 P1
|
||||
supersedes: col_str(batch, i, "supersedes"), // 2026-10-13 P1
|
||||
last_recalled_at: col_str(batch, i, "last_recalled_at"),
|
||||
created_at: col_str(batch, i, "created_at"),
|
||||
updated_at: col_str(batch, i, "updated_at"),
|
||||
@@ -1000,6 +1025,8 @@ impl LanceDBOps {
|
||||
delete_reason: col_str(&batch, i, "delete_reason"),
|
||||
depends_on: String::new(),
|
||||
derived_from: String::new(),
|
||||
source_events: col_str(&batch, i, "source_events"), // 2026-10-13 P1
|
||||
supersedes: col_str(&batch, i, "supersedes"), // 2026-10-13 P1
|
||||
last_recalled_at: String::new(),
|
||||
created_at: col_str(&batch, i, "created_at"),
|
||||
updated_at: col_str(&batch, i, "updated_at"),
|
||||
@@ -1075,6 +1102,8 @@ impl LanceDBOps {
|
||||
delete_reason: col_str(&batch, i, "delete_reason"),
|
||||
depends_on: String::new(),
|
||||
derived_from: String::new(),
|
||||
source_events: col_str(&batch, i, "source_events"), // 2026-10-13 P1
|
||||
supersedes: col_str(&batch, i, "supersedes"), // 2026-10-13 P1
|
||||
last_recalled_at: col_str(&batch, i, "last_recalled_at"),
|
||||
created_at: col_str(&batch, i, "created_at"),
|
||||
updated_at: col_str(&batch, i, "updated_at"),
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
Reference in New Issue
Block a user