Files
小唯 45726d26a7 fix(selfoptimize): t_e5997ca4 gap 计数器写侧统一 — +1 只在 open→closed 迁移点 + 计数器 v2 版本化重置
根因(小怡 2026-10-17 终审实测定位):写侧仍有未收口的事件式自增点,
ClosedGaps(9) 越过 TotalGaps(2),gap_closure_rate 被 -1 断言拦下但指标永久不可解读。
  ① routes/gaps.go:44  POST /close 在 Close() 之后无条件 Dash.RecordGapClosed()
     ⇒ 同一缺口每次调用都 +1(无限计数)。且实测现行注册为前缀路由
     /api/v1/gaps/close/(无 {topic} 通配)⇒ PathValue 恒为 ""、端点恒 400,
     该自增点当时不可达,但一旦注册改通配即复活。
  ② server.go:1950  gap_scan 自动修复循环 AutoRepair 成功只计数不关缺口
     ⇒ 同一缺口每轮再 +1(无限虚增,线上 9 vs 2 的主要来源)。

修复:
  - Close/RecordHit 返回 bool(是否真发生 open→closed 迁移);+1 唯一入口
    收敛到迁移点内部;RecordGapClosed 降为包内 recordGapClosed(编译期堵死
    跨包事件式自增)。
  - gaps.go 删无条件 +1;补前缀路由 topic 解析(端点自此真正可用),
    响应如实区分 closed / already_closed。
  - server.go 修复循环改「修复成功 ⇒ 关闭缺口」(RepairHandler 同语义),
    下一轮 !g.Closed 即跳过,计数只在迁移点。
  - 历史 9 vs 2 处置选 (b) 计数器版本化重置:dashboard_schema_version=
    dashboard_schema_v2 标记入 Redis HASH + 本地 JSON(既有 90 天 TTL 键,
    不新增键);首载无标记 ⇒ ClosedGaps/TotalGaps 归零并回写标记(一次性、
    可机械复核),标记在位 ⇒ 保真。代价:丢失不可信的 gap 历史累计。
  - 口径不变:ClosedGaps/TotalGaps = 缺口个数;Metrics() 越界断言保留作
    安全网(不当修复用)。

测试:
  - selfoptimize: Close×3 / RecordHit×3 / 修复循环 3 轮 ⇒ 各只 +1、rate<=1;
    SchemaV2 一次性重置 + 标记在位保真(v1 文件 9/2 载入归零、v2 值保真)。
  - routes: POST /close ×2(现行前缀注册 + {topic} 通配注册两形态)⇒ 只 +1、
    auto_* 计数器快照不变;新增 TestMain 把 ZHIYI_DASHBOARD_PATH 指到临时目录
    (先例:selfoptimize 包同款,防测试写生产落盘点)。
  - 判别力证明(/tmp 改前树 c015feb 旁证副本,不进仓库):逐字复刻改前两写
    路径 ⇒ ClosedGaps diff=6 > TotalGaps=2(rate 3.0 越界,线上 9 vs 2 同型)
    FAIL;改后同场景 diff=2、rate=1.0。

边界:只动 gap 计数器与调用点;部署不在本卡(t_ad887e7c,待牧尘放行)。
2026-10-17 22:12:40 +08:00

149 lines
5.1 KiB
Go
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
// 织忆 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)
}
}