Compare commits
3
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
45726d26a7 | ||
|
|
c015febb49 | ||
|
|
44fd0e95b4 |
@@ -4,6 +4,7 @@ package routes
|
||||
import (
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
"strings"
|
||||
|
||||
"github.com/xiaoxue/memoryweave/internal/selfoptimize"
|
||||
)
|
||||
@@ -32,17 +33,31 @@ func (ga *GapAPI) List(w http.ResponseWriter, r *http.Request) {
|
||||
})
|
||||
}
|
||||
|
||||
// POST /api/v1/gaps/{topic}/close
|
||||
// POST /api/v1/gaps/close/{topic}(现行前缀注册 /api/v1/gaps/close/;亦兼容 {topic} 通配注册)
|
||||
func (ga *GapAPI) Close(w http.ResponseWriter, r *http.Request) {
|
||||
topic := r.PathValue("topic")
|
||||
if topic == "" {
|
||||
// 现行注册是前缀路由(模式无 {topic} 通配 ⇒ PathValue 恒为 "",端点此前恒 400):
|
||||
// 回落剥前缀取 topic。若日后改注册为 /api/v1/gaps/{topic}/close,PathValue 直接命中。
|
||||
const prefix = "/api/v1/gaps/close/"
|
||||
if strings.HasPrefix(r.URL.Path, prefix) {
|
||||
topic = r.URL.Path[len(prefix):]
|
||||
}
|
||||
}
|
||||
if topic == "" {
|
||||
respondError(w, 400, "topic required")
|
||||
return
|
||||
}
|
||||
|
||||
ga.Detector.Close(topic)
|
||||
selfoptimize.Dash.RecordGapClosed()
|
||||
respond(w, 200, map[string]string{"status": "closed", "topic": topic})
|
||||
// t_e5997ca4:计数口径 = 「缺口个数」。+1 只发生在 GapDetector 的 open→closed 迁移点
|
||||
// (Close 内部);旧的无条件 selfoptimize.Dash.RecordGapClosed() 已删除 —— 那是同一
|
||||
// 缺口可被无限计数、ClosedGaps(9) 越过 TotalGaps(2) 的写侧根因 #1。
|
||||
switch ga.Detector.Close(topic) {
|
||||
case true:
|
||||
respond(w, 200, map[string]string{"status": "closed", "topic": topic})
|
||||
default:
|
||||
respond(w, 200, map[string]string{"status": "already_closed", "topic": topic})
|
||||
}
|
||||
}
|
||||
|
||||
// POST /api/v1/gaps/detect — 手动触发缺口检测(miss 计数)
|
||||
|
||||
@@ -0,0 +1,112 @@
|
||||
// 织忆 MemoryWeave — gap 关闭端点写侧回归(t_e5997ca4 卡 AC2)
|
||||
//
|
||||
// POST /close 打两回(httptest)⇒ gap 计数器只 +1;auto 等其余计数器不受影响。
|
||||
package routes
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"io"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"testing"
|
||||
|
||||
"github.com/xiaoxue/memoryweave/internal/selfoptimize"
|
||||
)
|
||||
|
||||
// makeGapTopic 3 次 miss 命中默认阈值 3 ⇒ 生成缺口(TotalGaps +1)。
|
||||
func makeGapTopic(t *testing.T, gd *selfoptimize.GapDetector, topic string) {
|
||||
t.Helper()
|
||||
var gap *selfoptimize.Gap
|
||||
for i := 0; i < 3; i++ {
|
||||
if gap = gd.RecordMiss(topic); gap != nil {
|
||||
break
|
||||
}
|
||||
}
|
||||
if gap == nil {
|
||||
t.Fatalf("expected gap for %q after 3 misses", topic)
|
||||
}
|
||||
}
|
||||
|
||||
func postGapClose(t *testing.T, url string) (int, map[string]string) {
|
||||
t.Helper()
|
||||
resp, err := http.Post(url, "application/json", nil)
|
||||
if err != nil {
|
||||
t.Fatalf("POST %s: %v", url, err)
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
var body map[string]string
|
||||
if err := json.NewDecoder(resp.Body).Decode(&body); err != nil {
|
||||
b, _ := io.ReadAll(resp.Body)
|
||||
t.Fatalf("POST %s: 非 JSON 响应 %q: %v", url, b, err)
|
||||
}
|
||||
return resp.StatusCode, body
|
||||
}
|
||||
|
||||
// 卡 AC2:现行注册形态(前缀路由,topic 在 /api/v1/gaps/close/ 之后)打两回 ⇒ 只 +1。
|
||||
func TestGapAPI_CloseTwice_CounterOnlyOnce(t *testing.T) {
|
||||
gd := selfoptimize.NewGapDetector(nil, nil)
|
||||
makeGapTopic(t, gd, "close-twice-topic")
|
||||
|
||||
baseClosed := selfoptimize.Dash.ClosedGapsCount()
|
||||
baseTotal := selfoptimize.Dash.TotalGapsCount()
|
||||
baseMetrics := selfoptimize.Dash.Metrics() // auto_* 快照(应不受影响)
|
||||
|
||||
api := NewGapAPI(gd)
|
||||
mux := http.NewServeMux()
|
||||
mux.HandleFunc("/api/v1/gaps/close/", api.Close) // 与 server.go:1205 现行注册同形
|
||||
ts := httptest.NewServer(mux)
|
||||
defer ts.Close()
|
||||
|
||||
code1, body1 := postGapClose(t, ts.URL+"/api/v1/gaps/close/close-twice-topic")
|
||||
if code1 != 200 || body1["status"] != "closed" {
|
||||
t.Fatalf("第 1 次 POST: got %d %v, want 200 closed", code1, body1)
|
||||
}
|
||||
code2, body2 := postGapClose(t, ts.URL+"/api/v1/gaps/close/close-twice-topic")
|
||||
if code2 != 200 || body2["status"] != "already_closed" {
|
||||
t.Fatalf("第 2 次 POST: got %d %v, want 200 already_closed(不得再动计数)", code2, body2)
|
||||
}
|
||||
|
||||
if got := selfoptimize.Dash.ClosedGapsCount() - baseClosed; got != 1 {
|
||||
t.Fatalf("2× POST close 后 ClosedGaps 增量: got %d, want 1(改前为 +3 ⇒ 虚增)", got)
|
||||
}
|
||||
if got := selfoptimize.Dash.TotalGapsCount(); got != baseTotal {
|
||||
t.Errorf("TotalGaps 不应被 close 端点移动: got %d want %d", got, baseTotal)
|
||||
}
|
||||
|
||||
after := selfoptimize.Dash.Metrics()
|
||||
if after["gap_closure_rate"] > 1 {
|
||||
t.Errorf("gap_closure_rate = %f 越界", after["gap_closure_rate"])
|
||||
}
|
||||
// auto(冲突)计数器与 gap 关闭事件无关 ⇒ 快照不变(「auto 不适用」)
|
||||
for _, k := range []string{"auto_resolve_rate", "auto_resolve_samples", "auto_resolve_valid"} {
|
||||
if after[k] != baseMetrics[k] {
|
||||
t.Errorf("auto 计数器被 gap 关闭污染: %s got %f want %f", k, after[k], baseMetrics[k])
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// {topic} 通配注册形态(若日后把 server.go 注册改成 /api/v1/gaps/{topic}/close):
|
||||
// PathValue 直接命中,计数语义不变(+1 只在首次)。
|
||||
func TestGapAPI_CloseWildcardRegistration(t *testing.T) {
|
||||
gd := selfoptimize.NewGapDetector(nil, nil)
|
||||
makeGapTopic(t, gd, "wildcard-topic")
|
||||
|
||||
baseClosed := selfoptimize.Dash.ClosedGapsCount()
|
||||
|
||||
api := NewGapAPI(gd)
|
||||
mux := http.NewServeMux()
|
||||
mux.HandleFunc("/api/v1/gaps/{topic}/close", api.Close)
|
||||
ts := httptest.NewServer(mux)
|
||||
defer ts.Close()
|
||||
|
||||
code, body := postGapClose(t, ts.URL+"/api/v1/gaps/wildcard-topic/close")
|
||||
if code != 200 || body["status"] != "closed" {
|
||||
t.Fatalf("通配注册第 1 次 POST: got %d %v, want 200 closed", code, body)
|
||||
}
|
||||
if _, body2 := postGapClose(t, ts.URL+"/api/v1/gaps/wildcard-topic/close"); body2["status"] != "already_closed" {
|
||||
t.Errorf("通配注册第 2 次 POST: got %v, want already_closed", body2)
|
||||
}
|
||||
if got := selfoptimize.Dash.ClosedGapsCount() - baseClosed; got != 1 {
|
||||
t.Fatalf("通配注册 2× POST 后 ClosedGaps 增量: got %d, want 1", got)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,24 @@
|
||||
// 织忆 MemoryWeave — 路由层测试隔离(t_e5997ca4 起)
|
||||
//
|
||||
// 单元测试不得写到生产落盘点。selfoptimize 包已有同款 TestMain 先例
|
||||
// (曾实测:整套测试跑完把 /var/lib/memoryweave/dashboard.json 写成测试数字)。
|
||||
// gap close/repair 端点会触发 Dash.persist()(本地 JSON 兜底)⇒ 统一重定向到临时目录。
|
||||
package routes
|
||||
|
||||
import (
|
||||
"os"
|
||||
"path/filepath"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestMain(m *testing.M) {
|
||||
dir, err := os.MkdirTemp("", "routes-test-dash-*")
|
||||
if err != nil {
|
||||
// 宁可测试直接失败,也不写生产落盘点
|
||||
panic(err)
|
||||
}
|
||||
_ = os.Setenv("ZHIYI_DASHBOARD_PATH", filepath.Join(dir, "dashboard.json"))
|
||||
code := m.Run()
|
||||
_ = os.RemoveAll(dir)
|
||||
os.Exit(code)
|
||||
}
|
||||
@@ -356,25 +356,34 @@ func (tc *TuningConfig) RunHandler(w http.ResponseWriter, r *http.Request) {
|
||||
|
||||
// POST /api/v1/tuning/analytics — 运行因果分析
|
||||
func (tc *TuningConfig) AnalyticsHandler(w http.ResponseWriter, r *http.Request) {
|
||||
// 基于指标间的关系给出建议
|
||||
m := selfoptimize.Dash.Metrics()
|
||||
|
||||
suggestions := []string{}
|
||||
if m["recall_usefulness_rate"] < 0.5 && m["avg_distill_loss"] > 0.3 {
|
||||
suggestions = append(suggestions, "蒸馏质量低导致召回率低 — 建议检查 Embedding 模型")
|
||||
}
|
||||
if m["deprecated_per_day"] > 10 {
|
||||
suggestions = append(suggestions, "废弃率过高 — 正在流失大量记忆,检查冲突检测阈值")
|
||||
}
|
||||
if m["gap_closure_rate"] < 0.3 {
|
||||
suggestions = append(suggestions, "缺口闭环率过低 — Agent 未回应缺口学习请求")
|
||||
}
|
||||
if m["auto_resolve_rate"] < 0.5 {
|
||||
suggestions = append(suggestions, "自动裁决率低 — 规则覆盖不全,考虑扩展策略")
|
||||
}
|
||||
|
||||
suggestions := AnalyticsSuggestions(m)
|
||||
respond(w, 200, map[string]interface{}{
|
||||
"metrics": m,
|
||||
"suggestions": suggestions,
|
||||
})
|
||||
}
|
||||
|
||||
// AnalyticsSuggestions 依据指标间关系给出调优建议(纯函数,便于单测反例:N/A 不产生建议)。
|
||||
//
|
||||
// ⚠️ 每条建议的比率比较都必须先判 N/A(ratioFor 已封装:-1 哨兵 / valid=0 / 样本不足 ⇒ 不可用)。
|
||||
// 若直接 `m[key] < 阈值`,-1 会恒真 ⇒ 无数据也误报建议(本卡 t_c70f385c 事故面)。
|
||||
// deprecated_per_day 是计数(恒 ≥0,非比率),不走 ratioFor。
|
||||
func AnalyticsSuggestions(m map[string]float64) []string {
|
||||
suggestions := []string{}
|
||||
if hr, ok := ratioFor(m, "recall_usefulness_rate"); ok && hr < 0.5 {
|
||||
if dl, ok2 := ratioFor(m, "avg_distill_loss"); ok2 && dl > 0.3 {
|
||||
suggestions = append(suggestions, "蒸馏质量低导致召回率低 — 建议检查 Embedding 模型")
|
||||
}
|
||||
}
|
||||
if m["deprecated_per_day"] > 10 {
|
||||
suggestions = append(suggestions, "废弃率过高 — 正在流失大量记忆,检查冲突检测阈值")
|
||||
}
|
||||
if g, ok := ratioFor(m, "gap_closure_rate"); ok && g < 0.3 {
|
||||
suggestions = append(suggestions, "缺口闭环率过低 — Agent 未回应缺口学习请求")
|
||||
}
|
||||
if a, ok := ratioFor(m, "auto_resolve_rate"); ok && a < 0.5 {
|
||||
suggestions = append(suggestions, "自动裁决率低 — 规则覆盖不全,考虑扩展策略")
|
||||
}
|
||||
return suggestions
|
||||
}
|
||||
|
||||
@@ -0,0 +1,38 @@
|
||||
// AnalyticsSuggestions N/A 哨兵护栏 —— 反例 + 正向对照。
|
||||
//
|
||||
// 本卡 t_c70f385c:AnalyticsHandler 的建议 builder 原为裸 `m[key] < 阈值`,
|
||||
// -1 哨兵(样本不足/越界被拦)会让 `-1 < 0.5` 恒真 ⇒ 无数据也误报建议。
|
||||
// 现统一走 ratioFor(已封装 N/A + valid=0 + 样本不足判定)。
|
||||
package routes
|
||||
|
||||
import "testing"
|
||||
|
||||
// TestAnalyticsSuggestions_NA_NoFiring 反例:全 N/A 哨兵(-1)不产生任何建议(避免误报)。
|
||||
func TestAnalyticsSuggestions_NA_NoFiring(t *testing.T) {
|
||||
na := map[string]float64{
|
||||
"recall_usefulness_rate": -1, "recall_usefulness_samples": 0, "recall_usefulness_valid": 0,
|
||||
"avg_distill_loss": -1, "avg_distill_loss_samples": 0, "avg_distill_loss_valid": 0,
|
||||
"gap_closure_rate": -1, "gap_closure_samples": 0, "gap_closure_valid": 0,
|
||||
"auto_resolve_rate": -1, "auto_resolve_samples": 0, "auto_resolve_valid": 0,
|
||||
"deprecated_per_day": 0,
|
||||
}
|
||||
if s := AnalyticsSuggestions(na); len(s) != 0 {
|
||||
t.Fatalf("全 N/A 不应产生任何建议,实际 %d 条: %v", len(s), s)
|
||||
}
|
||||
}
|
||||
|
||||
// TestAnalyticsSuggestions_ValidLow 正向对照:有效且低于阈值时产生建议(护栏没把功能焊死)。
|
||||
func TestAnalyticsSuggestions_ValidLow(t *testing.T) {
|
||||
m := map[string]float64{
|
||||
"recall_usefulness_rate": 0.2, "recall_usefulness_samples": 100, "recall_usefulness_valid": 1,
|
||||
"gap_closure_rate": 0.1, "gap_closure_samples": 100, "gap_closure_valid": 1,
|
||||
"auto_resolve_rate": 0.2, "auto_resolve_samples": 100, "auto_resolve_valid": 1,
|
||||
"avg_distill_loss": 0.1, "avg_distill_loss_samples": 100, "avg_distill_loss_valid": 1,
|
||||
"deprecated_per_day": 0,
|
||||
}
|
||||
s := AnalyticsSuggestions(m)
|
||||
// 至少触发「gap 闭环率过低」+「自动裁决率低」两条
|
||||
if len(s) < 2 {
|
||||
t.Fatalf("有效且低于阈值应产生 ≥2 条建议,实际 %d 条: %v", len(s), s)
|
||||
}
|
||||
}
|
||||
@@ -1947,7 +1947,12 @@ func NewServer() http.Handler {
|
||||
for _, g := range gaps {
|
||||
if !g.Closed && routes.GapRepair != nil {
|
||||
if routes.GapRepair.AutoRepair(g) {
|
||||
selfoptimize.Dash.RecordGapClosed()
|
||||
// t_e5997ca4:AutoRepair 只做「修复」不关缺口。旧代码在此
|
||||
// 无条件 Dash.RecordGapClosed() 却不置 g.Closed ⇒ 同一缺口每轮
|
||||
// gap_scan 都再 +1(ClosedGaps 无限虚增,线上 9 vs 2 的写侧根因 #2)。
|
||||
// 现按 RepairHandler 语义:修复成功 = 关闭该缺口;+1 只发生在
|
||||
// Close 的 open→closed 迁移点(内部),下一轮 !g.Closed 即跳过。
|
||||
gapDetector.Close(g.Topic)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -122,20 +122,28 @@ func (te *TriggerExecutor) evaluate(t *TriggerDef, metrics map[string]float64) b
|
||||
// 检查最近的 miss 计数。
|
||||
// 2026-10-17:recall_hit_rate 已退役(恒=1、无区分度),改用 recall_usefulness_rate
|
||||
// (返回且被使用)作为「召回已产生可用结果、应清除 miss」的信号。
|
||||
// rate>0 天然排除 N/A 哨兵(-1>0 为 false)⇒ 无数据时不 fire。
|
||||
rate, ok := metrics["recall_usefulness_rate"]
|
||||
return ok && rate > 0 && t.LastFired.IsZero()
|
||||
case TQualityDrop:
|
||||
threshold, _ := t.Condition.(float64)
|
||||
return metrics["recall_usefulness_rate"] < threshold
|
||||
// N/A 哨兵(-1,样本不足/越界被拦)不得当「低于阈值」触发 —— 先排除。
|
||||
v, ok := metrics["recall_usefulness_rate"]
|
||||
return ok && !IsNA(v) && v < threshold
|
||||
case TGapDetected:
|
||||
return metrics["gap_closure_rate"] < 0.5
|
||||
// ⚠️ 事故面:gap_closure_rate=-1(样本不足/越界)时 `-1 < 0.5` 恒真 ⇒ 每轮 fire。
|
||||
// 必须先判 N/A:无数据 ⇒ 不触发缺口学习。
|
||||
v, ok := metrics["gap_closure_rate"]
|
||||
return ok && !IsNA(v) && v < 0.5
|
||||
case TConflict:
|
||||
// 原判据 metrics["auto_resolve_rate"] < 0.5 —— 该值恒为 0,故恒 true,t6 空转。
|
||||
// 新判据:人侧数据(画像/心迹/牵挂)有冲突时才 fire。
|
||||
return hasProfileOrHeartConflict(metrics)
|
||||
case TVValueLow:
|
||||
threshold, _ := t.Condition.(float64)
|
||||
return metrics["recall_usefulness_rate"] < threshold
|
||||
// N/A 哨兵先排除(同 TQualityDrop)。
|
||||
v, ok := metrics["recall_usefulness_rate"]
|
||||
return ok && !IsNA(v) && v < threshold
|
||||
case TDecayCritical:
|
||||
return metrics["deprecated_per_day"] > 5
|
||||
}
|
||||
|
||||
@@ -0,0 +1,53 @@
|
||||
// 触发器 N/A 哨兵护栏 —— 反例 + 正向对照。
|
||||
//
|
||||
// 本卡 t_c70f385c(小怡终审 2026-10-17 21:05)事故面:
|
||||
// 加了「samples<20 ⇒ -1」的最小样本门后,gap_closure_rate=-1 时
|
||||
// `executor.go:131 case TGapDetected: return metrics["gap_closure_rate"] < 0.5` 的
|
||||
// `-1 < 0.5` 恒真 ⇒ 触发器每轮都 fire。这与旧 recall_hit_rate 恒=1 是**同一类
|
||||
// 判定失真(方向相反)**。要求:所有消费点先显式判 N/A,且每个消费点配一条反例测试。
|
||||
package selfoptimize
|
||||
|
||||
import "testing"
|
||||
|
||||
// TestTriggerEvaluate_NA_Sentinel 反例:N/A 哨兵(-1)不得触发任何比率类触发器。
|
||||
func TestTriggerEvaluate_NA_Sentinel(t *testing.T) {
|
||||
te := &TriggerExecutor{}
|
||||
na := map[string]float64{
|
||||
"recall_usefulness_rate": -1,
|
||||
"gap_closure_rate": -1,
|
||||
"auto_resolve_rate": -1,
|
||||
"avg_distill_loss": -1,
|
||||
}
|
||||
if te.evaluate(&TriggerDef{Type: TGapDetected, Condition: true}, na) {
|
||||
t.Fatal("gap_closure_rate=-1(N/A)不应触发 t5,实际触发了")
|
||||
}
|
||||
if te.evaluate(&TriggerDef{Type: TQualityDrop, Condition: 0.3}, na) {
|
||||
t.Fatal("recall_usefulness_rate=-1(N/A)不应触发 t4,实际触发了")
|
||||
}
|
||||
if te.evaluate(&TriggerDef{Type: TVValueLow, Condition: 0.2}, na) {
|
||||
t.Fatal("recall_usefulness_rate=-1(N/A)不应触发 t7,实际触发了")
|
||||
}
|
||||
if te.evaluate(&TriggerDef{Type: TRecallMiss, Condition: 3}, na) {
|
||||
t.Fatal("recall_usefulness_rate=-1(N/A)不应触发 t3(rate>0 不成立),实际触发了")
|
||||
}
|
||||
}
|
||||
|
||||
// TestTriggerEvaluate_ValidLow 正向对照:有效且低于阈值时仍要触发(护栏没把功能焊死)。
|
||||
func TestTriggerEvaluate_ValidLow(t *testing.T) {
|
||||
te := &TriggerExecutor{}
|
||||
valid := map[string]float64{
|
||||
"recall_usefulness_rate": 0.2,
|
||||
"gap_closure_rate": 0.2,
|
||||
}
|
||||
if !te.evaluate(&TriggerDef{Type: TGapDetected, Condition: true}, valid) {
|
||||
t.Fatal("gap_closure_rate=0.2 (<0.5, 有效) 应触发 t5")
|
||||
}
|
||||
if !te.evaluate(&TriggerDef{Type: TQualityDrop, Condition: 0.3}, valid) {
|
||||
t.Fatal("recall_usefulness_rate=0.2 (<0.3, 有效) 应触发 t4")
|
||||
}
|
||||
// 有效且高于阈值 ⇒ 不触发
|
||||
hi := map[string]float64{"gap_closure_rate": 0.9, "recall_usefulness_rate": 0.9}
|
||||
if te.evaluate(&TriggerDef{Type: TGapDetected, Condition: true}, hi) {
|
||||
t.Fatal("gap_closure_rate=0.9 (>0.5, 有效) 不应触发 t5")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,148 @@
|
||||
// 织忆 MemoryWeave — gap 计数器写侧统一回归(t_e5997ca4)
|
||||
//
|
||||
// 口径铁律:ClosedGaps/TotalGaps = 「缺口个数」(同一缺口至多计 1 次)。
|
||||
// +1 的唯一合法入口 = GapDetector 的 open→closed 迁移点(Close/RecordHit 内部)。
|
||||
package selfoptimize
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"testing"
|
||||
)
|
||||
|
||||
// createGapForTest 3 次 miss 命中默认阈值 3 ⇒ 生成缺口(TotalGaps +1)。
|
||||
func createGapForTest(t *testing.T, gd *GapDetector, topic string) *Gap {
|
||||
t.Helper()
|
||||
var gap *Gap
|
||||
for i := 0; i < 3; i++ {
|
||||
if gap = gd.RecordMiss(topic); gap != nil {
|
||||
break
|
||||
}
|
||||
}
|
||||
if gap == nil {
|
||||
t.Fatalf("expected gap for %s after 3 misses (threshold=%d)", topic, GapThreshold())
|
||||
}
|
||||
return gap
|
||||
}
|
||||
|
||||
// 卡 AC1:同一 topic 连续 Close() 3 次 ⇒ ClosedGaps 只 +1,gap_closure_rate <= 1。
|
||||
func TestGapCounter_CloseThreeTimesCountsOnce(t *testing.T) {
|
||||
zeroDash()
|
||||
gd := NewGapDetector(nil, nil)
|
||||
createGapForTest(t, gd, "idempotent-close")
|
||||
|
||||
baseClosed := Dash.ClosedGaps
|
||||
if !gd.Close("idempotent-close") {
|
||||
t.Fatal("第 1 次 Close 应返回 true(open→closed 真迁移)")
|
||||
}
|
||||
if gd.Close("idempotent-close") {
|
||||
t.Fatal("第 2 次 Close 应返回 false(已关闭,no-op)")
|
||||
}
|
||||
if gd.Close("idempotent-close") {
|
||||
t.Fatal("第 3 次 Close 应返回 false(已关闭,no-op)")
|
||||
}
|
||||
|
||||
if got := Dash.ClosedGaps - baseClosed; got != 1 {
|
||||
t.Fatalf("3× Close 后 ClosedGaps 增量: got %d, want 1(同一缺口只计 1 次)", got)
|
||||
}
|
||||
m := Dash.Metrics()
|
||||
if m["gap_closure_rate"] > 1 {
|
||||
t.Errorf("gap_closure_rate = %f 越界(>1),写侧仍有污染", m["gap_closure_rate"])
|
||||
}
|
||||
}
|
||||
|
||||
// 召回命中自动关闭入口同口径:RecordHit ×3 ⇒ +1。
|
||||
func TestGapCounter_RecordHitCountsOnce(t *testing.T) {
|
||||
zeroDash()
|
||||
gd := NewGapDetector(nil, nil)
|
||||
createGapForTest(t, gd, "record-hit-topic")
|
||||
|
||||
baseClosed := Dash.ClosedGaps
|
||||
if !gd.RecordHit("record-hit-topic") {
|
||||
t.Fatal("第 1 次 RecordHit 应返回 true")
|
||||
}
|
||||
if gd.RecordHit("record-hit-topic") {
|
||||
t.Fatal("第 2 次 RecordHit 应返回 false")
|
||||
}
|
||||
if gd.RecordHit("record-hit-topic") {
|
||||
t.Fatal("第 3 次 RecordHit 应返回 false")
|
||||
}
|
||||
if got := Dash.ClosedGaps - baseClosed; got != 1 {
|
||||
t.Fatalf("3× RecordHit 后 ClosedGaps 增量: got %d, want 1", got)
|
||||
}
|
||||
}
|
||||
|
||||
// 卡根因 #2 的修复面:server.go gap_scan 自动修复循环。
|
||||
// 修复后语义 = 「修复成功 ⇒ 关闭缺口」,+1 只在迁移点发生;
|
||||
// 改前模式(事件式 +1 且不关缺口)同一场景为每轮 +1(3 轮 = +3 ⇒ 无限虚增)。
|
||||
func TestGapCounter_AutoRepairLoopPatternCountsOnce(t *testing.T) {
|
||||
zeroDash()
|
||||
gd := NewGapDetector(nil, nil)
|
||||
g := createGapForTest(t, gd, "autorepair-loop")
|
||||
|
||||
baseClosed := Dash.ClosedGaps
|
||||
for cycle := 0; cycle < 3; cycle++ { // 模拟 3 轮 gap_scan
|
||||
if !g.Closed {
|
||||
repaired := true // AutoRepair 对 Type B/C(ldb 在场)恒 true 的替代
|
||||
if repaired {
|
||||
gd.Close(g.Topic) // 修复后口径:关闭缺口,+1 仅在 Close 迁移点
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if got := Dash.ClosedGaps - baseClosed; got != 1 {
|
||||
t.Fatalf("3 轮修复循环后 ClosedGaps 增量: got %d, want 1(改前模式为 +3 ⇒ 虚增)", got)
|
||||
}
|
||||
}
|
||||
|
||||
// 卡任务 3 (b):计数器版本化一次性重置。
|
||||
// v1 落盘(无 dashboard_schema_version 标记,线上 9/2 值)加载 ⇒ gap 双计数器归 0 + 回写标记,
|
||||
// 其余计数器保真;标记在位后加载 ⇒ 保真、不再重置(一次性,可机械复核)。
|
||||
func TestDashboard_SchemaV2OneTimeReset(t *testing.T) {
|
||||
p := filepath.Join(t.TempDir(), "dash.json")
|
||||
t.Setenv("ZHIYI_DASHBOARD_PATH", p)
|
||||
|
||||
v1 := `{"useful_count":5,"not_useful_count":1,"total_recalls":10,"hit_count":8,` +
|
||||
`"closed_gaps":9,"total_gaps":2,"cascade_fixed_total":0,"total_fixes":0,` +
|
||||
`"deprecated_today":0,"deprecated_date":"","distill_loss_sum":0,"distill_loss_count":0,` +
|
||||
`"distill_success_count":0,"auto_resolved_conflicts":0,"total_conflicts":0}`
|
||||
if err := os.WriteFile(p, []byte(v1), 0o600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
zeroDash()
|
||||
if err := loadDashboardLocal(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if Dash.ClosedGaps != 0 || Dash.TotalGaps != 0 {
|
||||
t.Fatalf("v1 加载应一次性重置 gap 计数器: got closed=%d total=%d, want 0/0", Dash.ClosedGaps, Dash.TotalGaps)
|
||||
}
|
||||
if Dash.UsefulCount != 5 || Dash.HitCount != 8 {
|
||||
t.Errorf("其余计数器应保真: useful=%d hit=%d, want 5/8", Dash.UsefulCount, Dash.HitCount)
|
||||
}
|
||||
|
||||
// 标记应已回写落盘
|
||||
var st dashboardState
|
||||
if b, err := os.ReadFile(p); err == nil {
|
||||
_ = json.Unmarshal(b, &st)
|
||||
if st.SchemaVersion != dashboardSchemaV2 {
|
||||
t.Errorf("v2 标记未回写: got %q want %q", st.SchemaVersion, dashboardSchemaV2)
|
||||
}
|
||||
}
|
||||
|
||||
// 第二次加载(标记在位 + 新口径累计值)⇒ 保真、不再重置
|
||||
Dash.mu.Lock()
|
||||
Dash.ClosedGaps = 7
|
||||
Dash.TotalGaps = 20
|
||||
Dash.persist() // 测试环境 redisPersistence=nil ⇒ 写本地 JSON(ZHIYI_DASHBOARD_PATH 已指到临时目录)
|
||||
Dash.mu.Unlock()
|
||||
|
||||
zeroDash()
|
||||
if err := loadDashboardLocal(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if Dash.ClosedGaps != 7 || Dash.TotalGaps != 20 {
|
||||
t.Fatalf("v2 标记在位应保真: got %d/%d, want 7/20", Dash.ClosedGaps, Dash.TotalGaps)
|
||||
}
|
||||
}
|
||||
@@ -16,6 +16,17 @@ import (
|
||||
// Redis persistence key
|
||||
const dashboardRedisKey = "zhiyi:dashboard"
|
||||
|
||||
// dashboardSchemaV2 缺口计数器版本标记(t_e5997ca4,三选一改 (b):计数器版本化重置)。
|
||||
//
|
||||
// 依据:历史 ClosedGaps/TotalGaps 被事件式自增污染(线上实测 closed_gaps=9 vs
|
||||
// total_gaps=2,Redis HASH zhiyi:dashboard),且无法对账还原「哪 9 次关闭对应哪 2 个
|
||||
// 缺口」——(a) min() 对账是伪造数据,(c) 等 TotalGaps 追上的时长不可估且期间指标恒 -1。
|
||||
// 做法:首次加载见到 marker 缺失/非 v2 ⇒ 一次性把 ClosedGaps/TotalGaps 重置为 0 并回写
|
||||
// marker;此后加载保真(v2 起按「缺口个数」口径从头累计)。
|
||||
// 代价(写明):丢失 gap 双计数器的历史累计值——其本身就是不可信数据(虚增产物),
|
||||
// 不掩盖。其他计数器(useful/cascade/auto/distill)口径无事件污染,一律不动。
|
||||
const dashboardSchemaV2 = "dashboard_schema_v2"
|
||||
|
||||
// dashboardLocalPath 本地 JSON 落盘点 —— Redis 不可用时的兜底(2026-09-27 加)
|
||||
//
|
||||
// 背景:本机无 Redis(无 redis-cli/redis-server、6379 无监听、单元无 REDIS_ADDR/URL)
|
||||
@@ -49,6 +60,8 @@ type dashboardState struct {
|
||||
DistillSuccessCount int `json:"distill_success_count"`
|
||||
AutoResolvedConflicts int `json:"auto_resolved_conflicts"`
|
||||
TotalConflicts int `json:"total_conflicts"`
|
||||
// t_e5997ca4:计数器版本标记(见 dashboardSchemaV2 注释)。
|
||||
SchemaVersion string `json:"dashboard_schema_version"`
|
||||
}
|
||||
|
||||
func todayStr() string { return time.Now().Format("2006-01-02") }
|
||||
@@ -96,6 +109,13 @@ func loadDashboardLocal() error {
|
||||
Dash.DistillSuccessCount = st.DistillSuccessCount
|
||||
Dash.AutoResolvedConflicts = st.AutoResolvedConflicts
|
||||
Dash.TotalConflicts = st.TotalConflicts
|
||||
// t_e5997ca4 (b):版本化一次性重置。本地 JSON 无 v2 标记(旧版/缺失)⇒ 丢弃被
|
||||
// 事件式自增污染的 gap 双计数器,回写标记;v2 标记在位 ⇒ 保真(新口径累计值)。
|
||||
if st.SchemaVersion != dashboardSchemaV2 {
|
||||
Dash.ClosedGaps = 0
|
||||
Dash.TotalGaps = 0
|
||||
Dash.persist() // 回写 v2 标记(调用方已持 Dash.mu ✓;Redis 不可用则落本地 JSON)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
@@ -118,6 +138,7 @@ func (d *Dashboard) persistLocalLocked() {
|
||||
DistillSuccessCount: d.DistillSuccessCount,
|
||||
AutoResolvedConflicts: d.AutoResolvedConflicts,
|
||||
TotalConflicts: d.TotalConflicts,
|
||||
SchemaVersion: dashboardSchemaV2, // t_e5997ca4:v2 常驻回写(新安装/旧版升级都自动打标)
|
||||
}
|
||||
b, err := json.Marshal(st)
|
||||
if err != nil {
|
||||
@@ -152,6 +173,7 @@ func (d *Dashboard) persist() {
|
||||
_ = redisPersistence.HSet(dashboardRedisKey, "distill_success_count", strconv.Itoa(d.DistillSuccessCount))
|
||||
_ = redisPersistence.HSet(dashboardRedisKey, "auto_resolved_conflicts", strconv.Itoa(d.AutoResolvedConflicts))
|
||||
_ = redisPersistence.HSet(dashboardRedisKey, "total_conflicts", strconv.Itoa(d.TotalConflicts))
|
||||
_ = redisPersistence.HSet(dashboardRedisKey, "dashboard_schema_version", dashboardSchemaV2) // t_e5997ca4:v2 标记常驻回写
|
||||
_ = redisPersistence.Expire(dashboardRedisKey, 90*24*time.Hour) // 90 天 TTL
|
||||
}
|
||||
|
||||
@@ -209,6 +231,13 @@ func loadDashboard() error {
|
||||
if v, err := strconv.Atoi(data["total_conflicts"]); err == nil {
|
||||
Dash.TotalConflicts = v
|
||||
}
|
||||
// t_e5997ca4 (b):版本化一次性重置(Redis 路径)。HASH 无 v2 标记(旧版遗留/缺失)⇒
|
||||
// 丢弃被事件式自增污染的 gap 双计数器(线上 9 vs 2 实例),回写标记;v2 在位 ⇒ 保真。
|
||||
if data["dashboard_schema_version"] != dashboardSchemaV2 {
|
||||
Dash.ClosedGaps = 0
|
||||
Dash.TotalGaps = 0
|
||||
Dash.persist() // 回写 v2 标记(调用方已持 Dash.mu ✓)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
@@ -260,6 +289,15 @@ func rateOrNA(num, den int) float64 {
|
||||
return math.Round(float64(num)/float64(den)*100) / 100
|
||||
}
|
||||
|
||||
// IsNA 判定指标值是否为「无数据」哨兵(metricNA < 0)。
|
||||
//
|
||||
// ⚠️ 消费者铁律:触发器 / 调优建议 / 面板解读等所有消费点在拿比率值跟阈值
|
||||
// 比较之前,必须先排除 N/A。-1 是哨兵(样本不足 或 越界被拦),不是「低分」,
|
||||
// 若直接 `v < 阈值` 会恒为 true ⇒ 每轮误触发(本卡 t_c70f385c 事故面:
|
||||
// gap_closure_rate=-1 让「降低 gap 阈值」触发器每轮 fire,与旧 recall_hit_rate 恒=1
|
||||
// 是同类判定失真、方向相反)。故:v < 0 ⇒ 跳过 / 不触发。
|
||||
func IsNA(v float64) bool { return v < 0 }
|
||||
|
||||
// minRateSamples 是率类指标的最小样本门。
|
||||
//
|
||||
// 样本太少(< 20)时,即使比率为真值也**统计上不可解读** —— 例如 auto_resolve_rate
|
||||
@@ -638,27 +676,38 @@ func (gd *GapDetector) List() []*Gap {
|
||||
return result
|
||||
}
|
||||
|
||||
func (gd *GapDetector) Close(topic string) {
|
||||
// Close 关闭 topic 对应的缺口,返回本次调用是否真的发生了 open→closed 迁移。
|
||||
//
|
||||
// t_e5997ca4 写侧统一:ClosedGaps/TotalGaps 口径为「缺口个数」(同一缺口至多计 1 次)。
|
||||
// +1 的唯一入口在本迁移点(g.Closed false→true 时),重复调用/多入口重复关闭永不虚增;
|
||||
// 外部调用方(routes / server 循环)禁止再做无条件 RecordGapClosed 式事件自增
|
||||
// ——历史 9 vs 2 不一致(closed_gaps=9 / total_gaps=2)正是那样污染的。
|
||||
// 返回值语义:true = 首次关闭(仪表盘计数已随迁移 +1);
|
||||
// false = 已关闭或未知 topic(no-op,调用方不得再动计数)。
|
||||
func (gd *GapDetector) Close(topic string) bool {
|
||||
gd.mu.Lock()
|
||||
defer gd.mu.Unlock()
|
||||
// 统一「缺口个数」口径:仅当缺口从未关闭时才算一次闭环(与 RecordHit 一致),
|
||||
// 否则同一缺口被 Close 重复调用会让 ClosedGaps 虚增、gap_closure_rate 越界 > 1。
|
||||
if g, ok := gd.gaps[topic]; ok && !g.Closed {
|
||||
g.Closed = true
|
||||
gd.persistGaps()
|
||||
Dash.RecordGapClosed() // 同步仪表盘
|
||||
Dash.recordGapClosed() // 迁移内 +1(唯一入口)
|
||||
return true
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
// RecordHit 记录一次召回命中,自动关闭该 topic 的 open gap
|
||||
func (gd *GapDetector) RecordHit(topic string) {
|
||||
// RecordHit 记录一次召回命中,自动关闭该 topic 的 open gap。
|
||||
// 返回语义与 Close 一致:true = 本次命中真的发生了 open→closed 迁移。
|
||||
func (gd *GapDetector) RecordHit(topic string) bool {
|
||||
gd.mu.Lock()
|
||||
defer gd.mu.Unlock()
|
||||
if g, ok := gd.gaps[topic]; ok && !g.Closed {
|
||||
g.Closed = true
|
||||
gd.persistGaps()
|
||||
Dash.RecordGapClosed()
|
||||
Dash.recordGapClosed() // 迁移内 +1(唯一入口)
|
||||
return true
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
// ClearMisses 清除某个 topic 的 miss 计数(recall 命中后调用)
|
||||
@@ -887,14 +936,34 @@ func (d *Dashboard) RecordCorrection(source string) {
|
||||
d.persist()
|
||||
}
|
||||
|
||||
// RecordGapClosed 记录缺口关闭
|
||||
func (d *Dashboard) RecordGapClosed() {
|
||||
// recordGapClosed 记录缺口关闭(+1 ClosedGaps 并持久化)。
|
||||
//
|
||||
// ⚠️ t_e5997ca4 起降为包内(小写):+1 的唯一合法入口是 GapDetector 的
|
||||
// open→closed 迁移点(Close / RecordHit 内部)。跨包事件式无条件调用
|
||||
// (旧 gaps.go:44 / server.go:1950 那种)会让同一缺口被无限计数、
|
||||
// ClosedGaps 越过 TotalGaps(历史 9 vs 2 的根因)⇒ 用包边界从编译期堵死。
|
||||
// 需要「本次是否真的关闭」语义的外部调用方,看 Close/RecordHit 的 bool 返回值。
|
||||
func (d *Dashboard) recordGapClosed() {
|
||||
d.mu.Lock()
|
||||
defer d.mu.Unlock()
|
||||
d.ClosedGaps++
|
||||
d.persist()
|
||||
}
|
||||
|
||||
// ClosedGapsCount 只读快照访问器(跨包审计/测试用;调用方自持锁语义不暴露)。
|
||||
func (d *Dashboard) ClosedGapsCount() int {
|
||||
d.mu.RLock()
|
||||
defer d.mu.RUnlock()
|
||||
return d.ClosedGaps
|
||||
}
|
||||
|
||||
// TotalGapsCount 只读快照访问器(跨包审计/测试用)。
|
||||
func (d *Dashboard) TotalGapsCount() int {
|
||||
d.mu.RLock()
|
||||
defer d.mu.RUnlock()
|
||||
return d.TotalGaps
|
||||
}
|
||||
|
||||
// RecordConflictResolved 记录冲突解决
|
||||
func (d *Dashboard) RecordConflictResolved(auto bool) {
|
||||
d.mu.Lock()
|
||||
|
||||
@@ -0,0 +1,130 @@
|
||||
package storage
|
||||
|
||||
import (
|
||||
"encoding/binary"
|
||||
"io"
|
||||
"net"
|
||||
"os"
|
||||
"os/exec"
|
||||
"path/filepath"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
// t_576714de AC2:「边车即使短暂不可用 ⇒ zhiyid 的 IPC 客户端能重连」拆成两半验证:
|
||||
//
|
||||
// ① 挂死不无限阻塞:侧车接受连接后永不响应(模拟 thrash 中被 kill / 卡住)时,
|
||||
// 旧实现 io.ReadFull 无 deadline ⇒ 客户端永久挂起(「边车好了它还挂着」)。
|
||||
// 修复后读 deadline 封顶,超时即返回错误,调用方降级(Search→本地兜底),recall 不挂。
|
||||
// ② 真·重连:每次 rpc 都是新 dial。侧车被杀 ⇒ 快速失败(不挂起);侧车重启 ⇒ 下一次
|
||||
// rpc 重新 dial 成功,无需持有长连接。
|
||||
//
|
||||
// TestIPCReadDeadlineBoundsHungSidecar 是纯 Go 自包含(无需真实 sidecar 二进制),恒跑。
|
||||
// TestIPCReconnectAfterSidecarRestart 需真实 sidecar(env 门控,未设则跳过)。
|
||||
|
||||
func TestIPCReadDeadlineBoundsHungSidecar(t *testing.T) {
|
||||
// Unix socket sun_path 上限 108 字节:t.TempDir() 路径过长会 EINVAL,改用 /tmp 短路径。
|
||||
tmp, err := os.MkdirTemp(os.TempDir(), "zyri")
|
||||
if err != nil {
|
||||
t.Fatalf("mkdtemp: %v", err)
|
||||
}
|
||||
defer os.RemoveAll(tmp)
|
||||
sock := filepath.Join(tmp, "h.sock")
|
||||
l, err := net.Listen("unix", sock)
|
||||
if err != nil {
|
||||
t.Fatalf("listen: %v", err)
|
||||
}
|
||||
defer l.Close()
|
||||
// 侧车替身:accept 后读满请求(长度前缀 + body)但【永不回响应】= 模拟挂死。
|
||||
go func() {
|
||||
for {
|
||||
c, aerr := l.Accept()
|
||||
if aerr != nil {
|
||||
return
|
||||
}
|
||||
go func(conn net.Conn) {
|
||||
var lenBuf [4]byte
|
||||
_, _ = io.ReadFull(conn, lenBuf[:])
|
||||
n := binary.BigEndian.Uint32(lenBuf[:])
|
||||
buf := make([]byte, n)
|
||||
_, _ = io.ReadFull(conn, buf)
|
||||
// 之后不回任何字节 → 客户端 ReadFull 一直阻塞到读 deadline。
|
||||
}(c)
|
||||
}
|
||||
}()
|
||||
|
||||
origRead, origWrite := ipcReadTimeout, ipcWriteTimeout
|
||||
ipcReadTimeout = 800 * time.Millisecond
|
||||
ipcWriteTimeout = 5 * time.Second
|
||||
defer func() { ipcReadTimeout, ipcWriteTimeout = origRead, origWrite }()
|
||||
|
||||
rc := NewRustLanceDBClient(sock, nil)
|
||||
start := time.Now()
|
||||
_, rpcErr := rc.rpc(ipcReq{Type: "lancedb_search", Vector: make([]float32, 1024), TopK: 5})
|
||||
elapsed := time.Since(start)
|
||||
|
||||
if rpcErr == nil {
|
||||
t.Fatalf("期望读 deadline 超时返回错误,实际成功(deadline 未生效)")
|
||||
}
|
||||
if elapsed < 600*time.Millisecond {
|
||||
t.Fatalf("错误返回过早(%s)—— 不像读 deadline 触发(应是 ~%s 后)", elapsed, ipcReadTimeout)
|
||||
}
|
||||
if elapsed > 15*time.Second {
|
||||
t.Fatalf("仍长时间阻塞(%s)—— 读 deadline 未封顶,挂死未被兜住", elapsed)
|
||||
}
|
||||
t.Logf("挂死侧车被读 deadline 兜住:err=%v in %s(上限 %s,不再无限阻塞 ⇒ recall 可降级不挂)", rpcErr, elapsed, ipcReadTimeout)
|
||||
}
|
||||
|
||||
// startSidecarForTest 启动真实 sidecar(socket 路径 + 数据目录);返回 *exec.Cmd 供后续 kill。
|
||||
func startSidecarForTest(t *testing.T, bin, sock, dataDir string) *exec.Cmd {
|
||||
t.Helper()
|
||||
cmd := exec.Command(bin, "--mode", "socket", "--socket", sock, "--data-dir", dataDir)
|
||||
cmd.Stdout, cmd.Stderr = io.Discard, io.Discard
|
||||
if err := cmd.Start(); err != nil {
|
||||
t.Fatalf("启动 sidecar 失败: %v", err)
|
||||
}
|
||||
return cmd
|
||||
}
|
||||
|
||||
func TestIPCReconnectAfterSidecarRestart(t *testing.T) {
|
||||
bin := os.Getenv("ZHIYI_TEST_SIDECAR_BIN")
|
||||
dataDir := os.Getenv("ZHIYI_TEST_DATA_DIR")
|
||||
if bin == "" || dataDir == "" {
|
||||
t.Skip("ZHIYI_TEST_SIDECAR_BIN / ZHIYI_TEST_DATA_DIR 未设置,跳过真·重连验证")
|
||||
}
|
||||
sock := filepath.Join(dataDir, "reconnect-test.sock")
|
||||
|
||||
// 1) 起 sidecar → rpc 成功
|
||||
proc := startSidecarForTest(t, bin, sock, dataDir)
|
||||
time.Sleep(4 * time.Second)
|
||||
rc := NewRustLanceDBClient(sock, nil)
|
||||
if _, err := rc.rpc(ipcReq{Type: "zhiyi_ping"}); err != nil {
|
||||
proc.Process.Kill()
|
||||
t.Fatalf("重启前 ping 应成功: %v", err)
|
||||
}
|
||||
|
||||
// 2) 杀掉 sidecar → 下一次 rpc【快速失败】(dial 上限 5s),不挂起
|
||||
if err := proc.Process.Kill(); err != nil {
|
||||
t.Logf("kill warning: %v", err)
|
||||
}
|
||||
_ = proc.Wait()
|
||||
start := time.Now()
|
||||
_, derr := rc.rpc(ipcReq{Type: "zhiyi_ping"})
|
||||
downElapsed := time.Since(start)
|
||||
if derr == nil {
|
||||
t.Fatalf("sidecar 被杀后 rpc 应失败,实际成功(未感知不可用)")
|
||||
}
|
||||
if downElapsed > 6*time.Second {
|
||||
t.Fatalf("sidecar 不可用时未快速失败(用了 %s > 6s dial 上限)—— 疑似挂起", downElapsed)
|
||||
}
|
||||
t.Logf("sidecar 不可用 ⇒ rpc 快速失败 in %s(dial 上限 5s,不挂起)", downElapsed)
|
||||
|
||||
// 3) 重启 sidecar(Rust 侧会清掉陈旧 socket 再 bind)→ 下一次 rpc 成功 = 重连成立
|
||||
proc2 := startSidecarForTest(t, bin, sock, dataDir)
|
||||
defer func() { _ = proc2.Process.Kill() }()
|
||||
time.Sleep(4 * time.Second)
|
||||
if _, err := rc.rpc(ipcReq{Type: "zhiyi_ping"}); err != nil {
|
||||
t.Fatalf("sidecar 重启后 rpc 应成功(重连),实际: %v", err)
|
||||
}
|
||||
t.Log("sidecar 重启后 rpc 成功 = 重连成立(每次 rpc 新 dial,无需长连接)")
|
||||
}
|
||||
@@ -35,6 +35,18 @@ func NewRustLanceDBClient(sockPath string, emb *Embedder) *RustLanceDBClient {
|
||||
|
||||
// ─── IPC 协议 ────────────────────────────────────────────
|
||||
|
||||
// t_576714de:单次重读被行数上限截断后,最重的一次响应(20000 行 JSON)在内存
|
||||
// 紧张时实测 ~43s。读 deadline 取 120s(>> 任何合法操作,≪ 无限阻塞);侧车接受
|
||||
// 连接后挂死/被 kill 时,旧实现 io.ReadFull 无 deadline ⇒ 客户端永久阻塞
|
||||
// (「边车好了它还挂着」)。封顶后超时即返回错误,调用方降级(Search→本地兜底),
|
||||
// 且每次 rpc 都是新 dial ⇒ 侧车恢复后下一次调用天然重连。
|
||||
// 用 var(非 const)便于测试临时缩短读超时验证「挂死不被无限阻塞」。
|
||||
var (
|
||||
ipcDialTimeout = 5 * time.Second
|
||||
ipcWriteTimeout = 30 * time.Second
|
||||
ipcReadTimeout = 120 * time.Second
|
||||
)
|
||||
|
||||
type ipcReq struct {
|
||||
Type string `json:"type"`
|
||||
Table string `json:"table,omitempty"`
|
||||
@@ -63,6 +75,9 @@ type ipcResp struct {
|
||||
Result string `json:"result"` // lancedb search uses this
|
||||
FailureStep string `json:"failure_step"`
|
||||
ErrorDetail string `json:"error_detail"`
|
||||
// t_576714de:单次重读被 Rust 侧行数上限截断时 = true(部分结果,非全量)。
|
||||
// 旧 sidecar 无此字段 ⇒ 缺省 false,向后兼容。
|
||||
Truncated bool `json:"truncated"`
|
||||
}
|
||||
|
||||
// updateField lancedb_update 的单列更新项:Value 为 SQL 表达式
|
||||
@@ -73,22 +88,37 @@ type updateField struct {
|
||||
}
|
||||
|
||||
func (rc *RustLanceDBClient) rpc(req ipcReq) (*ipcResp, error) {
|
||||
conn, err := net.DialTimeout("unix", rc.sockPath, 5*time.Second)
|
||||
// 每次调用都是新 dial:侧车不可用(socket 消失/无监听)⇒ 快速失败;
|
||||
// 侧车恢复后下一次调用天然重连(t_576714de AC)。
|
||||
conn, err := net.DialTimeout("unix", rc.sockPath, ipcDialTimeout)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("ipc dial: %w", err)
|
||||
}
|
||||
defer conn.Close()
|
||||
// 给已建立连接封顶读/写 deadline:侧车接受连接后挂死/被 kill ⇒ 旧实现
|
||||
// io.ReadFull 无限阻塞(「边车好了它还挂着」)。现超时即降级,热路径 recall 不受阻。
|
||||
now := time.Now()
|
||||
_ = conn.SetWriteDeadline(now.Add(ipcWriteTimeout))
|
||||
_ = conn.SetReadDeadline(now.Add(ipcReadTimeout))
|
||||
|
||||
body, _ := json.Marshal(req)
|
||||
lenBuf := make([]byte, 4)
|
||||
binary.BigEndian.PutUint32(lenBuf, uint32(len(body)))
|
||||
conn.Write(lenBuf)
|
||||
conn.Write(body)
|
||||
if _, err := conn.Write(lenBuf); err != nil {
|
||||
return nil, fmt.Errorf("ipc write len: %w", err)
|
||||
}
|
||||
if _, err := conn.Write(body); err != nil {
|
||||
return nil, fmt.Errorf("ipc write body: %w", err)
|
||||
}
|
||||
|
||||
io.ReadFull(conn, lenBuf)
|
||||
if _, err := io.ReadFull(conn, lenBuf); err != nil {
|
||||
return nil, fmt.Errorf("ipc read len (sidecar down/hung, read deadline %s): %w", ipcReadTimeout, err)
|
||||
}
|
||||
msgLen := binary.BigEndian.Uint32(lenBuf)
|
||||
respBuf := make([]byte, msgLen)
|
||||
io.ReadFull(conn, respBuf)
|
||||
if _, err := io.ReadFull(conn, respBuf); err != nil {
|
||||
return nil, fmt.Errorf("ipc read body (sidecar down/hung, read deadline %s): %w", ipcReadTimeout, err)
|
||||
}
|
||||
|
||||
var resp ipcResp
|
||||
if err := json.Unmarshal(respBuf, &resp); err != nil {
|
||||
@@ -243,6 +273,10 @@ func (rc *RustLanceDBClient) Search(table string, vector []float32, topK int, na
|
||||
Vector []float32 `json:"vector"`
|
||||
}
|
||||
json.Unmarshal([]byte(resp.ReportJSON), &raw)
|
||||
if resp.Truncated {
|
||||
// t_576714de:Rust 侧单次重读被行数上限截断(部分结果,非全量)—— 显式日志,禁静默。
|
||||
log.Printf("[ipc] Search truncated: single-read cap applied, got %d rows (partial result)", len(raw))
|
||||
}
|
||||
if len(raw) == 0 {
|
||||
log.Printf("[ipc] Search: resp.ReportJSON unmarshal gave 0 results, falling back to localSearch (Result=%q)", resp.Result)
|
||||
return rc.localSearch(vector, topK, namespaceFilter), nil
|
||||
@@ -428,6 +462,10 @@ func (rc *RustLanceDBClient) ScanAll() ([]models.MemoryRecord, error) {
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("scan_all unmarshal: %w", err)
|
||||
}
|
||||
if resp.Truncated {
|
||||
// t_576714de:单次扫描被行数上限截断(部分结果)—— 显式日志,禁静默。
|
||||
log.Printf("[ipc] ScanAll truncated: single-read cap applied, got %d rows (partial)", len(out))
|
||||
}
|
||||
// 同步到本地缓存(与 GetSkillCandidates 同款)
|
||||
_local.mu.Lock()
|
||||
for i := range out {
|
||||
@@ -515,6 +553,10 @@ func (rc *RustLanceDBClient) ScanDeleted() ([]models.MemoryRecord, error) {
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("scan_deleted unmarshal: %w", err)
|
||||
}
|
||||
if resp.Truncated {
|
||||
// t_576714de:单次扫描被行数上限截断(部分结果)—— 显式日志,禁静默。
|
||||
log.Printf("[ipc] ScanDeleted truncated: single-read cap applied, got %d rows (partial)", len(out))
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
|
||||
|
||||
@@ -1058,8 +1058,9 @@ impl LanceDBOps {
|
||||
|
||||
/// 全表扫描(元数据;2026-09-21 治本改造)
|
||||
/// ① 用 Select 投影跳过 vector 列(1024 维 = 4KB/条,Step 3/4 都不需要)
|
||||
/// ② 上限从 10000 提到 200000(原值会静默丢记录:库已有 10065 条)
|
||||
pub fn scan_all(&self) -> Result<Vec<MemoryRecord>, Box<dyn std::error::Error>> {
|
||||
/// ② 上限由调用方传入 max_rows(IPC 边界 = 单次重读硬上限 heavy_read_max_rows(),
|
||||
/// 整合内部全量 = 200_000;t_576714de)
|
||||
pub fn scan_all(&self, max_rows: usize) -> Result<Vec<MemoryRecord>, Box<dyn std::error::Error>> {
|
||||
let db = rt().block_on(lancedb::connect(self.data_dir.to_str().unwrap()).execute())?;
|
||||
let tbl = rt().block_on(db.open_table("memories").execute())?;
|
||||
|
||||
@@ -1081,7 +1082,7 @@ impl LanceDBOps {
|
||||
tbl.query()
|
||||
.only_if("is_deleted = false")
|
||||
.select(Select::columns(META_COLUMNS))
|
||||
.limit(200_000)
|
||||
.limit(max_rows)
|
||||
.execute()
|
||||
)?);
|
||||
|
||||
@@ -1143,8 +1144,9 @@ impl LanceDBOps {
|
||||
/// 都过滤 is_deleted=false —— 存量 11228 条 is_deleted=true 的行**没有任何读路径能看**
|
||||
/// (唯独 stats 能 count)。回填脚本需要枚举已删除行以回填 delete_reason 并出直方图。
|
||||
///
|
||||
/// 只读元数据(跳 vector),上限 200000。带 delete_reason 列(供回填时跳过已回填的)。
|
||||
pub fn scan_deleted(&self) -> Result<Vec<MemoryRecord>, Box<dyn std::error::Error>> {
|
||||
/// 只读元数据(跳 vector),上限由调用方传入 max_rows(IPC 边界 = 单次重读硬上限,
|
||||
/// 整合/回填脚本按需传全量;t_576714de)。带 delete_reason 列(供回填时跳过已回填的)。
|
||||
pub fn scan_deleted(&self, max_rows: usize) -> Result<Vec<MemoryRecord>, Box<dyn std::error::Error>> {
|
||||
let db = rt().block_on(lancedb::connect(self.data_dir.to_str().unwrap()).execute())?;
|
||||
let tbl = rt().block_on(db.open_table("memories").execute())?;
|
||||
|
||||
@@ -1164,7 +1166,7 @@ impl LanceDBOps {
|
||||
tbl.query()
|
||||
.only_if("is_deleted = true")
|
||||
.select(Select::columns(META_COLUMNS))
|
||||
.limit(200_000)
|
||||
.limit(max_rows)
|
||||
.execute()
|
||||
)?);
|
||||
|
||||
|
||||
+73
-12
@@ -76,6 +76,22 @@ impl Drop for ConsolidatingGuard {
|
||||
static HEAVY_READ_DEFAULT: usize = 2;
|
||||
static HEAVY_READ_WAIT_MS: u64 = 100;
|
||||
|
||||
// ─── 单次重读行数上限(方案②,t_576714de,2026-10-17 残留缺口)────────
|
||||
// N=2 准入只拦「并发叠加」,不拦「单次请求自身的内存量」:一个 top_k=1000000 /
|
||||
// scan_all 请求可独自吞下全表(实测 43547 行 × 1024 维向量 ≈ 260MB Rust + JSON ~650MB),
|
||||
// 照样 thrash(t_eedb2d39 根因复盘定性的 ② 单次量无上限)。
|
||||
// 治本:给单次重读的**返回行数**设硬上限(默认 20000,env ZHIYI_HEAVY_READ_MAX_ROWS 可调)。
|
||||
// 请求量超上限 ⇒ 截断到上限 + 标记 truncated:true(降级返回部分结果,而非硬吃内存)。
|
||||
// 热路径 recall 的 top_k ≤ 1000 永不触发;只挡 admin/穷举型单次大请求。
|
||||
static HEAVY_READ_MAX_ROWS_DEFAULT: usize = 20000;
|
||||
|
||||
fn heavy_read_max_rows() -> usize {
|
||||
match std::env::var("ZHIYI_HEAVY_READ_MAX_ROWS") {
|
||||
Ok(v) => v.trim().parse::<usize>().unwrap_or(HEAVY_READ_MAX_ROWS_DEFAULT).max(1),
|
||||
Err(_) => HEAVY_READ_MAX_ROWS_DEFAULT,
|
||||
}
|
||||
}
|
||||
|
||||
fn heavy_read_permits() -> usize {
|
||||
match std::env::var("ZHIYI_HEAVY_READ_CONCURRENCY") {
|
||||
Ok(v) => v.trim().parse::<usize>().unwrap_or(HEAVY_READ_DEFAULT),
|
||||
@@ -253,6 +269,10 @@ struct ConsolidateResponse {
|
||||
report_json: String,
|
||||
failure_step: String,
|
||||
error_detail: String,
|
||||
// 方案②(t_576714de):单次重读被行数上限截断时为 true(降级返回部分结果)。
|
||||
// 旧 Go 客户端无此字段 ⇒ serde 缺省 false,向后兼容。
|
||||
#[serde(default)]
|
||||
truncated: bool,
|
||||
}
|
||||
|
||||
fn main() {
|
||||
@@ -416,9 +436,14 @@ fn handle_client(mut stream: UnixStream, args: &Args, lancedb: LanceDBOps, state
|
||||
let v: Vec<f32> = msg["vector"].as_array()
|
||||
.map(|a| a.iter().filter_map(|v| v.as_f64()).map(|v| v as f32).collect())
|
||||
.unwrap_or_default();
|
||||
let tk = msg["top_k"].as_u64().unwrap_or(10) as usize;
|
||||
let requested = msg["top_k"].as_u64().unwrap_or(10) as usize;
|
||||
// 空 namespace = 不过滤(匹配所有)
|
||||
let ns = msg["namespace"].as_str().filter(|s| !s.is_empty());
|
||||
// 方案②(t_576714de):单次重读行数硬上限 —— 截断到上限,超限标 truncated:true,
|
||||
// 降级返回部分结果而非让单个请求独自吞下全表向量(43547 行 ≈ 260MB Rust + JSON)。
|
||||
let cap = heavy_read_max_rows();
|
||||
let tk = requested.min(cap);
|
||||
let truncated = requested > tk;
|
||||
// 重读准入(t_690cc333 方案①):top_k>1000 的重搜索是内存放大器,
|
||||
// 计入信号量 N;无许可 ⇒ 有界等待后拒绝 heavy_read_busy。
|
||||
let _perm = if tk > 1000 {
|
||||
@@ -435,7 +460,15 @@ fn handle_client(mut stream: UnixStream, args: &Args, lancedb: LanceDBOps, state
|
||||
None
|
||||
};
|
||||
match lancedb.search(&v, tk, ns) {
|
||||
Ok(r) => send_ok(&mut stream, &serde_json::to_string(&r).unwrap_or_default()),
|
||||
Ok(r) => {
|
||||
let json = serde_json::to_string(&r).unwrap_or_default();
|
||||
if truncated {
|
||||
eprintln!("[zhiyi-ipc] search top_k={} CLAMPED to {} (single-read cap {}), truncated=true", requested, r.len(), cap);
|
||||
send_ok_truncated(&mut stream, &json);
|
||||
} else {
|
||||
send_ok(&mut stream, &json);
|
||||
}
|
||||
}
|
||||
Err(e) => send_error(&mut stream, "lancedb_search", &e.to_string()),
|
||||
}
|
||||
}
|
||||
@@ -559,8 +592,19 @@ fn handle_client(mut stream: UnixStream, args: &Args, lancedb: LanceDBOps, state
|
||||
return;
|
||||
}
|
||||
};
|
||||
match lancedb.scan_all() {
|
||||
Ok(r) => send_ok(&mut stream, &serde_json::to_string(&r).unwrap_or_default()),
|
||||
// 方案②(t_576714de):单次扫描行数上限 —— 超上限截断 + truncated:true(降级部分结果)。
|
||||
let cap = heavy_read_max_rows();
|
||||
match lancedb.scan_all(cap) {
|
||||
Ok(r) => {
|
||||
let json = serde_json::to_string(&r).unwrap_or_default();
|
||||
let trunc = r.len() >= cap;
|
||||
if trunc {
|
||||
eprintln!("[zhiyi-ipc] scan_all hit cap {} → truncated=true", cap);
|
||||
send_ok_truncated(&mut stream, &json);
|
||||
} else {
|
||||
send_ok(&mut stream, &json);
|
||||
}
|
||||
}
|
||||
Err(e) => send_error(&mut stream, "lancedb_scan_all", &e.to_string()),
|
||||
}
|
||||
}
|
||||
@@ -577,8 +621,19 @@ fn handle_client(mut stream: UnixStream, args: &Args, lancedb: LanceDBOps, state
|
||||
return;
|
||||
}
|
||||
};
|
||||
match lancedb.scan_deleted() {
|
||||
Ok(r) => send_ok(&mut stream, &serde_json::to_string(&r).unwrap_or_default()),
|
||||
// 方案②(t_576714de):单次扫描行数上限 —— 超上限截断 + truncated:true。
|
||||
let cap = heavy_read_max_rows();
|
||||
match lancedb.scan_deleted(cap) {
|
||||
Ok(r) => {
|
||||
let json = serde_json::to_string(&r).unwrap_or_default();
|
||||
let trunc = r.len() >= cap;
|
||||
if trunc {
|
||||
eprintln!("[zhiyi-ipc] scan_deleted hit cap {} → truncated=true", cap);
|
||||
send_ok_truncated(&mut stream, &json);
|
||||
} else {
|
||||
send_ok(&mut stream, &json);
|
||||
}
|
||||
}
|
||||
Err(e) => send_error(&mut stream, "lancedb_scan_deleted", &e.to_string()),
|
||||
}
|
||||
}
|
||||
@@ -621,6 +676,7 @@ fn handle_client(mut stream: UnixStream, args: &Args, lancedb: LanceDBOps, state
|
||||
"consolidating": CONSOLIDATING.load(Ordering::SeqCst),
|
||||
"heavy_read_in_flight": state.heavy_read.in_flight(),
|
||||
"heavy_read_permits": heavy_read_permits(),
|
||||
"heavy_read_max_rows": heavy_read_max_rows(),
|
||||
"ts": chrono::Utc::now().to_rfc3339_opts(chrono::SecondsFormat::Secs, true),
|
||||
});
|
||||
send_ok(&mut stream, &resp.to_string());
|
||||
@@ -671,11 +727,16 @@ fn handle_client(mut stream: UnixStream, args: &Args, lancedb: LanceDBOps, state
|
||||
}
|
||||
|
||||
fn send_ok(stream: &mut UnixStream, json: &str) {
|
||||
let resp = ConsolidateResponse { status: "ok".into(), report_json: json.to_string(), failure_step: "".into(), error_detail: "".into() };
|
||||
let resp = ConsolidateResponse { status: "ok".into(), report_json: json.to_string(), failure_step: String::new(), error_detail: String::new(), truncated: false };
|
||||
send_response(stream, &resp);
|
||||
}
|
||||
/// 方案②(t_576714de):被行数上限截断的正常返回(report_json=部分结果,truncated=true)。
|
||||
fn send_ok_truncated(stream: &mut UnixStream, json: &str) {
|
||||
let resp = ConsolidateResponse { status: "ok".into(), report_json: json.to_string(), failure_step: String::new(), error_detail: String::new(), truncated: true };
|
||||
send_response(stream, &resp);
|
||||
}
|
||||
fn send_error(stream: &mut UnixStream, step: &str, detail: &str) {
|
||||
let resp = ConsolidateResponse { status: "error".into(), report_json: "".into(), failure_step: step.to_string(), error_detail: detail.to_string() };
|
||||
let resp = ConsolidateResponse { status: "error".into(), report_json: String::new(), failure_step: step.to_string(), error_detail: detail.to_string(), truncated: false };
|
||||
send_response(stream, &resp);
|
||||
}
|
||||
|
||||
@@ -806,8 +867,8 @@ fn run_consolidation(args: &Args, lancedb: &LanceDBOps) -> ConsolidationReport {
|
||||
if args.mode == "full" {
|
||||
let calibrator = DecayCalibrator::new();
|
||||
let old_rates = decay_calibrate::default_decay_rates();
|
||||
// 从 LanceDB 加载真实样本
|
||||
let all_records = lancedb.scan_all().unwrap_or_default();
|
||||
// 整合内部全量扫描(非 IPC 边界,需全量;行数上限只作用于 IPC 单次重读,t_576714de)。
|
||||
let all_records = lancedb.scan_all(200_000).unwrap_or_default();
|
||||
let now_secs = std::time::SystemTime::now()
|
||||
.duration_since(std::time::UNIX_EPOCH)
|
||||
.unwrap_or_default()
|
||||
@@ -846,8 +907,8 @@ fn run_consolidation(args: &Args, lancedb: &LanceDBOps) -> ConsolidationReport {
|
||||
eprintln!("[consolidate] Step 4: BGE HTTP (port 8000) unreachable — skipping quality backtrace");
|
||||
} else {
|
||||
let backtracer = QualityBacktracer::new(&args.llm_endpoint, &args.llm_model, &args.llm_api_key);
|
||||
// 从 LanceDB 加载(content = distilled, source metadata = original)
|
||||
let all_records = lancedb.scan_all().unwrap_or_default();
|
||||
// 从 LanceDB 加载(content = distilled, source metadata = original)。整合内部全量,非 IPC 边界。
|
||||
let all_records = lancedb.scan_all(200_000).unwrap_or_default();
|
||||
let samples: Vec<QualitySample> = all_records
|
||||
.iter()
|
||||
.filter(|r| !r.content.is_empty())
|
||||
|
||||
+11
-6
@@ -29,12 +29,17 @@ d=json.load(sys.stdin)
|
||||
# 2026-10-17:recall_hit_rate 已退役(恒=1、无区分度)。召回质量改用 recall_usefulness_rate
|
||||
#(返回且被使用);-1 表示样本不足/无负反馈 = 数据不可解读,跳过告警,不误报。
|
||||
hit = d.get('recall_usefulness_rate', -1)
|
||||
loss = d.get('avg_distill_loss', 0)
|
||||
gap = d.get('gap_closure_rate', 0)
|
||||
auto = d.get('auto_resolve_rate', 0)
|
||||
print(f'召回有用率: {hit:.0%}, 蒸馏损失: {loss:.2f}, gap闭合: {gap}/天, auto_resolve: {auto}')
|
||||
if loss > 0.3: print('⚠️ avg_distill_loss 超标')
|
||||
if hit >= 0 and hit < 0.5: print('⚠️ recall_usefulness_rate 低于阈值')
|
||||
loss = d.get('avg_distill_loss', -1)
|
||||
gap = d.get('gap_closure_rate', -1)
|
||||
auto = d.get('auto_resolve_rate', -1)
|
||||
# -1 哨兵 = 样本不足/越界被拦,不可解读 ⇒ 显示 —(N/A),不得当成具体数字误导。
|
||||
def fmt(v, pct=False):
|
||||
if v is None or v < 0:
|
||||
return '—(N/A)'
|
||||
return ('%.0f%%' % (v*100)) if pct else ('%.2f' % v)
|
||||
print('召回有用率: %s, 蒸馏损失: %s, gap闭合率: %s, auto_resolve率: %s' % (fmt(hit, True), fmt(loss), fmt(gap, True), fmt(auto, True)))
|
||||
if loss is not None and loss >= 0 and loss > 0.3: print('⚠️ avg_distill_loss 超标')
|
||||
if hit is not None and hit >= 0 and hit < 0.5: print('⚠️ recall_usefulness_rate 低于阈值')
|
||||
" 2>/dev/null
|
||||
|
||||
# 4. 蒸馏状态
|
||||
|
||||
@@ -29,12 +29,17 @@ d=json.load(sys.stdin)
|
||||
# 2026-10-17:recall_hit_rate 已退役(恒=1、无区分度)。召回质量改用 recall_usefulness_rate
|
||||
#(返回且被使用);-1 表示样本不足/无负反馈 = 数据不可解读,跳过告警,不误报。
|
||||
hit = d.get('recall_usefulness_rate', -1)
|
||||
loss = d.get('avg_distill_loss', 0)
|
||||
gap = d.get('gap_closure_rate', 0)
|
||||
auto = d.get('auto_resolve_rate', 0)
|
||||
print(f'召回有用率: {hit:.0%}, 蒸馏损失: {loss:.2f}, gap闭合: {gap}/天, auto_resolve: {auto}')
|
||||
if loss > 0.3: print('⚠️ avg_distill_loss 超标')
|
||||
if hit >= 0 and hit < 0.5: print('⚠️ recall_usefulness_rate 低于阈值')
|
||||
loss = d.get('avg_distill_loss', -1)
|
||||
gap = d.get('gap_closure_rate', -1)
|
||||
auto = d.get('auto_resolve_rate', -1)
|
||||
# -1 哨兵 = 样本不足/越界被拦,不可解读 ⇒ 显示 —(N/A),不得当成具体数字误导。
|
||||
def fmt(v, pct=False):
|
||||
if v is None or v < 0:
|
||||
return '—(N/A)'
|
||||
return ('%.0f%%' % (v*100)) if pct else ('%.2f' % v)
|
||||
print('召回有用率: %s, 蒸馏损失: %s, gap闭合率: %s, auto_resolve率: %s' % (fmt(hit, True), fmt(loss), fmt(gap, True), fmt(auto, True)))
|
||||
if loss is not None and loss >= 0 and loss > 0.3: print('⚠️ avg_distill_loss 超标')
|
||||
if hit is not None and hit >= 0 and hit < 0.5: print('⚠️ recall_usefulness_rate 低于阈值')
|
||||
" 2>/dev/null
|
||||
|
||||
# 4. 蒸馏状态
|
||||
|
||||
Reference in New Issue
Block a user