阶段1: schema + 存储/召回路 - StandingAnswer 增 Op *OpCard(trigger/steps/pre_check/verify/rollback/risk), 存量库 ALTER ADD COLUMN op(幂等) - Upsert 签名加 op;op=nil 改写答案不丢结构卡(COALESCE op,op) - LookupStandingAnswer 按 op.trigger 变体归一化精确匹配(零 fuzzy) - RecallWithMetaTraced 前置短路:常设答案命中 ⇒ 零检索零 LLM 直接返回 - Upsert 后 refreshStandingAnswers 清缓存 ⇒ 写后新卡即时可见 - 测试:OpCardTrigger 命中/多变体/原句并存/无 fuzzy;Upsert 清缓存即时可见 验收实跑:op 落库 41 条,trigger 变体召回 live,评测 40/40 三连复现
1535 lines
64 KiB
Go
1535 lines
64 KiB
Go
// Package storage 提供记忆召回完成管线:编码 → 向量搜索 → 重排 → MMR → 图谱扩展 → 预取推送
|
||
package storage
|
||
|
||
import (
|
||
"context"
|
||
"encoding/json"
|
||
"fmt"
|
||
"log"
|
||
"math"
|
||
"os"
|
||
"sort"
|
||
"strconv"
|
||
"strings"
|
||
"sync/atomic"
|
||
"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) // 去中心基准
|
||
// 2026-10-21(t_5624c0ff → 牧尘批准「按推荐执行」):融合权重可配。
|
||
// 1.0 = 纯向量(reranker 余弦分,不混 BM25/质量分);0.7 = 历史默认。
|
||
// 依据:MoA 四槽 + 实测 strict n=134 —— 现状 fuse 0.1125 vs 纯向量 0.1898(现状是负收益 39%),
|
||
// 且 A/C 绝对差 0.0121 在 n=134 上不显著 ⇒ 不值得为它背 9% 硬失败率(worst −100%)。
|
||
// 回滚:ZHIYI_FUSION_W=0.7(或删掉该 env)即逐位回到改动前。
|
||
fusionW = envFloat("ZHIYI_FUSION_W", 0.7)
|
||
// fuseModeProof 2026-10-26(Step3,对应 t_9acaa74d §5 A′ 的 nouse 臂):
|
||
// 融合第二槽改为 **QualityFromProof(证据条数,确定性)**,彻底不含
|
||
// importance=recency×(1+ln(seen)) 与 V 值 —— 老卡实测「usage 特征单独为负资产」
|
||
// (imp-only 0.0579 / seen-only 0.0335 NDCG@5,只有纯向量的 1/3)。
|
||
// 默认关 ⇒ 逐位等价现状;开启需同时把 FUSION_W 调<1(否则第二槽权重 0,等于没开)。
|
||
// 回滚 = 去掉 ZHIYI_FUSE_MODE。每次调用读 env(测试可 t.Setenv 翻转)。
|
||
|
||
// 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", 720)
|
||
)
|
||
|
||
// ── t_d32e5f8a L2 模式召回注入(env 门控 ZHIYI_PATTERN_RECALL,默认 0 ⇒ 行为零变化)──
|
||
// Provider 由 server.go 装配:读 graph_nodes(type='pattern'),按 query/namespace 匹配
|
||
// 出 top-k pattern,作为 Category="pattern" 的召回条目附带返回(设计 §4.1「命中即注入」)。
|
||
// 未注册 Provider(默认 =0 时 server 不注册)⇒ 注入块整体跳过,召回结果逐条不变。
|
||
// 注册了 Provider 但 ZHIYI_PATTERN_RECALL=0 ⇒ 同样跳过(关时零变化,AC3 判据)。
|
||
var PatternRecallProvider func(query, namespace string, topK int) []models.RecallResult
|
||
|
||
// patternRecallEnabled 每次调用读 env(测试可 t.Setenv 翻转,无需重跑 init)。
|
||
// 默认(未设)= 关闭。
|
||
func patternRecallEnabled() bool {
|
||
switch strings.ToLower(os.Getenv("ZHIYI_PATTERN_RECALL")) {
|
||
case "1", "true", "on":
|
||
return true
|
||
}
|
||
return false
|
||
}
|
||
|
||
// ── P3 Peer 召回注入(t_f8fc97e6,设计 §5 Peer Representation)────────────────
|
||
// Provider 由 server.go 装配:读 graph.db 的 peers 表,按 query 里是否命中某实体
|
||
// 返回该 peer 的四层推理画像,作为 Category="peer" 的召回条目附带返回。
|
||
// 未注册 Provider(默认 =0 时 server 不注册)⇒ 注入块整体跳过,召回结果逐条不变(AC2)。
|
||
var PeerRecallProvider func(query, namespace string, topK int) []models.RecallResult
|
||
|
||
// peerRecallEnabled 每次调用读 env(默认关,零行为变化,AC2 判据)。
|
||
func peerRecallEnabled() bool {
|
||
switch strings.ToLower(os.Getenv("ZHIYI_PEER_RECALL")) {
|
||
case "1", "true", "on":
|
||
return true
|
||
}
|
||
return false
|
||
}
|
||
|
||
// bitemporalEnabled 每次调用读 env(t_3ada332b):ZHIYI_BITEMPORAL=1 才启用
|
||
// bi-temporal 有效期降权;默认 0 ⇒ 行为零变化(AC2/AC3 判据)。
|
||
func bitemporalEnabled() bool {
|
||
switch strings.ToLower(os.Getenv("ZHIYI_BITEMPORAL")) {
|
||
case "1", "true", "on":
|
||
return true
|
||
}
|
||
return false
|
||
}
|
||
|
||
// BitemporalEnabled 导出 bi-temporal 开关(供 API 层在补充通道/图谱注入后做同一口径过滤)。
|
||
func BitemporalEnabled() bool { return bitemporalEnabled() }
|
||
|
||
// ValidityExpired 导出有效期判定(同上;空串=永久有效,解析失败保守视为未过期)。
|
||
func ValidityExpired(validTo string, now time.Time) bool { return validityExpired(validTo, now) }
|
||
|
||
// validityExpired 判断记忆的语义有效期是否已过(valid_to < now ⇒ 失效)。
|
||
// valid_to 空串 = 永久有效(NULL 语义,永不失效)。解析失败保守视为未失效(不误伤)。
|
||
func validityExpired(validTo string, now time.Time) bool {
|
||
if validTo == "" {
|
||
return false
|
||
}
|
||
t, err := time.Parse(time.RFC3339, validTo)
|
||
if err != nil {
|
||
return false
|
||
}
|
||
return t.Before(now)
|
||
}
|
||
|
||
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
|
||
}
|
||
|
||
// envInt 每次调用读 env(t_da61c470 改点B):解析失败回落 def(同 envFloat 语义,整型版)。
|
||
func envInt(key string, def int) int {
|
||
if v := os.Getenv(key); v != "" {
|
||
if n, err := strconv.Atoi(v); err == nil {
|
||
return n
|
||
}
|
||
log.Printf("[recall] %s=%q 无法解析为整数,回落默认 %d", 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
|
||
}
|
||
|
||
// ── 2026-10-16 (t_34ec2b1f P0):时间偏置 × 信任系数门(ZHIYI_TIME_BIAS_TRUST,默认关)──
|
||
//
|
||
// 背景(小怡实测,非推测):时间偏置**无条件**施加 ⇒ 「新鲜」压过「可信」——
|
||
// 一条 q=0.5 的迁移残留(source=wiki:recovery:P0,当天写入,同内容库内 5 份重复)
|
||
// 靠「新」被抬到 rank1。
|
||
//
|
||
// 门开(ZHIYI_TIME_BIAS_TRUST=1)时,时间偏置乘信任系数 f(source, quality)∈[0,1]。
|
||
// 回归护栏(2026-10-16 A/B 实证):全量不可信族清零会误降 152 金标里的
|
||
// 高质量 legacy 答案(q=0.755/0.805)⇒ 152=73<75、golden=13<14;故**只降
|
||
// 「可靠打分且低质」(0<q<0.6)**,其余一律 f=1.0 保原偏置:
|
||
// · q<=0(未打分)/ q>=0.6(含 0.755 echo 常量)⇒ f=1.0:质量未知或正常/高,不罚;
|
||
// · 0<q<0.6 且不可信源族(legacy/recovery/migrat,见 isUntrustedSource)⇒ f=0:
|
||
// 低质迁移/恢复残留彻底不享受新鲜度加分(卡面 P0 实案:q=0.5 wiki:recovery:P0
|
||
// 残留靠「新」霸 rank1);
|
||
// · 0<q<0.6 且可信源 ⇒ f=q:按质量比例降权,f 单调,f(0.5)=0.5 显著小于 f(1.0)=1.0。
|
||
// q 取可信 DB 原始质量分(RawQualityScore 优先,与 Step 3.5 同口径:IPC 路径
|
||
// candidates[i].QualityScore 是已融合/饱和值,不可用)。
|
||
//
|
||
// 门关(默认/未设/≠1)⇒ 本函数返回 1.0、时间偏置循环走旧语句
|
||
// (timeDecayBias*recency,逐位等价现状;同 t_e9a4d18f / t_492e3f22 模式)。
|
||
// 每次调用读 env(测试可 t.Setenv 翻转,同 bitemporalEnabled 模式)。
|
||
func timeBiasTrustGate() bool {
|
||
switch strings.ToLower(os.Getenv("ZHIYI_TIME_BIAS_TRUST")) {
|
||
case "1", "true", "on":
|
||
return true
|
||
}
|
||
return false
|
||
}
|
||
|
||
// isUntrustedSource t_34ec2b1f:不可信源族判定(迁移/recovery/legacy 族)。
|
||
// 归一:TrimSpace + ToLower 后——
|
||
// · legacy 族:HasPrefix "legacy"(覆盖 legacy / legacy:pre0926 …)
|
||
// · recovery 族:Contains "recovery"(覆盖 recovery:* / wiki:recovery:P0 …)
|
||
// · 迁移族:Contains "migrat"(现行 0 条,防御性覆盖将来迁移写入方)
|
||
// 空来源不算不可信(存量大量无 source 条目,不惩罚缺失)。
|
||
func isUntrustedSource(source string) bool {
|
||
s := strings.ToLower(strings.TrimSpace(source))
|
||
if s == "" {
|
||
return false
|
||
}
|
||
return strings.HasPrefix(s, "legacy") ||
|
||
strings.Contains(s, "recovery") ||
|
||
strings.Contains(s, "migrat")
|
||
}
|
||
|
||
// timeBiasTrustFactor t_34ec2b1f:时间偏置的信任系数 f(source, dbQuality) ∈ [0,1]。
|
||
// 门关 ⇒ 恒 1.0(旧行为,逐位等价);门开(ZHIYI_TIME_BIAS_TRUST=1)时,
|
||
// **只降「可靠打分且低质」(0<q<0.6) 的条目**,其余(q=0 未打分 / q=0.755 echo 常量 /
|
||
// q>=0.6 正常或高质量)**一律 f=1.0 保原偏置**——这是回归护栏的实证依据:
|
||
// 2026-10-16 A/B 实测「不可信族全量清零 + 全量按 IsReliableQuality 降权」⇒
|
||
// 152=73<75、golden=13<14,根因是 152 金标答案里有 7 条是 legacy:pre0926(q=0.755/0.805,
|
||
// 高质量或 echo 值)被误降;本设计把它们排除在降权外,可信域排序不变。
|
||
//
|
||
// 门开时 0<q<0.6 的降权:
|
||
// · 不可信源族(recovery/legacy/migrat,见 isUntrustedSource)⇒ f=0:
|
||
// 低质迁移/恢复残留**彻底不享受**新鲜度加分(卡面 P0 实案:q=0.5 recovery 残留
|
||
// 靠「新」霸 rank1)。
|
||
// · 可信源 ⇒ f=q:按质量比例降权(f(0.5)=0.5 显著小于 f(1.0)=1.0,单调;
|
||
// 即 AC2 方向「bias × f(quality_score)」)。
|
||
// q 取可信 DB 原始质量分(RawQualityScore 优先,与 Step 3.5 同口径:IPC 路径
|
||
// candidates[i].QualityScore 是已融合/饱和值,不可用);与 ZHIYI_SOURCE_TIER_BIAS 组合
|
||
// 时作用域不相交(tier 只加 decision 来源,不含于不可信族;降权只作用 0<q<0.6,
|
||
// 与 tier 的 decision 加分不重叠)⇒ 不双重计数(单测断言)。
|
||
func timeBiasTrustFactor(c *models.MemoryRecord, dbQuality float64) float64 {
|
||
if !timeBiasTrustGate() {
|
||
return 1.0
|
||
}
|
||
q := dbQuality
|
||
if c.RawQualityScore != nil {
|
||
q = *c.RawQualityScore
|
||
}
|
||
// 只处理「可靠打分且低质」(0<q<0.6);q<=0(未打分)/ q>=0.6(含 0.755 echo)保原偏置。
|
||
if q <= 0 || q >= 0.6 {
|
||
return 1.0
|
||
}
|
||
if isUntrustedSource(c.Source) {
|
||
return 0 // 低质不可信族:彻底清零
|
||
}
|
||
return q // 低质可信源:按比例降
|
||
}
|
||
|
||
// 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"
|
||
|
||
// nsFallbackMin 2026-10-26(牧尘令):ns 作用域兜底阈值 —— 作用域内候选少于此值就补一次
|
||
// 全库搜索。背景:agent_id 派生的 <agent>-main 里几乎没货(实测 6/7 条),
|
||
// 而不传 agent_id 是 200 条 ⇒ 带 agent_id 的调用静默劣化且不报错。
|
||
// 默认 20;**ZHIYI_NS_FALLBACK_MIN=0 即关闭**(回滚开关,逐位回到改动前)。
|
||
func nsFallbackMin() int {
|
||
if v := strings.TrimSpace(os.Getenv("ZHIYI_NS_FALLBACK_MIN")); v != "" {
|
||
if n, err := strconv.Atoi(v); err == nil && n >= 0 {
|
||
return n
|
||
}
|
||
}
|
||
return 20
|
||
}
|
||
|
||
// fuseModeProof 2026-10-26(Step3 / t_9acaa74d §5 A′ 的 nouse 臂):
|
||
// ZHIYI_FUSE_MODE=proof ⇒ 融合第二槽 = QualityFromProof(证据条数,确定性),
|
||
// 不含 importance(recency×seen)/V。默认关 ⇒ 零行为变化。
|
||
// 老卡实测:usage 特征单独为负资产(imp-only 0.0579 / seen-only 0.0335 @NDCG@5),
|
||
// 而 nouse 臂 strict 0.2019 > 纯向量 0.1898 ⇒ 方向对,但尾部仍需保位机制。
|
||
func fuseModeProof() bool {
|
||
switch strings.ToLower(os.Getenv("ZHIYI_FUSE_MODE")) {
|
||
case "proof", "nouse":
|
||
return true
|
||
}
|
||
return false
|
||
}
|
||
|
||
// 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
|
||
// TraceID / Status / PartialReason(2026-10-26 t_trace_p0 + t_contract_p0):
|
||
// 响应契约的最小可观测面 —— trace_id 贯穿整条链路,status=partial 时
|
||
// 调用方不得把「空结果」解读为「不存在」。
|
||
TraceID string
|
||
Status string // complete | partial(空串等价 complete,向后兼容)
|
||
PartialReason string
|
||
// Truncated(t_3aa2a8c1):本次召回的粗检索单次重读是否被 Rust 侧行数上限截断
|
||
// (lancedb_search 单次重读 cap,默认 20000,env ZHIYI_HEAVY_READ_MAX_ROWS 可调)。
|
||
// true = 部分结果:candidates_scanned/count 反映截断后状态,调用方不得当作「全量」。
|
||
// 缓存命中路径 / 纯 Go 后端(无行数上限)⇒ false。
|
||
Truncated bool
|
||
// StandingAnswerHit(t_standing_recall, 2026-10-25):本次召回被常设答案精确通道
|
||
// 置顶注入时,记录命中的 question_id;未命中为空。仅观测用,不参与打分。
|
||
StandingAnswerHit string
|
||
}
|
||
|
||
// SearchTruncationReporter 可选扩展接口(t_3aa2a8c1):能报告「粗检索单次重读是否被
|
||
// Rust 侧行数上限截断」的存储后端。RustLanceDBClient(IPC 路径)实现之;
|
||
// 纯 Go 后端 / 测试 fake 不实现 ⇒ 按「恒未截断」处理(其 Search 没有行数上限,
|
||
// 零值语义,行为不变)。
|
||
type SearchTruncationReporter interface {
|
||
SearchWithTruncation(table string, vector []float32, topK int, namespaceFilter string) ([]models.MemoryRecord, bool, error)
|
||
}
|
||
|
||
// RecallWithMeta 同 Recall,但额外返回召回元数据(候选池真实大小 + 是否命中缓存)。
|
||
// 缓存命中时无法重建候选池 ⇒ CandidatesScanned = 0(保守:无法测量就报 0,不虚报)。
|
||
// defaultMMRDiversity 是 MMR 的默认多样性权重(请求未显式指定时生效)。
|
||
// 由 routes 的调参器经 SetDefaultMMRDiversity 推送 —— 消费者持值、调参器推送,
|
||
// 避免 storage←routes 的反向依赖(import 环)。
|
||
// 初值 0.3 与 core.go 原硬编码一致 ⇒ 接线当天行为不变。
|
||
var defaultMMRDiversity atomic.Value // float64
|
||
|
||
func init() { defaultMMRDiversity.Store(0.3) }
|
||
|
||
// SetDefaultMMRDiversity 由调参器推送新的默认多样性权重。
|
||
// 安全边界:diversity 只在 (0,1] 有意义(MMR 公式 mmr=(1-λ)*rel+λ*(1-maxSim))。
|
||
func SetDefaultMMRDiversity(v float64) {
|
||
if v <= 0 || v > 1 {
|
||
return
|
||
}
|
||
defaultMMRDiversity.Store(v)
|
||
}
|
||
|
||
// DefaultMMRDiversity 返回当前默认多样性权重。
|
||
func DefaultMMRDiversity() float64 {
|
||
if v, ok := defaultMMRDiversity.Load().(float64); ok {
|
||
return v
|
||
}
|
||
return 0.3
|
||
}
|
||
|
||
// RecallWithMeta 是召回的唯一外部入口:内部先走原有语义/词面管线,再叠加
|
||
// 「常设答案精确通道」(t_standing_recall,2026-10-25)。
|
||
// 通道默认关(ZHIYI_STANDING_ANSWER=1 才生效)⇒ 关闭时与旧行为逐位一致。
|
||
func (p *RecallPipeline) RecallWithMeta(query, namespace string, topK int, diversity float64) ([]models.RecallResult, RecallMeta, error) {
|
||
return p.RecallWithMetaOpts(query, namespace, topK, diversity, false)
|
||
}
|
||
|
||
// RecallWithMetaOpts 2026-10-26:allowNSFallback=true 时,若 namespace 作用域候选过少
|
||
// (ZHIYI_NS_FALLBACK_MIN,默认 20),补一次全库搜索并合并。
|
||
// 只有 **agent_id 派生** 的作用域才该传 true —— 显式传 namespace 的调用方传 false,
|
||
// 否则会跨域泄漏不该看到的记忆。
|
||
func (p *RecallPipeline) RecallWithMetaOpts(query, namespace string, topK int, diversity float64, allowNSFallback bool) ([]models.RecallResult, RecallMeta, error) {
|
||
return p.RecallWithMetaTraced(context.Background(), query, namespace, topK, diversity, allowNSFallback, nil)
|
||
}
|
||
|
||
// RecallWithMetaTraced(2026-10-26 t_trace_p0):带 ctx(deadline 可中断)+ 链路追踪的召回入口。
|
||
// 旧方法全部委托到本方法、tr=nil ⇒ 旧调用方行为逐位不变。tr 非 nil 时记录各阶段耗时/通道贡献。
|
||
// ctx 在每个阶段边界检查,超时 ⇒ 立即返回已得结果并把 status 标为 partial(reason=deadline_exceeded),
|
||
// 调用方据此区分「真的没有」与「扫了一半就超时」(Air Canada 式静默幻觉的结构性入口)。
|
||
func (p *RecallPipeline) RecallWithMetaTraced(ctx context.Context, query, namespace string, topK int, diversity float64, allowNSFallback bool, tr *RecallTrace) ([]models.RecallResult, RecallMeta, error) {
|
||
if ctx == nil {
|
||
ctx = context.Background()
|
||
}
|
||
// 常设答案精确命中 ⇒ 零检索零 LLM 直接返回,不进入 rerank/LLM:
|
||
// 省 LLM 配额,且程序性记忆层在 LLM 过载(429)时仍可用。
|
||
// 命中口径是归一化后整句相等(question + op.trigger 变体),无模糊面,
|
||
// 不会误吞泛化查询;未命中时走下面的完整召回,行为逐位不变。
|
||
if sa := standingAnswerFor(query); sa != nil {
|
||
return []models.RecallResult{{
|
||
ID: "standing:" + sa.QuestionID,
|
||
Content: sa.Answer,
|
||
Category: "standing_answer",
|
||
Score: 1.0,
|
||
Timestamp: sa.UpdatedAt.Format(time.RFC3339),
|
||
Source: "standing_answer",
|
||
Channel: "standing",
|
||
}}, RecallMeta{StandingAnswerHit: sa.QuestionID, Status: "ok"}, nil
|
||
}
|
||
results, meta, err := p.recallWithMetaInner(ctx, query, namespace, topK, diversity, allowNSFallback, tr)
|
||
if tr != nil {
|
||
meta.TraceID = tr.TraceID
|
||
if tr.Status == "partial" {
|
||
meta.Status = "partial"
|
||
meta.PartialReason = tr.PartialReason
|
||
}
|
||
}
|
||
if err != nil {
|
||
return results, meta, err
|
||
}
|
||
return results, meta, err
|
||
}
|
||
|
||
func (p *RecallPipeline) recallWithMetaInner(ctx context.Context, query, namespace string, topK int, diversity float64, allowNSFallback bool, tr *RecallTrace) ([]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)
|
||
st := time.Now()
|
||
if tr != nil {
|
||
tr.CacheHit = true
|
||
tr.TopK = topK
|
||
tr.StageNote("cache_hit", st, len(filtered), "候选池不可重建(读 60s 内快照)")
|
||
}
|
||
return filtered, RecallMeta{CacheHit: true, Status: "complete"}, nil
|
||
}
|
||
}
|
||
}
|
||
return p.recallUncached(ctx, query, namespace, topK, diversity, allowNSFallback, tr)
|
||
}
|
||
|
||
// 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(ctx context.Context, query, namespace string, topK int, diversity float64, allowFallback bool, tr *RecallTrace) ([]models.RecallResult, RecallMeta, error) {
|
||
if topK <= 0 {
|
||
topK = 10
|
||
}
|
||
if ctx == nil {
|
||
ctx = context.Background()
|
||
}
|
||
if tr != nil {
|
||
tr.TopK = topK
|
||
}
|
||
|
||
// Step 1: Encode query
|
||
stEncode := time.Now()
|
||
queryVec, err := p.embedder.EncodeQuery(query)
|
||
if err != nil {
|
||
if tr != nil {
|
||
tr.StageNote("encode", stEncode, 0, err.Error())
|
||
tr.Error = err.Error()
|
||
}
|
||
return nil, RecallMeta{}, fmt.Errorf("recall encode: %w", err)
|
||
}
|
||
if tr != nil {
|
||
tr.Stage("encode", stEncode, 0)
|
||
}
|
||
|
||
// 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
|
||
stCoarse := time.Now()
|
||
// t_3aa2a8c1:Rust 侧单次重读行数上限的 truncated 上抛到 recall 响应。
|
||
// 只有实现了可选扩展接口 SearchTruncationReporter 的后端(RustLanceDBClient)
|
||
// 会上报截断;未实现的(纯 Go / 测试 fake)保持旧 Search ⇒ 恒未截断。
|
||
truncated := false
|
||
reporter, _ := p.lancedb.(SearchTruncationReporter)
|
||
searchCoarse := func(topK int, ns string) ([]models.MemoryRecord, error) {
|
||
if reporter != nil {
|
||
recs, t, err := reporter.SearchWithTruncation("memories", queryVec, topK, ns)
|
||
if err == nil {
|
||
truncated = truncated || t
|
||
}
|
||
return recs, err
|
||
}
|
||
return p.lancedb.Search("memories", queryVec, topK, ns)
|
||
}
|
||
if namespace == "" {
|
||
all, err := searchCoarse(200, "") // 空 ns = 不过滤 = 全库
|
||
if err == nil {
|
||
candidates = append(candidates, all...)
|
||
}
|
||
} else {
|
||
namespaces := []string{namespace}
|
||
if namespace != "shared" {
|
||
namespaces = append(namespaces, "shared")
|
||
}
|
||
for _, ns := range namespaces {
|
||
pool := 50
|
||
if recallV2Enabled() {
|
||
pool = 200 // 实测相关记忆可能排在向量 #126 ⇒ top-50 池根本够不着
|
||
}
|
||
nsResults, err := searchCoarse(pool, ns)
|
||
if err != nil {
|
||
continue
|
||
}
|
||
candidates = append(candidates, nsResults...)
|
||
}
|
||
}
|
||
if tr != nil {
|
||
tr.Stage("coarse_search", stCoarse, len(candidates))
|
||
tr.CandidatesScanned = len(candidates)
|
||
}
|
||
// deadline 边界(t_contract_p0):粗检索已超时 ⇒ 立刻返回 partial,
|
||
// 不继续做重排/MMR(省算力,也让调用方拿到明确的「不完整」信号)。
|
||
if err := ctx.Err(); err != nil {
|
||
if tr != nil {
|
||
tr.MarkPartial("deadline_exceeded")
|
||
}
|
||
return nil, RecallMeta{CandidatesScanned: len(candidates), Truncated: truncated, Status: "partial", PartialReason: "deadline_exceeded"}, nil
|
||
}
|
||
// 2026-10-26:**ns 作用域兜底**(牧尘令,可逆)。
|
||
// 背景:请求带 agent_id 时 resolveRecallNamespace 会派生 <agent>-main,
|
||
// 而该 ns 里几乎没有货 —— 实测 default-main 池 6 条 / xiaoyi-main 6 / prof-cloud-main 7,
|
||
// 不传 agent_id 则是 200 条。结果:召回静默劣化到个位数,不报错(见 note §M9)。
|
||
// 规则:仅当 allowFallback=true(= agent_id 派生作用域,**显式传 namespace 的调用方不兜底**,
|
||
// 避免跨域泄漏);候选数 < ZHIYI_NS_FALLBACK_MIN(默认 20,0=关闭)则补一次全库搜索并合并。
|
||
// 回滚:ZHIYI_NS_FALLBACK_MIN=0(或删该 env)即逐位回到改动前。
|
||
if allowFallback && namespace != "" {
|
||
if minN := nsFallbackMin(); minN > 0 && len(candidates) < minN {
|
||
fullLib, err := searchCoarse(200, "")
|
||
if err == nil && len(fullLib) > 0 {
|
||
log.Printf("[recall] ns 兜底:namespace=%q 仅 %d 条候选(<%d) ⇒ 合并全库 %d 条",
|
||
namespace, len(candidates), minN, len(fullLib))
|
||
candidates = append(candidates, fullLib...)
|
||
}
|
||
}
|
||
}
|
||
|
||
// 去重(按 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.2 (t_2afae95e FTS 词面通道, env-gate ZHIYI_RECALL_FTS 默认关):
|
||
// 词面检索命中单独留位 —— 稀有 ASCII 词/标识符/数字(MMR、8080、
|
||
// session-to-zhiyi 这类)在 embedding 主导的向量 top-N 里进不了池
|
||
// (实测相关记忆向量排 #126/12094),这里按内容检索(TF-IDF 倒排)
|
||
// 把它们捞回来。
|
||
// 为什么不并入主候选池:主池候选带 1024 维向量喂 RerankWithVectors,
|
||
// FTS 命中记录只有内容(Vector 置空)⇒ 混入会让整段 rerank 回退
|
||
// 文本重编码路径(2000 字 3.9s)⇒ 融合改走「rerank+MMR 之后按分尾部
|
||
// 追加」(诊断第 3 条:融合必须在 rerank 之后才算数;尾部追加不挤头部
|
||
// 相对顺序 ⇒ AC4 主路径零回归)。
|
||
// 门控关 ⇒ 本块不执行(零行为变化)。
|
||
var ftsTail []models.MemoryRecord
|
||
ftsScoreOf := map[string]float64{} // id → 词面分(只用于尾部排序)
|
||
stFts := time.Now()
|
||
if ftsEnabled() {
|
||
ftsScores := ftsInstance.FtsSearch(query, 30)
|
||
for id, s := range ftsScores {
|
||
if seen[id] {
|
||
continue // 向量池已有 ⇒ 头部排序归主路径,不重复
|
||
}
|
||
rec, ok := FtsRecord(id)
|
||
if !ok {
|
||
continue
|
||
}
|
||
switch rec.Category {
|
||
case "episodes", "对话", "对话记录", "raw", "episodic":
|
||
continue // 与 Step 2.5 同口径:原始对话不进结果
|
||
}
|
||
if namespace != "" && rec.Namespace != namespace && rec.Namespace != "shared" {
|
||
continue // 带 ns 时 §1.3 作用域同口径(本 ns + shared)
|
||
}
|
||
ftsScoreOf[rec.ID] = s // 词面分只进排序;展示分保持 DB 原值(rec.QualityScore 不动)
|
||
ftsTail = append(ftsTail, rec)
|
||
}
|
||
// 词面分降序(同分按 id 稳定)
|
||
sort.SliceStable(ftsTail, func(i, j int) bool {
|
||
if ftsScoreOf[ftsTail[i].ID] != ftsScoreOf[ftsTail[j].ID] {
|
||
return ftsScoreOf[ftsTail[i].ID] > ftsScoreOf[ftsTail[j].ID]
|
||
}
|
||
return ftsTail[i].ID < ftsTail[j].ID
|
||
})
|
||
if len(ftsTail) > 0 {
|
||
log.Printf("[recall] FTS 词面通道命中 %d 条(候选池 %d)", len(ftsTail), len(candidates))
|
||
}
|
||
}
|
||
if tr != nil {
|
||
tr.Stage("fts_recall", stFts, len(ftsTail))
|
||
}
|
||
|
||
// 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
|
||
|
||
// 2026-10-14 (t_3ada332b):bi-temporal 有效期降权。valid_to < now 的事实
|
||
// 不入 top-k(从候选池剔除),但【仍在库、仍可显式查询】——non-lossy,不删历史。
|
||
// 开关默认关 ZHIYI_BITEMPORAL=0 ⇒ 本块整体跳过,召回结果逐条不变(零行为变化)。
|
||
// 全失效时降级回原行为(与上面 raw 过滤同策略,避免召回被清空)。
|
||
if bitemporalEnabled() {
|
||
now := time.Now()
|
||
live := make([]models.MemoryRecord, 0, len(candidates))
|
||
var expired int
|
||
for _, c := range candidates {
|
||
if validityExpired(c.ValidTo, now) {
|
||
expired++
|
||
continue
|
||
}
|
||
live = append(live, c)
|
||
}
|
||
if len(live) > 0 {
|
||
if expired > 0 {
|
||
log.Printf("[recall] bi-temporal 降权 %d 条失效事实(%d 条仍有效候选,non-lossy 保留在库)", expired, len(live))
|
||
}
|
||
candidates = live
|
||
}
|
||
}
|
||
|
||
// 候选池真实大小捕获点:LanceDB ANN 返回 + 去重 + 原始对话过滤之后、
|
||
// 截断/rerank/MMR 之前 —— 这才是 "scanned candidates" 的真实含义。
|
||
poolSize := len(candidates)
|
||
|
||
// 截断候选池(全库模式候选来自更多命名空间,池子放宽到 100)
|
||
candCap := 50
|
||
if namespace == "" {
|
||
candCap = 100
|
||
if recallV2Enabled() {
|
||
candCap = 300
|
||
}
|
||
}
|
||
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))
|
||
stBm25 := time.Now()
|
||
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)
|
||
if recallV2Enabled() {
|
||
kwScore = ComputeBM25ScoreV2(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]*fusionW + kwScore*(1-fusionW)
|
||
} 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 tr != nil {
|
||
tr.Stage("bm25", stBm25, len(candidates))
|
||
}
|
||
|
||
if len(candidates) == 0 && len(ftsTail) == 0 {
|
||
// 自动记录召回缺口(gap_scan 触发器会在 30min 冷却后分类)
|
||
// t_2afae95e:FTS 尾部位命中也算有结果 ⇒ 不记 miss、不走空返回
|
||
if p.recordMiss != nil {
|
||
p.recordMiss(query, namespace)
|
||
}
|
||
if len(ftsTail) == 0 {
|
||
return []models.RecallResult{}, RecallMeta{CandidatesScanned: poolSize, Truncated: truncated}, 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 预算
|
||
// 被打爆的直接原因。向量不齐/维度不符时自动回退文本重排(行为与旧版一致)。
|
||
stRerank := time.Now()
|
||
docs := make([]string, len(candidates))
|
||
docVecs := make([][]float32, len(candidates))
|
||
for i, c := range candidates {
|
||
docs[i] = c.Content
|
||
docVecs[i] = c.Vector
|
||
}
|
||
// V2: 重排候选放宽 —— 实测相关记忆 cosine 排名 #126,topK*2(=20) 处就被切掉了。
|
||
rerankN := topK * 2
|
||
if recallV2Enabled() && rerankN < 150 {
|
||
rerankN = 150
|
||
}
|
||
// t_da61c470 改点B · rerankN 下限 env 门控(默认 10 = V2 OFF 现值 ⇒ 零行为变化):
|
||
// 救「池内有货被二次截断」(8081 组目标 ANN #17~21 / QE 扩写后淇县 #13,
|
||
// 都在 rerankN=10 门外)。A/B 时设 25:ZHIYI_RERANK_N_FLOOR=25;回滚 = unset。
|
||
// 只抬下限、不抬上界:V2 ON 的 150 保持不动;floor 仅在 topK*2(或 150)之上生效。
|
||
if floor := envInt("ZHIYI_RERANK_N_FLOOR", 10); floor > rerankN {
|
||
rerankN = floor
|
||
}
|
||
reranked, err := p.reranker.RerankWithVectors(queryVec, docs, docVecs, rerankN)
|
||
if err != nil {
|
||
log.Printf("[recall] 向量重排跳过(%v),回退文本重排", err)
|
||
reranked, err = p.reranker.Rerank(query, docs, rerankN)
|
||
}
|
||
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.6 (V2, 2026-10-14): 关键词分融入**最终**排序。
|
||
// 为什么必须放在 rerank 之后:Step 3.5 的 BM25 融合作用在 candidates 上,
|
||
// 而紧接着的 rerank 会按 cosine 重新打分并只留 rerankN 条 ⇒ 关键词分被整段丢弃
|
||
// (实测:V2 开着与关着结果逐条相同,就是这么丢的)。
|
||
if recallV2Enabled() {
|
||
for i := range reranked {
|
||
idx := reranked[i].Index
|
||
if idx < 0 || idx >= len(candidates) {
|
||
continue
|
||
}
|
||
kw := ComputeBM25ScoreV2(query, candidates[idx].Content)
|
||
reranked[i].Score = reranked[i].Score*fusionW + kw*(1-fusionW)
|
||
}
|
||
}
|
||
|
||
// 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 教训)。
|
||
// 2026-10-16 (t_34ec2b1f P0):时间偏置 × 信任系数门 ZHIYI_TIME_BIAS_TRUST
|
||
//(默认关 ⇒ else 分支走旧语句,逐位等价现状;门关时连乘法都不产生)。
|
||
if timeDecayBias > 0 {
|
||
if timeBiasTrustGate() {
|
||
for i := range reranked {
|
||
idx := reranked[i].Index
|
||
if idx >= 0 && idx < len(candidates) {
|
||
coef := timeBiasTrustFactor(&candidates[idx], dbQuality[idx])
|
||
reranked[i].Score += timeDecayBias * coef * recency(candidates[idx].UpdatedAt, timeDecayHalflife)
|
||
}
|
||
}
|
||
} else {
|
||
// 旧路径(门关=默认):与 t_e9a4d18f 原始循环逐位一致。
|
||
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
|
||
if tr != nil {
|
||
tr.Stage("rerank_fusion", stRerank, len(reranked))
|
||
}
|
||
// deadline 边界:重排已超时 ⇒ 返回 partial(不继续 MMR/图谱扩展)。
|
||
if ctx.Err() != nil {
|
||
if tr != nil {
|
||
tr.MarkPartial("deadline_exceeded")
|
||
}
|
||
return nil, RecallMeta{CandidatesScanned: poolSize, Truncated: truncated, Status: "partial", PartialReason: "deadline_exceeded"}, nil
|
||
}
|
||
stMMR := time.Now()
|
||
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*fusionW + c.QualityScore*(1-fusionW)
|
||
if fuseModeProof() {
|
||
// 第二槽换成确定性证据分:条数饱和 x/(x+K),无 seen/时间/V。
|
||
base = score*fusionW + QualityFromProof(&c)*(1-fusionW)
|
||
}
|
||
// 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,
|
||
// A10 (t_d618dc7c):人工有用单独计数直通(nil=NULL=从未被人工点过)
|
||
HumanUsefulCount: c.HumanUsefulCount,
|
||
// 2026-10-13 (t_e9a4d18f P0):过期标记(默认 720h,仅展示不参与排序)
|
||
Stale: isStale(c.UpdatedAt, staleAfterHours),
|
||
// 2026-10-26(t_trace_p0 / P1 supersede):来源通道 + 版本/取代关系直通
|
||
Channel: "vector",
|
||
Version: c.Version,
|
||
ValidFrom: c.ValidFrom,
|
||
ValidTo: c.ValidTo,
|
||
Supersedes: c.Supersedes,
|
||
SupersededBy: c.SupersededBy,
|
||
Superseded: len(c.SupersededBy) > 0,
|
||
})
|
||
}
|
||
}
|
||
if tr != nil {
|
||
tr.Stage("mmr_select", stMMR, len(results))
|
||
}
|
||
|
||
// Step 3.8 (t_2afae95e FTS 词面通道尾部保证位, 门控同 Step 2.2):
|
||
// 词面命中在 **rerank+MMR 之后**才并入最终结果(诊断第 3 条:rerank 之前
|
||
// 融合会被 cosine 重排整段覆盖)。规则(只动尾部、不挤头部相对顺序):
|
||
// - 结果不足 topK ⇒ 追加到 topK 封顶;
|
||
// - 结果已满 topK ⇒ 尾部最多让给 FTS 前 3 条 **ASCII 档**命中(分≥0.5,
|
||
// 即命中查询里的稀有 ASCII 词/数字/标识符);bigram 噪声档(分<0.32)
|
||
// 不占尾部位(它只配填充未占满的余位)⇒ 头部向量文档至多让 3 位,
|
||
// 且仅当 FTS 侧真有强词面命中时(本查询的关键词就靠这几条保命,
|
||
// 实测 MMR 查询 top-1 是 E1 档文档、MMR 档排 #2 ⇒ 1 个槽位不够)。
|
||
// 去重:已在结果里的 ID 不重复追加(向量池已捞到的由主路径排序管)。
|
||
// 门控关 ⇒ ftsTail 恒 nil ⇒ 整块零行为变化。
|
||
if len(ftsTail) > 0 {
|
||
inResult := map[string]bool{}
|
||
for _, r := range results {
|
||
inResult[r.ID] = true
|
||
}
|
||
// 尾部位只认 ASCII 档(词面分≥0.5 = 命中查询的稀有 ASCII 词);
|
||
// bigram 噪声档(<0.32)不抢已有结果的槽位。
|
||
// t_da61c470 改点A:bigram-only(纯 CJK,ascii_terms 为空)查询的尾部位门槛
|
||
// 单独可配 —— 默认 0.5(= 现状,bigram 档分 <0.32 仍被整段拦,零行为变化);
|
||
// A/B 设 ZHIYI_FTS_BIGRAM_TAIL_GATE≈0.15 ⇒ 纯 CJK 专名(淇县/鹤壁/卫都街道/
|
||
// 生物制造/小米笔记本…,bigram 档分 0.16~0.256)能拿到尾部位。
|
||
// 混合/ASCII 查询不受影响(tailGate 恒 0.5,权重公式不动)。
|
||
// t_287c6d51 分档:门禁按 query 的 bigram 数分档 —— 1-bigram(2 字专名)档
|
||
// 读 ZHIYI_FTS_BIGRAM_TAIL_GATE(A/B 设 ~0.15);≥2-bigram 档与混合/ASCII 档
|
||
// 恒 0.5 不动(防 t_da61c470 长词噪声重演)。默认全 0.5 = 零行为变化。
|
||
tailGate := 0.5
|
||
if IsBigramOnlyQuery(query) {
|
||
tailGate = FtsBigramTailGateForQuery(query)
|
||
}
|
||
fresh := make([]models.MemoryRecord, 0, len(ftsTail))
|
||
for _, rec := range ftsTail {
|
||
if inResult[rec.ID] {
|
||
continue
|
||
}
|
||
if ftsScoreOf[rec.ID] >= tailGate {
|
||
fresh = append(fresh, rec)
|
||
}
|
||
}
|
||
if len(fresh) == 0 {
|
||
// 无强词面命中 ⇒ 不动主路径(bigram 档不补位,避免噪声挤头部)
|
||
} else {
|
||
// 预算:不足 topK ⇒ 追加到 topK 封顶;已满 ⇒ 尾部最多 3 个 ASCII 档
|
||
// 槽位(头部至多让 3 位;回归面收敛且只在 FTS 真有命中时发生)
|
||
budget := topK - len(results)
|
||
if len(results) >= topK {
|
||
budget = 3
|
||
}
|
||
nAppend := budget
|
||
if nAppend > len(fresh) {
|
||
nAppend = len(fresh)
|
||
}
|
||
if len(results) >= topK && nAppend > 0 {
|
||
// t_bd718662 P1:让位数不得超过现有条数。原实现在 len(results)==topK 时
|
||
// 硬编码 budget=3,topK∈{1,2} 且 fresh 够多时 cut=len(results)-nAppend<0
|
||
// ⇒ results[:cut] 负索引 panic(线上 trace: `slice bounds out of range [:-2]`
|
||
// @ recall.go:846)。修后 cut≥0 恒成立;全仓唯一裁剪点仍在此(AC-D:
|
||
// 任何路径不返回 > topK 条 —— 让位只做等量替换,不做追加扩张)。
|
||
if nAppend > len(results) {
|
||
nAppend = len(results)
|
||
}
|
||
cut := len(results) - nAppend
|
||
results = results[:cut] // 让出尾部 nAppend 位(头部至多动 3 位)
|
||
}
|
||
for i := 0; i < nAppend; i++ {
|
||
rec := fresh[i]
|
||
// 展示分口径(与主路径「响应值==库值」铁律对齐):
|
||
// QualityScore = DB 原值(词面分不进展示分,只进排序)
|
||
// Score = 词面分(0..1,本条的通道分;FtsBoosted=true 可辨来源)
|
||
results = append(results, models.RecallResult{
|
||
ID: rec.ID,
|
||
Content: rec.Content,
|
||
Category: rec.Category,
|
||
Score: ftsScoreOf[rec.ID],
|
||
Timestamp: rec.CreatedAt.Format(time.RFC3339),
|
||
Namespace: rec.Namespace,
|
||
AgentID: rec.AgentID,
|
||
Source: rec.Source,
|
||
QualityScore: rec.QualityScore,
|
||
QualityScoreReliable: false, // FTS 记录未经过质量融合 ⇒ 标不可信(审计可辨)
|
||
FtsBoosted: true,
|
||
Channel: "fts",
|
||
Version: rec.Version,
|
||
ValidFrom: rec.ValidFrom,
|
||
ValidTo: rec.ValidTo,
|
||
Supersedes: rec.Supersedes,
|
||
SupersededBy: rec.SupersededBy,
|
||
Superseded: len(rec.SupersededBy) > 0,
|
||
Stale: isStale(rec.UpdatedAt, staleAfterHours),
|
||
// A10 (t_d618dc7c):人工有用单独计数直通(nil=NULL=从未被人工点过)
|
||
HumanUsefulCount: rec.HumanUsefulCount,
|
||
})
|
||
}
|
||
}
|
||
}
|
||
|
||
// Step 5: 图谱融合扩展(不再作为后备补丁,每次 recall 都跑 1 跳)
|
||
stGraph := time.Now()
|
||
graphAdded := 0
|
||
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 {
|
||
e.Channel = "graph"
|
||
results = append(results, e)
|
||
graphAdded++
|
||
}
|
||
}
|
||
}
|
||
if tr != nil {
|
||
tr.Stage("graph_expand", stGraph, graphAdded)
|
||
}
|
||
|
||
// Step 6: 去重(相同 content 只保留最高分)
|
||
stDedup := time.Now()
|
||
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
|
||
if tr != nil {
|
||
tr.Stage("dedupe", stDedup, len(results))
|
||
}
|
||
|
||
// Step 6.2: t_d32e5f8a L2 模式召回注入(env 门控 ZHIYI_PATTERN_RECALL,默认 0)
|
||
// 命中 pattern 时以 Category="pattern" 附带 top-k 返回(设计「命中即注入」)。
|
||
// 默认关 ⇒ 整块跳过,results 逐条不变(AC3 判据:固定 query 前后 diff 为空)。
|
||
if patternRecallEnabled() && PatternRecallProvider != nil {
|
||
for _, pr := range PatternRecallProvider(query, namespace, 3) {
|
||
// 去重:不重复追加已在结果里的条目
|
||
dup := false
|
||
for _, r := range results {
|
||
if r.ID == pr.ID {
|
||
dup = true
|
||
break
|
||
}
|
||
}
|
||
if !dup {
|
||
pr.Channel = "pattern"
|
||
results = append(results, pr)
|
||
}
|
||
}
|
||
}
|
||
|
||
// Step 6.3: t_f8fc97e6 P3 Peer 推理画像注入(env 门控 ZHIYI_PEER_RECALL,默认 0)
|
||
// query 命中某实体时附带该 peer 的四层画像(Category="peer")。默认关 ⇒ 整块跳过(AC2)。
|
||
if peerRecallEnabled() && PeerRecallProvider != nil {
|
||
for _, pr := range PeerRecallProvider(query, namespace, 1) {
|
||
dup := false
|
||
for _, r := range results {
|
||
if r.ID == pr.ID {
|
||
dup = true
|
||
break
|
||
}
|
||
}
|
||
if !dup {
|
||
pr.Channel = "peer"
|
||
results = append(results, pr)
|
||
}
|
||
}
|
||
}
|
||
|
||
// 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)
|
||
}
|
||
}()
|
||
|
||
// Step 8: 热门度观测点(t_23b6a940 AC7,report-only、零排序影响):
|
||
// 记录最终 rank1 的 recall_verified_count;连续越 p95 阈值满 N 个 query ⇒
|
||
// ALERT 日志行(传感器通道),传感器端 zhiyi-popwatch.py 转既有告警通道。
|
||
// 仅观测主 ANN 池出来的 rank1(图谱扩展/FTS 尾部位注入的 rank1 无池内计数,
|
||
// 跳过不记)——热度偏置的作用面恰在主池 rerank 漏斗。
|
||
if len(results) > 0 {
|
||
for i := range candidates {
|
||
if candidates[i].ID == results[0].ID {
|
||
PopWatchRecord(results[0].ID, int64(candidates[i].RecallVerifiedCount))
|
||
break
|
||
}
|
||
}
|
||
}
|
||
|
||
// 契约(t_contract_p0):status 默认 complete;行数上限截断 ⇒ partial(
|
||
// 调用方不得把截断后的空/少结果解读为「不存在」)。
|
||
status := "complete"
|
||
partialReason := ""
|
||
if truncated {
|
||
status = "partial"
|
||
partialReason = "row_cap_truncated"
|
||
if tr != nil {
|
||
tr.MarkPartial("row_cap_truncated")
|
||
}
|
||
}
|
||
return results, RecallMeta{CandidatesScanned: poolSize, Truncated: truncated, Status: status, PartialReason: partialReason}, nil
|
||
}
|
||
|
||
// recallV2 开关(2026-10-14)。默认关 ⇒ 行为零变化。
|
||
// 起因:实测查询「织忆如何通过 E1 提取和 MMR 实现多样去重」捞不到含 MMR 的记忆
|
||
// (该记忆向量排名 #126/12094,在 per-ns top-50 池外;且旧 ComputeBM25Score
|
||
// 用 strings.Fields 只按空格分词、整段短语做子串计数 ⇒ 中文查询关键词分几乎恒 0
|
||
// ⇒ 融合分退化为「饱和的 quality_score」⇒ 排序实际由向量原始顺序决定)。
|
||
// 判定:env ZHIYI_RECALL_V2=1 或标志文件存在(后者可在不重启的情况下 A/B)。
|
||
func recallV2Enabled() bool {
|
||
if os.Getenv("ZHIYI_RECALL_V2") == "1" {
|
||
return true
|
||
}
|
||
flag := os.Getenv("ZHIYI_RECALL_V2_FLAG")
|
||
if flag == "" {
|
||
flag = "/var/lib/memoryweave/recall-v2.on"
|
||
}
|
||
_, err := os.Stat(flag)
|
||
return err == nil
|
||
}
|
||
|
||
// tokenizeQueryV2 把查询切成:ASCII 词(>=2 字符,含标识符/缩写/数字)+ CJK 字符二元组。
|
||
// 为什么不用 strings.Fields:中文没有空格,整块短语永远匹配不到文档里的连续子串。
|
||
func tokenizeQueryV2(q string) (ascii []string, bigrams []string) {
|
||
runes := []rune(strings.ToLower(q))
|
||
seenB := map[string]bool{}
|
||
var cur []rune
|
||
flush := func() {
|
||
if len(cur) >= 2 {
|
||
ascii = append(ascii, string(cur))
|
||
}
|
||
cur = cur[:0]
|
||
}
|
||
for i := 0; i < len(runes); i++ {
|
||
r := runes[i]
|
||
if (r >= 'a' && r <= 'z') || (r >= '0' && r <= '9') || r == '_' || r == '-' || r == '.' {
|
||
cur = append(cur, r)
|
||
continue
|
||
}
|
||
flush()
|
||
if r >= 0x4E00 && r <= 0x9FFF && i+1 < len(runes) {
|
||
nx := runes[i+1]
|
||
if nx >= 0x4E00 && nx <= 0x9FFF {
|
||
bg := string([]rune{r, nx})
|
||
if !seenB[bg] {
|
||
seenB[bg] = true
|
||
bigrams = append(bigrams, bg)
|
||
}
|
||
}
|
||
}
|
||
}
|
||
flush()
|
||
return
|
||
}
|
||
|
||
// ComputeBM25ScoreV2 中文可用的关键词分:ASCII 词权重 3.0(中文语料里稀有 ⇒ 高信息量,
|
||
// 充当 IDF 的廉价代理),CJK 二元组权重 1.0。归一化到 [0,1]。
|
||
func ComputeBM25ScoreV2(query, doc string) float64 {
|
||
ascii, bigrams := tokenizeQueryV2(query)
|
||
docLower := strings.ToLower(doc)
|
||
total, hit := 0.0, 0.0
|
||
// ASCII 词权重 10.0:中文语料里 ASCII 缩写/标识符极稀有 ⇒ 命中即高信息量
|
||
// (廉价 IDF 代理)。若只给 1.0,中文二元组的噪声会淹没稀有词信号。
|
||
for _, t := range ascii {
|
||
total += 10.0
|
||
if strings.Contains(docLower, t) {
|
||
hit += 10.0
|
||
}
|
||
}
|
||
for _, b := range bigrams {
|
||
total += 1.0
|
||
if strings.Contains(docLower, b) {
|
||
hit += 1.0
|
||
}
|
||
}
|
||
if total == 0 || hit == 0 {
|
||
return 0
|
||
}
|
||
score := hit / total
|
||
if score > 1.0 {
|
||
score = 1.0
|
||
}
|
||
return score
|
||
}
|
||
|
||
// 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 isMemoryRowID(r.ID) {
|
||
ids = append(ids, r.ID)
|
||
}
|
||
}
|
||
if len(ids) == 0 {
|
||
return
|
||
}
|
||
if RecallWriteBufferInstance != nil {
|
||
RecallWriteBufferInstance.Record(ids)
|
||
return
|
||
}
|
||
go p.incrementRecallCount(results)
|
||
}
|
||
|
||
// isMemoryRowID 只认真实落在 memories 表里的行 ID(mem_*)。
|
||
//
|
||
// 2026-10-26(t_0a54c12b 写入放大复发):召回结果集里混着大量**不属于 memories 表**的 ID:
|
||
// - ep_* = episodes 原始轮次(另一张表)
|
||
// - n_* = 图谱扩展节点(graph_expanded;实测 memories 表 40383 行里 n_* 前缀 = 0)
|
||
//
|
||
// 这些 ID 送进 update_recall_batch 只会产生「谓词命中 0 行」的提交 —— 而 LanceDB 是 MVCC,
|
||
// **每次提交无论命中几行都是一个版本**。实测 2026-10-26 21:26 一条批:
|
||
// `delta=1 ids=791 rows=10`(命中率 1.3%)、`delta=2 ids=32 rows=0`(纯空转版本)。
|
||
// 过滤后 ① 每条 batch 命中率回到 ~100% ② pending 涨得慢 ⇒ 阈值 flush 次数降一个量级。
|
||
func isMemoryRowID(id string) bool {
|
||
return strings.HasPrefix(id, "mem_")
|
||
}
|
||
|
||
// incrementRecallCount 旧版逐条同步写(每条结果 = 1 个 LanceDB 版本)。
|
||
// 已不作为主路径,仅保留为缓冲不可用时的兜底。
|
||
func (p *RecallPipeline) incrementRecallCount(results []models.RecallResult) {
|
||
now := time.Now().Format(time.RFC3339)
|
||
for _, r := range results {
|
||
if isMemoryRowID(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
|
||
}
|