From d7a73d7e6c73f7263121f215634ef895e635e297 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=B0=8F=E5=94=AF?= Date: Mon, 26 Oct 2026 16:29:43 +0800 Subject: [PATCH] =?UTF-8?q?fix(recall):=20top=5Fk=20=E6=94=B6=E5=8F=A3=20+?= =?UTF-8?q?=20=E6=81=A2=E5=A4=8D=20main=20=E5=8F=AF=E6=9E=84=E5=BB=BA?= =?UTF-8?q?=E6=80=A7?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 1) top_k 收口(t_9025b0eb) /api/v1/recall 无视 top_k:top_k=5 实测返回 341 条(5 distilled + 336 graph_expanded), top_k=10 返回 521 条。因 ExpandFromResults 扩展结果 append 无上限。 后果:插件记忆预取被撑爆(journal 实测单次 flush 合并 900/780/613/549/351 条), 真相关条目落在被截断段;count 失真;使用追踪按千级记账稀释指标。 修法:capRecallResults —— results = 主结果 ≤top_k;扩展单独走 graph_expanded 字段 (上限 top_k,能力仍可观测);主结果不足时用扩展补齐(稀疏查询仍受益)。 + core_topk_test.go 5 例 6 断言钉住契约。 2) 恢复 main 可构建性(P0,非本卡范围但阻塞一切构建) rebase 丢了 metrics.ConsolLastSuccessTime / ConsolConsecutiveFailures / ConsolidateBusyWaitTotal / MetaNoteRejectTotal 的定义(只在 f96c828), 而调用方已进 main,且 consolidation_track.go 整个文件不在树上 ⇒ go build 失败。 从 f96c828 原样恢复 4 个指标定义并注册;从 2275b83 恢复 consolidation_track.go。 --- go/internal/api/routes/consolidation_track.go | 163 ++++++++++++++++++ go/internal/api/routes/core.go | 99 +++++++++-- go/internal/api/routes/core_topk_test.go | 76 ++++++++ go/internal/metrics/metrics.go | 36 ++++ 4 files changed, 358 insertions(+), 16 deletions(-) create mode 100644 go/internal/api/routes/consolidation_track.go create mode 100644 go/internal/api/routes/core_topk_test.go diff --git a/go/internal/api/routes/consolidation_track.go b/go/internal/api/routes/consolidation_track.go new file mode 100644 index 0000000..93c2886 --- /dev/null +++ b/go/internal/api/routes/consolidation_track.go @@ -0,0 +1,163 @@ +// 织忆 MemoryWeave — 整合链路健康跟踪(t_10757bd5) +// +// 背景(2026-10-24 小怡体检实测): +// - t_distill(15min) 与 t_consolidation 同时触发 consolPipe, +// Rust 侧互斥整合槽被占用时 Go 立即降级 Go 启发式 ⇒ consolidate_busy ~55 次/日静默堆积 +// - /health 只看 sidecar TCP 连通性 ⇒ 整合链路持续失败也假绿 +// +// 本文件提供: +// 1. ConsolidationTracker — 记录连续失败次数 + 最近一次成功时间(供 /health 读) +// 2. busyWaitRetry — Rust sidecar 报 busy 时等待 3s×3 次再降级(整合全程 ~126s) +// 3. 引用 metrics 包新增的 5 个指标(AC5:失败路径带计数) +package routes + +import ( + "strings" + "sync" + "time" + + "github.com/xiaoxue/memoryweave/internal/consolidate" + "github.com/xiaoxue/memoryweave/internal/metrics" +) + +// ─── ConsolidationTracker ──────────────────────────────────── + +var ( + consTracker = &ConsolidationTracker{} + consTrackerOnce sync.Once +) + +// ConsolidationTracker 记录整合链路健康状态(内存态,重启归零; +// 重启后健康端点读到 ConsecutiveFailures=0 ⇒ 正确,因为该链路确实刚起步)。 +type ConsolidationTracker struct { + mu sync.Mutex + LastSuccess time.Time + LastAttempt time.Time + startup time.Time + ConsecutiveFailures int + Skips int64 // t_10757bd5:需要"跳过"而非失败的次数(并发触发 / sidecar busy) + lastSkip string // 最近一次跳过原因 + // lastError 最近一次失败原因(供 /health 暴露,便于人工诊断) + lastError string +} + +// GetConsolTracker 返回全局 tracker 单例 +func GetConsolTracker() *ConsolidationTracker { + if consTracker.startup.IsZero() { + consTracker.mu.Lock() + if consTracker.startup.IsZero() { + consTracker.startup = time.Now() + } + consTracker.mu.Unlock() + } + return consTracker +} + +// RecordSuccess 整合成功(归零) +func (t *ConsolidationTracker) RecordSuccess() { + t.mu.Lock() + defer t.mu.Unlock() + t.LastAttempt = time.Now() + t.LastSuccess = time.Now() + t.ConsecutiveFailures = 0 + t.lastError = "" + metrics.ConsolLastSuccessTime.SetToCurrentTime() + metrics.ConsolConsecutiveFailures.Set(0) +} + +// RecordSkip 本次触发被**跳过**(不是失败)。 +// +// t_10757bd5 关键语义修正(2026-10-24 22:45 实测发现): +// `consolidate_busy` 的真实含义是「另一个整合正在跑」,不是链路坏。 +// 把它记成失败会让 /health 报 degraded —— 明明整合正在正常工作,却又是一次假红。 +// 只有真正的错误(sidecar 崩、DB 错、超时)才算 failure。 +func (t *ConsolidationTracker) RecordSkip(reason string) { + t.mu.Lock() + defer t.mu.Unlock() + t.LastAttempt = time.Now() + t.Skips++ + t.lastSkip = reason +} + +// RecordFailure 整合失败(+1) +func (t *ConsolidationTracker) RecordFailure(err string) { + t.mu.Lock() + defer t.mu.Unlock() + t.LastAttempt = time.Now() + t.ConsecutiveFailures++ + t.lastError = err + metrics.ConsolConsecutiveFailures.Set(float64(t.ConsecutiveFailures)) +} + +// HealthStatus 返回健康端点应报的状态: +// - 连续**真失败** ≥ 3 ⇒ "degraded" +// - 进程启动已超 2 小时却从未成功过 ⇒ "degraded"(跳过不算成功,也不算失败) +// - 上次成功距今 > 2 小时(15min 周期 × 8)⇒ "degraded" +// - 否则 "ok" +func (t *ConsolidationTracker) HealthStatus() (string, int, time.Duration, string) { + t.mu.Lock() + defer t.mu.Unlock() + fails := t.ConsecutiveFailures + var sinceSuccess time.Duration + if t.LastSuccess.IsZero() { + sinceSuccess = 0 // 从未成功 + } else { + sinceSuccess = time.Since(t.LastSuccess) + } + status := "ok" + if fails >= 3 { + status = "degraded" + } + if t.LastSuccess.IsZero() { + if !t.startup.IsZero() && time.Since(t.startup) > 2*time.Hour { + status = "degraded" + } + } else if sinceSuccess > 2*time.Hour { + status = "degraded" + } + return status, fails, sinceSuccess, t.lastError +} + +// Snapshot 供 /health 暴露完整字段(含跳过次数,便于区分「忙」与「坏」) +func (t *ConsolidationTracker) Snapshot() (fails int, skips int64, lastSkip string, lastErr string) { + t.mu.Lock() + defer t.mu.Unlock() + return t.ConsecutiveFailures, t.Skips, t.lastSkip, t.lastError +} + +// ─── busyWaitRetry ─────────────────────────────────────────── + +// busyWaitRetry 对 Rust sidecar consolidate_busy 做有限等待重试。 +// +// 原理:Rust 整合全程约 126s(DBSCAN + 衰减校准),触发器每 15min 一次, +// 两个触发器同秒到达时第二个撞 busy。等待 3s × 3 次(共 9s); +// 9s 后仍 busy 说明 sidecar 真有长任务(或正在做 full 模式), +// 降级 Go 启发式并记录 tracker(由调用方负责)。 +// +// 返回语义: +// - (report, false, nil) = 成功拿到报告 +// - (nil, true, nil) = 重试耗尽仍 busy(调用方应走降级 + RecordFailure) +// - (nil, false, err) = 非 busy 错误(调用方直接返回) +func busyWaitRetry(dataDir, sqlitePath, mode string) (report *consolidate.Result, stillBusy bool, err error) { + const ( + maxRetries = 3 + waitDur = 3 * time.Second + ) + for i := 0; i <= maxRetries; i++ { + if i > 0 { + metrics.ConsolidateBusyWaitTotal.Inc() + time.Sleep(waitDur) + } + report, err = consolidate.Run(dataDir, sqlitePath, mode) + if err == nil { + return report, false, nil + } + if strings.Contains(err.Error(), "consolidate_busy") { + continue // 仍 busy,重试 + } + // 非 busy 错误直接返回 + return nil, false, err + } + // 重试耗尽仍 busy + return nil, true, nil +} diff --git a/go/internal/api/routes/core.go b/go/internal/api/routes/core.go index 0ac40d3..1ace913 100644 --- a/go/internal/api/routes/core.go +++ b/go/internal/api/routes/core.go @@ -16,9 +16,9 @@ import ( "github.com/xiaoxue/memoryweave/internal/distill" "github.com/xiaoxue/memoryweave/internal/governance" + "github.com/xiaoxue/memoryweave/internal/metanote" "github.com/xiaoxue/memoryweave/internal/metrics" "github.com/xiaoxue/memoryweave/internal/models" - "github.com/xiaoxue/memoryweave/internal/metanote" "github.com/xiaoxue/memoryweave/internal/selfoptimize" "github.com/xiaoxue/memoryweave/internal/storage" ) @@ -636,14 +636,14 @@ func (a *API) Recall(w http.ResponseWriter, r *http.Request) { var meta storage.RecallMeta results, meta, err = a.Pipeline.RecallWithMetaOpts(req.Query, req.Namespace, req.Limit, req.Diversity, nsDerivedFromAgent) annScanned = meta.CandidatesScanned - cacheHit = meta.CacheHit // t_1c12e000 + cacheHit = meta.CacheHit // t_1c12e000 truncated = meta.Truncated // t_3aa2a8c1 case "hybrid": // BM25 + vector combined (H1: BM25 scoring inside Pipeline.Recall) var meta storage.RecallMeta results, meta, err = a.Pipeline.RecallWithMetaOpts(req.Query, req.Namespace, req.Limit, req.Diversity, nsDerivedFromAgent) annScanned = meta.CandidatesScanned - cacheHit = meta.CacheHit // t_1c12e000 + cacheHit = meta.CacheHit // t_1c12e000 truncated = meta.Truncated // t_3aa2a8c1 } if err != nil { @@ -652,7 +652,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 + cacheHit = false // t_1c12e000:graph 兜底结果不来自 search cache truncated = false // t_3aa2a8c1:graph.db 兜底结果不经 IPC 粗检索 ⇒ 无截断可言 w.Header().Set("X-Fallback", "graph") } else { @@ -698,12 +698,12 @@ func (a *API) Recall(w http.ResponseWriter, r *http.Request) { vv = storage.VValueProvider(m.ID) } results = append(results, models.RecallResult{ - ID: m.ID, - Content: m.Content, - Category: m.Category, - Score: 0.5, // shared 结果降权,使用默认分 - QualityScore: m.QualityScore, - VValue: vv, + ID: m.ID, + Content: m.Content, + Category: m.Category, + Score: 0.5, // shared 结果降权,使用默认分 + QualityScore: m.QualityScore, + VValue: vv, HumanUsefulCount: m.HumanUsefulCount, // A10 (t_d618dc7c) }) } @@ -742,12 +742,12 @@ func (a *API) Recall(w http.ResponseWriter, r *http.Request) { vv = storage.VValueProvider(m.ID) } results = append(results, models.RecallResult{ - ID: m.ID, - Content: m.Content, - Category: m.Category, - Score: 0.45, // 笔记知识降权:不挤掉主记忆,但能被看到 - QualityScore: m.QualityScore, - VValue: vv, + ID: m.ID, + Content: m.Content, + Category: m.Category, + Score: 0.45, // 笔记知识降权:不挤掉主记忆,但能被看到 + QualityScore: m.QualityScore, + VValue: vv, HumanUsefulCount: m.HumanUsefulCount, // A10 (t_d618dc7c) }) } @@ -819,6 +819,17 @@ func (a *API) Recall(w http.ResponseWriter, r *http.Request) { } storage.RecordRecalled(recs) } + // ── 2026-10-26 (t_9025b0eb) top_k 收口:图谱扩展不得撑爆返回集 ── + // 现象:/api/v1/recall 完全无视 top_k —— top_k=5 实测返回 1905/1625 条、top_k=10 返回 + // 2227/1859 条,其中 99% 是 category=graph_expanded(图谱扩展 append 无上限)。 + // 后果:插件记忆预取被撑到 103,299 chars 截断(真相关条目落在被截断段)、count 失真、 + // ⑤使用追踪按千级结果记账。 + // 契约修正(主结果优先): + // results = 主检索结果(category != graph_expanded),截断到 req.Limit; + // 主结果不足 req.Limit 时用扩展结果按原顺序补齐(稀疏查询仍有扩展收益)。 + // graph_expanded = 扩展结果**单独成字段**(上限 req.Limit)——能力仍可观测、可统计, + // 但不再挤占主结果、不再污染 results/count。 + results, graphExpanded := capRecallResults(results, req.Limit) if results == nil { results = []models.RecallResult{} } @@ -827,6 +838,9 @@ func (a *API) Recall(w http.ResponseWriter, r *http.Request) { "count": len(results), "candidates_scanned": annScanned, "mode": req.Mode, + // 2026-10-26 (t_9025b0eb):扩展结果单独成字段,避免撑爆 results。 + // 键恒存在(可为空数组),便于探针/统计区分「无扩展」与「字段缺失」。 + "graph_expanded": graphExpanded, // t_1c12e000:AC3 —— 缓存命中/回源扫表必须可区分。 // true ⇒ candidates_scanned=0 是「读了 60s 内的旧快照」(含 L1/L2); // false ⇒ 本次真扫了表(candidates_scanned 为真实候选池大小)。 @@ -1476,3 +1490,56 @@ func (a *API) EdgeFeedback(w http.ResponseWriter, r *http.Request) { func (a *API) PopWatch(w http.ResponseWriter, r *http.Request) { respond(w, 200, storage.PopWatchSnapshot()) } + +// capRecallResults —— 2026-10-26 (t_9025b0eb) top_k 收口语义(纯函数,可单测)。 +// +// 输入是 pipeline 返回的原始结果(主检索在前、图谱扩展 append 在后,扩展无上限)。 +// 输出: +// +// prim = 主检索结果(category != graph_expanded),截断到 limit; +// 若主结果不足 limit,用扩展结果按原顺序补齐(稀疏查询仍有扩展收益)。 +// expanded = 剩余扩展结果,单独成字段返回,上限 limit(能力可观测,但不挤占主结果)。 +// +// 为什么不是「直接 results[:limit]」:扩展结果全部排在主结果之后,直接截断会让 +// category=graph_expanded 恒为 0 ⇒ 能力虽在跑但对外永久失明(本仓 2026-10 已因同类 +// 「接线≠出数」栽过一次)。所以既收口、又保留可观测通道。 +func capRecallResults(results []models.RecallResult, limit int) (prim, expanded []models.RecallResult) { + if limit <= 0 { + limit = 10 + } + prim = make([]models.RecallResult, 0, limit) + if len(results) == 0 { + return prim, []models.RecallResult{} + } + exp := make([]models.RecallResult, 0, len(results)) + for _, r := range results { + if r.Category == "graph_expanded" { + exp = append(exp, r) + } else { + prim = append(prim, r) + } + } + if len(exp) == 0 { + if len(prim) > limit { + prim = prim[:limit] + } + return prim, []models.RecallResult{} + } + if len(prim) > limit { + prim = prim[:limit] + } + if room := limit - len(prim); room > 0 { + if room > len(exp) { + room = len(exp) + } + prim = append(prim, exp[:room]...) + exp = exp[room:] + } + if len(exp) > limit { + exp = exp[:limit] + } + if expanded == nil { + expanded = exp + } + return prim, expanded +} diff --git a/go/internal/api/routes/core_topk_test.go b/go/internal/api/routes/core_topk_test.go new file mode 100644 index 0000000..c79f976 --- /dev/null +++ b/go/internal/api/routes/core_topk_test.go @@ -0,0 +1,76 @@ +package routes + +import ( + "testing" + + "github.com/xiaoxue/memoryweave/internal/models" +) + +// 2026-10-26 (t_9025b0eb):top_k 收口契约测试。 +// 起因:/api/v1/recall 完全无视 top_k —— top_k=5 实测返回 1905/1625 条(99% graph_expanded), +// 插件记忆预取被撑到 103,299 chars 截断、count 失真、使用追踪按千级结果记账。 +// 钉住四件事:① results 不超过 limit ② 主结果不被扩展挤掉 ③ 扩展仍可见且不超 limit +// ④ 稀疏查询(主结果 < limit)时扩展能补齐。 +func TestCapRecallResults(t *testing.T) { + mk := func(n int, cat string) []models.RecallResult { + out := make([]models.RecallResult, n) + for i := 0; i < n; i++ { + out[i] = models.RecallResult{ID: cat + string(rune('a'+i%26)), Category: cat, Content: cat} + } + return out + } + cases := []struct { + name string + prim, exp int + limit int + wantPrim int + wantExp int + primCategory string + }{ + {"主结果足额_扩展不得进results", 10, 1900, 5, 5, 5, "distilled"}, + {"主结果只有2条_扩展补齐到limit", 2, 900, 5, 5, 5, "distilled"}, + {"无扩展_纯截断", 30, 0, 10, 10, 0, "distilled"}, + {"扩展少于limit", 1, 3, 5, 4, 0, "distilled"}, + {"空结果", 0, 0, 5, 0, 0, ""}, + } + for _, c := range cases { + t.Run(c.name, func(t *testing.T) { + all := append(mk(c.prim, "distilled"), mk(c.exp, "graph_expanded")...) + prim, exp := capRecallResults(all, c.limit) + if len(prim) != c.wantPrim { + t.Fatalf("prim=%d want %d", len(prim), c.wantPrim) + } + if len(exp) != c.wantExp { + t.Fatalf("expanded=%d want %d", len(exp), c.wantExp) + } + if len(prim)+len(exp) > c.limit*2 { + t.Fatalf("总量失控: prim=%d exp=%d", len(prim), len(exp)) + } + // 主结果条数不得超过原始主结果数(不得凭空造) + n := 0 + for _, r := range prim { + if r.Category != "graph_expanded" { + n++ + } + } + if n > c.prim { + t.Fatalf("主结果 %d 条,超过输入 %d 条(凭空造)", n, c.prim) + } + if c.primCategory != "" && c.prim > 0 && n == 0 { + t.Fatalf("主结果被扩展挤光:%+v", prim) + } + }) + } +} + +// limit 非法(0/负数)时按默认 10 处理,不做无界返回。 +func TestCapRecallResultsDefaultLimit(t *testing.T) { + all := make([]models.RecallResult, 50) + for i := range all { + all[i] = models.RecallResult{Category: "distilled"} + } + prim, _ := capRecallResults(all, 0) + if len(prim) != 10 { + t.Fatalf("limit=0 应回落 10,得到 %d", len(prim)) + } +} diff --git a/go/internal/metrics/metrics.go b/go/internal/metrics/metrics.go index 213bfa6..55eb051 100644 --- a/go/internal/metrics/metrics.go +++ b/go/internal/metrics/metrics.go @@ -35,6 +35,38 @@ var ( }, ) + // ─── 整合(consolidate)可观测性 ─────────── + // 2026-10-26:这三个指标与 MetaNoteRejectTotal 的定义在 rebase 时被丢弃(定义只在 + // a8dfa37 里),而调用方(consolidation_track.go / core.go)已进 main ⇒ HEAD 编不过。 + // 从 a8dfa37 原样恢复定义并注册,恢复 main 可构建性。 + ConsolidateBusyWaitTotal = prometheus.NewCounter( + prometheus.CounterOpts{ + Name: "zhiyi_consolidate_busy_wait_total", + Help: "Rust 侧报 consolidate_busy 时 Go 侧主动等待重试的次数", + }, + ) + // 最近一次整合成功时间(Unix 秒) + ConsolLastSuccessTime = prometheus.NewGauge( + prometheus.GaugeOpts{ + Name: "zhiyi_consolidate_last_success_time", + Help: "最近一次 Rust 整合完成时间(Unix 秒);0 = 从未成功", + }, + ) + // 整合连续失败次数 + ConsolConsecutiveFailures = prometheus.NewGauge( + prometheus.GaugeOpts{ + Name: "zhiyi_consolidate_consecutive_failures", + Help: "连续整合失败次数(任意一次成功归零)", + }, + ) + // metanote shadow 写前置校验拒绝计数 + MetaNoteRejectTotal = prometheus.NewCounter( + prometheus.CounterOpts{ + Name: "zhiyi_metanote_reject_total", + Help: "metanote shadow 422 拒绝累计次数", + }, + ) + // ─── LLM 调用计数 ────────────────────────── DistillLLMCallsToday = prometheus.NewGauge( prometheus.GaugeOpts{ @@ -124,6 +156,10 @@ func init() { RequestDuration, DistillQueueDepth, ConflictsPending, + ConsolidateBusyWaitTotal, + ConsolLastSuccessTime, + ConsolConsecutiveFailures, + MetaNoteRejectTotal, DistillLLMCallsToday, ConsolidateFailuresTotal, HitEventAppendFailedTotal,