fix(distill): 修评分 echo 闸门失效 + 空 id 软删防御(P0-1/P0-2/P1-1)

P0-1 治本·去 echo 源
  engine.go 的 5D 评分 prompt 曾把示例写成具体数字(0.8/0.7/0.6/0.9/0.7),
  模型直接照抄 ⇒ 每条 overall 恒为 0.755(按 Weights 加权)⇒ 永久 ≥0.7 阈值
  ⇒ 评分闸门从未真正生效,实际只剩「文本长度」在扛质量,生产者于是学会拉长文本过关。
  改为类型占位符 <小数>,并显式禁止沿用固定数值组合。

P0-2 治本·echo 检测 + 影子模式
  新增 IsEchoScore(比对历史示例向量);闸门命中时默认只记 [SHADOW] would-drop,
  不真丢(ZHIYI_SCORE_SHADOW=0 切回真拦)。原因:闸门修好后会首次开始真拦,
  需先观察样本分布,避免一次性批量误杀。

P1-1 防御·空 id 软删
  DB 存在 id/content 全空的垃圾行 → 命中 <30 字碎片快速道 → SoftDelete("")
  → Rust IPC 拒绝 "id required" → 调用方吞错照样 forgotten++ ⇒ 刷日志 + 计数虚高。
  RustLanceDBClient.SoftDelete 入口拒绝空 id;admin.go/server.go 四处调用点
  补 id != "" 守卫 + 失败不计数。

测试(均含阳性/阴性对照):
  TestIsEchoScore_Positive / _Negative / TestEchoVectorMatchesWeightedOverall
  / TestPromptHasNoEchoLiterals(回归守卫,防示例数字被写回)
  TestSoftDelete_RejectsEmptyID / _NonEmptyIDPassesGuard
