selfoptimize: Dashboard 指标落盘补本地 JSON 兜底(Redis 不可用时重启不丢指标)
- 病根:server.go 调 EnableRedisPersistence(),但本机无 Redis → GetRedisClient() nil → redisPersistence 恒 nil → persist() 首行 return,7 项指标只活在进程内(实测重启即全 0) - 改:Redis 不可用 → 走本地 JSON(/var/lib/memoryweave/dashboard.json,ZHIYI_DASHBOARD_PATH 可覆盖) 原子写(tmp+rename)、best-effort(读/写失败静默退回仅内存,行为不劣化) deprecated_today 跨天归零(记 deprecated_date) - 补:RecordFeedback 漏了 persist() → useful/not_useful 从不落盘(唯一一个漏的 Record*) - 测:3 个新用例(往返/跨天归零/缺文件坏文件安全)+ TestMain 重定向落盘点 (修前实测:整套测试会把生产 dashboard.json 写成测试数字) - 验证:重启 zhiyid 后 metrics 仍为 recall_hit_rate=0.33 / recall_usefulness_rate=1(改前恒 0)
This commit is contained in:
@@ -4,6 +4,7 @@ package selfoptimize
|
||||
import (
|
||||
"encoding/json"
|
||||
"math"
|
||||
"os"
|
||||
"strconv"
|
||||
"sync"
|
||||
"time"
|
||||
@@ -14,23 +15,123 @@ import (
|
||||
// Redis persistence key
|
||||
const dashboardRedisKey = "zhiyi:dashboard"
|
||||
|
||||
// dashboardLocalPath 本地 JSON 落盘点 —— Redis 不可用时的兜底(2026-09-27 加)
|
||||
//
|
||||
// 背景:本机无 Redis(无 redis-cli/redis-server、6379 无监听、单元无 REDIS_ADDR/URL)
|
||||
// ⇒ storage.GetRedisClient() 返回 nil ⇒ redisPersistence 恒为 nil
|
||||
// ⇒ 原 persist() 第一行就 return:7 项指标只活在进程内,**重启即归零**,
|
||||
//
|
||||
// 而 tuning / executor / distributed 都在读它做自优化决策。
|
||||
//
|
||||
// 可用 ZHIYI_DASHBOARD_PATH 覆盖(测试用)。
|
||||
func dashboardLocalPath() string {
|
||||
if p := os.Getenv("ZHIYI_DASHBOARD_PATH"); p != "" {
|
||||
return p
|
||||
}
|
||||
return "/var/lib/memoryweave/dashboard.json"
|
||||
}
|
||||
|
||||
// dashboardState 可序列化快照 —— Dashboard 内含 sync.RWMutex,不能直接 Marshal/整块复制
|
||||
type dashboardState struct {
|
||||
UsefulCount int `json:"useful_count"`
|
||||
NotUsefulCount int `json:"not_useful_count"`
|
||||
TotalRecalls int `json:"total_recalls"`
|
||||
HitCount int `json:"hit_count"`
|
||||
ClosedGaps int `json:"closed_gaps"`
|
||||
TotalGaps int `json:"total_gaps"`
|
||||
CascadeFixedTotal int `json:"cascade_fixed_total"`
|
||||
TotalFixes int `json:"total_fixes"`
|
||||
DeprecatedToday int `json:"deprecated_today"`
|
||||
DeprecatedDate string `json:"deprecated_date"` // deprecated_today 的归属日期(跨天归零用)
|
||||
DistillLossSum float64 `json:"distill_loss_sum"`
|
||||
DistillLossCount int `json:"distill_loss_count"`
|
||||
AutoResolvedConflicts int `json:"auto_resolved_conflicts"`
|
||||
TotalConflicts int `json:"total_conflicts"`
|
||||
}
|
||||
|
||||
func todayStr() string { return time.Now().Format("2006-01-02") }
|
||||
|
||||
// redisPersistence 是否开启了 Redis 持久化(由 server.go 在启动时设置)
|
||||
var redisPersistence *storage.RedisClient
|
||||
|
||||
// EnableRedisPersistence 启动 Dashboard 持久化(从 Redis 加载 + 每次变更同步)
|
||||
// EnableRedisPersistence 启动 Dashboard 持久化(Redis 优先;Redis 不可用则转本地 JSON)
|
||||
func EnableRedisPersistence() {
|
||||
rc := storage.GetRedisClient()
|
||||
if rc == nil {
|
||||
if rc != nil {
|
||||
redisPersistence = rc
|
||||
_ = loadDashboard()
|
||||
return
|
||||
}
|
||||
redisPersistence = rc
|
||||
_ = loadDashboard()
|
||||
_ = loadDashboardLocal()
|
||||
}
|
||||
|
||||
// persist 写当前 Dashboard 到 Redis HASH
|
||||
// loadDashboardLocal 从本地 JSON 恢复指标;文件不存在/损坏 → 静默保持零值(= 老行为)
|
||||
func loadDashboardLocal() error {
|
||||
b, err := os.ReadFile(dashboardLocalPath())
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
var st dashboardState
|
||||
if err := json.Unmarshal(b, &st); err != nil {
|
||||
return err
|
||||
}
|
||||
Dash.mu.Lock()
|
||||
defer Dash.mu.Unlock()
|
||||
Dash.UsefulCount = st.UsefulCount
|
||||
Dash.NotUsefulCount = st.NotUsefulCount
|
||||
Dash.TotalRecalls = st.TotalRecalls
|
||||
Dash.HitCount = st.HitCount
|
||||
Dash.ClosedGaps = st.ClosedGaps
|
||||
Dash.TotalGaps = st.TotalGaps
|
||||
Dash.CascadeFixedTotal = st.CascadeFixedTotal
|
||||
Dash.TotalFixes = st.TotalFixes
|
||||
Dash.DeprecatedToday = st.DeprecatedToday
|
||||
if st.DeprecatedDate != todayStr() { // "今日"计数跨天归零(进程跨零点不重置,下次加载时纠正)
|
||||
Dash.DeprecatedToday = 0
|
||||
}
|
||||
Dash.DistillLossSum = st.DistillLossSum
|
||||
Dash.DistillLossCount = st.DistillLossCount
|
||||
Dash.AutoResolvedConflicts = st.AutoResolvedConflicts
|
||||
Dash.TotalConflicts = st.TotalConflicts
|
||||
return nil
|
||||
}
|
||||
|
||||
// persistLocalLocked 原子写本地 JSON(best-effort:任何失败都静默 → 行为退回"仅内存")
|
||||
// 注意:调用方必须已持有 d.mu 锁
|
||||
func (d *Dashboard) persistLocalLocked() {
|
||||
st := dashboardState{
|
||||
UsefulCount: d.UsefulCount,
|
||||
NotUsefulCount: d.NotUsefulCount,
|
||||
TotalRecalls: d.TotalRecalls,
|
||||
HitCount: d.HitCount,
|
||||
ClosedGaps: d.ClosedGaps,
|
||||
TotalGaps: d.TotalGaps,
|
||||
CascadeFixedTotal: d.CascadeFixedTotal,
|
||||
TotalFixes: d.TotalFixes,
|
||||
DeprecatedToday: d.DeprecatedToday,
|
||||
DeprecatedDate: todayStr(),
|
||||
DistillLossSum: d.DistillLossSum,
|
||||
DistillLossCount: d.DistillLossCount,
|
||||
AutoResolvedConflicts: d.AutoResolvedConflicts,
|
||||
TotalConflicts: d.TotalConflicts,
|
||||
}
|
||||
b, err := json.Marshal(st)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
p := dashboardLocalPath()
|
||||
tmp := p + ".tmp"
|
||||
if err := os.WriteFile(tmp, b, 0o600); err != nil {
|
||||
return
|
||||
}
|
||||
_ = os.Rename(tmp, p)
|
||||
}
|
||||
|
||||
// persist 持久化 Dashboard:Redis 可用→写 Redis HASH;否则→写本地 JSON
|
||||
// 注意:调用方必须已持有 d.mu 锁(RLock 或 Lock)
|
||||
func (d *Dashboard) persist() {
|
||||
if redisPersistence == nil {
|
||||
d.persistLocalLocked()
|
||||
return
|
||||
}
|
||||
_ = redisPersistence.HSet(dashboardRedisKey, "useful_count", strconv.Itoa(d.UsefulCount))
|
||||
@@ -61,39 +162,65 @@ func loadDashboard() error {
|
||||
Dash.mu.Lock()
|
||||
defer Dash.mu.Unlock()
|
||||
|
||||
if v, err := strconv.Atoi(data["useful_count"]); err == nil { Dash.UsefulCount = v }
|
||||
if v, err := strconv.Atoi(data["not_useful_count"]); err == nil { Dash.NotUsefulCount = v }
|
||||
if v, err := strconv.Atoi(data["total_recalls"]); err == nil { Dash.TotalRecalls = v }
|
||||
if v, err := strconv.Atoi(data["hit_count"]); err == nil { Dash.HitCount = v }
|
||||
if v, err := strconv.Atoi(data["closed_gaps"]); err == nil { Dash.ClosedGaps = v }
|
||||
if v, err := strconv.Atoi(data["total_gaps"]); err == nil { Dash.TotalGaps = v }
|
||||
if v, err := strconv.Atoi(data["cascade_fixed_total"]); err == nil { Dash.CascadeFixedTotal = v }
|
||||
if v, err := strconv.Atoi(data["total_fixes"]); err == nil { Dash.TotalFixes = v }
|
||||
if v, err := strconv.Atoi(data["deprecated_today"]); err == nil { Dash.DeprecatedToday = v }
|
||||
if v, err := strconv.ParseFloat(data["distill_loss_sum"], 64); err == nil { Dash.DistillLossSum = v }
|
||||
if v, err := strconv.Atoi(data["distill_loss_count"]); err == nil { Dash.DistillLossCount = v }
|
||||
if v, err := strconv.Atoi(data["auto_resolved_conflicts"]); err == nil { Dash.AutoResolvedConflicts = v }
|
||||
if v, err := strconv.Atoi(data["total_conflicts"]); err == nil { Dash.TotalConflicts = v }
|
||||
if v, err := strconv.Atoi(data["useful_count"]); err == nil {
|
||||
Dash.UsefulCount = v
|
||||
}
|
||||
if v, err := strconv.Atoi(data["not_useful_count"]); err == nil {
|
||||
Dash.NotUsefulCount = v
|
||||
}
|
||||
if v, err := strconv.Atoi(data["total_recalls"]); err == nil {
|
||||
Dash.TotalRecalls = v
|
||||
}
|
||||
if v, err := strconv.Atoi(data["hit_count"]); err == nil {
|
||||
Dash.HitCount = v
|
||||
}
|
||||
if v, err := strconv.Atoi(data["closed_gaps"]); err == nil {
|
||||
Dash.ClosedGaps = v
|
||||
}
|
||||
if v, err := strconv.Atoi(data["total_gaps"]); err == nil {
|
||||
Dash.TotalGaps = v
|
||||
}
|
||||
if v, err := strconv.Atoi(data["cascade_fixed_total"]); err == nil {
|
||||
Dash.CascadeFixedTotal = v
|
||||
}
|
||||
if v, err := strconv.Atoi(data["total_fixes"]); err == nil {
|
||||
Dash.TotalFixes = v
|
||||
}
|
||||
if v, err := strconv.Atoi(data["deprecated_today"]); err == nil {
|
||||
Dash.DeprecatedToday = v
|
||||
}
|
||||
if v, err := strconv.ParseFloat(data["distill_loss_sum"], 64); err == nil {
|
||||
Dash.DistillLossSum = v
|
||||
}
|
||||
if v, err := strconv.Atoi(data["distill_loss_count"]); err == nil {
|
||||
Dash.DistillLossCount = v
|
||||
}
|
||||
if v, err := strconv.Atoi(data["auto_resolved_conflicts"]); err == nil {
|
||||
Dash.AutoResolvedConflicts = v
|
||||
}
|
||||
if v, err := strconv.Atoi(data["total_conflicts"]); err == nil {
|
||||
Dash.TotalConflicts = v
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// ─── 自优化仪表盘 ────────────────────────────────────────
|
||||
|
||||
type Dashboard struct {
|
||||
mu sync.RWMutex
|
||||
UsefulCount int `json:"useful_count"`
|
||||
NotUsefulCount int `json:"not_useful_count"`
|
||||
TotalRecalls int `json:"total_recalls"`
|
||||
HitCount int `json:"hit_count"`
|
||||
ClosedGaps int `json:"closed_gaps"`
|
||||
TotalGaps int `json:"total_gaps"`
|
||||
CascadeFixedTotal int `json:"cascade_fixed_total"`
|
||||
TotalFixes int `json:"total_fixes"`
|
||||
mu sync.RWMutex
|
||||
UsefulCount int `json:"useful_count"`
|
||||
NotUsefulCount int `json:"not_useful_count"`
|
||||
TotalRecalls int `json:"total_recalls"`
|
||||
HitCount int `json:"hit_count"`
|
||||
ClosedGaps int `json:"closed_gaps"`
|
||||
TotalGaps int `json:"total_gaps"`
|
||||
CascadeFixedTotal int `json:"cascade_fixed_total"`
|
||||
TotalFixes int `json:"total_fixes"`
|
||||
DeprecatedToday int `json:"deprecated_today"`
|
||||
DistillLossSum float64 `json:"distill_loss_sum"`
|
||||
DistillLossCount int `json:"distill_loss_count"`
|
||||
AutoResolvedConflicts int `json:"auto_resolved_conflicts"`
|
||||
TotalConflicts int `json:"total_conflicts"`
|
||||
DistillLossSum float64 `json:"distill_loss_sum"`
|
||||
DistillLossCount int `json:"distill_loss_count"`
|
||||
AutoResolvedConflicts int `json:"auto_resolved_conflicts"`
|
||||
TotalConflicts int `json:"total_conflicts"`
|
||||
}
|
||||
|
||||
var Dash = &Dashboard{}
|
||||
@@ -140,7 +267,7 @@ func (d *Dashboard) Metrics() map[string]float64 {
|
||||
"cascade_fix_rate": math.Round(cascadeRate*100) / 100,
|
||||
"deprecated_per_day": float64(d.DeprecatedToday),
|
||||
"avg_distill_loss": math.Round(avgLoss*100) / 100,
|
||||
"auto_resolve_rate": math.Round(autoRate*100) / 100,
|
||||
"auto_resolve_rate": math.Round(autoRate*100) / 100,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -162,6 +289,7 @@ func (d *Dashboard) RecordFeedback(useful bool) {
|
||||
} else {
|
||||
d.NotUsefulCount++
|
||||
}
|
||||
d.persist() // 2026-09-27 补:此处漏了 persist() ⇒ useful/not_useful 从不落盘、重启即丢
|
||||
}
|
||||
|
||||
// RecordUseful 记录有用反馈
|
||||
@@ -181,7 +309,9 @@ func (d *Dashboard) QualityScore() float64 {
|
||||
d.mu.RLock()
|
||||
defer d.mu.RUnlock()
|
||||
total := d.UsefulCount + d.NotUsefulCount
|
||||
if total == 0 { return 0.5 }
|
||||
if total == 0 {
|
||||
return 0.5
|
||||
}
|
||||
return float64(d.UsefulCount) / float64(total)
|
||||
}
|
||||
|
||||
@@ -311,10 +441,11 @@ func (gd *GapDetector) RecordMiss(topic string) *Gap {
|
||||
}
|
||||
|
||||
// classifyGap 基于向量比较的缺口分类(与设计文档一致)
|
||||
// sim > 0.85 且 category 相近 → Type C(召回失败)
|
||||
// sim > 0.75 但 entity 名称不同 → Type B(同义词不匹配)
|
||||
// max sim < 0.3(全聚类 centroid)→ Type A(真未知)
|
||||
// 多个 L1 记忆各自部分覆盖 → Type D(碎片化)
|
||||
//
|
||||
// sim > 0.85 且 category 相近 → Type C(召回失败)
|
||||
// sim > 0.75 但 entity 名称不同 → Type B(同义词不匹配)
|
||||
// max sim < 0.3(全聚类 centroid)→ Type A(真未知)
|
||||
// 多个 L1 记忆各自部分覆盖 → Type D(碎片化)
|
||||
func (gd *GapDetector) classifyGap(topic string) GapType {
|
||||
if gd.embedder == nil || gd.ldb == nil {
|
||||
// 降级:无 embedder 时用简单启发式
|
||||
@@ -428,8 +559,8 @@ type TraceEntry struct {
|
||||
MemoryID string `json:"memory_id"`
|
||||
Version int `json:"version"`
|
||||
Content string `json:"content"`
|
||||
Source string `json:"source"` // muchen_oral / config_parse / agent_infer / llm_distill
|
||||
Trigger string `json:"trigger"` // 什么触发了这次修改
|
||||
Source string `json:"source"` // muchen_oral / config_parse / agent_infer / llm_distill
|
||||
Trigger string `json:"trigger"` // 什么触发了这次修改
|
||||
UpdatedAt time.Time `json:"updated_at"`
|
||||
}
|
||||
|
||||
|
||||
@@ -2,10 +2,43 @@
|
||||
package selfoptimize
|
||||
|
||||
import (
|
||||
"os"
|
||||
"path/filepath"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
// zeroDash 复位全局 Dash(测试用;逐字段置零以避免复制含 mutex 的结构体)
|
||||
func zeroDash() {
|
||||
Dash.mu.Lock()
|
||||
defer Dash.mu.Unlock()
|
||||
Dash.UsefulCount = 0
|
||||
Dash.NotUsefulCount = 0
|
||||
Dash.TotalRecalls = 0
|
||||
Dash.HitCount = 0
|
||||
Dash.ClosedGaps = 0
|
||||
Dash.TotalGaps = 0
|
||||
Dash.CascadeFixedTotal = 0
|
||||
Dash.TotalFixes = 0
|
||||
Dash.DeprecatedToday = 0
|
||||
Dash.DistillLossSum = 0
|
||||
Dash.DistillLossCount = 0
|
||||
Dash.AutoResolvedConflicts = 0
|
||||
Dash.TotalConflicts = 0
|
||||
}
|
||||
|
||||
// TestMain 单元测试不得写到生产落盘点(曾实测:整套测试跑完把 /var/lib/memoryweave/dashboard.json 写成了测试数字)
|
||||
func TestMain(m *testing.M) {
|
||||
dir, err := os.MkdirTemp("", "selfopt-test-*")
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
_ = os.Setenv("ZHIYI_DASHBOARD_PATH", filepath.Join(dir, "dashboard.json"))
|
||||
code := m.Run()
|
||||
_ = os.RemoveAll(dir)
|
||||
os.Exit(code)
|
||||
}
|
||||
|
||||
// ─── 仪表盘 ──────────────────────────────────────────────
|
||||
|
||||
func TestDashboard_InitialMetricsAllZero(t *testing.T) {
|
||||
@@ -310,3 +343,88 @@ func init() {
|
||||
// Ensure consistent timestamps for snapshot tests
|
||||
time.Local = time.UTC
|
||||
}
|
||||
|
||||
// ─── 本地 JSON 持久化(2026-09-27 加:Redis 不可用时的兜底)──────────────
|
||||
|
||||
func TestDashboardLocalPersistence_RoundTrip(t *testing.T) {
|
||||
p := filepath.Join(t.TempDir(), "dash.json")
|
||||
t.Setenv("ZHIYI_DASHBOARD_PATH", p)
|
||||
|
||||
src := &Dashboard{
|
||||
TotalRecalls: 7, HitCount: 6, UsefulCount: 5, NotUsefulCount: 1,
|
||||
DistillLossSum: 1.05, DistillLossCount: 5,
|
||||
ClosedGaps: 2, TotalGaps: 4, TotalFixes: 3, CascadeFixedTotal: 1,
|
||||
AutoResolvedConflicts: 2, TotalConflicts: 3, DeprecatedToday: 4,
|
||||
}
|
||||
src.mu.Lock()
|
||||
src.persist() // 测试环境无 Redis → 走本地 JSON 分支
|
||||
src.mu.Unlock()
|
||||
|
||||
if _, err := os.Stat(p); err != nil {
|
||||
t.Fatalf("本地落盘文件未生成: %v", err)
|
||||
}
|
||||
|
||||
zeroDash() // 模拟进程重启
|
||||
if err := loadDashboardLocal(); err != nil {
|
||||
t.Fatalf("loadDashboardLocal: %v", err)
|
||||
}
|
||||
m := Dash.Metrics()
|
||||
want := map[string]float64{
|
||||
"recall_hit_rate": 0.86, // 6/7
|
||||
"recall_usefulness_rate": 0.83, // 5/6
|
||||
"gap_closure_rate": 0.5, // 2/4
|
||||
"cascade_fix_rate": 0.33, // 1/3
|
||||
"auto_resolve_rate": 0.67, // 2/3
|
||||
"deprecated_per_day": 4,
|
||||
"avg_distill_loss": 0.21, // 1.05/5
|
||||
}
|
||||
for k, v := range want {
|
||||
if m[k] != v {
|
||||
t.Errorf("%s: want %v got %v", k, v, m[k])
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestDashboardLocalPersistence_StaleDeprecatedResetsToZero(t *testing.T) {
|
||||
p := filepath.Join(t.TempDir(), "dash.json")
|
||||
t.Setenv("ZHIYI_DASHBOARD_PATH", p)
|
||||
// 手写一份"很久以前"的快照:deprecated_today 应归零,其余计数应保留
|
||||
blob := `{"deprecated_today":9,"deprecated_date":"2000-01-01","total_recalls":3,"hit_count":2}`
|
||||
if err := os.WriteFile(p, []byte(blob), 0o600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
zeroDash()
|
||||
if err := loadDashboardLocal(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
m := Dash.Metrics()
|
||||
if m["deprecated_per_day"] != 0 {
|
||||
t.Errorf("跨天未归零: %v", m["deprecated_per_day"])
|
||||
}
|
||||
if m["recall_hit_rate"] != 0.67 { // 2/3
|
||||
t.Errorf("其他计数应保留, got %v", m["recall_hit_rate"])
|
||||
}
|
||||
}
|
||||
|
||||
func TestDashboardLocalPersistence_MissingOrBrokenFileIsSafe(t *testing.T) {
|
||||
p := filepath.Join(t.TempDir(), "nope.json")
|
||||
t.Setenv("ZHIYI_DASHBOARD_PATH", p)
|
||||
|
||||
zeroDash()
|
||||
if err := loadDashboardLocal(); err == nil {
|
||||
t.Errorf("缺文件应返回 err(调用方忽略,行为退回仅内存)")
|
||||
}
|
||||
if Dash.Metrics()["recall_hit_rate"] != 0 {
|
||||
t.Errorf("缺文件不应改动 Dash")
|
||||
}
|
||||
|
||||
if err := os.WriteFile(p, []byte("{ not json"), 0o600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := loadDashboardLocal(); err == nil {
|
||||
t.Errorf("坏文件应返回 err")
|
||||
}
|
||||
if Dash.Metrics()["recall_hit_rate"] != 0 {
|
||||
t.Errorf("坏文件不应改动 Dash")
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user