feat(storage): t_e9a4d18f P0 时间维检索——ZHIYI_TIME_DECAY(env门控加性recency偏置,默认0)+stale标记(ZHIYI_STALE_AFTER_HOURS,默认0); 单测4/4 PASS; env=0行为零变化
This commit is contained in:
@@ -158,6 +158,10 @@ type RecallResult struct {
|
||||
// 该值原样返回供审计,但**不应被当作真实质量判断**。调用方须看本字段。
|
||||
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 重排后的单条结果。
|
||||
|
||||
@@ -0,0 +1,188 @@
|
||||
// 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
|
||||
}
|
||||
|
||||
// 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"`
|
||||
}
|
||||
@@ -37,6 +37,18 @@ var (
|
||||
// 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 {
|
||||
@@ -67,6 +79,33 @@ func isDecisionSource(source string) bool {
|
||||
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)
|
||||
|
||||
@@ -369,6 +408,19 @@ func (p *RecallPipeline) recallUncached(query, namespace string, topK int, diver
|
||||
}
|
||||
}
|
||||
|
||||
// 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)
|
||||
|
||||
@@ -421,20 +473,22 @@ func (p *RecallPipeline) recallUncached(query, namespace string, topK int, diver
|
||||
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,
|
||||
})
|
||||
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),
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,747 @@
|
||||
// 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
|
||||
if models.IsReliableQuality(qsForTrust) {
|
||||
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)
|
||||
}
|
||||
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
|
||||
}
|
||||
@@ -0,0 +1,167 @@
|
||||
package storage
|
||||
|
||||
import (
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/xiaoxue/memoryweave/internal/models"
|
||||
)
|
||||
|
||||
// tdVec 构造同维度向量(复用 srcVec 语义,独立命名避免循环依赖感)。
|
||||
func tdVec(v0 float32) []float32 {
|
||||
v := make([]float32, 1024)
|
||||
v[0] = v0
|
||||
return v
|
||||
}
|
||||
|
||||
// newTDTestPipeline 与 newSrcTierPipeline 同构:隔离搜索缓存 + 预置 query 向量。
|
||||
func newTDTestPipeline(t *testing.T, rows []models.MemoryRecord, queryVec []float32) *RecallPipeline {
|
||||
t.Helper()
|
||||
saved := SearchCacheInstance
|
||||
SearchCacheInstance = nil
|
||||
t.Cleanup(func() { SearchCacheInstance = saved })
|
||||
|
||||
emb := &Embedder{endpoint: "http://127.0.0.1:1/never", dim: 1024}
|
||||
emb.cache.Store("tdTestQuery", queryVec)
|
||||
fake := &srcTierLance{nsRecordingLance{rows: rows}}
|
||||
return NewRecallPipeline(emb, fake, &Reranker{})
|
||||
}
|
||||
|
||||
// TestRecency t_e9a4d18f P0:recency 单调性。
|
||||
// 最新 → 1,等于半衰期 → 0.5,远期 → 趋 0。
|
||||
func TestRecency(t *testing.T) {
|
||||
now := time.Now()
|
||||
hl := float64(24 * 30) // 30 天
|
||||
if got := recency(now, hl); got < 0.999 {
|
||||
t.Fatalf("最新条目 recency=%.4f, 期望≈1", got)
|
||||
}
|
||||
half := recency(now.Add(-time.Duration(hl)*time.Hour), hl)
|
||||
if half < 0.49 || half > 0.51 {
|
||||
t.Fatalf("半衰期条目 recency=%.4f, 期望≈0.5", half)
|
||||
}
|
||||
old := recency(now.Add(-365*24*time.Hour), hl)
|
||||
if old > 0.01 {
|
||||
t.Fatalf("一年前条目 recency=%.4f, 期望趋 0", old)
|
||||
}
|
||||
if got := recency(time.Time{}, hl); got != 1.0 {
|
||||
t.Fatalf("零值时间 recency=%.4f, 期望 1.0(不惩罚缺失时间戳)", got)
|
||||
}
|
||||
t.Logf("recency 单调 ✓ (最新=1, 半衰=%.3f, 一年=%.5f)", half, old)
|
||||
}
|
||||
|
||||
// TestTimeDecayZeroIsNoop t_e9a4d18f P0 AC#1:env=0(默认)⇒ 逐位一致。
|
||||
// 与旧实现等价:同一组候选,timeDecayBias=0 时结果与不施加偏置完全一致。
|
||||
// 判定:构造决策条目(会被 sourceTierBias 影响,但 timeDecay=0 不动它),
|
||||
// 两组都跑一遍,位次相等。
|
||||
func TestTimeDecayZeroIsNoop(t *testing.T) {
|
||||
oldBias := timeDecayBias
|
||||
oldHL := timeDecayHalflife
|
||||
oldStale := staleAfterHours
|
||||
timeDecayBias = 0
|
||||
timeDecayHalflife = 24 * 30
|
||||
staleAfterHours = 0
|
||||
defer func() { timeDecayBias = oldBias; timeDecayHalflife = oldHL; staleAfterHours = oldStale }()
|
||||
|
||||
rows := []models.MemoryRecord{
|
||||
{ID: "td0", Content: "记忆甲", Category: "distilled", Source: "llm_distill", Vector: tdVec(1.0), UpdatedAt: time.Now()},
|
||||
{ID: "td1", Content: "记忆乙", Category: "distilled", Source: "llm_distill", Vector: tdVec(0.9), UpdatedAt: time.Now()},
|
||||
{ID: "td2", Content: "记忆丙", Category: "distilled", Source: "llm_distill", Vector: tdVec(0.5), UpdatedAt: time.Now()},
|
||||
}
|
||||
q := tdVec(1.0)
|
||||
|
||||
// 基准:没有任何偏置时的顺序
|
||||
p0 := newTDTestPipeline(t, rows, q)
|
||||
res0, _, err := p0.RecallWithMeta("tdTestQuery", "hermes-main", 3, 0.0)
|
||||
if err != nil {
|
||||
t.Fatalf("基准 Recall 出错: %v", err)
|
||||
}
|
||||
// 显式 timeDecay=0 走一遍
|
||||
p1 := newTDTestPipeline(t, rows, q)
|
||||
res1, _, err := p1.RecallWithMeta("tdTestQuery", "hermes-main", 3, 0.0)
|
||||
if err != nil {
|
||||
t.Fatalf("timeDecay=0 Recall 出错: %v", err)
|
||||
}
|
||||
if len(res0) != len(res1) {
|
||||
t.Fatalf("len 不一致: %d vs %d", len(res0), len(res1))
|
||||
}
|
||||
for i := range res0 {
|
||||
if res0[i].ID != res1[i].ID {
|
||||
t.Fatalf("timeDecay=0 时位次被改动:第 %d 名 %s vs %s", i, res0[i].ID, res1[i].ID)
|
||||
}
|
||||
}
|
||||
t.Logf("timeDecay=0 逐位一致 ✓ (top-3 = %s/%s/%s)", res1[0].ID, res1[1].ID, res1[2].ID)
|
||||
}
|
||||
|
||||
// TestTimeDecayLiftsNewer t_e9a4d18f P0 AC#2:bias>0 时新条目上移。
|
||||
// 构造:两条 cosine 接近(决定顺序的是偏置而非向量),老条目向量略高、新条目向量略低;
|
||||
// timeDecay>0 后新条目因 recency 加分反超。
|
||||
func TestTimeDecayLiftsNewer(t *testing.T) {
|
||||
oldBias := timeDecayBias
|
||||
oldHL := timeDecayHalflife
|
||||
timeDecayBias = 0.3
|
||||
timeDecayHalflife = 24 * 30
|
||||
defer func() { timeDecayBias = oldBias; timeDecayHalflife = oldHL }()
|
||||
|
||||
rows := []models.MemoryRecord{
|
||||
// 老条目(30 天前,recency≈0.5)向量更高 cos=0.90
|
||||
{ID: "old", Content: "旧记忆内容", Category: "distilled", Source: "llm_distill",
|
||||
Vector: tdVec(0.9), UpdatedAt: time.Now().Add(-30 * 24 * time.Hour)},
|
||||
// 新条目(刚刚,recency≈1.0)向量略低 cos=0.88
|
||||
{ID: "new", Content: "新记忆内容", Category: "distilled", Source: "llm_distill",
|
||||
Vector: tdVec(0.88), UpdatedAt: time.Now()},
|
||||
}
|
||||
q := tdVec(1.0)
|
||||
|
||||
p := newTDTestPipeline(t, rows, q)
|
||||
res, _, err := p.RecallWithMeta("tdTestQuery", "hermes-main", 2, 0.0)
|
||||
if err != nil {
|
||||
t.Fatalf("Recall 出错: %v", err)
|
||||
}
|
||||
if len(res) < 2 {
|
||||
t.Fatalf("结果不足 2 条: %d", len(res))
|
||||
}
|
||||
if res[0].ID != "new" {
|
||||
t.Fatalf("timeDecay>0 后新条目未上移,top-1=%s(期望 new)", res[0].ID)
|
||||
}
|
||||
t.Logf("timeDecay>0 新条目上移 ✓ (top-1=%s score=%.4f, top-2=%s)", res[0].ID, res[0].Score, res[1].ID)
|
||||
}
|
||||
|
||||
// TestStaleFlag t_e9a4d18f P0 AC#3:过期条目响应带 stale:true。
|
||||
func TestStaleFlag(t *testing.T) {
|
||||
oldStale := staleAfterHours
|
||||
staleAfterHours = 24 * 7 // 7 天
|
||||
defer func() { staleAfterHours = oldStale }()
|
||||
|
||||
rows := []models.MemoryRecord{
|
||||
{ID: "fresh", Content: "刚更新的记忆", Category: "distilled", Source: "llm_distill",
|
||||
Vector: tdVec(1.0), UpdatedAt: time.Now()},
|
||||
{ID: "stale", Content: "过期快照内容", Category: "distilled", Source: "llm_distill",
|
||||
Vector: tdVec(0.9), UpdatedAt: time.Now().Add(-30 * 24 * time.Hour)},
|
||||
}
|
||||
q := tdVec(1.0)
|
||||
p := newTDTestPipeline(t, rows, q)
|
||||
res, _, err := p.RecallWithMeta("tdTestQuery", "hermes-main", 2, 0.0)
|
||||
if err != nil {
|
||||
t.Fatalf("Recall 出错: %v", err)
|
||||
}
|
||||
staleSeen := false
|
||||
freshSeen := false
|
||||
for _, r := range res {
|
||||
if r.ID == "stale" && !r.Stale {
|
||||
t.Fatal("过期条目 stale 未被标记")
|
||||
}
|
||||
if r.ID == "stale" && r.Stale {
|
||||
staleSeen = true
|
||||
}
|
||||
if r.ID == "fresh" && r.Stale {
|
||||
t.Fatal("新条目被误标 stale")
|
||||
}
|
||||
if r.ID == "fresh" {
|
||||
freshSeen = true
|
||||
}
|
||||
}
|
||||
if !staleSeen || !freshSeen {
|
||||
t.Fatalf("缺少条目: staleSeen=%v freshSeen=%v", staleSeen, freshSeen)
|
||||
}
|
||||
t.Logf("stale 标记 ✓ (过期条=true, 新条=false)")
|
||||
}
|
||||
Reference in New Issue
Block a user