This commit is contained in:
小唯
2026-10-06 17:21:41 +08:00
parent 57c55a7cca
commit fc7b8e74bd
6 changed files with 183 additions and 16 deletions
+16 -4
View File
@@ -84,8 +84,15 @@ func (aa *AdminAPI) Forget(w http.ResponseWriter, r *http.Request) {
// 2026-09-07 方案A 碎片快速道(与 server.go decay trigger 一致):
// <30 字且 >20 天未访问 → 直接遗忘(碎片 recall_count 可能虚高, 绕过保命)
if len([]rune(content)) < 30 && time.Since(lastAccess).Hours()/24 > 20 {
if err := aa.LanceDB.SoftDelete(strVal(mem["id"]), "auto_forget_fragment"); err != nil {
log.Printf("[softdelete] failed id: %v", err)
// 🔴 2026-10-06:空 id 直接跳过(DB 里有 id/content 全空的垃圾行会命中这条快速道);
// 且 SoftDelete 失败不再计数 —— 原实现失败照样 forgotten++ ⇒ 遗忘计数虚高。
id := strVal(mem["id"])
if id == "" {
continue
}
if err := aa.LanceDB.SoftDelete(id, "auto_forget_fragment"); err != nil {
log.Printf("[softdelete] failed id=%q: %v", id, err)
continue
}
forgotten++
continue
@@ -95,8 +102,13 @@ func (aa *AdminAPI) Forget(w http.ResponseWriter, r *http.Request) {
degree := extractTopEntityDegree(content, aa.GraphStore)
if aa.Forgetter.ShouldForget(lastAccess, recallCnt, tier, degree) {
if err := aa.LanceDB.SoftDelete(strVal(mem["id"]), "auto_forget"); err != nil {
log.Printf("[softdelete] failed id: %v", err)
id := strVal(mem["id"])
if id == "" {
continue
}
if err := aa.LanceDB.SoftDelete(id, "auto_forget"); err != nil {
log.Printf("[softdelete] failed id=%q: %v", id, err)
continue
}
forgotten++
}
+14 -6
View File
@@ -1637,9 +1637,14 @@ func NewServer() http.Handler {
contentStr = cs
}
if len([]rune(contentStr)) < 30 && time.Since(lastAccessed).Hours()/24 > 20 {
if id, ok := m["id"].(string); ok {
_ = ldb.SoftDelete(id, "auto_forget_fragment")
decayForgotten++
// 🔴 2026-10-06:`ok` 断言会放行空串(DB 存在 id 全空的垃圾行)⇒ SoftDelete("")
// 被 Rust 拒绝、错误被吞 ⇒ 每轮刷错误日志 + 计数虚高。补 id != "" 且失败不计数。
if id, ok := m["id"].(string); ok && id != "" {
if err := ldb.SoftDelete(id, "auto_forget_fragment"); err != nil {
log.Printf("[decay] softdelete failed id=%q: %v", id, err)
} else {
decayForgotten++
}
}
continue
}
@@ -1661,11 +1666,14 @@ func NewServer() http.Handler {
degree = graphStore.GetEntityDegree(entity)
}
if forgetter.ShouldForget(lastAccessed, recallCount, tier, degree) {
if id, ok := m["id"].(string); ok {
if id, ok := m["id"].(string); ok && id != "" {
forgetter.ScanAndForget(id)
// 实际执行软删除(持久化到 LanceDB)
_ = ldb.SoftDelete(id, "auto_forget")
decayForgotten++
if err := ldb.SoftDelete(id, "auto_forget"); err != nil {
log.Printf("[decay] softdelete failed id=%q: %v", id, err)
} else {
decayForgotten++
}
}
}
}
+45 -6
View File
@@ -11,6 +11,7 @@ import (
"log"
"math/rand"
"net/http"
"os"
"strings"
"sync"
"sync/atomic"
@@ -94,6 +95,34 @@ var Weights = FiveDScore{
RU: 0.20,
}
// ─── 评分 echo 检测(2026-10-06)──────────────────────────────
//
// 背景:callLLM5D 的 prompt 曾把「示例评分」写成具体数字(0.8/0.7/0.6/0.9/0.7),
// 模型直接照抄这组数值 —— 于是每条内容的 overall 恒为 0.755(= 按 Weights 加权),
// 永久 ≥ 0.7 阈值 ⇒ 评分闸门从未真正生效,实际只剩「文本长度」在扛质量。
//
// 这里只做「检测 + 影子记录」,**不改变丢弃行为**;先观察样本,再决定是否真拦。
// 影子默认开启;设 ZHIYI_SCORE_SHADOW=0 可关(关掉 = 恢复按分数真丢)。
// echoScoreVectors 是历史 prompt 里出现过的示例评分向量(照抄即命中)。
var echoScoreVectors = [][5]float64{
{0.8, 0.7, 0.6, 0.9, 0.7}, // engine.go 旧 prompt 示例
}
// IsEchoScore 判断评分是否在照抄 prompt 示例(照抄 ⇒ 该评分不可信)。
func IsEchoScore(s FiveDScore) bool {
for _, v := range echoScoreVectors {
if s.IS == v[0] && s.SU == v[1] && s.PA == v[2] && s.VD == v[3] && s.RU == v[4] {
return true
}
}
return false
}
// scoreShadowMode 影子模式:true(默认)= 只在日志里记录"本该被丢",不真丢。
// 设环境变量 ZHIYI_SCORE_SHADOW=0 关闭影子(= 恢复真拦)。
var scoreShadowMode = os.Getenv("ZHIYI_SCORE_SHADOW") != "0"
// ─── 蒸馏引擎 ────────────────────────────────────────────────
// Engine 蒸馏引擎
@@ -419,10 +448,18 @@ func (e *Engine) distillOne(input DistillInput) DistillResult {
// LLM 打分天然偏低(短、无上下文),不应因分数被丢弃——否则"牧尘不在招商局工作"
// 这类关键事实永远到不了 memories,t6 永远比对不到。
if !isSoulfulShortFact(input.Content) {
log.Printf("[distill] score below threshold for %s, skip", input.EpisodeID)
// 即使阈值未通过,仍然用 LLM 实体提取(如果有的话)
if len(llmResp.Entities) == 0 {
return DistillResult{}
if scoreShadowMode {
// 影子模式(2026-10-06):闸门此前因 echo bug 从未真正生效,
// 修好 prompt 后它会首次开始真拦 —— 先只记录"本该被丢",观察样本分布,
// 避免一次性批量误杀。ZHIYI_SCORE_SHADOW=0 可切回真拦。
log.Printf("[distill][SHADOW] would-drop episode=%s overall=%.3f vd=%.2f echo=%v content=%q",
input.EpisodeID, overall, score.VD, IsEchoScore(score), truncate(input.Content, 80))
} else {
log.Printf("[distill] score below threshold for %s, skip", input.EpisodeID)
// 即使阈值未通过,仍然用 LLM 实体提取(如果有的话)
if len(llmResp.Entities) == 0 {
return DistillResult{}
}
}
}
}
@@ -531,9 +568,11 @@ func (e *Engine) callLLM5D(content string) (LLMResponse, error) {
- entities: 提到的关键实体(系统名、工具名、人名、技术名词)
输出格式(严格JSON):
{"facts": ["独立事实1", "独立事实2"], "decisions": ["决定1"], "conclusions": ["结论1"], "actions_taken": ["行动1"], "open_questions": ["问题1"], "entities": ["entity1", "entity2"], "is": 0.8, "su": 0.7, "pa": 0.6, "vd": 0.9, "ru": 0.7}
{"facts": ["独立事实1", "独立事实2"], "decisions": ["决定1"], "conclusions": ["结论1"], "actions_taken": ["行动1"], "open_questions": ["问题1"], "entities": ["entity1", "entity2"], "is": <小数>, "su": <小数>, "pa": <小数>, "vd": <小数>, "ru": <小数>}
评分说明:is/su/pa/vd/ru 是 0.0 到 1.0 之间的浮点数(越高越好),不要用 0-10 整数。
评分说明:is/su/pa/vd/ru 必须是 0.0 到 1.0 之间的浮点数(越高越好),不得用 0-10 整数。
🔴 上面五个 <小数> 是**类型占位符,不是示例数值**。你必须依据**本次内容**独立打分,各维度可以不同。
严禁沿用固定的数值组合(例如 0.8/0.7/0.6/0.9/0.7)——照抄示例分数会被系统判为无效评分并整条丢弃。
要求:除非消息完全无意义,否则提取并输出为事实。facts 要详尽,不要只给1条摘要。
内容:
+67
View File
@@ -0,0 +1,67 @@
package distill
import (
"os"
"strings"
"testing"
)
// TestIsEchoScore_Positive 阳性对照:照抄旧 prompt 示例 → 必须报 true。
// 量具铁律:新量具先用正例证明它会报阳性,否则"没报警"毫无意义。
func TestIsEchoScore_Positive(t *testing.T) {
echo := FiveDScore{IS: 0.8, SU: 0.7, PA: 0.6, VD: 0.9, RU: 0.7}
if !IsEchoScore(echo) {
t.Fatalf("阳性对照失败:照抄示例 %+v 未被识别为 echo(量具失灵)", echo)
}
}
// TestIsEchoScore_Negative 阴性对照:不得滥报。
func TestIsEchoScore_Negative(t *testing.T) {
cases := map[string]FiveDScore{
"仅一位不同": {IS: 0.8, SU: 0.7, PA: 0.6, VD: 0.9, RU: 0.8},
"全零": {},
"真实差异评分": {IS: 0.95, SU: 0.4, PA: 0.2, VD: 0.85, RU: 0.6},
"全一分": {IS: 1, SU: 1, PA: 1, VD: 1, RU: 1},
}
for name, s := range cases {
if IsEchoScore(s) {
t.Errorf("阴性对照失败[%s]:%+v 被误判为 echo(滥报)", name, s)
}
}
}
// TestEchoVectorMatchesWeightedOverall 证明 echo 向量的加权分恰好是观测到的恒定值 0.755。
// 这条是"因果链"的证据固化:0.755 ≥ 0.7 阈值 ⇒ 闸门恒不触发。
func TestEchoVectorMatchesWeightedOverall(t *testing.T) {
echo := FiveDScore{IS: 0.8, SU: 0.7, PA: 0.6, VD: 0.9, RU: 0.7}
overall := echo.IS*Weights.IS + echo.SU*Weights.SU + echo.PA*Weights.PA +
echo.VD*Weights.VD + echo.RU*Weights.RU
// 0.80*0.20 + 0.70*0.20 + 0.60*0.15 + 0.90*0.25 + 0.70*0.20 = 0.755
if overall < 0.7549 || overall > 0.7551 {
t.Fatalf("加权分应为 0.755,实得 %.4f(权重被改动?)", overall)
}
if overall < 0.7 {
t.Fatalf("echo 加权分 %.4f < 0.7 阈值 —— 与「闸门恒不触发」的观测矛盾", overall)
}
}
// TestPromptHasNoEchoLiterals 回归守卫:prompt 里不得再出现具体的示例评分数字。
// 起因:示例写成具体数值 ⇒ 模型照抄 ⇒ 每条 overall 恒为 0.755 ⇒ 评分闸门形同虚设。
func TestPromptHasNoEchoLiterals(t *testing.T) {
src, err := os.ReadFile("engine.go")
if err != nil {
t.Fatalf("读 engine.go 失败: %v", err)
}
s := string(src)
if !strings.Contains(s, `"is": <小数>`) {
t.Fatal("回归:prompt 里已找不到 <小数> 占位符 —— 示例可能又被写成具体数字")
}
if strings.Contains(s, `"is": 0.8, "su": 0.7, "pa": 0.6, "vd": 0.9, "ru": 0.7`) {
t.Fatal("回归:prompt 里重新出现了具体示例评分(echo 源)")
}
// 占位符必须带"禁止沿用固定数值"的显式约束,否则模型仍会编造固定值
if !strings.Contains(s, "严禁沿用固定的数值组合") {
t.Error("prompt 缺少「禁止沿用固定数值组合」的约束句")
}
}
+7
View File
@@ -582,6 +582,13 @@ func (rc *RustLanceDBClient) GetTopByQuality(agentID string, limit int) ([]model
}
func (rc *RustLanceDBClient) SoftDelete(id, reason string) error {
// 🔴 2026-10-06 防御:空 id 会被 Rust IPC 直接拒绝("id required"),
// 而调用方曾忽略错误照样计数(admin.go forgotten++),造成「遗忘计数虚高 + 每轮刷错误日志」。
// 根因:DB 里存在 id/content 全空的垃圾行 → 命中 <30 字碎片快速道 → SoftDelete("")。
// 在入口直接挡掉,返回可辨识错误(调用方据此跳过、不计数)。
if strings.TrimSpace(id) == "" {
return fmt.Errorf("soft delete: empty id rejected (reason=%s)", reason)
}
_local.mu.Lock()
if m, ok := _local.memories[id]; ok {
m.IsDeleted = true
@@ -0,0 +1,34 @@
package storage
import (
"strings"
"testing"
)
// TestSoftDelete_RejectsEmptyID 阳性对照:空 id 必须在入口被挡,**不得走 IPC**。
//
// 起因:DB 存在 id/content 全空的垃圾行 → 命中 <30 字碎片快速道 → SoftDelete("")
// → Rust IPC 拒绝("id required")→ 调用方吞掉错误照样 forgotten++ ⇒ 每轮刷错误日志 + 遗忘计数虚高。
func TestSoftDelete_RejectsEmptyID(t *testing.T) {
// 故意不给 sockPath:守卫若失效就会走 IPC 并返回 dial 错误,据此区分"守卫生效"与"守卫失效"。
rc := &RustLanceDBClient{}
for _, bad := range []string{"", " ", "\t", "\n "} {
err := rc.SoftDelete(bad, "unit_test")
if err == nil {
t.Fatalf("空 id %q 未被拒绝(守卫失效)", bad)
}
if !strings.Contains(err.Error(), "empty id rejected") {
t.Fatalf("空 id %q 走了 IPC 而非入口守卫,错误=%v", bad, err)
}
}
}
// TestSoftDelete_NonEmptyIDPassesGuard 阴性对照:非空 id 不得被守卫误拦(不滥报)。
// 期望:走到 IPC 并因 socket 缺失而失败 —— 错误里绝不能出现 "empty id rejected"。
func TestSoftDelete_NonEmptyIDPassesGuard(t *testing.T) {
rc := &RustLanceDBClient{}
err := rc.SoftDelete("mem_unit_test_nonexistent", "unit_test")
if err != nil && strings.Contains(err.Error(), "empty id rejected") {
t.Fatalf("非空 id 被空 id 守卫误拦(滥报): %v", err)
}
}