fix(storage): t_34ec2b1f 时间偏置×信任系数门 ZHIYI_TIME_BIAS_TRUST(默认关·逐位等价)

门关=现状(旧循环, 连乘法都不产生)。门开只降「可靠打分且低质」(0<q<0.6):
  · 不可信族(legacy/recovery/migrat) f=0 → 低质迁移/恢复残留不享受新鲜度加分(P0: q=0.5 wiki:recovery:P0 残留 rank1→9)
  · 可信源 f=q(单调, f(0.5)=0.5<f(1.0)=1.0)
  · q<=0(未打分)/q>=0.6(含0.755 echo) 保原偏置 f=1.0 —— 回归护栏: 全量不可信族清零会误降 152 金标里高质量 legacy(q=0.755/0.805)答案(实测 152=73<75, golden=13<14), 本设计将其排除
与 ZHIYI_SOURCE_TIER_BIAS 作用域不相交(tier 只加 decision, 不含于不可信族)→ 不双重计数。
A/B(隔离实例·独立数据副本·不碰生产7821): 152=76≥75, golden=14/14 不退化; AC1 低质被抬升 396→194(-51%); AC4 双口径一致。
单测: TestIsUntrustedSource / TestTimeBiasTrustFactorMonotonic / TestTimeBiasGate{Off,On,NoDoubleCount}。
This commit is contained in:
小唯
2026-10-16 23:05:56 +08:00
parent a214cf4a0e
commit 0c0494dabd
2 changed files with 343 additions and 4 deletions
+98 -4
View File
@@ -174,6 +174,87 @@ func isStale(updated time.Time, thresholdHours float64) bool {
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)
@@ -615,11 +696,24 @@ func (p *RecallPipeline) recallUncached(query, namespace string, topK int, diver
// 与 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 {
for i := range reranked {
idx := reranked[i].Index
if idx >= 0 && idx < len(candidates) {
reranked[i].Score += timeDecayBias * recency(candidates[idx].UpdatedAt, timeDecayHalflife)
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)
}
}
}
}
@@ -0,0 +1,245 @@
package storage
import (
"math"
"testing"
"time"
"github.com/xiaoxue/memoryweave/internal/models"
)
// tbtF 构造 *float64(RawQualityScore 注入用)。
func tbtF(v float64) *float64 { return &v }
// newTBTTestPipeline 与 newTDTestPipeline 同构:隔离搜索缓存 + 预置 query 向量。
func newTBTTestPipeline(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("tbtQuery", queryVec)
fake := &srcTierLance{nsRecordingLance{rows: rows}}
return NewRecallPipeline(emb, fake, &Reranker{})
}
// TestIsUntrustedSource t_34ec2b1f:不可信源族判定。
func TestIsUntrustedSource(t *testing.T) {
cases := []struct {
src string
want bool
}{
{"legacy:pre0926", true},
{"legacy", true},
{"recovery:P0-shadow-log", true},
{"wiki:recovery:P0", true},
{"WIKI:Recovery:P0", true}, // 归一小写
{"migration:batch1", true},
{"wiki:vault:备份恢复方案.md", false}, // 中文「恢复」不算
{"wiki:decision", false},
{"llm_distill", false},
{"wiki:worklog-note", false},
{"", false}, // 空来源不惩罚
}
for _, c := range cases {
if got := isUntrustedSource(c.src); got != c.want {
t.Errorf("isUntrustedSource(%q)=%v, want %v", c.src, got, c.want)
}
}
}
// TestTimeBiasTrustFactorMonotonic t_34ec2b1f:f 单调 + 不可信源/不可信质量 ⇒ 0。
func TestTimeBiasTrustFactorMonotonic(t *testing.T) {
t.Setenv("ZHIYI_TIME_BIAS_TRUST", "1")
now := time.Now()
check := func(src string, raw *float64, dbQS float64) float64 {
return timeBiasTrustFactor(&models.MemoryRecord{Source: src, RawQualityScore: raw, UpdatedAt: now}, dbQS)
}
if got := check("wiki:recovery:P0", tbtF(0.5), 0.5); got != 0 {
t.Fatalf("不可信源(recovery 族)且低质打分(0.5) f=%.4f, 期望 0(不享受新鲜度)", got)
}
if got := check("legacy:pre0926", tbtF(0.4), 0.4); got != 0 {
t.Fatalf("legacy 族且低质打分(0.4) f=%.4f, 期望 0", got)
}
if got := check("legacy:pre0926", tbtF(0.9), 0.9); got != 1.0 {
t.Fatalf("legacy 族但高质量(0.9>=0.6) 应保原偏置 f=1.0(152 金标答案含高质量 legacy,回归护栏),got %.4f", got)
}
if got := check("llm_distill", nil, 0); got != 1.0 {
t.Fatalf("未打分(q=0)应保原偏置 f=1.0(不罚未知质量),got %.4f", got)
}
if got := check("llm_distill", tbtF(0.755), 0.755); got != 1.0 {
t.Fatalf("echo bug 常量 0.755(不可信、>=0.6)应保原偏置 f=1.0,got %.4f", got)
}
if got := check("llm_distill", nil, 0.5); got != 0.5 {
t.Fatalf("可信打分低质 q=0.5 f=%.4f, 期望 0.5", got)
}
if got := check("llm_distill", nil, 0.8); got != 1.0 {
t.Fatalf("q=0.8>=0.6 应保原偏置 f=1.0,got %.4f", got)
}
if got := check("llm_distill", tbtF(1.0), 0); got != 1.0 {
t.Fatalf("RawQualityScore=1.0 f=%.4f, 期望 1.0(Raw 优先于 dbQS)", got)
}
// 单调性:q 升 ⇒ f 不降
prev := -1.0
for _, q := range []float64{0.2, 0.5, 0.8, 1.0} {
f := check("llm_distill", tbtF(q), q)
if f < prev {
t.Fatalf("f 非单调:f(%.1f)=%.4f < 前值 %.4f", q, f, prev)
}
prev = f
}
if f05 := check("llm_distill", tbtF(0.5), 0.5); f05 >= 0.99 {
t.Fatalf("f(0.5)=%.3f 应显著小于 f(1.0)=1.0", f05)
}
// 门关 ⇒ 恒 1.0(旧行为逐位等价)
t.Setenv("ZHIYI_TIME_BIAS_TRUST", "0")
if got := check("wiki:recovery:P0", tbtF(1.0), 1.0); got != 1.0 {
t.Fatalf("门关时 f 应恒 1.0(旧行为),got %.4f", got)
}
}
// tbtRows 构造「可信新条目 vs 低质迁移残留新条目」场景。
// 向量同轴(cos 相同)⇒ 决定顺序的只有偏置,与 TestTimeDecayLiftsNewer 同构。
func tbtRows() []models.MemoryRecord {
now := time.Now()
return []models.MemoryRecord{
// 可信新条目(qs=1.0,llm_distill,刚刚更新)
{ID: "trusted-new", Content: "可信新事实", Category: "distilled", Source: "llm_distill",
QualityScore: 1.0, Vector: tbtVec(0.9), UpdatedAt: now},
// 低质迁移残留(qs=0.5,recovery 族,当天写入)—— t_34ec2b1f 实案形态
{ID: "legacy-residue", Content: "迁移残留内容", Category: "distilled", Source: "wiki:recovery:P0",
QualityScore: 0.5, Vector: tbtVec(0.9), UpdatedAt: now},
}
}
// tbtVec 构造 1024 维同轴向量(复用 srcVec 语义,独立命名避免冲突)。
func tbtVec(v0 float32) []float32 {
v := make([]float32, 1024)
v[0] = v0
return v
}
// TestTimeBiasGateOffKeepsUnconditionalLift t_34ec2b1f AC2:
// 门关(默认)时时间偏置**无条件**施加(现状行为逐位保留)⇒ 低质迁移残留被抬到第一。
func TestTimeBiasGateOffKeepsUnconditionalLift(t *testing.T) {
t.Setenv("ZHIYI_TIME_BIAS_TRUST", "") // 未设 = 默认关
oldBias, oldHL := timeDecayBias, timeDecayHalflife
timeDecayBias, timeDecayHalflife = 0.05, 24*30
defer func() { timeDecayBias, timeDecayHalflife = oldBias, oldHL }()
p := newTBTTestPipeline(t, tbtRows(), tbtVec(1.0))
res, _, err := p.RecallWithMeta("tbtQuery", "hermes-main", 2, 0.0)
if err != nil || len(res) < 2 {
t.Fatalf("Recall 出错或结果不足: %v (n=%d)", err, len(res))
}
// 两条 cos 相同;residue 与 trusted 都「新」;区分项:
// 展示分 = 0.7*(rerank+bias) + 0.3*dbQuality(fused) ⇒ residue qs=0.5 更低,
// 但时间偏置对两者相等(都新)⇒ trusted(qs 高)仍应第一;
// 若把 trusted 换成「旧」条目,residue 会反超 —— 用旧 trusted 构造(下测试)。
if res[0].ID != "trusted-new" {
t.Fatalf("全新一致时可信条目应领先,top-1=%s", res[0].ID)
}
}
// TestTimeBiasGateOnDampsResidue t_34ec2b1f AC2 核心行为 + 阳性对照:
// 可信**旧**条目 vs 低质迁移残留**新**条目:
// · 门关(现状):residue 靠 recency 反超(= 卡面实案,rank1 被低质残留占)
// · 门开:residue 时间偏置被清零 ⇒ 可信旧条目回第一(f 生效的方向证明)
func TestTimeBiasGateOnDampsResidue(t *testing.T) {
oldBias, oldHL := timeDecayBias, timeDecayHalflife
timeDecayBias, timeDecayHalflife = 0.05, 24*30
defer func() { timeDecayBias, timeDecayHalflife = oldBias, oldHL }()
mkRows := func() []models.MemoryRecord {
now := time.Now()
return []models.MemoryRecord{
// 可信旧条目:cosine 与 residue 相同(同轴),质量 1.0,30 天前更新(rec≈0.5)
{ID: "trusted-old", Content: "可信旧事实", Category: "distilled", Source: "llm_distill",
QualityScore: 1.0, Vector: tbtVec(0.9), UpdatedAt: now.Add(-30 * 24 * time.Hour)},
// 低质迁移残留:刚刚更新(rec≈1.0),qs=0.5
{ID: "legacy-residue", Content: "迁移残留内容", Category: "distilled", Source: "wiki:recovery:P0",
QualityScore: 0.5, Vector: tbtVec(0.9), UpdatedAt: now},
}
}
run := func(gate string) string {
t.Setenv("ZHIYI_TIME_BIAS_TRUST", gate)
p := newTBTTestPipeline(t, mkRows(), tbtVec(1.0))
res, _, err := p.RecallWithMeta("tbtQuery", "hermes-main", 2, 0.0)
if err != nil || len(res) < 2 {
t.Fatalf("Recall 出错: %v", err)
}
return res[0].ID
}
if got := run(""); got != "legacy-residue" {
t.Fatalf("门关(现状)期望低质新残留反超(阳性对照,复现卡面实案),top-1=%s", got)
}
if got := run("1"); got != "trusted-old" {
t.Fatalf("门开后低质迁移残留应失去时间加分、可信旧条目回第一,top-1=%s", got)
}
}
// TestTimeBiasGateNoDoubleCountWithSourceTier t_34ec2b1f AC2:
// 门开 + sourceTierBias 同时非 0:decision 来源只被加一次 tier 偏置,
// 时间偏置按 f(q) 缩放 —— 两者不重叠不叠加。
func TestTimeBiasGateNoDoubleCountWithSourceTier(t *testing.T) {
t.Setenv("ZHIYI_TIME_BIAS_TRUST", "1")
oldBias, oldHL, oldTier := timeDecayBias, timeDecayHalflife, sourceTierBias
timeDecayBias, timeDecayHalflife, sourceTierBias = 0.3, 24*30, 0.2
defer func() { timeDecayBias, timeDecayHalflife, sourceTierBias = oldBias, oldHL, oldTier }()
// decision 来源、q=0.5(f=0.5):时间偏置应为 0.3*0.5*rec,tier 偏置 0.2 只加一次
now := time.Now()
rows := []models.MemoryRecord{
{ID: "dec", Content: "决策记录内容", Category: "distilled", Source: "wiki:decision",
QualityScore: 0.5, Vector: tbtVec(0.9), UpdatedAt: now},
{ID: "fill", Content: "流水对照内容", Category: "distilled", Source: "llm_distill",
QualityScore: 0.5, Vector: tbtVec(0.9), UpdatedAt: now},
}
q := tbtVec(1.0)
// 基准:无任何偏置
timeDecayBias, sourceTierBias = 0, 0
pBase := newTBTTestPipeline(t, rows, q)
resBase, _, err := pBase.RecallWithMeta("tbtQuery", "hermes-main", 2, 0.0)
if err != nil {
t.Fatalf("基准 Recall 出错: %v", err)
}
baseScore := map[string]float64{}
for _, r := range resBase {
baseScore[r.ID] = r.Score
}
// 门开 + 双偏置
timeDecayBias, sourceTierBias = 0.3, 0.2
p := newTBTTestPipeline(t, rows, q)
res, _, err := p.RecallWithMeta("tbtQuery", "hermes-main", 2, 0.0)
if err != nil {
t.Fatalf("门开 Recall 出错: %v", err)
}
byID := map[string]float64{}
for _, r := range res {
byID[r.ID] = r.Score
}
recNow := 1.0 // UpdatedAt=now ⇒ recency≈1
// got-base = 0.7*(偏置增量)(cosine rerank 与展示质量分在两次运行中相同)
// dec:tier +0.2(只加一次)+ 时间 0.3*0.5*recNow(f(0.5)=0.5,不双重计入)
// fill:无 tier;时间 0.3*0.5*recNow
wantDec := 0.7 * (0.2 + 0.3*0.5*recNow) // = 0.7*0.35 = 0.245
wantFill := 0.7 * (0.3 * 0.5 * recNow) // = 0.7*0.15 = 0.105
for name, want := range map[string]float64{"dec": wantDec, "fill": wantFill} {
base, hasBase := baseScore[name]
got, hasGot := byID[name]
if !hasBase || !hasGot {
t.Fatalf("缺条目 %s (base=%v got=%v)", name, hasBase, hasGot)
}
if diff := math.Abs((got-base) - want); diff > 1e-6 {
t.Fatalf("增量不符 %s: got-base=%.6f, 期望=%.6f(tier 偏置只计一次、时间偏置按 f(q) 缩放)", name, got-base, want)
}
}
t.Logf("dec: base=%.4f got=%.4f(+%0.4f)fill: base=%.4f got=%.4f(+%0.4f)",
baseScore["dec"], byID["dec"], byID["dec"]-baseScore["dec"],
baseScore["fill"], byID["fill"], byID["fill"]-baseScore["fill"])
}