ga-meta-1b-3 t_1c12e000: 缓存失效写路径收口——TTL 1h→60s + 蒸馏/merge 落库后 Invalidate + recall 响应 cache_hit + cache/stats 暴露 search_cache 计数

This commit is contained in:
小唯
2026-10-13 01:38:11 +08:00
parent ba81121efa
commit 5b9f75cc7f
5 changed files with 329 additions and 18 deletions
+26 -3
View File
@@ -278,6 +278,11 @@ func (a *API) mergeMemory(existing models.MemoryRecord, newContent, newCategory,
"updated_at": existing.UpdatedAt.Format(time.RFC3339),
"content": existing.Content,
})
// t_1c12e000:merge 直接改 memories 表(content/version)⇒ 该 namespace 的
// query 缓存读到的是合并前旧内容 ⇒ 失效(与蒸馏落库失效同一原则:写 memories 必失效)。
if storage.SearchCacheInstance != nil && existing.Namespace != "" {
storage.SearchCacheInstance.Invalidate(existing.Namespace)
}
}
// cosineSimilarity 计算两个向量的余弦相似度
@@ -361,6 +366,9 @@ func (a *API) Recall(w http.ResponseWriter, r *http.Request) {
var results []models.RecallResult
var err error
// t_1c12e000:cache_hit 显式标注——缓存命中(candidates_scanned=0 是「读旧快照」
// 而非「真没扫到」)与回源扫表必须可区分。
cacheHit := false
// t_2d4e3b92 引入 + t_a70b07e1 语义修订 + t_949840b1 名实相符:
// annScanned = 主路径(Pipeline.Recall / graph 兜底)粗检索候选池真实大小
// (LanceDB ANN 返回 + 去重 + 原始对话过滤之后、rerank/MMR 截断之前捕获)。
@@ -378,7 +386,10 @@ func (a *API) Recall(w http.ResponseWriter, r *http.Request) {
// Pure keyword search: LanceDB + BM25 re-rank, or graph.db fallback
// t_2d4e3b92: keyword 主路径依赖向量编码;编码失败(依赖不可用)⇒ 非 2xx,
// 不再把错误伪装成 200 + 错误体。
kwResults, kwErr := a.Pipeline.Recall(req.Query, req.Namespace, req.Limit, req.Diversity)
// t_1c12e000:keyword 路径同样收进 RecallWithMeta(Pipeline.Recall 内部
// 走同一缓存键),只为把 cache_hit 带回响应——旧版用 Recall 丢掉了 meta。
var kwMeta storage.RecallMeta
kwResults, kwMeta, kwErr := a.Pipeline.RecallWithMeta(req.Query, req.Namespace, req.Limit, req.Diversity)
if kwErr != nil {
// 主路径硬错误(向量编码/rerank 依赖不可用):即便兜底能补结果,也按 502 上报,
// 调用方据此走失败路径而不是把依赖故障误判成"无匹配"
@@ -387,13 +398,17 @@ func (a *API) Recall(w http.ResponseWriter, r *http.Request) {
log.Printf("[recall:keyword] failed: %v", kwErr)
return
}
cacheHit = kwMeta.CacheHit
if len(kwResults) == 0 {
// 真无匹配(正常业务):成功 schema,results=[] + candidates_scanned 供区分
fallbackResults := a.GraphStore.FallbackTextSearch(req.Query, req.Namespace, req.Limit)
results = convertFallbackResults(fallbackResults)
respond(w, 200, map[string]interface{}{
"results": results, "count": len(results), "mode": "keyword",
"results": results,
"count": len(results),
"candidates_scanned": 0, // keyword 路径未做 ANN 扫描
"mode": "keyword",
"cache_hit": false, // graph 兜底结果不来自 search cache
})
return
}
@@ -406,8 +421,9 @@ 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 时显式标注
})
return
case "semantic":
@@ -416,11 +432,13 @@ func (a *API) Recall(w http.ResponseWriter, r *http.Request) {
var meta storage.RecallMeta
results, meta, err = a.Pipeline.RecallWithMeta(req.Query, req.Namespace, req.Limit, req.Diversity)
annScanned = meta.CandidatesScanned
cacheHit = meta.CacheHit // t_1c12e000
case "hybrid":
// BM25 + vector combined (H1: BM25 scoring inside Pipeline.Recall)
var meta storage.RecallMeta
results, meta, err = a.Pipeline.RecallWithMeta(req.Query, req.Namespace, req.Limit, req.Diversity)
annScanned = meta.CandidatesScanned
cacheHit = meta.CacheHit // t_1c12e000
}
if err != nil {
// P0: 降级到 graph.db 关键词搜索(仅 hybrid/semantic 主路径依赖向量/rerank)
@@ -428,6 +446,7 @@ func (a *API) Recall(w http.ResponseWriter, r *http.Request) {
if len(fallbackResults) > 0 {
results = convertFallbackResults(fallbackResults)
annScanned = len(fallbackResults)
cacheHit = false // t_1c12e000:graph 兜底结果不来自 search cache
w.Header().Set("X-Fallback", "graph")
} else {
// t_2d4e3b92: 主路径与兜底都失败 ⇒ 非 2xx + 统一错误体(绝不在 200 里塞错误)
@@ -546,6 +565,10 @@ func (a *API) Recall(w http.ResponseWriter, r *http.Request) {
"count": len(results),
"candidates_scanned": annScanned,
"mode": req.Mode,
// t_1c12e000:AC3 —— 缓存命中/回源扫表必须可区分。
// true ⇒ candidates_scanned=0 是「读了 60s 内的旧快照」(含 L1/L2);
// false ⇒ 本次真扫了表(candidates_scanned 为真实候选池大小)。
"cache_hit": cacheHit,
})
// H3: Async trust score update
+25 -7
View File
@@ -178,6 +178,10 @@ func NewServer() http.Handler {
// 回写蒸馏产物到记忆库(LanceDB)
// 2026-09-07 方案B 质量门槛: 碎片(<20字)/噪声句(状态汇报/桥接/reflection)不入库,
// 与已有记忆完全重复跳过(蒸馏直写不走 commit exact_dup, 需本层查重)。
// 2026-10-13 t_1c12e000:distilled facts 是 memories 表的唯一写入点。
// 只要有任何一条真的 InsertMemory 成功 ⇒ 该 namespace 的 query 缓存作废
//("先写再问" 场景:写完之后立刻可被之前问过但当时还没内容的答案命中)。
factsLanded := false
for _, fact := range result.Facts {
// 2026-09-10 P0:直写路径同样脱敏(这里绕过 FilterQualityFacts,
// 事故里泄漏进镜像的记忆正是从这条路径入库的)。
@@ -228,8 +232,18 @@ func NewServer() http.Handler {
log.Printf("[srcprobe] 蒸馏落库 episode=%s input.Source=%q → mem.Source=%q", input.EpisodeID, input.Source, mem.Source)
if err := ldb.InsertMemory(mem); err != nil {
log.Printf("[distill] commit fact failed: %v", err)
} else {
factsLanded = true // t_1c12e000:确有 distilled fact 落库
}
}
// t_1c12e000:写路径缓存失效(方案 A)——distilled facts 是 memories 唯一写点。
// 本进程 Invalidate(ns) 清 L1+L2;跨 Agent 广播复用 commit handler 的
// PushCacheInvalidate(已注册 cache.invalidate 订阅),此处不重复广播。
if factsLanded && storage.SearchCacheInstance != nil {
storage.SearchCacheInstance.Invalidate(input.Namespace)
log.Printf("[cache] 蒸馏落库后失效 namespace=%s(%d 条 facts,episode=%s)",
input.Namespace, len(result.Facts), input.EpisodeID)
}
// 冲突检测:加载已有记忆进行比较
// 必须用**新内容的真实向量**做语义检索取近邻;用零向量在语义索引上
// 返回的只是"范数最小"的任意行,真正的矛盾对象不在比对集里 → 永远检不出冲突。
@@ -346,15 +360,19 @@ func NewServer() http.Handler {
mux.HandleFunc("/health", routes.HandleHealth)
mux.HandleFunc("/api/v1/health", routes.HandleHealth)
// 图谱缓存统计
// 图谱缓存统计 + 搜索缓存统计(t_1c12e000:并入 search_cache 段,
// 暴露 hits/misses/invalidated/size/ttl,写频对命中率的影响可观测)
mux.HandleFunc("/api/v1/cache/stats", func(w http.ResponseWriter, r *http.Request) {
if cachedGraphStoreRef != nil {
respondJSON(w, 200, map[string]interface{}{
"graph_cache": cachedGraphStoreRef.Stats(),
})
} else {
respondJSON(w, 200, map[string]interface{}{"graph_cache": nil})
resp := map[string]interface{}{
"graph_cache": nil,
}
if cachedGraphStoreRef != nil {
resp["graph_cache"] = cachedGraphStoreRef.Stats()
}
if storage.SearchCacheInstance != nil {
resp["search_cache"] = storage.SearchCacheInstance.Stats()
}
respondJSON(w, 200, resp)
})
// ─── Prometheus /metrics ─────────────────────
mux.Handle("/metrics", metrics.Handler())
+10 -2
View File
@@ -107,11 +107,18 @@ var qstrustVerbose = os.Getenv("ZHIYI_QSTRUST_VERBOSE") == "1"
// 原始对话过滤之后的候选数,在 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,但额外返回召回元数据(候选池真实大小)。
// RecallWithMeta 同 Recall,但额外返回召回元数据(候选池真实大小 + 是否命中缓存)。
// 缓存命中时无法重建候选池 ⇒ CandidatesScanned = 0(保守:无法测量就报 0,不虚报)。
func (p *RecallPipeline) RecallWithMeta(query, namespace string, topK int, diversity float64) ([]models.RecallResult, RecallMeta, error) {
// topK 先归一:缓存键必须与写入侧用的 topK 一致。recallUncached 内部也会归一,
@@ -129,7 +136,8 @@ func (p *RecallPipeline) RecallWithMeta(query, namespace string, topK int, diver
filtered = results
}
p.recordRecallWrites(filtered)
return filtered, RecallMeta{}, nil
// t_1c12e000:命中缓存 ⇒ 显式告知调用方(candidates_scanned 恒 0)
return filtered, RecallMeta{CacheHit: true}, nil
}
}
}
+37 -6
View File
@@ -62,7 +62,10 @@ var (
func getRedisCacheInstance() *RedisCache {
redisCacheOnce.Do(func() {
redisCacheInstance = NewRedisCache(1 * time.Hour)
// 2026-10-13 t_1c12e000:L2 TTL 与 L1 同步 60s。
// 只改 L1 不改 L2 ⇒ L2 里 1h 的陈旧快照会在 L1 重建(重启/驱逐回填
// 重置 CreatedAt=now)后继续续命 1h ⇒ 写后盲区的陈旧窗口仍远超 60s。
redisCacheInstance = NewRedisCache(60 * time.Second)
})
return redisCacheInstance
}
@@ -76,6 +79,10 @@ type SearchCache struct {
maxSize int
ttl time.Duration
l2 L2CacheBackend // 可选 L2 缓存(Redis),nil 时只有 L1
// 2026-10-13 t_1c12e000:命中/未命中/失效计数(mu 保护下自增,Stats 在 RLock 下读取)。
hits uint64
misses uint64
invalidated uint64
}
type CacheEntry struct {
@@ -123,6 +130,7 @@ func (sc *SearchCache) Get(query, namespace string, topK int, diversity float64)
if ok && time.Since(entry.CreatedAt) <= sc.ttl {
sc.mu.Lock()
entry.Hits++
sc.hits++ // t_1c12e000:命中计数(L1 命中)
sc.mu.Unlock()
return entry.Results, true
}
@@ -141,11 +149,16 @@ func (sc *SearchCache) Get(query, namespace string, topK int, diversity float64)
CreatedAt: time.Now(),
Hits: 1,
}
sc.hits++ // t_1c12e000:L2 命中(回填 L1)也计为命中
sc.mu.Unlock()
return data, true
}
}
// 两级全 miss
sc.mu.Lock()
sc.misses++ // t_1c12e000:未命中计数(走回源扫表)
sc.mu.Unlock()
return nil, false
}
@@ -183,10 +196,14 @@ func (sc *SearchCache) Stats() map[string]interface{} {
sc.mu.RLock()
defer sc.mu.RUnlock()
return map[string]interface{}{
"size": len(sc.entries),
"max_size": sc.maxSize,
"ttl": sc.ttl.String(),
"l2_enabled": sc.l2 != nil,
"size": len(sc.entries),
"max_size": sc.maxSize,
"ttl": sc.ttl.String(),
"l2_enabled": sc.l2 != nil,
// t_1c12e000:命中/未命中/失效计数(命中率 = hits/(hits+misses),写频影响可观测)
"hits": sc.hits,
"misses": sc.misses,
"invalidated": sc.invalidated,
}
}
@@ -200,11 +217,16 @@ func (sc *SearchCache) Stats() map[string]interface{} {
func (sc *SearchCache) Invalidate(namespace string) {
prefix := cacheKeyNSPrefix(namespace)
sc.mu.Lock()
removed := 0
for key := range sc.entries {
if strings.HasPrefix(key, prefix) {
delete(sc.entries, key)
removed++
}
}
if removed > 0 {
sc.invalidated += uint64(removed) // t_1c12e000:失效计数(写路径失效的量可观测)
}
sc.mu.Unlock()
if sc.l2 != nil {
sc.l2.DelPrefix(prefix)
@@ -215,11 +237,16 @@ func (sc *SearchCache) Invalidate(namespace string) {
func (sc *SearchCache) InvalidateKey(query, namespace string) {
prefix := cacheKeyQueryPrefix(query, namespace)
sc.mu.Lock()
removed := 0
for key := range sc.entries {
if strings.HasPrefix(key, prefix) {
delete(sc.entries, key)
removed++
}
}
if removed > 0 {
sc.invalidated += uint64(removed)
}
sc.mu.Unlock()
if sc.l2 != nil {
sc.l2.DelPrefix(prefix)
@@ -281,5 +308,9 @@ func cacheKeyQueryPrefix(query, namespace string) string {
var SearchCacheInstance *SearchCache
func init() {
SearchCacheInstance = NewSearchCacheWithRedis(1000, 1*time.Hour)
// 2026-10-13 t_1c12e000:TTL 1h → 60s(陈旧窗口上限)。
// 写路径(commit→蒸馏→落库)已加 Invalidate(方案 A),60s 是双保险:
// 任何**漏网**写点(新调用方/异常路径)最多让同一 query 读 60s 旧快照,
// 而不是 1h。命中率代价由 Stats() 的 hits/misses 观测后再决定是否收窄。
SearchCacheInstance = NewSearchCacheWithRedis(1000, 60*time.Second)
}
@@ -0,0 +1,231 @@
package storage
import (
"strings"
"testing"
"time"
"github.com/xiaoxue/memoryweave/internal/models"
)
// ─── t_1c12e000:写路径缓存失效 + cache_hit + TTL60s ──────────────────
// 复现本卡「先 query(当时没内容/旧内容)→ commit 落库新内容 → 同 query 再问」
// 的「写后立即读」场景:落库方(server.go OnDistillComplete)对 namespace 调
// Invalidate 后,同一 query 必须回源扫表(CacheHit=false、candidates_scanned>0),
// 不再读旧快照。
// invalidatingLance 记录 Search 调用次数(=回源次数)与命中的行。
type invalidatingLance struct {
LanceDB
Rows []models.MemoryRecord
Searches int
}
func (f *invalidatingLance) Search(table string, vector []float32, topK int, namespaceFilter string) ([]models.MemoryRecord, error) {
f.Searches++
return f.Rows, nil
}
// Update 覆写:后台 goroutine 回写 recall_count 若不覆写会落到 nil 接口 panic(同 nsRecordingLance)。
func (f *invalidatingLance) Update(table, id string, fields map[string]any) error { return nil }
// fakeL2 L2CacheBackend 假实现:记录 DelPrefix 调用,验证 Invalidate 会同步清 L2。
type fakeL2 struct {
data map[string][]byte
delPrefixes []string
}
func (f *fakeL2) Get(key string) ([]byte, bool) { v, ok := f.data[key]; return v, ok }
func (f *fakeL2) Set(key string, data []byte, ttl time.Duration) {
f.data[key] = data
}
func (f *fakeL2) Del(key string) { delete(f.data, key) }
func (f *fakeL2) DelPrefix(prefix string) int {
f.delPrefixes = append(f.delPrefixes, prefix)
n := 0
for k := range f.data {
if strings.HasPrefix(k, prefix) {
delete(f.data, k)
n++
}
}
return n
}
const waQuery = "write-then-read 探针 query t1c12e000"
// newWAPipeline 构造带 L2(fakeL2)的 SearchCache 的 RecallPipeline(隔离进程级单例)。
func newWAPipeline(t *testing.T, fake *invalidatingLance) *RecallPipeline {
t.Helper()
savedInst := SearchCacheInstance
SearchCacheInstance = NewSearchCacheWithRedisForTest(100, 60*time.Second, &fakeL2{data: map[string][]byte{}})
t.Cleanup(func() { SearchCacheInstance = savedInst })
emb := &Embedder{endpoint: "http://127.0.0.1:1/never", dim: 1024}
vec := make([]float32, 1024)
for i := range vec {
vec[i] = 0.01
}
emb.cache.Store(waQuery, vec)
return NewRecallPipeline(emb, fake, &Reranker{})
}
// TestWriteAfterRead_InvalidateBreaksStale(AC1/AC4 核心):
// ① 旧行在库 → query(回源+写缓存)
// ② 同 query 再问 → 命中缓存(CacheHit=true、candidates_scanned=0)——事故里被读旧快照的形态
// ③ 模拟落库:新行入库 + Invalidate(ns)(server.go OnDistillComplete 新行为)
// ④ 同 query 再问 → 必须回源(CacheHit=false)且看到新行。
func TestWriteAfterRead_InvalidateBreaksStale(t *testing.T) {
fake := &invalidatingLance{Rows: []models.MemoryRecord{
{ID: "mem_old", Content: "旧事实:写之前问到的答案", Category: "distilled"},
}}
p := newWAPipeline(t, fake)
// 阶段 1:query → 回源扫表(有旧行)
res1, meta1, err := p.RecallWithMeta(waQuery, "hermes-main", 5, 0.3)
if err != nil {
t.Fatalf("阶段1 出错: %v", err)
}
if meta1.CacheHit {
t.Fatal("阶段1 首次 query 应回源扫表(CacheHit=false),不应命中缓存")
}
if len(res1) == 0 {
t.Fatal("阶段1 应有旧行结果")
}
// 阶段 2:同 query 再问 → 命中缓存(不扫表)——这就是「写后盲区」的被读旧快照形态
_, meta2, err := p.RecallWithMeta(waQuery, "hermes-main", 5, 0.3)
if err != nil {
t.Fatalf("阶段2 出错: %v", err)
}
if !meta2.CacheHit {
t.Fatal("阶段2 应立即命中缓存(CacheHit=true)——写缓存机制未生效")
}
if meta2.CandidatesScanned != 0 {
t.Errorf("缓存命中时 candidates_scanned 应恒 0(不重建候选池),实际 %d", meta2.CandidatesScanned)
}
// 阶段 3:模拟落库(server.go OnDistillComplete 的新行为):新行入库 + Invalidate(ns)
fake.Rows = append(fake.Rows, models.MemoryRecord{
ID: "mem_new", Content: "新事实:写后立即可读的蒸馏产物", Category: "distilled",
})
SearchCacheInstance.Invalidate("hermes-main")
// 阶段 4:同 query 再问 → 必须回源扫表、看到新行
res4, meta4, err := p.RecallWithMeta(waQuery, "hermes-main", 5, 0.3)
if err != nil {
t.Fatalf("阶段4 出错: %v", err)
}
if meta4.CacheHit {
t.Fatal("Invalidate 后同 query 仍命中缓存 ⇒ 写后盲区未堵")
}
if fake.Searches < 3 {
t.Errorf("Invalidate 后应触发第 3 次回源扫表,实际 Search 共 %d 次", fake.Searches)
}
found := false
for _, r := range res4 {
if r.ID == "mem_new" {
found = true
}
}
if !found {
t.Fatalf("写后立刻读应看到新行 mem_new(%d 条结果)", len(res4))
}
}
// TestRecallCacheHitFlagFreshPath:回源扫表路径 CacheHit=false 且候选池真实大小如实上报。
func TestRecallCacheHitFlagFreshPath(t *testing.T) {
fake := &invalidatingLance{Rows: []models.MemoryRecord{
{ID: "m1", Content: "记忆 A 蒸馏事实", Category: "distilled"},
}}
p := newWAPipeline(t, fake)
_, meta, err := p.RecallWithMeta(waQuery, "wiki", 5, 0.3)
if err != nil {
t.Fatalf("出错: %v", err)
}
if meta.CacheHit {
t.Error("首次 query 不应命中缓存")
}
if meta.CandidatesScanned < 1 {
t.Errorf("回源路径 candidates_scanned 应≥1(粗检索池真实大小),实际 %d", meta.CandidatesScanned)
}
}
// TestSearchCacheStatsCounters:Stats 暴露 hits/misses/invalidated(cache/stats 端点数据源)+ TTL=60s。
func TestSearchCacheStatsCounters(t *testing.T) {
c := NewSearchCache(100, 60*time.Second)
c.Set("q", "ns", 5, 0.3, mustResults(2))
c.Get("q", "ns", 5, 0.3) // hit
c.Get("q2", "ns", 5, 0.3) // miss(未 Set 过)
c.Invalidate("ns") // invalidated=1
st := c.Stats()
if st["hits"].(uint64) != 1 {
t.Errorf("hits=%v want 1", st["hits"])
}
if st["misses"].(uint64) != 1 {
t.Errorf("misses=%v want 1", st["misses"])
}
if st["invalidated"].(uint64) != 1 {
t.Errorf("invalidated=%v want 1", st["invalidated"])
}
// TTL 必须 60s(方案 B):陈旧窗口上限
if st["ttl"].(string) != "1m0s" {
t.Errorf("ttl=%v want 1m0s(60s 陈旧窗口上限)", st["ttl"])
}
}
// TestSearchCacheTTL60sExpiry:TTL 60s 内有效、过 60s 即失效(陈旧窗口机械判据)。
func TestSearchCacheTTL60sExpiry(t *testing.T) {
c := NewSearchCache(100, 60*time.Second)
c.Set("q", "ns", 5, 0.3, mustResults(1))
if _, ok := c.Get("q", "ns", 5, 0.3); !ok {
t.Fatal("TTL 内应命中")
}
// 手工把 CreatedAt 拨到 61s 前 ⇒ 必失效
c.mu.Lock()
for k := range c.entries {
c.entries[k].CreatedAt = time.Now().Add(-61 * time.Second)
}
c.mu.Unlock()
if _, ok := c.Get("q", "ns", 5, 0.3); ok {
t.Error("超过 60s TTL 仍命中 ⇒ 陈旧窗口 >60s")
}
}
// TestGlobalInstanceTTLIs60s:全局单例 TTL 就是 60s(防止有人把 init 改回 1h 后测试静默全绿)。
func TestGlobalInstanceTTLIs60s(t *testing.T) {
if SearchCacheInstance == nil {
t.Fatal("SearchCacheInstance 未初始化")
}
if SearchCacheInstance.ttl != 60*time.Second {
t.Errorf("全局缓存 TTL=%v want 60s(1h 盲区复现形态)", SearchCacheInstance.ttl)
}
}
// TestInvalidateClearsL2:L2 里的同名键必须随 Invalidate 一起删掉——
// 只清 L1 不清 L2 ⇒ 进程重启/驱逐回填时旧快照复活(1h 盲区续命的另一条路)。
func TestInvalidateClearsL2(t *testing.T) {
l2 := &fakeL2{data: map[string][]byte{}}
c := NewSearchCacheWithRedisForTest(100, 60*time.Second, l2)
c.Set("q", "hermes-main", 5, 0.3, mustResults(1))
if len(l2.data) == 0 {
t.Fatal("Set 后 L2 应有键")
}
prefix := cacheKeyNSPrefix("hermes-main")
for k := range l2.data {
if !strings.HasPrefix(k, prefix) {
t.Fatalf("L2 键 %q 不在 hermes-main 前缀下", k)
}
}
c.Invalidate("hermes-main")
if len(l2.data) != 0 {
t.Errorf("Invalidate 后 L2 仍残留 %d 键", len(l2.data))
}
if len(l2.delPrefixes) != 1 || l2.delPrefixes[0] != prefix {
t.Errorf("Invalidate 应按前缀 DelPrefix(%q),实际 %v", prefix, l2.delPrefixes)
}
}
// NewSearchCacheWithRedisForTest 供测试注入自定义 L2(导出仅为测试可达性;生产走包内 &redisL2Adapter{})。
func NewSearchCacheWithRedisForTest(maxSize int, ttl time.Duration, l2 L2CacheBackend) *SearchCache {
return newSearchCache(maxSize, ttl, l2)
}