fix(recall): 默认调用改全库跨命名空间召回(t_24eceed0 返修)

病根:纺忆写入侧按 agent/域把记忆分到 19 个命名空间(实测 300 采样:
hermes-main 139、wiki-curator-main 35、wiki 30、shared 29、soulful-xiaowei 27、
a06-main 11、domain:* 13…),而默认调用(无 namespace / 无 agent_id)
被推导成 default-main ⇒ 只搜 default-main+shared,全表 10172 条实测仅得 11 个候选,
99.9% 记忆在默认召回的盲区(t_24eceed0 worker 交付只改了推导来源,未解决跨 ns)。

修复:
① api/routes: 新增 resolveRecallNamespace() 纯函数 —— 显式 ns 原样、只有 agent_id 才推导、
   两者都空返回 "" 表示全库;Recall 与 RecallDebug 共用同一函数(debug 如实反映 recall)
② storage/recall.go: namespace=="" → Search(..., 200, "") 全库单次检索(空过滤=不过滤),
   候选池上限 50→100;显式 ns 路径完全不变([ns, shared])
③ 全库模式下关闭两段补丁式补搜(shared / wiki-curator-main),避免重复候选与白花 embedding

测试(8 条,含反证):
- routes: resolveRecallNamespace 5 用例(核心判据:空+空 必须返回 "")
- storage: 全库单次检索(记录 Search 实参)/ 显式 ns 保持 [ns shared] / shared 不重复搜
- 反证:还原旧行为 → 两组量具均 FAIL ✓("默认调用被解析成 hermes-main,又只能看到极小一片记忆")
踩坑记录:stub 用嵌入接口技巧时须一并覆写 Update(),否则后台 recall_count 回写 goroutine
落到 nil 接口 panic。
This commit is contained in:
小唯
2026-09-21 15:15:07 +08:00
parent 1b2bd417b2
commit 266a85a5d2
4 changed files with 222 additions and 21 deletions
+24 -9
View File
@@ -255,10 +255,8 @@ func (a *API) Recall(w http.ResponseWriter, r *http.Request) {
if req.Limit <= 0 {
req.Limit = 10
}
if req.Namespace == "" {
// 按 §1.3 推导 namespace,与 commit 端点保持一致:使用 category 和 content(此处以 Query 近似)
req.Namespace = classifyNamespace("general", req.AgentID, req.Query)
}
// 2026-09-21 五修(t_24eceed0 返修):无 ns 且无 agent_id → namespace="" → 全库跨 ns 召回
req.Namespace = resolveRecallNamespace(req.Namespace, req.AgentID, req.Query)
// H4: Default diversity — balance relevance & diversity
if req.Diversity <= 0 {
@@ -312,7 +310,7 @@ func (a *API) Recall(w http.ResponseWriter, r *http.Request) {
}
// E4.2: 跨 agent 知识共享 — recall 结果在 (0, top_k) 时,补充搜索 "shared" namespace
if len(results) > 0 && len(results) < 3 && req.Namespace != "shared" {
if len(results) > 0 && len(results) < 3 && req.Namespace != "shared" && req.Namespace != "" {
vec, encErr := a.Embedder.EncodeSingle(req.Query)
if encErr == nil {
shared, _ := a.LanceDB.Search("memories", vec, 5, "shared")
@@ -341,7 +339,7 @@ func (a *API) Recall(w http.ResponseWriter, r *http.Request) {
// wiki_curator 把「笔记→知识」写进 wiki-curator-main,而主召回只搜
// req.Namespace/shared ⇒ 33+ 条笔记知识长期在盲区(召回永远看不到)。
// 这里补搜:主结果不足 top_k 时,从额外命名空间补齐(去重 + 降权 0.45)。
if req.Namespace != "wiki-curator-main" {
if req.Namespace != "wiki-curator-main" && req.Namespace != "" {
if vec, encErr := a.Embedder.EncodeSingle(req.Query); encErr == nil {
for _, extra := range []string{"wiki-curator-main"} {
extraHits, _ := a.LanceDB.Search("memories", vec, 5, extra)
@@ -452,9 +450,8 @@ func (a *API) RecallDebug(w http.ResponseWriter, r *http.Request) {
if req.Limit <= 0 {
req.Limit = 10
}
if req.Namespace == "" {
req.Namespace = deriveNamespace(req.AgentID)
}
// 2026-09-21 五修:与 Recall 完全一致(同一解析函数),保证 debug 端点如实反映 Recall 行为
req.Namespace = resolveRecallNamespace(req.Namespace, req.AgentID, req.Query)
type stepInfo struct {
Step string `json:"step"`
@@ -853,6 +850,24 @@ func deriveNamespace(agentID string) string {
return agentID + "-main"
}
// resolveRecallNamespace 决定召回实际使用的 namespace(2026-09-21 五修,t_24eceed0 返修):
// - 调用方显式给了 namespace → 原样使用(作用域限定,语义不变)
// - 只给了 agent_id → 按 §1.3 用 classifyNamespace 推导(与 commit 端点一致)
// - 两者都空 → 返回 "",表示「全库跨命名空间召回」由 RecallPipeline 处理
//
// 修前:两者都空时会推导成 default-main ⇒ 只搜 default-main+shared,
// 而真实记忆散在 hermes-main / wiki-curator-main / wiki / soulful-xiaowei / a06-main /
// domain:* 等 19 个 ns(实测全表 10172 条,默认调用只拿到 11 个候选)。
func resolveRecallNamespace(namespace, agentID, query string) string {
if namespace != "" {
return namespace
}
if agentID != "" {
return classifyNamespace("general", agentID, query)
}
return "" // 全库跨 ns 召回
}
func classifyNamespace(category, agentID, content string) string {
// 如果显式传入 namespace 且非空,信任调用方
// (此函数仅在 namespace 为空时调用)
@@ -0,0 +1,62 @@
package routes
import "testing"
// TestResolveRecallNamespace 覆盖 2026-09-21 五修(t_24eceed0 返修)的 ns 解析规则。
//
// 病根:修前「无 namespace 且无 agent_id」会推导成 default-main,导致默认召回
// 只搜 default-main + shared,而真实记忆散在 hermes-main / wiki-curator-main / wiki /
// soulful-xiaowei / a06-main / domain:* 等 19 个命名空间(全表 10172 条,实测只拿到 11 个候选)。
//
// 判据:两者都空必须返回 ""(= 全库跨 ns),而不是任何具体 ns。
func TestResolveRecallNamespace(t *testing.T) {
cases := []struct {
name string
namespace string
agentID string
query string
want string
why string
}{
{
name: "无ns无agentID_必须全库", namespace: "", agentID: "",
query: "蒸馏模型日限计数器", want: "",
why: "核心判据:默认调用必须跨全部 ns 检索(返回空串 = 不过滤 = 全库)",
},
{
name: "显式ns_原样作用域", namespace: "hermes-main", agentID: "",
query: "任意", want: "hermes-main",
why: "调用方显式指定时不得改写语义",
},
{
name: "显式ns优先于agentID", namespace: "shared", agentID: "hermes-a06",
query: "任意", want: "shared",
why: "显式 ns 优先级最高",
},
{
name: "只有agentID_推导ns", namespace: "", agentID: "hermes-a06",
query: "任意", want: "hermes-main",
why: "有 agent_id 时按 §1.3 推导,保持既有作用域行为",
},
{
name: "只有agentID_openclaw", namespace: "", agentID: "openclaw",
query: "任意", want: "openclaw-main",
why: "openclaw 前缀推导",
},
}
for _, c := range cases {
got := resolveRecallNamespace(c.namespace, c.agentID, c.query)
if got != c.want {
t.Errorf("✗ %s: resolveRecallNamespace(%q,%q) = %q, want %q —— %s",
c.name, c.namespace, c.agentID, got, c.want, c.why)
continue
}
t.Logf("✓ %s: got=%q", c.name, got)
}
// 独立强调:全库判据不能被"看起来像 ns"的默认值替代
if got := resolveRecallNamespace("", "", "x"); got != "" {
t.Fatalf("✗ 回归:默认调用被解析成 %q,又只能看到极小一片记忆", got)
}
}
+29 -12
View File
@@ -87,17 +87,30 @@ func (p *RecallPipeline) Recall(query, namespace string, topK int, diversity flo
// 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
namespaces := []string{namespace}
if namespace != "shared" {
namespaces = append(namespaces, "shared")
}
for _, ns := range namespaces {
nsResults, err := p.lancedb.Search("memories", queryVec, 50, ns)
if err != nil {
continue
if namespace == "" {
all, err := p.lancedb.Search("memories", queryVec, 200, "") // 空 ns = 不过滤 = 全库
if err == nil {
candidates = append(candidates, all...)
}
} else {
namespaces := []string{namespace}
if namespace != "shared" {
namespaces = append(namespaces, "shared")
}
for _, ns := range namespaces {
nsResults, err := p.lancedb.Search("memories", queryVec, 50, ns)
if err != nil {
continue
}
candidates = append(candidates, nsResults...)
}
candidates = append(candidates, nsResults...)
}
// 去重(按 ID)
seen := make(map[string]bool)
@@ -137,9 +150,13 @@ func (p *RecallPipeline) Recall(query, namespace string, topK int, diversity flo
}
candidates = filtered
// 截断到 top 50
if len(candidates) > 50 {
candidates = candidates[:50]
// 截断候选池(全库模式候选来自更多命名空间,池子放宽到 100)
candCap := 50
if namespace == "" {
candCap = 100
}
if len(candidates) > candCap {
candidates = candidates[:candCap]
}
// Step 3.5: BM25 keyword scoring — amplify keyword-relevant results
@@ -0,0 +1,107 @@
package storage
import (
"testing"
"github.com/xiaoxue/memoryweave/internal/models"
)
// nsRecordingLance 用「嵌入接口」技巧:只覆写 Search 记录实参,
// 其余 LanceDB 方法由嵌入的接口提供(测试中不会被调用)。
type nsRecordingLance struct {
LanceDB
nsFilters []string
topKs []int
rows []models.MemoryRecord
}
func (f *nsRecordingLance) Search(table string, vector []float32, topK int, namespaceFilter string) ([]models.MemoryRecord, error) {
f.nsFilters = append(f.nsFilters, namespaceFilter)
f.topKs = append(f.topKs, topK)
out := make([]models.MemoryRecord, 0, len(f.rows))
for _, r := range f.rows {
out = append(out, r)
}
return out, nil
}
// Update 也被覆写:RecallPipeline 会在后台 goroutine 里回写 recall_count,
// 若不覆写则落到嵌入的 nil 接口 → 后台 goroutine panic(实测踩坑)。
func (f *nsRecordingLance) Update(table, id string, fields map[string]any) error { return nil }
const nsTestQuery = "蒸馏模型日限计数器跨天重置"
// newNSTestPipeline 构造一个不依赖网络/磁盘的 RecallPipeline:
// Embedder 走预置缓存(命中缓存即不发起 HTTP),Reranker 无 key 无 embedder → 优雅降级。
func newNSTestPipeline(fake *nsRecordingLance) *RecallPipeline {
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(nsTestQuery, vec) // 预置缓存 → EncodeSingle 不再走网络
p := NewRecallPipeline(emb, fake, &Reranker{})
return p
}
// TestRecallEmptyNamespaceSearchesAll 判据:namespace=="" 必须以「空过滤」检索(= 全库跨 ns)。
// 修前不变量:空 ns 会被拆成 ["", "shared"],或调用方先推导成 default-main ⇒ 只看到一小片。
func TestRecallEmptyNamespaceSearchesAll(t *testing.T) {
fake := &nsRecordingLance{rows: []models.MemoryRecord{
{ID: "m1", Content: "记忆 A", Category: "distilled"},
}}
p := newNSTestPipeline(fake)
if _, err := p.Recall(nsTestQuery, "", 5, 0.3); err != nil {
t.Fatalf("Recall 出错: %v", err)
}
if len(fake.nsFilters) == 0 {
t.Fatal("✗ Search 从未被调用")
}
if fake.nsFilters[0] != "" {
t.Errorf("✗ 全库召回未生效:Search 收到过滤 %q,应为空串(全库)", fake.nsFilters[0])
}
t.Logf("✓ 全库召回:Search 过滤=%q topK=%d(共 %d 次调用)", fake.nsFilters[0], fake.topKs[0], len(fake.nsFilters))
// 全库模式应只搜一次(不再叠加 shared,避免重复候选)
if len(fake.nsFilters) != 1 {
t.Errorf("✗ 全库模式应只发起 1 次 Search,实际 %d 次:%v", len(fake.nsFilters), fake.nsFilters)
}
}
// TestRecallExplicitNamespaceStaysScoped 回归保护:显式 ns 行为不得被改成全库。
func TestRecallExplicitNamespaceStaysScoped(t *testing.T) {
fake := &nsRecordingLance{rows: []models.MemoryRecord{
{ID: "m1", Content: "记忆 A", Category: "distilled"},
}}
p := newNSTestPipeline(fake)
if _, err := p.Recall(nsTestQuery, "hermes-main", 5, 0.3); err != nil {
t.Fatalf("Recall 出错: %v", err)
}
want := []string{"hermes-main", "shared"}
if len(fake.nsFilters) != len(want) {
t.Fatalf("✗ 作用域召回搜索次数 %d,want %d:%v", len(fake.nsFilters), len(want), fake.nsFilters)
}
for i, w := range want {
if fake.nsFilters[i] != w {
t.Errorf("✗ 第 %d 次过滤=%q,want %q", i, fake.nsFilters[i], w)
}
}
t.Logf("✓ 显式 ns 保持作用域:%v", fake.nsFilters)
}
// TestRecallSharedNamespaceNoDoubleSearch 边界:ns=shared 只搜一次(不重复追加 shared)。
func TestRecallSharedNamespaceNoDoubleSearch(t *testing.T) {
fake := &nsRecordingLance{rows: []models.MemoryRecord{
{ID: "m1", Content: "记忆 A", Category: "distilled"},
}}
p := newNSTestPipeline(fake)
if _, err := p.Recall(nsTestQuery, "shared", 5, 0.3); err != nil {
t.Fatalf("Recall 出错: %v", err)
}
if len(fake.nsFilters) != 1 || fake.nsFilters[0] != "shared" {
t.Errorf("✗ shared 应只搜一次,实际 %v", fake.nsFilters)
}
t.Logf("✓ shared 不重复搜索:%v", fake.nsFilters)
}