fix(tuning): 调参接线消费方 + 阻尼 + 持久化(治「旋钮没接到任何东西」)
实测三真相(2026-10-14): ① 无消费者 —— grep Tuner. 全仓只有 3 处路由注册,没有任何代码读 Diversity/GapThreshold/DecayRate/DistillInterval ⇒ 调参改了数字、行为零变化。 ② 不幂等(棘轮)—— 同一判据每调一次推一步:连跑两次 decay 0.015→0.018→0.0216。 ③ 不持久化 —— 包级内存变量,重启即回默认。 修法: - 接线:storage.SetDefaultMMRDiversity / selfoptimize.SetGapThreshold(消费者持值、调参器推送, 避免 storage←routes 反向依赖)。初值对齐消费方真实默认(Diversity 0.5→0.3)⇒ 当天行为不变。 - 阻尼:同一参数 6h 冷却。 - 持久化:/var/lib/memoryweave/tuning-state.json(env ZHIYI_TUNING_STATE 可覆盖),启动 load+接线。 - 删规则3(废弃率→提高衰减率):方向危险 —— NewForgetter 注释记载 「0.015→0.03 曾致误删(36天库龄下 0-recall 长记忆全被清)」。 - 删规则5(蒸馏损失→缩短蒸馏间隔):无正确消费方 —— engine.go 的 batchTimeout 是 「队列冻结兜底 ticker」(安全网),不是蒸馏节奏。 测试 4 个:哨兵/少样本拦截、冷却、推送、持久化(含「健康数据仍能调」反向验证)。
This commit is contained in:
@@ -371,8 +371,10 @@ func (a *API) Recall(w http.ResponseWriter, r *http.Request) {
|
||||
req.Namespace = resolveRecallNamespace(req.Namespace, req.AgentID, req.Query)
|
||||
|
||||
// H4: Default diversity — balance relevance & diversity
|
||||
// 2026-10-14:改读 storage 的推送值(默认 0.3,与下方原硬编码一致 ⇒ 行为不变),
|
||||
// 让调参器能真正影响召回 —— 此前调参改了 Tuner.Diversity 但没人读(空转)。
|
||||
if req.Diversity <= 0 {
|
||||
req.Diversity = 0.3
|
||||
req.Diversity = storage.DefaultMMRDiversity()
|
||||
}
|
||||
|
||||
var results []models.RecallResult
|
||||
@@ -432,7 +434,7 @@ func (a *API) Recall(w http.ResponseWriter, r *http.Request) {
|
||||
kwResults = kwResults[:req.Limit]
|
||||
}
|
||||
respond(w, 200, map[string]interface{}{
|
||||
"results": kwResults, "count": len(kwResults), "mode": "keyword",
|
||||
"results": kwResults, "count": len(kwResults), "mode": "keyword",
|
||||
"candidates_scanned": 0,
|
||||
"cache_hit": cacheHit, // t_1c12e000:keyword 主路径命中 search cache 时显式标注
|
||||
})
|
||||
|
||||
@@ -2,12 +2,16 @@
|
||||
package routes
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"log"
|
||||
"net/http"
|
||||
"os"
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"github.com/xiaoxue/memoryweave/internal/selfoptimize"
|
||||
"github.com/xiaoxue/memoryweave/internal/storage"
|
||||
)
|
||||
|
||||
// TuningConfig 可自动调优的参数
|
||||
@@ -26,6 +30,11 @@ type TuningConfig struct {
|
||||
// lastSkipped 上一次 AutoTune 里「因指标不可用而跳过」的规则与原因。
|
||||
// 让外部能区分「健康所以没调」与「数据不可用所以没调」——后者需要修数据源,不是好事。
|
||||
lastSkipped []string
|
||||
|
||||
// lastMoveAt 每个参数上一次被改动的时间 —— 用于冷却(治棘轮)。
|
||||
lastMoveAt map[string]time.Time
|
||||
// persistEnabled 仅全局 Tuner 为 true;测试里构造的实例为 false ⇒ 不写盘。
|
||||
persistEnabled bool
|
||||
}
|
||||
|
||||
type TuningEvent struct {
|
||||
@@ -37,13 +46,25 @@ type TuningEvent struct {
|
||||
}
|
||||
|
||||
var Tuner = &TuningConfig{
|
||||
Diversity: 0.5,
|
||||
// ⚠️ 初值必须等于**真实消费方的默认值**,否则接线当天就改变生产行为:
|
||||
// Diversity 对齐 storage.DefaultMMRDiversity() 的 0.3(core.go 原硬编码),原为 0.5。
|
||||
Diversity: 0.3,
|
||||
DecayRate: 0.015,
|
||||
GapThreshold: 3,
|
||||
DistillInterval: 5,
|
||||
ConsolidateAfter: 50,
|
||||
|
||||
lastMoveAt: map[string]time.Time{},
|
||||
persistEnabled: true,
|
||||
}
|
||||
|
||||
// tuneCooldown 同一参数的调参冷却时间。
|
||||
// 为什么需要:**AutoTune 不幂等** —— 同一判据每调一次就推一步(实测连跑两次:
|
||||
// decay_rate 0.015→0.018→0.0216、distill_interval 5→4→3),直到撞上限。
|
||||
// 闭环每天跑一次 ⇒ 几天内把参数顶到极值。冷却把「持续推进」限制成
|
||||
// 「同一指标须持续越界多个窗口,才多次调整」。
|
||||
const tuneCooldown = 6 * time.Hour
|
||||
|
||||
// minTuningSamples 调参判据的最小样本数。
|
||||
// 为什么需要:小样本的比率噪声极大 —— 实测现网 recall_usefulness_rate 只有 9 个样本,
|
||||
// 8 好 1 坏 = 0.89,再来 1 个好评就 > 0.9 ⇒ 触发「降低 diversity」直接改生产参数。
|
||||
@@ -84,6 +105,92 @@ func ratioFor(metrics map[string]float64, valueKey string) (float64, bool) {
|
||||
return v, true
|
||||
}
|
||||
|
||||
// canMove 判断某参数当前是否允许改动(冷却窗口内不许重复动 —— 治棘轮)。
|
||||
func (tc *TuningConfig) canMove(param string) bool {
|
||||
last, ok := tc.lastMoveAt[param]
|
||||
return !ok || time.Since(last) >= tuneCooldown
|
||||
}
|
||||
|
||||
func (tc *TuningConfig) markMove(param string) {
|
||||
if tc.lastMoveAt == nil {
|
||||
tc.lastMoveAt = map[string]time.Time{}
|
||||
}
|
||||
tc.lastMoveAt[param] = time.Now()
|
||||
}
|
||||
|
||||
// pushToConsumers 把当前参数推给**真实消费方**。
|
||||
// 🔴 这一步是「调参有没有用」的分水岭:2026-10-14 实测,此前 Tuner 的全部字段
|
||||
// 没有任何读者(全仓只有 3 处路由注册引用它)⇒ 调参改了数字、行为零变化。
|
||||
func (tc *TuningConfig) pushToConsumers() {
|
||||
storage.SetDefaultMMRDiversity(tc.Diversity)
|
||||
selfoptimize.SetGapThreshold(tc.GapThreshold)
|
||||
}
|
||||
|
||||
// tuningStatePath 持久化路径(可用 ZHIYI_TUNING_STATE 覆盖,便于测试/隔离)。
|
||||
func tuningStatePath() string {
|
||||
if p := os.Getenv("ZHIYI_TUNING_STATE"); p != "" {
|
||||
return p
|
||||
}
|
||||
return "/var/lib/memoryweave/tuning-state.json"
|
||||
}
|
||||
|
||||
type tuningState struct {
|
||||
Diversity float64 `json:"diversity"`
|
||||
GapThreshold int `json:"gap_threshold"`
|
||||
LastMoveAt map[string]string `json:"last_move_at"`
|
||||
UpdatedAt string `json:"updated_at"`
|
||||
}
|
||||
|
||||
// persist 落盘(失败只告警,不影响调参本身)。
|
||||
func (tc *TuningConfig) persist() {
|
||||
if !tc.persistEnabled {
|
||||
return
|
||||
}
|
||||
st := tuningState{Diversity: tc.Diversity, GapThreshold: tc.GapThreshold,
|
||||
LastMoveAt: map[string]string{}, UpdatedAt: time.Now().Format(time.RFC3339)}
|
||||
for k, v := range tc.lastMoveAt {
|
||||
st.LastMoveAt[k] = v.Format(time.RFC3339)
|
||||
}
|
||||
data, err := json.MarshalIndent(st, "", " ")
|
||||
if err != nil {
|
||||
log.Printf("[tuning] 序列化失败: %v", err)
|
||||
return
|
||||
}
|
||||
if err := os.WriteFile(tuningStatePath(), data, 0o644); err != nil {
|
||||
log.Printf("[tuning] 落盘失败: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
// load 启动时载入持久化参数(无文件则用默认值),并立即接线到消费方。
|
||||
// 没有这一步,重启即回默认 ⇒ 调参成果每次重启清零。
|
||||
func (tc *TuningConfig) load() {
|
||||
data, err := os.ReadFile(tuningStatePath())
|
||||
if err == nil {
|
||||
var st tuningState
|
||||
if json.Unmarshal(data, &st) == nil {
|
||||
if st.Diversity > 0 {
|
||||
tc.Diversity = st.Diversity
|
||||
}
|
||||
if st.GapThreshold > 0 {
|
||||
tc.GapThreshold = st.GapThreshold
|
||||
}
|
||||
for k, v := range st.LastMoveAt {
|
||||
if t, e := time.Parse(time.RFC3339, v); e == nil {
|
||||
if tc.lastMoveAt == nil {
|
||||
tc.lastMoveAt = map[string]time.Time{}
|
||||
}
|
||||
tc.lastMoveAt[k] = t
|
||||
}
|
||||
}
|
||||
log.Printf("[tuning] 已载入持久化参数 diversity=%.3f gap_threshold=%d(%s)",
|
||||
tc.Diversity, tc.GapThreshold, st.UpdatedAt)
|
||||
}
|
||||
}
|
||||
tc.mu.Lock()
|
||||
tc.pushToConsumers()
|
||||
tc.mu.Unlock()
|
||||
}
|
||||
|
||||
// AutoTune 基于仪表盘指标自动调参
|
||||
func (tc *TuningConfig) AutoTune(metrics map[string]float64) []TuningEvent {
|
||||
tc.mu.Lock()
|
||||
@@ -102,13 +209,17 @@ func (tc *TuningConfig) AutoTune(metrics map[string]float64) []TuningEvent {
|
||||
if !hitOK {
|
||||
note("rule1_hit_rate", "指标不可用(无数据/退化/样本<30)")
|
||||
}
|
||||
if hitOK && hitRate < 0.5 {
|
||||
if hitOK && hitRate < 0.5 && !tc.canMove("diversity") {
|
||||
note("rule1_hit_rate", "冷却中(距上次调整 <"+tuneCooldown.String()+")")
|
||||
}
|
||||
if hitOK && hitRate < 0.5 && tc.canMove("diversity") {
|
||||
newDiversity := tc.Diversity + 0.1
|
||||
if newDiversity > 1.0 {
|
||||
newDiversity = 1.0
|
||||
}
|
||||
events = append(events, recordTuning(tc, "diversity", tc.Diversity, newDiversity, "recall_hit_rate < 0.5"))
|
||||
tc.Diversity = newDiversity
|
||||
tc.markMove("diversity")
|
||||
}
|
||||
|
||||
// 2. 召回有用率 > 0.9 → 降低 diversity(更精准)
|
||||
@@ -116,58 +227,62 @@ func (tc *TuningConfig) AutoTune(metrics map[string]float64) []TuningEvent {
|
||||
if !usefulOK {
|
||||
note("rule2_usefulness", "指标不可用(无数据/退化/样本<30)")
|
||||
}
|
||||
if usefulOK && usefulRate > 0.9 {
|
||||
if usefulOK && usefulRate > 0.9 && !tc.canMove("diversity") {
|
||||
note("rule2_usefulness", "冷却中(距上次调整 <"+tuneCooldown.String()+")")
|
||||
}
|
||||
if usefulOK && usefulRate > 0.9 && tc.canMove("diversity") {
|
||||
newDiversity := tc.Diversity - 0.05
|
||||
if newDiversity < 0.1 {
|
||||
newDiversity = 0.1
|
||||
}
|
||||
events = append(events, recordTuning(tc, "diversity", tc.Diversity, newDiversity, "recall_usefulness_rate > 0.9"))
|
||||
tc.Diversity = newDiversity
|
||||
tc.markMove("diversity")
|
||||
}
|
||||
|
||||
// 3. 废弃率 > 5/day → 提高衰减率(加快清理)
|
||||
if deprecated, ok := metrics["deprecated_per_day"]; ok && deprecated >= 0 && deprecated > 5 {
|
||||
newDecay := tc.DecayRate * 1.2
|
||||
if newDecay > 0.05 {
|
||||
newDecay = 0.05
|
||||
}
|
||||
events = append(events, recordTuning(tc, "decay_rate", tc.DecayRate, newDecay, "deprecated_per_day > 5"))
|
||||
tc.DecayRate = newDecay
|
||||
}
|
||||
// 3.(2026-10-14 移除)废弃率 → 提高衰减率。
|
||||
// 移除理由:这个方向危险。governance.NewForgetter 上方注释记载:
|
||||
// 「2026-09-07 方案A: 0.015→0.03 曾致误删(36天库龄下 0-recall 长记忆全被清, 405字CNB经验被删)」。
|
||||
// 自动调参朝这个方向推 = 把那条事故路重新铺上;而收益只是「加快清理」。
|
||||
// 若要恢复,必须先有「误删可回滚 + 删除前抽样人工确认」的保护,不能只靠阈值。
|
||||
|
||||
// 4. 缺口闭环率 < 0.5 → 降低 gap 阈值
|
||||
gapRate, gapOK := ratioFor(metrics, "gap_closure_rate")
|
||||
if !gapOK {
|
||||
note("rule4_gap_threshold", "指标不可用(无数据/退化/样本<30)")
|
||||
}
|
||||
if gapOK && gapRate < 0.5 {
|
||||
if gapOK && gapRate < 0.5 && !tc.canMove("gap_threshold") {
|
||||
note("rule4_gap_threshold", "冷却中(距上次调整 <"+tuneCooldown.String()+")")
|
||||
}
|
||||
if gapOK && gapRate < 0.5 && tc.canMove("gap_threshold") {
|
||||
newThreshold := tc.GapThreshold - 1
|
||||
if newThreshold < 2 {
|
||||
newThreshold = 2
|
||||
}
|
||||
events = append(events, recordTuningInt(tc, "gap_threshold", tc.GapThreshold, newThreshold, "gap_closure_rate < 0.5"))
|
||||
tc.GapThreshold = newThreshold
|
||||
tc.markMove("gap_threshold")
|
||||
}
|
||||
|
||||
// 5. 蒸馏损失 > 0.3 → 更频繁蒸馏
|
||||
loss, lossOK := ratioFor(metrics, "avg_distill_loss")
|
||||
if !lossOK {
|
||||
note("rule5_distill_interval", "指标不可用(无数据/退化/样本<30)")
|
||||
}
|
||||
if lossOK && loss > 0.3 {
|
||||
newInterval := tc.DistillInterval - 1
|
||||
if newInterval < 1 {
|
||||
newInterval = 1
|
||||
}
|
||||
events = append(events, recordTuningInt(tc, "distill_interval", tc.DistillInterval, newInterval, "avg_distill_loss > 0.3"))
|
||||
tc.DistillInterval = newInterval
|
||||
}
|
||||
// 5.(2026-10-14 移除)蒸馏损失 → 缩短蒸馏间隔。
|
||||
// 移除理由:**没有正确的消费方**。distill/engine.go:265 的 batchTimeout(5min)是
|
||||
// 「队列冻结兜底 ticker」(2026-10-06 修的「生产者停止即永久冻结」安全网),
|
||||
// **不是蒸馏节奏**。调安全网的周期治不了蒸馏质量 —— 接到错的地方比不接更坏。
|
||||
// 若将来真有「蒸馏节奏」消费者,再恢复本规则并接对目标。
|
||||
|
||||
tc.history = append(tc.history, events...)
|
||||
tc.lastSkipped = skipped
|
||||
if len(events) > 0 {
|
||||
tc.pushToConsumers() // 改了就必须接线,否则等于没改
|
||||
tc.persist() // 不落盘则重启即丢
|
||||
}
|
||||
return events
|
||||
}
|
||||
|
||||
// init 启动时载入持久化参数并接线(没有它:重启回默认 + 调参不生效)。
|
||||
func init() { Tuner.load() }
|
||||
|
||||
// LastSkipped 返回上一次调参里被跳过的规则及原因(只读快照)。
|
||||
func (tc *TuningConfig) LastSkipped() []string {
|
||||
tc.mu.RLock()
|
||||
|
||||
@@ -1,6 +1,12 @@
|
||||
package routes
|
||||
|
||||
import "testing"
|
||||
import (
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/xiaoxue/memoryweave/internal/selfoptimize"
|
||||
"github.com/xiaoxue/memoryweave/internal/storage"
|
||||
)
|
||||
|
||||
// TestAutoTuneGuard_SentinelAndSamples 双向验证护栏:
|
||||
// ① 无数据(-1 哨兵)不许改参数 —— 这是事故面:gap_closure_rate=-1 会让
|
||||
@@ -59,3 +65,63 @@ func TestAutoTuneGuard_SentinelAndSamples(t *testing.T) {
|
||||
t.Fatalf("Diversity 应被降低,实际 %v", tc3.Diversity)
|
||||
}
|
||||
}
|
||||
|
||||
// TestAutoTuneCooldown 冷却:同一参数在冷却窗口内不许被重复推进(治棘轮)。
|
||||
// 事故面(实测):AutoTune 不幂等 —— 连跑两次 decay 0.015→0.018→0.0216。
|
||||
func TestAutoTuneCooldown(t *testing.T) {
|
||||
tc := &TuningConfig{Diversity: 0.5, DecayRate: 0.015, GapThreshold: 3, DistillInterval: 5, ConsolidateAfter: 50}
|
||||
m := map[string]float64{
|
||||
"recall_usefulness_rate": 0.95,
|
||||
"recall_usefulness_samples": 100,
|
||||
"recall_usefulness_valid": 1,
|
||||
}
|
||||
if ev := tc.AutoTune(m); len(ev) != 1 {
|
||||
t.Fatalf("第一次应调 1 条,实际 %d", len(ev))
|
||||
}
|
||||
first := tc.Diversity
|
||||
if ev := tc.AutoTune(m); len(ev) != 0 {
|
||||
t.Fatalf("冷却窗口内不应再调,实际 %d 条: %+v", len(ev), ev)
|
||||
}
|
||||
if tc.Diversity != first {
|
||||
t.Fatalf("冷却期内参数被改动:%v → %v(棘轮复发)", first, tc.Diversity)
|
||||
}
|
||||
}
|
||||
|
||||
// TestAutoTunePushesToConsumers 推送:改完参数必须真的到消费方手里,
|
||||
// 否则就是「调参改了没人读的数字」(2026-10-14 实测的原状)。
|
||||
func TestAutoTunePushesToConsumers(t *testing.T) {
|
||||
orig := storage.DefaultMMRDiversity()
|
||||
defer storage.SetDefaultMMRDiversity(orig)
|
||||
tc := &TuningConfig{Diversity: 0.5, GapThreshold: 3}
|
||||
m := map[string]float64{
|
||||
"gap_closure_rate": 0.1,
|
||||
"gap_closure_samples": 100,
|
||||
"gap_closure_valid": 1,
|
||||
}
|
||||
before := selfoptimize.GapThreshold()
|
||||
ev := tc.AutoTune(m)
|
||||
if len(ev) != 1 {
|
||||
t.Fatalf("应触发 1 条(gap 阈值),实际 %d", len(ev))
|
||||
}
|
||||
if tc.GapThreshold != before-1 {
|
||||
t.Fatalf("期望阈值 %d→%d,实际 %d", before, before-1, tc.GapThreshold)
|
||||
}
|
||||
if got := selfoptimize.GapThreshold(); got != tc.GapThreshold {
|
||||
t.Fatalf("没推到消费方:selfoptimize.GapThreshold()=%d,Tuner=%d", got, tc.GapThreshold)
|
||||
}
|
||||
}
|
||||
|
||||
// TestTuningPersistence 持久化:换实例后能从盘上读回(否则重启即回默认)。
|
||||
func TestTuningPersistence(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
t.Setenv("ZHIYI_TUNING_STATE", dir+"/tuning-state.json")
|
||||
|
||||
a := &TuningConfig{Diversity: 0.42, GapThreshold: 4, persistEnabled: true, lastMoveAt: map[string]time.Time{}}
|
||||
a.persist()
|
||||
|
||||
b := &TuningConfig{Diversity: 0.3, GapThreshold: 3, lastMoveAt: map[string]time.Time{}}
|
||||
b.load()
|
||||
if b.Diversity != 0.42 || b.GapThreshold != 4 {
|
||||
t.Fatalf("未读回持久化参数:diversity=%v gap=%v", b.Diversity, b.GapThreshold)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -7,6 +7,7 @@ import (
|
||||
"os"
|
||||
"strconv"
|
||||
"sync"
|
||||
"sync/atomic"
|
||||
"time"
|
||||
|
||||
"github.com/xiaoxue/memoryweave/internal/storage"
|
||||
@@ -317,7 +318,7 @@ func (d *Dashboard) Metrics() map[string]float64 {
|
||||
|
||||
"deprecated_per_day": float64(d.DeprecatedToday),
|
||||
|
||||
"distill_success_count": float64(d.DistillSuccessCount),
|
||||
"distill_success_count": float64(d.DistillSuccessCount),
|
||||
"avg_distill_loss": avgLoss,
|
||||
"avg_distill_loss_samples": float64(d.DistillLossCount),
|
||||
"avg_distill_loss_valid": b2f(d.DistillLossCount > 0),
|
||||
@@ -481,13 +482,33 @@ func NewGapDetector(emb *storage.Embedder, ldb storage.LanceDB) *GapDetector {
|
||||
}
|
||||
|
||||
// RecordMiss 记录一次召回失败
|
||||
// gapThreshold 是「同一 topic 累计几次 miss 才生成 gap」的阈值。
|
||||
// 由 routes 的调参器经 SetGapThreshold 推送;安全边界 [2,10]:
|
||||
// 下界 2 防「一次偶然即成缺口」把缺口表灌爆,上界 10 防阈值大到永不生成(闭环静默死掉)。
|
||||
var gapThreshold atomic.Int64
|
||||
|
||||
func init() { gapThreshold.Store(3) }
|
||||
|
||||
// SetGapThreshold 由调参器推送新的缺口阈值(越界值一律忽略)。
|
||||
func SetGapThreshold(n int) {
|
||||
if n < 2 || n > 10 {
|
||||
return
|
||||
}
|
||||
gapThreshold.Store(int64(n))
|
||||
}
|
||||
|
||||
// GapThreshold 返回当前缺口阈值。
|
||||
func GapThreshold() int { return int(gapThreshold.Load()) }
|
||||
|
||||
func (gd *GapDetector) RecordMiss(topic string) *Gap {
|
||||
gd.mu.Lock()
|
||||
defer gd.mu.Unlock()
|
||||
|
||||
gd.misses[topic]++
|
||||
gd.persistMisses()
|
||||
if gd.misses[topic] >= 3 {
|
||||
// 2026-10-14:阈值改读调参器推送值(默认 3,与原硬编码一致 ⇒ 行为不变)。
|
||||
// 此前 Tuner.GapThreshold 没有任何读者 ⇒ 调参改了也不生效。
|
||||
if gd.misses[topic] >= GapThreshold() {
|
||||
if _, exists := gd.gaps[topic]; !exists {
|
||||
gap := &Gap{
|
||||
Topic: topic,
|
||||
|
||||
@@ -9,6 +9,7 @@ import (
|
||||
"os"
|
||||
"strconv"
|
||||
"strings"
|
||||
"sync/atomic"
|
||||
"time"
|
||||
|
||||
"github.com/xiaoxue/memoryweave/internal/models"
|
||||
@@ -229,6 +230,31 @@ type RecallMeta struct {
|
||||
|
||||
// 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
|
||||
}
|
||||
|
||||
func (p *RecallPipeline) RecallWithMeta(query, namespace string, topK int, diversity float64) ([]models.RecallResult, RecallMeta, error) {
|
||||
// topK 先归一:缓存键必须与写入侧用的 topK 一致。recallUncached 内部也会归一,
|
||||
// 若此处不先归一,topK<=0 的调用读到的是"归一前的键"、永远命中不了自己写的条目。
|
||||
@@ -553,22 +579,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,
|
||||
// 2026-10-13 (t_e9a4d18f P0):过期标记(默认关闭 ⇒ 恒 false 不输出)
|
||||
Stale: isStale(c.UpdatedAt, staleAfterHours),
|
||||
})
|
||||
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),
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
Reference in New Issue
Block a user