Files
memoryweave/go/internal/storage/standing_match.go
T
小唯 ff92b0578a feat(standing): 程序性记忆层步骤卡 schema + trigger 变体召回,命中即短路 (t_3636b872)
阶段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 三连复现
2026-10-28 07:05:08 +08:00

227 lines
7.3 KiB
Go
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
package storage
import (
"log"
"os"
"strings"
"sync"
"sync/atomic"
"time"
"unicode"
"github.com/xiaoxue/memoryweave/internal/models"
)
// 2026-10-25 (t_standing_recall) 常设答案 · 召回前置通道。
//
// 背景(实测,53 条真实提问基线):correct@1 = 20.8%,useful@5 = 88.7%;
// 6 条"完全跑偏"案例里 5 条的目标文档**根本不在向量 top-50 里**——不是排序问题,
// 是语义通道对"精确事实类"提问(端口/数字/标识符/专名)天然够不着。
// 故补一条**零检索、零 LLM**的精确通道:查询命中常设答案 → 直接置顶。
//
// 与既有 FTS 通道的区别:
// · FTS(t_2afae95e)只给尾部保证位,救不了 correct@1;
// · 本通道置顶,只匹配"已定型的精确事实",不做泛化,故误召回代价低(答错比答不上更糟,
// 所以阈值取保守值 + 只在环境开关开启时生效)。
//
// 开关:ZHIYI_STANDING_ANSWER=1 才生效(默认关 = 与旧行为逐位一致,便于 A/B 与一行回滚)。
// 回滚:删 drop-in 里该变量 + daemon-reload + restart。
// StandingAnswerEnabled 常设答案通道是否启用(默认关)。
func StandingAnswerEnabled() bool {
return os.Getenv("ZHIYI_STANDING_ANSWER") == "1"
}
// nearMissLogThreshold 近似命中日志阈值(**只用于日志**,不参与是否返回的决策)。
// 取 0.78:近似到这个程度说明"很像同一句但不是",正是该补 question 变体的信号。
const nearMissLogThreshold = 0.78
var (
standingCacheMu sync.RWMutex
standingCache []StandingAnswer
standingCacheAt time.Time
standingCacheTTL = 30 * time.Second
standingLookupHit atomic.Int64 // 观测:通道命中次数(/health 或日志复用)
)
// LookupStandingHitCount 返回本进程启动以来常设答案命中次数(观测用)。
func LookupStandingHitCount() int64 { return standingLookupHit.Load() }
// standingAnswerFor 若常设答案精确通道命中则返回该答案,否则 nil(零检索零 LLM)。
// 命中口径 = 归一化后整句相等(question + op.trigger 变体),变体是人工写入的精确问法,
// 无模糊面 ⇒ 可安全作为短路的唯一依据。
func standingAnswerFor(query string) *StandingAnswer {
if !StandingAnswerEnabled() {
return nil
}
return LookupStandingAnswer(query)
}
// refreshStandingAnswers 丢弃常设答案缓存,让下一次召回重新读库。
// 写入(Upsert)后必须调用,否则新卡/改卡在 standingCacheTTL 内对召回不可见。
func refreshStandingAnswers() {
standingCacheMu.Lock()
standingCache = nil
standingCacheAt = time.Time{}
standingCacheMu.Unlock()
}
// normalizeForMatch 归一化:小写 + 去掉所有非字母数字/非 CJK 字符(空格、标点、符号)。
func normalizeForMatch(s string) string {
var b strings.Builder
b.Grow(len(s))
for _, r := range strings.ToLower(s) {
if unicode.IsLetter(r) || unicode.IsDigit(r) {
b.WriteRune(r)
}
}
return b.String()
}
// bigrams 生成字符二元组集合(CJK 与拉丁一视同仁;长度 <2 时退化为单字符集合)。
func bigrams(s string) map[string]struct{} {
rs := []rune(s)
out := make(map[string]struct{}, len(rs))
if len(rs) < 2 {
if len(rs) == 1 {
out[string(rs)] = struct{}{}
}
return out
}
for i := 0; i+1 < len(rs); i++ {
out[string(rs[i:i+2])] = struct{}{}
}
return out
}
// diceSimilarity 字符二元组 Dice 系数(0..1)。
func diceSimilarity(a, b string) float64 {
if a == "" || b == "" {
return 0
}
if a == b {
return 1
}
ba, bb := bigrams(a), bigrams(b)
if len(ba) == 0 || len(bb) == 0 {
return 0
}
inter := 0
for g := range ba {
if _, ok := bb[g]; ok {
inter++
}
}
return 2 * float64(inter) / float64(len(ba)+len(bb))
}
// loadStandingAnswers 带 TTL 的常设答案快照(表极小,全量读;30s 内复用,避免热路径频繁查库)。
func loadStandingAnswers() []StandingAnswer {
standingCacheMu.RLock()
if time.Since(standingCacheAt) < standingCacheTTL {
cached := standingCache
standingCacheMu.RUnlock()
return cached
}
standingCacheMu.RUnlock()
standingCacheMu.Lock()
defer standingCacheMu.Unlock()
if time.Since(standingCacheAt) < standingCacheTTL { // 双检:并发下只读一次库
return standingCache
}
store := StandingStoreInstance
if store == nil {
return nil // 未初始化:通道静默失效,不影响召回
}
all, err := store.List()
if err != nil {
return standingCache
}
standingCache = all
standingCacheAt = time.Now()
return all
}
// LookupStandingAnswer 返回与 query 严格匹配的常设答案;无匹配返回 nil。
//
// 匹配口径 = **归一化后完全相等**(2026-10-25 实测修正):
// 先前用 bigram Dice 模糊匹配(阈值 0.78),上线后留出集立刻抓到真实误命中——
// 「织忆的服务跑在哪个端口」被判为「出图的服务跑在哪个端口」的匹配(仅主语两字之差,
// Dice≈0.82),把 ComfyUI 的 8188 当成织忆端口置顶。模板句 + 换主语 = 必错。
// 结论:常设答案只认**同一句话**;同义问法靠多行变体(question_id 不同)覆盖。
// 近似命中(Dice ≥ nearMissLogThreshold)只打日志不返回,用来发现该补哪些变体。
//
// 2026-10-28 (t_3636b872):若常设答案带 op 结构卡,则其 op.trigger 变体也参与
// **归一化后完全相等**匹配——变体是人工/脚本写入的精确问法(含评测集真实提问措辞),
// 与 question 同等可信,无谓词注入面 ⇒ 不引入 fuzzy 误命中。card_trigger_match 标出命中路径。
func LookupStandingAnswer(query string) *StandingAnswer {
q := normalizeForMatch(query)
if len([]rune(q)) < 2 {
return nil
}
all := loadStandingAnswers()
if len(all) == 0 {
return nil
}
var near *StandingAnswer
nearScore := 0.0
for i := range all {
a := &all[i]
cand := normalizeForMatch(a.Question)
if cand != "" {
if cand == q {
return a
}
if s := diceSimilarity(q, cand); s > nearScore {
nearScore = s
near = a
}
}
// op 结构卡的 trigger 变体:归一化后完全相等也算命中(提示词精确句)。
if a.Op != nil {
for _, t := range a.Op.Trigger {
tn := normalizeForMatch(t)
if tn != "" && tn == q {
return a
}
}
}
}
// 近似但不等:只记日志(便于补变体),绝不返回——错答比不答更贵。
if near != nil && nearScore >= nearMissLogThreshold {
log.Printf("[standing] near-miss %.2f(不返回)query=%q 最接近=%q id=%s",
nearScore, query, near.Question, near.QuestionID)
}
return nil
}
// PrependStandingAnswer 把常设答案置顶注入召回结果(去重 + 遵守 topK)。
func PrependStandingAnswer(results []models.RecallResult, sa *StandingAnswer, topK int) []models.RecallResult {
if sa == nil {
return results
}
id := "standing:" + sa.QuestionID
out := make([]models.RecallResult, 0, len(results)+1)
out = append(out, models.RecallResult{
ID: id,
Content: sa.Answer,
Category: "standing_answer",
Score: 1.0,
Timestamp: sa.UpdatedAt.Format(time.RFC3339),
Source: "standing_answer",
Channel: "standing",
})
for _, r := range results {
if r.ID == id {
continue
}
out = append(out, r)
}
if topK > 0 && len(out) > topK {
out = out[:topK]
}
standingLookupHit.Add(1)
return out
}