- governance.GraphStore 增 CountNodesByType(total, withID, lastUpdated),SQLite/内存/缓存三实现 - selfcheck cheap 增 pattern 段:rows / rows_with_id / last_produced_at / verdict verdict ∈ producing|zero_output|no_id|unknown_age|no_graph_store|unsupported - 实测:rows=0 verdict=zero_output(与 graph.db 只读复核一致),cheap 22ms - 动机:pattern 召回 0 命中时只能靠翻 7 天日志才发现「实现了≠出过数」
328 lines
11 KiB
Go
328 lines
11 KiB
Go
package routes
|
||
|
||
// 织忆自检端点(2026-10-26,牧尘批「三档」)
|
||
//
|
||
// 背景:织忆相关的定时自检脚本有 ~20 个,取数方式三套并存——
|
||
// ① 直连生产库 lancedb.connect("/var/lib/memoryweave")(绕过服务、schema 一改就静默腐烂)
|
||
// ② IPC socket 自定义协议
|
||
// ③ HTTP /api/v1/{stats,popwatch,metrics/self}
|
||
// 三套契约对同一个库,schema 变更时分开损坏。典型事故:pattern 自检脚本写死
|
||
// type='pattern',库里实际是 pattern_stat ⇒ 连续数月静默 0 输出。
|
||
//
|
||
// 本端点是**唯一取数契约**:把「读织忆内部状态」收敛成一份结构化 JSON。
|
||
// 设计边界(不做什么):
|
||
// - 不做判定/告警/投递 —— 阈值、渠道、评审留在外部 cron(观测者不能住在被观测者体内:
|
||
// zhiyid 一挂自检就跟着哑,内外同时沉默是更坏的故障)。
|
||
// - 不跑重活(eval 全量、备份、vacuum)—— 那些抢生产资源,留在 systemd-run 独立 scope。
|
||
//
|
||
// level 语义:
|
||
// - cheap(默认,<50ms):只读内存态/计数,不扫全表。
|
||
// - full(秒级):额外扫全表算碎片率/冗余率/近 7 天质量/写量分布(原 quality-watch 口径)。
|
||
//
|
||
// 兼容铁律:本端点返回的比率一律给「分子/分母/样本是否足够」,缺数据不返回 0
|
||
// (0 会被下游读成"很好")。沿用 selfoptimize 的 metricNA(-1) 语义。
|
||
|
||
import (
|
||
"encoding/json"
|
||
"fmt"
|
||
"math"
|
||
"net/http"
|
||
"os"
|
||
"path/filepath"
|
||
"strings"
|
||
"time"
|
||
|
||
"github.com/xiaoxue/memoryweave/internal/distill"
|
||
"github.com/xiaoxue/memoryweave/internal/selfoptimize"
|
||
"github.com/xiaoxue/memoryweave/internal/storage"
|
||
)
|
||
|
||
// SelfcheckSchemaVersion 变更返回结构时递增;消费方据此判兼容。
|
||
const SelfcheckSchemaVersion = "1"
|
||
|
||
// 与 zhiyi-quality-watch.py 同口径(该脚本已改为读本端点,口径只此一处)
|
||
const (
|
||
selfcheckFragLen = 20 // <20 字符 = 碎片
|
||
selfcheckDupMinSample = 5000 // 冗余率最小样本(活行),不足只报样本不判率
|
||
selfcheckScanLimit = 300000
|
||
)
|
||
|
||
type selfcheckQuality struct {
|
||
TotalRows int `json:"total_rows"`
|
||
LiveRows int `json:"live_rows"`
|
||
ScannedRows int `json:"scanned_rows"`
|
||
ScanTruncated bool `json:"scan_truncated"`
|
||
Coverage float64 `json:"coverage"` // 扫描行 / store 真实总量;<1 表示结果不完整,禁止据此下结论
|
||
FragLen int `json:"frag_len"`
|
||
|
||
FragRowsAll int `json:"frag_rows_all"`
|
||
FragRateAll float64 `json:"frag_rate_all"`
|
||
FragRowsLive int `json:"frag_rows_live"`
|
||
FragRateLive float64 `json:"frag_rate_live"`
|
||
|
||
DupGroups int `json:"dup_groups"`
|
||
DupExtraRows int `json:"dup_extra_rows"`
|
||
DupRate float64 `json:"dup_rate"`
|
||
DupSampleOK bool `json:"dup_sample_ok"`
|
||
|
||
NewRows7d int `json:"new_rows_7d"`
|
||
NewFragRows7d int `json:"new_frag_rows_7d"`
|
||
NewFragRate7d *float64 `json:"new_frag_rate_7d"` // nil = 近 7 天无新增(无分母)
|
||
}
|
||
|
||
type selfcheckDayCount struct {
|
||
Date string `json:"date"`
|
||
Rows int `json:"rows"`
|
||
Live int `json:"live"`
|
||
}
|
||
|
||
type selfcheckWriteVolume struct {
|
||
Days []selfcheckDayCount `json:"days"`
|
||
Today int `json:"today"`
|
||
Last7d int `json:"last_7d"`
|
||
Median7d float64 `json:"median_7d"`
|
||
P25_7d float64 `json:"p25_7d"`
|
||
}
|
||
|
||
// Selfcheck GET /api/v1/selfcheck?level=cheap|full
|
||
func (a *API) Selfcheck(w http.ResponseWriter, r *http.Request) {
|
||
start := time.Now()
|
||
if r.Method != http.MethodGet {
|
||
respondError(w, http.StatusMethodNotAllowed, "method not allowed")
|
||
return
|
||
}
|
||
level := strings.ToLower(strings.TrimSpace(r.URL.Query().Get("level")))
|
||
if level == "" {
|
||
level = "cheap"
|
||
}
|
||
if level != "cheap" && level != "full" {
|
||
respondError(w, http.StatusBadRequest, "level must be cheap|full")
|
||
return
|
||
}
|
||
|
||
rep := map[string]interface{}{
|
||
"schema_version": SelfcheckSchemaVersion,
|
||
"checked_at": time.Now().Format(time.RFC3339),
|
||
"level": level,
|
||
}
|
||
degraded := []string{}
|
||
|
||
// ── 存储总量 ───────────────────────────────
|
||
if st, err := a.LanceDB.Stats(); err != nil {
|
||
degraded = append(degraded, "store: "+err.Error())
|
||
} else {
|
||
total := numOf(st["total_memories"])
|
||
tomb := numOf(st["tombstone_count"])
|
||
live := total - tomb
|
||
if live < 0 {
|
||
live = 0
|
||
}
|
||
store := map[string]interface{}{
|
||
"backend": st["backend"],
|
||
"data_dir": st["data_dir"],
|
||
"total_memories": total,
|
||
"total_episodes": numOf(st["total_episodes"]),
|
||
"tombstone_count": tomb,
|
||
"live_memories": live,
|
||
}
|
||
if total > 0 {
|
||
store["tombstone_rate"] = round4(tomb / total)
|
||
} else {
|
||
store["tombstone_rate"] = -1.0 // N/A:空库无分母
|
||
}
|
||
rep["store"] = store
|
||
}
|
||
|
||
// ── 图谱 ───────────────────────────────────
|
||
if a.GraphStore != nil {
|
||
n, e, d := a.GraphStore.Stats()
|
||
rep["graph"] = map[string]interface{}{
|
||
"node_count": n,
|
||
"edge_count": e,
|
||
"density": round4(d),
|
||
}
|
||
} else {
|
||
degraded = append(degraded, "graph: store not initialised")
|
||
}
|
||
|
||
// ── pattern 召回的两侧健康(2026-10-26 新增)──────────
|
||
// 事故背景:`POST /api/v1/patterns/detect` 是短命单发端点,全库 0 cron、0 调用方,
|
||
// 于是 graph_nodes(type='pattern') 恒 0 行、recall 恒 0 命中,而日志层面完全沉默
|
||
// (只能靠人翻 7 天日志才发现「实现了 ≠ 出过数」)。这里把「写入端有没有产数」
|
||
// 变成一次 GET 就能读到的事实:rows=0 ⇒ 生产者坏了或从未接线,别去查读侧 SQL。
|
||
rep["pattern"] = patternHealth(a)
|
||
|
||
// ── 面板指标(反馈/蒸馏/gap/cascade,含 _valid/_samples 语义)──
|
||
rep["dashboard"] = selfoptimize.Dash.Metrics()
|
||
|
||
// ── 整合链路(内存态,<1ms)────────────────
|
||
tracker := GetConsolTracker()
|
||
consolStatus, consolFails, sinceSuccess, lastErr := tracker.HealthStatus()
|
||
_, consolSkips, lastSkip, _ := tracker.Snapshot()
|
||
rep["consolidate"] = map[string]interface{}{
|
||
"status": consolStatus,
|
||
"consec_failures": consolFails,
|
||
"skipped": consolSkips,
|
||
"last_skip": lastSkip,
|
||
"last_success_age": sinceSuccess.String(),
|
||
"last_error": lastErr,
|
||
}
|
||
|
||
// ── 缓存 / FTS ─────────────────────────────
|
||
cache := map[string]interface{}{"fts_index": storage.FtsIndexStats()}
|
||
if storage.SearchCacheInstance != nil {
|
||
cache["search_cache"] = storage.SearchCacheInstance.Stats()
|
||
}
|
||
rep["cache"] = cache
|
||
|
||
// ── 空壳拦截器(t_e11207f8 取证)───────────
|
||
checks, blocks, loaded, rulesPath := distill.PayloadGuardStats()
|
||
rep["payload_guard"] = map[string]interface{}{
|
||
"checks": checks,
|
||
"blocks": blocks,
|
||
"loaded": loaded,
|
||
"rules_path": rulesPath,
|
||
}
|
||
|
||
// ── 全量质量段(level=full):读卫星快照,不在本进程扫全表 ────────
|
||
// 设计:全表扫描是重活(4 万行 × 内容),且 daemon 还有 recall 要跑。
|
||
// 取数由仓库内 tools/selfcheck_full.py 完成(列投影只读,1.7s / 250MB,独立进程),
|
||
// 写 ~/.hermes/state/zhiyi-quality.json;本端点只读快照并标注新鲜度。
|
||
// 这样"取数"只有一处实现(跟 schema 同仓),"判定/告警"仍在外部 cron。
|
||
if level == "full" {
|
||
snap, err := loadQualitySnapshot()
|
||
if err != nil {
|
||
degraded = append(degraded, "quality: "+err.Error())
|
||
} else {
|
||
rep["quality"] = snap.Quality
|
||
rep["write_volume"] = snap.WriteVolume
|
||
rep["quality_as_of"] = snap.GeneratedAt
|
||
rep["quality_age_s"] = snap.AgeSeconds()
|
||
rep["quality_stale"] = snap.AgeSeconds() > qualityStaleAfter
|
||
}
|
||
}
|
||
|
||
if len(degraded) > 0 {
|
||
rep["degraded"] = degraded
|
||
}
|
||
rep["duration_ms"] = time.Since(start).Milliseconds()
|
||
|
||
w.Header().Set("Content-Type", "application/json")
|
||
w.WriteHeader(http.StatusOK)
|
||
json.NewEncoder(w).Encode(rep)
|
||
}
|
||
|
||
// qualityStaleAfter:快照超过这个时长未刷新 ⇒ 标记 stale(消费方不得据此下结论)。
|
||
const qualityStaleAfter = 6 * 3600
|
||
|
||
// qualitySnapshot 对应仓库内 tools/selfcheck_full.py 的产出。
|
||
// 字段名与 python 侧严格一致(schema_version=1)。
|
||
type qualitySnapshot struct {
|
||
SchemaVersion int `json:"schema_version"`
|
||
GeneratedAt string `json:"generated_at"`
|
||
Source struct {
|
||
DB string `json:"db"`
|
||
Table string `json:"table"`
|
||
Mode string `json:"mode"`
|
||
} `json:"source"`
|
||
DurationMS int `json:"duration_ms"`
|
||
Quality json.RawMessage `json:"quality"`
|
||
WriteVolume json.RawMessage `json:"write_volume"`
|
||
fileModTime time.Time
|
||
}
|
||
|
||
func (q *qualitySnapshot) AgeSeconds() int64 {
|
||
if q.fileModTime.IsZero() {
|
||
return -1
|
||
}
|
||
return int64(time.Since(q.fileModTime).Seconds())
|
||
}
|
||
|
||
// QualitySnapshotPath 允许用 env 覆盖(测试/灰度)。
|
||
func QualitySnapshotPath() string {
|
||
if p := strings.TrimSpace(os.Getenv("ZHIYI_QUALITY_SNAPSHOT")); p != "" {
|
||
return p
|
||
}
|
||
home, _ := os.UserHomeDir()
|
||
return filepath.Join(home, ".hermes", "state", "zhiyi-quality.json")
|
||
}
|
||
|
||
func loadQualitySnapshot() (*qualitySnapshot, error) {
|
||
p := QualitySnapshotPath()
|
||
fi, err := os.Stat(p)
|
||
if err != nil {
|
||
return nil, fmt.Errorf("快照不存在(先跑 tools/selfcheck_full.py):%w", err)
|
||
}
|
||
raw, err := os.ReadFile(p)
|
||
if err != nil {
|
||
return nil, err
|
||
}
|
||
var snap qualitySnapshot
|
||
if err := json.Unmarshal(raw, &snap); err != nil {
|
||
return nil, fmt.Errorf("快照解析失败: %w", err)
|
||
}
|
||
snap.fileModTime = fi.ModTime()
|
||
return &snap, nil
|
||
}
|
||
|
||
// numOf 把 stats 里可能是 float64/int/json.Number 的数值统一成 float64。
|
||
func numOf(v interface{}) float64 {
|
||
switch x := v.(type) {
|
||
case float64:
|
||
return x
|
||
case float32:
|
||
return float64(x)
|
||
case int:
|
||
return float64(x)
|
||
case int64:
|
||
return float64(x)
|
||
case json.Number:
|
||
f, _ := x.Float64()
|
||
return f
|
||
default:
|
||
return 0
|
||
}
|
||
}
|
||
|
||
func round4(f float64) float64 {
|
||
if math.IsNaN(f) || math.IsInf(f, 0) {
|
||
return -1
|
||
}
|
||
return math.Round(f*10000) / 10000
|
||
}
|
||
|
||
// patternHealth 一眼判定 pattern 召回是「有生产者」还是「恒 0」。
|
||
//
|
||
// 为什么需要它:2026-10-26 排查发现 pattern 召回 0 命中,真根因是写入端从未产数
|
||
// (detect 端点无 cron、无调用方),但表面症状看起来像读侧 SQL bug —— 白查一轮方向。
|
||
// 判据三类:
|
||
//
|
||
// producing 有行、有 id、有生产时间 → 读侧再 0 命中就该查 Match 阈值/properties;
|
||
// zero_output 0 行 → 生产端问题,别去动读侧 SQL;
|
||
// no_id 有行但 id 全空 → store.ListPatterns 会全 skip(存量冻结的典型形态)。
|
||
func patternHealth(a *API) map[string]interface{} {
|
||
out := map[string]interface{}{
|
||
"rows": -1, // -1 = 未知,别当 0 用
|
||
"rows_with_id": -1,
|
||
"last_produced_at": "",
|
||
"verdict": "unknown",
|
||
}
|
||
if a == nil || a.GraphStore == nil {
|
||
out["verdict"] = "no_graph_store"
|
||
return out
|
||
}
|
||
rows, withID, last := a.GraphStore.CountNodesByType("pattern")
|
||
out["rows"], out["rows_with_id"], out["last_produced_at"] = rows, withID, last
|
||
switch {
|
||
case rows == 0:
|
||
out["verdict"] = "zero_output"
|
||
case withID == 0:
|
||
out["verdict"] = "no_id"
|
||
case last == "":
|
||
out["verdict"] = "unknown_age"
|
||
default:
|
||
out["verdict"] = "producing"
|
||
}
|
||
return out
|
||
}
|