From 5b4f7cd95af4d858a9293608a1459e57196fc5c0 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=B0=8F=E5=94=AF?= Date: Mon, 21 Sep 2026 18:48:38 +0800 Subject: [PATCH] =?UTF-8?q?fix(eval=5Ftest):=20uid=E2=86=92ids=20=E6=9E=84?= =?UTF-8?q?=E5=BB=BA=E9=94=99=E8=AF=AF=EF=BC=88t=5F2d4e3b92=20AC=E2=91=A1?= =?UTF-8?q?=E2=91=A3=EF=BC=89?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- go/internal/api/routes/eval_test.go | 335 ++++++++++++++++++++++++++++ 1 file changed, 335 insertions(+) create mode 100644 go/internal/api/routes/eval_test.go diff --git a/go/internal/api/routes/eval_test.go b/go/internal/api/routes/eval_test.go new file mode 100644 index 0000000..0e64d71 --- /dev/null +++ b/go/internal/api/routes/eval_test.go @@ -0,0 +1,335 @@ +// 织忆 MemoryWeave — 评估系统测试 +// 覆盖:金标加载 / 空断言自守 / 关键词判据 / 反证 / 全量金标跑(需活服务) +package routes + +import ( + "bytes" + "encoding/json" + "fmt" + "io" + "net/http" + "os" + "path/filepath" + "testing" + "time" +) + +// ─── 反证辅助:liveRecallOnce ───────────────────────────────── +// 一次 recall API 调用同时拿 ids + top1_content,避免两条 HTTP(限流保护) +type recallResult struct { + IDs []string + Top1Content string + Error error +} + +func liveRecallOnce(query string, maxRetries int, retryWait time.Duration) recallResult { + payload, _ := json.Marshal(map[string]interface{}{"query": query, "top_k": 5}) + var lastErr error + for attempt := 0; attempt <= maxRetries; attempt++ { + if attempt > 0 { + time.Sleep(retryWait * time.Duration(attempt)) + } + req, _ := http.NewRequest("POST", "http://127.0.0.1:7821/api/v1/recall", bytes.NewReader(payload)) + req.Header.Set("Content-Type", "application/json") + req.Header.Set("X-API-Key", "zhiyi-dev-key-2026") + resp, err := http.DefaultClient.Do(req) + if err != nil { + lastErr = fmt.Errorf("HTTP 请求失败: %v", err) + continue + } + body, _ := io.ReadAll(resp.Body) + resp.Body.Close() + if resp.StatusCode == http.StatusUnauthorized { + return recallResult{Error: fmt.Errorf("HTTP 401 unauthorized(API key 无效)")} + } + if resp.StatusCode != http.StatusOK { + // 限流(429)或服务错误:读 retry_after_s,退避重试 + var errResp struct { + Error struct { + ErrorCode string `json:"code"` + ErrorMessage string `json:"message"` + RetryAfterSecs int `json:"retry_after_s"` + } `json:"error"` + } + _ = json.Unmarshal(body, &errResp) + lastErr = fmt.Errorf("HTTP %d (%s): %s", resp.StatusCode, errResp.Error.ErrorCode, errResp.Error.ErrorMessage) + if resp.StatusCode == http.StatusTooManyRequests { + // 限流退避:用 retry_after_s,至少 1s + wait := time.Duration(errResp.Error.RetryAfterSecs) * time.Second + if wait == 0 { + wait = 2 * time.Second + } + time.Sleep(wait) + continue + } + return recallResult{Error: lastErr} + } + var result struct { + Results []struct { + ID string `json:"id"` + Content string `json:"content"` + } `json:"results"` + } + if err := json.Unmarshal(body, &result); err != nil { + return recallResult{Error: fmt.Errorf("JSON 解析失败: %v | body=%s", err, string(body[:min(100, len(body))]))} + } + rr := recallResult{} + for _, r := range result.Results { + rr.IDs = append(rr.IDs, r.ID) + } + if len(result.Results) > 0 { + rr.Top1Content = result.Results[0].Content + } + return rr + } + return recallResult{Error: lastErr} +} + +// ─── AC① 空断言自守:validateExpectedIDs ──────────────────── + +func TestValidateExpectedIDs_RejectsBareMemPrefix(t *testing.T) { + // 裸前缀 "mem_" → 必须报 FATAL + err := validateExpectedIDs("测试查询", []string{"mem_"}) + if err == nil { + t.Fatal("✗ 裸前缀 mem_ 未报错(恒真断言漏检)") + } + va, ok := err.(*VacuousAssertionError) + if !ok { + t.Fatalf("✗ 期望 VacuousAssertionError,实际 %T: %v", err, err) + } + t.Logf("✓ 裸前缀拦截:%s", va.Error()) +} + +func TestValidateExpectedIDs_RejectsEmptyString(t *testing.T) { + err := validateExpectedIDs("测试查询", []string{""}) + if err == nil { + t.Fatal("✗ 空串期望值未报错") + } + t.Logf("✓ 空串拦截:%s", err.Error()) +} + +func TestValidateExpectedIDs_RejectsNone(t *testing.T) { + for _, bad := range []string{"None", "none", "NONE"} { + if err := validateExpectedIDs("测试查询", []string{bad}); err == nil { + t.Fatalf("✗ None 变体 %q 未报错", bad) + } + } + t.Log("✓ None 各变体全部拦截") +} + +func TestValidateExpectedIDs_AllowsRealID(t *testing.T) { + // 具体记忆 ID(mem_ + 数字)必须放行 + if err := validateExpectedIDs("测试查询", []string{"mem_1789153726378940805"}); err != nil { + t.Fatalf("✗ 真实 ID 被误拦: %v", err) + } + t.Log("✓ 真实 ID 放行") +} + +func TestValidateExpectedIDs_AllowsEmptySlice(t *testing.T) { + // 空 slice(bootstrap 无基线)允许,由上层决定是否记录 + if err := validateExpectedIDs("测试查询", []string{}); err != nil { + t.Fatalf("✗ 空 slice(bootstrap)被误拦: %v", err) + } + t.Log("✓ 空 slice 放行(bootstrap)") +} + +// ─── 关键词判据:checkKeywordRelevance ────────────────────── + +func TestCheckKeywordRelevance(t *testing.T) { + // 命中 + if !checkKeywordRelevance("用户偏好:牧尘喜欢直接动手", []string{"牧尘"}) { + t.Fatal("✗ 应命中「牧尘」") + } + // 未命中 + if checkKeywordRelevance("用户偏好:牧尘喜欢直接动手", []string{"技术栈"}) { + t.Fatal("✗ 不应命中「技术栈」") + } + // 大小写不敏感 + if !checkKeywordRelevance("MemoryWeave recall API 文档", []string{"RECALL"}) { + t.Fatal("✗ 大小写不敏感匹配失败") + } + // 空关键词 → 禁止(恒真退化) + if checkKeywordRelevance("任意内容", []string{}) { + t.Fatal("✗ 空关键词判据退化成恒真") + } + t.Log("✓ 关键词判据全部正确") +} + +// ─── LoadGoldenSet:加载 + 校验 ──────────────────────────── + +func TestLoadGoldenSet_ValidFile(t *testing.T) { + p := filepath.Join("testdata", "golden-set.json") + if _, err := os.Stat(p); err != nil { + t.Skipf("testdata 不在 CWD(测试需在 go/internal/api/routes/ 下跑): %v", err) + } + gs, err := LoadGoldenSet(p) + if err != nil { + t.Fatalf("✗ 加载金标集失败: %v", err) + } + if gs.Description == "" { + t.Error("✗ description 缺失") + } + // 12 条基线 + 2 条目标知识 + if len(gs.Items) != 14 { + t.Fatalf("✗ 期望 14 条(12 基线 + 2 目标),实际 %d", len(gs.Items)) + } + // 每条必须有 query + expected_ids(非裸前缀)+ must_include_keywords + for i, item := range gs.Items { + if item.Query == "" { + t.Fatalf("✗ item %d query 为空", i) + } + if len(item.ExpectedIDs) == 0 { + t.Fatalf("✗ item %d expected_ids 为空(金标必须有具体 ID)", i) + } + for _, id := range item.ExpectedIDs { + if id == "mem_" || id == "mem" || id == "" { + t.Fatalf("✗ item %d expected_ids 含裸前缀/空串 %q", i, id) + } + } + if len(item.MustIncludeKeywords) == 0 { + t.Fatalf("✗ item %d must_include_keywords 为空(禁止无关键词判据条目)", i) + } + } + t.Logf("✓ 金标集加载成功:%d 条,全部含具体 expected_ids + must_include_keywords", len(gs.Items)) +} + +func TestLoadGoldenSet_RejectsVacuousIDs(t *testing.T) { + // 构造一个含裸前缀的金标集 → 必须拒绝 + dir := t.TempDir() + bad := `{ + "description": "bad", + "items": [ + {"query": "q1", "expected_ids": ["mem_"], "must_include_keywords": ["a"]} + ] + }` + p := filepath.Join(dir, "bad.json") + os.WriteFile(p, []byte(bad), 0644) + if _, err := LoadGoldenSet(p); err == nil { + t.Fatal("✗ 含裸前缀 mem_ 的金标集未被拒绝") + } else { + t.Logf("✓ 含裸前缀的金标集被拒:%v", err) + } +} + +// ─── 全量金标跑(需活 zhiyid 服务;无服务时 skip)────────── +// 判据:14 条中 12 基线 + 2 目标,跑真实 recall,统计 pass/fail。 +// 校准后真实基线 = 12/14(2 条目标知识在库但召回 top-5 不稳定 → 允许 FAIL,不许抹平)。 + +func TestEvalGolden_Live(t *testing.T) { + // 探活 zhiyid(无服务 → 跳过,不污染 CI) + healthReq, _ := http.NewRequest("GET", "http://127.0.0.1:7821/api/v1/health", nil) + healthReq.Header.Set("X-API-Key", "zhiyi-dev-key-2026") + resp, err := http.DefaultClient.Do(healthReq) + if err != nil || resp == nil { + t.Skipf("zhiyid 服务不可达(%v),跳过全量金标实跑", err) + } + defer resp.Body.Close() + body, _ := io.ReadAll(resp.Body) + if resp.StatusCode != http.StatusOK { + t.Skipf("zhiyid 服务 HTTP %d: %s", resp.StatusCode, string(body[:min(80, len(body))])) + } + + // 用 LiveRecallPipeline(直接走 HTTP recall API)跑金标集 + gs, err := LoadGoldenSet(filepath.Join("testdata", "golden-set.json")) + if err != nil { + t.Fatalf("加载金标集失败: %v", err) + } + + pass, fail, warn, errorCount := 0, 0, 0, 0 + for i, item := range gs.Items { + // 空断言自守 + if err := validateExpectedIDs(item.Query, item.ExpectedIDs); err != nil { + t.Fatalf("item %d 空断言自守失败: %v", i, err) + } + + // 一次 HTTP 调用同时拿 ids + top1_content(限流保护) + rr := liveRecallOnce(item.Query, 3, 2*time.Second) + if rr.Error != nil { + errorCount++ + t.Logf("ERROR[%d] %q: recall 错误 %v", i, item.Query, rr.Error) + continue + } + + // 判据① ID 命中 + idHit := containsAny(rr.IDs, item.ExpectedIDs) + + // 判据② 关键词相关性 + kwHit := checkKeywordRelevance(rr.Top1Content, item.MustIncludeKeywords) + + if idHit && kwHit { + pass++ + t.Logf("PASS[%d] %q top1=%s", i, item.Query, firstID(rr.IDs)) + } else { + fail++ + why := []string{} + if !idHit { + // ID 漂移:基线 ID 不在 top-5,但关键词仍命中 → WARN(ID 漂移,内容切题) + if kwHit { + why = append(why, fmt.Sprintf("ID漂移(基线 %v ∉ top-5 %v, 但内容切题)", item.ExpectedIDs, rr.IDs[:min(3, len(rr.IDs))])) + warn++ + } else { + why = append(why, fmt.Sprintf("ID未命中(期望 %v, top-5 %v)", item.ExpectedIDs, rr.IDs[:min(3, len(rr.IDs))])) + } + } + if !kwHit { + why = append(why, fmt.Sprintf("关键词未命中(%v) | content_head: %s", item.MustIncludeKeywords, rr.Top1Content[:min(40, len(rr.Top1Content))])) + } + // ID 漂移但内容切题 → 降级为 WARN,不算 FAIL + if kwHit && !idHit { + fail-- + t.Logf("WARN[%d] %q %v", i, item.Query, why) + } else { + t.Logf("FAIL[%d] %q %v | top1: %s | kw_content_head: %s", i, item.Query, why, firstID(rr.IDs), rr.Top1Content[:min(40, len(rr.Top1Content))]) + } + } + + // 条目间隔 200ms(限流保护,避免连续打满令牌桶) + time.Sleep(200 * time.Millisecond) + } + + // 结尾打印真实数字,不写死任何期望值 + total := len(gs.Items) + t.Logf("RESULT: total=%d pass=%d fail=%d warn=%d error=%d(真实数字,无硬编码基线)", total, pass, fail, warn, errorCount) + // 漏跑检查:pass+fail+warn+error 必须 = 总条数 + if pass+fail+warn+errorCount != total { + t.Errorf("✗ 漏跑:pass+fail+warn+error=%d ≠ 总条数 %d", pass+fail+warn+errorCount, total) + } + // 关键词硬 FAIL(召回质量)→ 单独报告,不直接 fail 测试(基线允许 2~3 条已知失败) + // 真正让测试 fail 的条件:pass==0(全灭,判据可能已失效) + if pass == 0 { + t.Errorf("✗ 全灭(pass=0)——关键词判据可能失效或金标集 ID 已过期") + } + // 打印真实基线(供人工校准) + t.Logf("校准基线:pass=%d/%d(fail=%d warn=%d error=%d)", pass, total, fail, warn, errorCount) + // error 条目 → 服务问题,不计入 fail 但必须报告 + if errorCount > 0 { + t.Logf("⚠ %d 条 ERROR(recall API 调用失败,非召回质量问题)", errorCount) + } +} + +// containsAny 检查 expectedIDs 中是否有任意一个出现在 recalledIDs 中 +func containsAny(recalledIDs []string, expectedIDs []string) bool { + set := makeSet(expectedIDs) + for _, id := range recalledIDs { + if set[id] { + return true + } + } + return false +} + +// firstID 取 slice 第一个元素 +func firstID(ids []string) string { + if len(ids) == 0 { + return "(无)" + } + return ids[0] +} + +// min 取两个整数较小值 +func min(a, b int) int { + if a < b { + return a + } + return b +}