feat(distill): 硬规则拒绝可观测 rejected_by_rule 真计数 + lane=drop 死路定性 (t_a513b870)
- AC1: HardRulesPass 拆出 HardRulesPassWithReason,拒绝分支登记并发安全计数 (empty/too_short/chitchat/qa/sys_template/low_density/too_long 7 桶) + 至少一行 [GATE][REJECT] rule=<x> 日志;系统样板移入硬规则层,drop 只在硬规则层发生。 - AC2: rejected_by_rule 挂到已有 /api/v1/metrics(不开新端口), 字段 rejected_by_rule / rejected_by_rule_<bucket> / entered_queue / gate_attempts; handler 主体抽成 routes.MetricsJSON 便于单测。 - AC3: 单测覆盖全部分桶 + 并发 200 + httptest 真实端点读回 JSON。 - AC4(a): 承认 lane=drop 不可达(硬规则更严先拦),保留分支加防御注释,闸门只走 keep/observe。 - 发现 chitchat 规则同样不可达(pattern 全 <10 字,恒被 too_short 先短路)→ 测试钉死。 - 未打二进制/未改 drop-in/未重启 zhiyid(二进制由小怡统一构建部署)。
This commit is contained in:
@@ -37,8 +37,8 @@ func AutoDistillTrigger(episodeID string, content string, category string, names
|
||||
return
|
||||
}
|
||||
|
||||
// 1. 硬规则过滤
|
||||
if !distill.HardRulesPass(content) {
|
||||
// 1. 硬规则过滤(t_a513b870:带原因变体,拒绝在内部登记计数 + 打日志)
|
||||
if pass, _ := distill.HardRulesPassWithReason(content); !pass {
|
||||
return
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,62 @@
|
||||
// 织忆 MemoryWeave — /api/v1/metrics 的 JSON 组装(t_a513b870 AC2/AC3 提取)
|
||||
//
|
||||
// 把 server.go 里 /api/v1/metrics 的 handler 主体抽成纯函数,便于:
|
||||
// · handler 只做收尾 respondJSON
|
||||
// · 单测可借 httptest 起「真实端点」读回 JSON,证明 rejected_by_rule 存在且值正确
|
||||
//
|
||||
// 依赖注入:ldb 的 Stats() 以参数传入(测试可用假值),不在此持有全局 ldb。
|
||||
package routes
|
||||
|
||||
import (
|
||||
"github.com/xiaoxue/memoryweave/internal/distill"
|
||||
)
|
||||
|
||||
// MetricsJSON 组装 /api/v1/metrics 的响应 map(map[string]float64,与外层契约一致)。
|
||||
//
|
||||
// dash 为 selfoptimize.Dash.Metrics() 的取值(测试可传空/自定义);
|
||||
// stats 为 ldb.Stats() 的原样返回(nil=读不到,跳过 total_* 合并即可,不因存储故障
|
||||
// 让整端点 500 —— 与旧 handler 的 `if err == nil` 语义一致)。
|
||||
//
|
||||
// t_a513b870 AC2:在既有端点不新开端口的前提下,叠加蒸馏闸门拒绝真计数:
|
||||
// rejected_by_rule = 拒绝总数
|
||||
// rejected_by_rule_<bucket> = 各分桶拒绝数(empty/too_short/chitchat/qa/
|
||||
// sys_template/low_density/too_long)
|
||||
// entered_queue = 真正进入蒸馏队列的条数(⑪ 分母)
|
||||
// gate_attempts = 闸门评估总次数(pass+reject)
|
||||
func MetricsJSON(dash map[string]float64, stats map[string]interface{}) map[string]float64 {
|
||||
m := dash
|
||||
if m == nil {
|
||||
m = map[string]float64{}
|
||||
} else {
|
||||
m = cloneMap(m)
|
||||
}
|
||||
if stats != nil {
|
||||
if total, ok := stats["total_memories"].(float64); ok {
|
||||
m["total_memories"] = total
|
||||
}
|
||||
if total, ok := stats["total_episodes"].(float64); ok {
|
||||
m["total_episodes"] = total
|
||||
} else if cached, ok := stats["episodes_cached"].(float64); ok {
|
||||
// 旧 sidecar 回退:缓存值非真实总量;来源标记用 episodes_source=1.0 占位
|
||||
m["total_episodes"] = cached
|
||||
m["episodes_source_cached"] = 1
|
||||
}
|
||||
}
|
||||
|
||||
gAt, gEntered, byRule := distill.GateStats()
|
||||
m["rejected_by_rule"] = float64(distill.RejectedByRuleTotal())
|
||||
m["gate_attempts"] = float64(gAt)
|
||||
m["entered_queue"] = float64(gEntered)
|
||||
for b, v := range byRule {
|
||||
m["rejected_by_rule_"+b] = float64(v)
|
||||
}
|
||||
return m
|
||||
}
|
||||
|
||||
func cloneMap(m map[string]float64) map[string]float64 {
|
||||
out := make(map[string]float64, len(m))
|
||||
for k, v := range m {
|
||||
out[k] = v
|
||||
}
|
||||
return out
|
||||
}
|
||||
@@ -0,0 +1,121 @@
|
||||
package routes
|
||||
|
||||
// t_a513b870 AC3(端点冒烟):起真实 httptest 端点跑 /api/v1/metrics 读回 JSON,
|
||||
// 证明 rejected_by_rule 字段存在且值正确(5 个指定分桶 + 总数 + entered 分母)。
|
||||
// 计数进程级共享,全部用相对增量;端点 handler 走真实 MetricsJSON(与外层 server.go
|
||||
// 同一函数),仅 inject 假 ldb.Stats 返回(nil=读不到存储,不影响 rejected_* 合并)。
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"testing"
|
||||
|
||||
"github.com/xiaoxue/memoryweave/internal/distill"
|
||||
)
|
||||
|
||||
// metricsEndpoint 起一个只挂 /api/v1/metrics 的真实 HTTP 端点。
|
||||
func metricsEndpoint(t *testing.T, stats map[string]interface{}) (*httptest.Server, map[string]float64) {
|
||||
t.Helper()
|
||||
mux := http.NewServeMux()
|
||||
mux.HandleFunc("/api/v1/metrics", func(w http.ResponseWriter, r *http.Request) {
|
||||
m := MetricsJSON(nil, stats)
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
json.NewEncoder(w).Encode(m)
|
||||
})
|
||||
srv := httptest.NewServer(mux)
|
||||
t.Cleanup(srv.Close)
|
||||
return srv, map[string]float64{}
|
||||
}
|
||||
|
||||
func getMetrics(t *testing.T, srv *httptest.Server) map[string]float64 {
|
||||
t.Helper()
|
||||
resp, err := http.Get(srv.URL + "/api/v1/metrics")
|
||||
if err != nil {
|
||||
t.Fatalf("端点请求失败: %v", err)
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
if resp.StatusCode != 200 {
|
||||
t.Fatalf("端点状态码=%d,期望 200", resp.StatusCode)
|
||||
}
|
||||
var m map[string]float64
|
||||
if err := json.NewDecoder(resp.Body).Decode(&m); err != nil {
|
||||
t.Fatalf("端点响应不是合法 JSON map[string]float64: %v", err)
|
||||
}
|
||||
return m
|
||||
}
|
||||
|
||||
// TestMetricsEndpointRejectedByRule 真实端点读回:5 个指定分桶 + entered 分母值正确。
|
||||
func TestMetricsEndpointRejectedByRule(t *testing.T) {
|
||||
srv, _ := metricsEndpoint(t, nil)
|
||||
|
||||
// 基线:端点初始返回 rejected_by_rule 必须存在(零值桶也要有字段)
|
||||
base := getMetrics(t, srv)
|
||||
if _, ok := base["rejected_by_rule"]; !ok {
|
||||
t.Fatal("端点初始缺 rejected_by_rule 字段(AC2 字段名契约)")
|
||||
}
|
||||
|
||||
// 触发:5 个分桶各拒绝 1 条(用可经分类器命中的输入;拒绝由内部 RecordHardReject 登记)
|
||||
distill.HardRulesPassWithReason(" ") // empty
|
||||
distill.HardRulesPassWithReason("哦") // too_short
|
||||
distill.HardRulesPassWithReason("什么是闭包和递归以及高阶函数的设计原则与适用场景") // qa(≥10字越过过短)
|
||||
distill.HardRulesPassWithReason("[HEARTBEAT] tick") // sys_template
|
||||
// chitchat 分类器不可达(pattern<10字恒被过短短路),此处从计数器层给 1 条,
|
||||
// 证明读到 rejected_by_rule_chitchat 有真实语义。
|
||||
distill.RecordHardReject("chitchat", "probe-chitchat")
|
||||
// low_density 与 too_long 各 1 条
|
||||
distill.HardRulesPassWithReason("好的 好的 好的 好的 好 好")
|
||||
distill.HardRulesPassWithReason(genLongForRoute(5100))
|
||||
// entered 分母 +1
|
||||
distill.RecordEnteredQueue()
|
||||
|
||||
after := getMetrics(t, srv)
|
||||
|
||||
// 各分桶(相对基线的增量):5 指定桶各 ≥1 且 exactly 1 新增
|
||||
for _, wantFields := range []string{
|
||||
"rejected_by_rule_empty",
|
||||
"rejected_by_rule_too_short",
|
||||
"rejected_by_rule_qa",
|
||||
"rejected_by_rule_sys_template",
|
||||
"rejected_by_rule_chitchat",
|
||||
"rejected_by_rule_low_density",
|
||||
"rejected_by_rule_too_long",
|
||||
} {
|
||||
if _, ok := after[wantFields]; !ok {
|
||||
t.Fatalf("端点缺字段 %s(AC2 契约:rejected_by_rule_<bucket>)", wantFields)
|
||||
}
|
||||
}
|
||||
// 端点新增数 = 7 桶各 1 = constant;直接断言总数与 entered。
|
||||
// 全部新增拒绝 = 7,entered +1(用相对增量,勿受其他测试/前序污染)。
|
||||
if after["rejected_by_rule"]-base["rejected_by_rule"] < 7 {
|
||||
t.Fatalf("rejected_by_rule 增量=%v,期望 ≥7(至少五指定桶+密度+超长)",
|
||||
after["rejected_by_rule"]-base["rejected_by_rule"])
|
||||
}
|
||||
if after["entered_queue"]-base["entered_queue"] != 1 {
|
||||
t.Fatalf("entered_queue 增量=%v,期望 1", after["entered_queue"]-base["entered_queue"])
|
||||
}
|
||||
}
|
||||
|
||||
// TestMetricsEndpointKeepsTotalMemories 端点仍合并 total_memories/total_episodes(回归):
|
||||
// 抽离到 MetricsJSON 后不得丢旧契约。
|
||||
func TestMetricsEndpointKeepsTotalMemories(t *testing.T) {
|
||||
stats := map[string]interface{}{
|
||||
"total_memories": float64(1234),
|
||||
"total_episodes": float64(5678),
|
||||
}
|
||||
srv, _ := metricsEndpoint(t, stats)
|
||||
m := getMetrics(t, srv)
|
||||
if m["total_memories"] != 1234 || m["total_episodes"] != 5678 {
|
||||
t.Fatalf("total_memories/episodes 丢失: got %v/%v", m["total_memories"], m["total_episodes"])
|
||||
}
|
||||
}
|
||||
|
||||
func genLongForRoute(n int) string {
|
||||
src := "织忆系统今日排查审计指标运行状态良好,数据写入读取均正常,召回延迟处于低位。"
|
||||
b := []rune(src)
|
||||
out := make([]rune, 0, n)
|
||||
for len(out) < n {
|
||||
out = append(out, b...)
|
||||
}
|
||||
return string(out[:n])
|
||||
}
|
||||
@@ -714,21 +714,13 @@ func NewServer() http.Handler {
|
||||
// 自优化指标(Dashboard,含 avg_distill_loss)
|
||||
// total_episodes:Rust count_rows 真实值;旧 sidecar 回退 episodes_cached(进程内缓存,非总量)
|
||||
mux.HandleFunc("/api/v1/metrics", func(w http.ResponseWriter, r *http.Request) {
|
||||
m := selfoptimize.Dash.Metrics()
|
||||
if stats, err := ldb.Stats(); err == nil {
|
||||
if total, ok := stats["total_memories"].(float64); ok {
|
||||
m["total_memories"] = total
|
||||
}
|
||||
if total, ok := stats["total_episodes"].(float64); ok {
|
||||
m["total_episodes"] = total
|
||||
} else if cached, ok := stats["episodes_cached"].(float64); ok {
|
||||
// 旧 sidecar 回退:缓存值非真实总量,gauge 仍设值;
|
||||
// 来源标记写入响应 JSON(/api/v1/metrics 的 m 类型是 map[string]float64,
|
||||
// 无法直接加字符串字段,改为用 episodes_source=1.0 作为标记位)
|
||||
m["total_episodes"] = cached
|
||||
m["episodes_source_cached"] = 1 // 标记:此值来自进程内缓存(非 Rust count_rows)
|
||||
}
|
||||
var stats map[string]interface{}
|
||||
if s, err := ldb.Stats(); err == nil {
|
||||
stats = s
|
||||
}
|
||||
// t_a513b870 AC2:蒸馏闸门拒绝真计数 + total_* 合并统一走 MetricsJSON(单测可借
|
||||
// httptest 起真实端点读回 JSON 验证 rejected_by_rule)。
|
||||
m := routes.MetricsJSON(selfoptimize.Dash.Metrics(), stats)
|
||||
respondJSON(w, 200, m)
|
||||
})
|
||||
// ─── WebSocket 实时推送 ──────────────────────
|
||||
|
||||
@@ -54,6 +54,16 @@ var identityPreferencePatterns = []string{
|
||||
// ClassifyAdmission 对一条待蒸馏内容做确定性三路分诊。
|
||||
// 返回 lane 与人类可读的 reason(进日志,用于事后审计分诊是否合理)。
|
||||
// 本函数**零 LLM 调用**、纯确定性 —— 同一输入永远同一结果,可单测。
|
||||
//
|
||||
// 🔴 调用链可达性(t_a513b870 AC4 定性,2026-11-10 实测):
|
||||
// Enqueue(engine.go:422) 与 auto_distill.go:41 都**先跑 HardRulesPassWithReason**
|
||||
// 硬规则层(空/过短/闲聊/知识问答/密度/超长/系统样板 全在硬规则层拦截并 return),
|
||||
// ⇒ 能走到本函数的内容**已不可能命中下面 drop 分支**:
|
||||
// 空内容 / 系统样板(已移入硬规则层)/ 过短 <8 字(硬规则 <10 更严,先拦)。
|
||||
// 因此 lane=drop 在当前调用链**恒不可达**,7 天实测 lane=drop=0 属预期,非健康信号。
|
||||
// 保留 drop 分支仅作**防御**(若未来某条路径绕过硬规则直接调本函数,仍不致误放垃圾);
|
||||
// 闸门实际只走 keep/observe 两路。文献依据:不确定带永不丢弃(When to Forget 原文
|
||||
// "should not deprecate an uncertain memory"),drop 本就只在硬规则层发生。
|
||||
func ClassifyAdmission(content string) (AdmissionLane, string) {
|
||||
s := strings.TrimSpace(content)
|
||||
if s == "" {
|
||||
|
||||
@@ -419,12 +419,15 @@ func (e *Engine) Enqueue(input DistillInput) {
|
||||
e.mu.Lock()
|
||||
defer e.mu.Unlock()
|
||||
|
||||
if !HardRulesPass(input.Content) {
|
||||
// t_a513b870: 拒绝分支换成带原因的变体,拒绝在此登记计数 + 日志,黑洞消除。
|
||||
if pass, _ := HardRulesPassWithReason(input.Content); !pass {
|
||||
return
|
||||
}
|
||||
|
||||
e.queue = append(e.queue, input)
|
||||
e.pendingTokens += estimateTokens(input.Content)
|
||||
// t_a513b870: 分母「进入蒸馏队列的条数」= 真正 append 成功的一次。
|
||||
RecordEnteredQueue()
|
||||
|
||||
// P3 双缓冲触发:token 积累达阈值 或 条数达 batchSize 或 超时
|
||||
shouldFlush := e.pendingTokens >= e.flushTokenThreshold || len(e.queue) >= e.batchSize
|
||||
|
||||
@@ -0,0 +1,98 @@
|
||||
// 织忆 MemoryWeave — 蒸馏闸门拒绝的可观测计数器(t_a513b870 AC1)
|
||||
//
|
||||
// 背景:Enqueue / auto_distill 的硬规则拒绝分支曾经是**黑洞**——不打日志、不计数。
|
||||
// 7 天被硬规则拒掉多少条,系统里查不到。本文件把「在硬规则层拦掉多少」变成
|
||||
// 并发安全的真计数器,并按拒绝规则分桶;同时记录「进入蒸馏队列的量」作分母,
|
||||
// 让记分牌 ⑪ 的百分比与命中数同源(不再是 journal 两处拼凑)。
|
||||
package distill
|
||||
|
||||
import (
|
||||
"log"
|
||||
"sync"
|
||||
)
|
||||
|
||||
// rejectBuckets 硬规则拒绝的分桶(与 rules.go hardRejectReason 一一对应)。
|
||||
// 除卡上点名的 5 桶(空/过短/闲聊/知识问答/系统样板)外,密度不足与超长也是
|
||||
// HardRulesPass 的真实拒绝原因——不计数它们=重新制造黑洞,故一并纳入。
|
||||
var rejectBuckets = []string{
|
||||
"empty", // 空内容
|
||||
"too_short", // 过短(<10字且非人侧短事实)
|
||||
"chitchat", // 纯闲聊/问候
|
||||
"qa", // 纯知识问答
|
||||
"sys_template", // 系统样板(textfilter.IsSystemTemplate,2026-11-10 移入硬规则层)
|
||||
"low_density", // 内容密度 < 0.3
|
||||
"too_long", // 超长(>5000 字符)
|
||||
}
|
||||
|
||||
// gateCounter 硬规则闸门计数(并发安全)。单实例进程内共享,跨 Go/Rust 进程不共享:
|
||||
// 计数语义 = 本进程自启动以来的累计(重启清零),与 journal 窗口口径不同属预期。
|
||||
type gateCounter struct {
|
||||
mu sync.Mutex
|
||||
byRule map[string]uint64 // rule -> 拒绝次数
|
||||
attempts uint64 // 闸门被评估的总次数(含 pass+reject)
|
||||
entered uint64 // 通过闸门、真正进入蒸馏队列的次数
|
||||
}
|
||||
|
||||
var gate = &gateCounter{byRule: map[string]uint64{}}
|
||||
|
||||
func init() {
|
||||
// 预置全部分桶,保证读端(/api/v1/metrics)对零拒绝桶也能稳定出字段。
|
||||
for _, b := range rejectBuckets {
|
||||
gate.byRule[b] = 0
|
||||
}
|
||||
}
|
||||
|
||||
// RecordHardReject 登记一次硬规则拒绝(须在 reject 分支上、拿到具体 rule 再调)。
|
||||
// 幂等调用方约定:同一 logical 内容被 auto_distill:41 与 Enqueue:422 双层评估时,
|
||||
// 只有先到的拒绝分支会登记(后一层不会到达)——故 rejected 不重复计数。
|
||||
// 并发安全:内置 mutex(auto_distill 不持有 engine.mu,不能依赖调用方加锁)。
|
||||
func RecordHardReject(rule string, content string) {
|
||||
gate.mu.Lock()
|
||||
gate.attempts++
|
||||
if _, ok := gate.byRule[rule]; !ok {
|
||||
gate.byRule[rule] = 0
|
||||
}
|
||||
gate.byRule[rule]++
|
||||
gate.mu.Unlock()
|
||||
|
||||
// 至少一行日志(AC1),含 rule 名,供 journal 审计与坏样本回归 grep。
|
||||
log.Printf("[GATE][REJECT] rule=%s content=%q", rule, truncate(content, 60))
|
||||
}
|
||||
|
||||
// RecordGatePass 登记一次闸门通过(Enqueue 判定 pass )。auto_distill 的 pass 分支
|
||||
// 会再去 Enqueue 二次评估,那里也会判定一次 pass——两处均为真实闸门评估,attempts
|
||||
// 如实累计;entered 只在 Enqueue 真正 append 后 +1,作 ⑪ 的干净分母。
|
||||
func RecordGatePass() {
|
||||
gate.mu.Lock()
|
||||
gate.attempts++
|
||||
gate.mu.Unlock()
|
||||
}
|
||||
|
||||
// RecordEnteredQueue 登记一次真正入队(Enqueue append 成功后调)。作 ⑪ 分母。
|
||||
func RecordEnteredQueue() {
|
||||
gate.mu.Lock()
|
||||
gate.entered++
|
||||
gate.mu.Unlock()
|
||||
}
|
||||
|
||||
// GateStats 返回闸门计数快照(读端用,禁止直接摸 gate 内部)。
|
||||
// byRule 为副本;attempts/entered 为累计整型。
|
||||
func GateStats() (attempts uint64, entered uint64, byRule map[string]uint64) {
|
||||
gate.mu.Lock()
|
||||
defer gate.mu.Unlock()
|
||||
m := make(map[string]uint64, len(gate.byRule))
|
||||
for k, v := range gate.byRule {
|
||||
m[k] = v
|
||||
}
|
||||
return gate.attempts, gate.entered, m
|
||||
}
|
||||
|
||||
// RejectedByRuleTotal 拒绝总次数(所有分桶之和)。读端 /api/v1/metrics 简化为一个数。
|
||||
func RejectedByRuleTotal() uint64 {
|
||||
_, _, byRule := GateStats()
|
||||
var t uint64
|
||||
for _, v := range byRule {
|
||||
t += v
|
||||
}
|
||||
return t
|
||||
}
|
||||
@@ -0,0 +1,198 @@
|
||||
package distill
|
||||
|
||||
// t_a513b870 AC3:硬规则拒绝计数单测 —— 5 个指定分桶(+密度/超长两个伴随分桶)
|
||||
// 各命中 1 条 → 该分桶计数 +1;进入队列的分母同步 +1。计数为进程级共享状态,
|
||||
// 故全部断言用「相对增量」(测试前快照 → 测试后差值),避免与其他测试相互污染。
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"sync"
|
||||
"testing"
|
||||
)
|
||||
|
||||
// gateDelta 采样当前闸门计数,返回变化前后差值的断言辅助闭包。
|
||||
// 用法:bl := gateDelta(); 触发 N 次; bl.expectReject("empty", 1) 等。
|
||||
type gateDelta struct {
|
||||
attempts, entered uint64
|
||||
byRule map[string]uint64
|
||||
}
|
||||
|
||||
func captureGateDelta() gateDelta {
|
||||
var (
|
||||
bl gateDelta
|
||||
attempts uint64
|
||||
entered uint64
|
||||
m map[string]uint64
|
||||
)
|
||||
attempts, entered, m = GateStats()
|
||||
bl.attempts, bl.entered = attempts, entered
|
||||
bl.byRule = map[string]uint64{}
|
||||
for k, v := range m {
|
||||
bl.byRule[k] = v
|
||||
}
|
||||
return bl
|
||||
}
|
||||
|
||||
func (bl gateDelta) deltaAttempts() uint64 { a, _, _ := GateStats(); return a - bl.attempts }
|
||||
func (bl gateDelta) deltaEntered() uint64 { _, e, _ := GateStats(); return e - bl.entered }
|
||||
func (bl gateDelta) deltaRule(rule string) uint64 {
|
||||
_, _, m := GateStats()
|
||||
return m[rule] - bl.byRule[rule]
|
||||
}
|
||||
|
||||
// TestHardRulesRejectBuckets 覆盖「可经规则分类器命中的」拒绝分桶各 1 条 → 各分桶 +1,
|
||||
// 且返回的 reason 与分桶一致(reason 即分桶名,供日志审计对齐)。
|
||||
//
|
||||
// ⚠️ 测试输入必须满足「先序规则全不命中」才能到达目标桶(规则按
|
||||
// 空→样板→过短→闲聊→知识问答→密度→超长 顺序短路):
|
||||
// · 闲聊桶的 pattern 全部 <10 字 ⇒ 恒先被「过短(<10字)」拦截 → **不可达**
|
||||
// (与 lane=drop 同构的坏样本;chitchat 桶的计数能力另在
|
||||
// TestRejectCounterEveryBucket 用直调 RecordHardReject 验证)
|
||||
// · 知识问答/x 类前缀输入必须 ≥10 字才能越过「过短」到达 qa 桶
|
||||
// · 超长输入必须内容多样(信息密度 ≥0.3)才能越过「密度」到达 too_long 桶
|
||||
func TestHardRulesRejectBuckets(t *testing.T) {
|
||||
cases := []struct {
|
||||
rule string
|
||||
content string
|
||||
}{
|
||||
{"empty", " \n"}, // 空内容
|
||||
{"too_short", "哦"}, // 过短(<10字且非人侧短事实)
|
||||
{"qa", "什么是闭包和递归以及高阶函数的设计原则与适用场景"}, // 知识问答(≥10字越过过短)
|
||||
{"sys_template", "[HEARTBEAT] tick 2026-11-10"}, // 系统样板
|
||||
{"low_density", "好的 好的 好的 好的 好的 好 好"}, // 低密度重复
|
||||
{"too_long", genLong(5500)}, // 超长(>5000字符),内容多样保密度
|
||||
}
|
||||
|
||||
for _, c := range cases {
|
||||
t.Run(c.rule, func(t *testing.T) {
|
||||
bl := captureGateDelta()
|
||||
pass, reason := HardRulesPassWithReason(c.content)
|
||||
if pass {
|
||||
t.Fatalf("[%s] 期望拒绝,实际通过: %.40q", c.rule, c.content)
|
||||
}
|
||||
if reason != c.rule {
|
||||
t.Fatalf("[%s] reason=%q,期望 %q(reason 必须与分桶同名,供日志/读端对齐)", c.rule, reason, c.rule)
|
||||
}
|
||||
if got := bl.deltaRule(c.rule); got != 1 {
|
||||
t.Fatalf("[%s] 分桶计数 delta=%d,期望 1(同一输入只计一次)", c.rule, got)
|
||||
}
|
||||
// 拒绝不进入队列:entered 必须为 0
|
||||
if en := bl.deltaEntered(); en != 0 {
|
||||
t.Fatalf("[%s] 拒绝却 entered delta=%d,期望 0(拒绝项不得入队)", c.rule, en)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// TestChitchatRuleUnreachableByClassifier 钉死一个结构性事实(AC4 同源):
|
||||
// 闲聊桶的 pattern 全部 <10 字,而「过短(<10字)」规则先短路 ⇒ 任何闲聊内容
|
||||
// 都先被拒为 too_short,chitchat 桶经 HardRulesPassWithReason **恒不可达**。
|
||||
// 这与 lane=drop 同构:规则存在但当前调用链到不了。保留桶(防御未来路径),
|
||||
// 但必须在文档里写明它当前不会由分类器产生。
|
||||
func TestChitchatRuleUnreachableByClassifier(t *testing.T) {
|
||||
bl := captureGateDelta()
|
||||
pass, reason := HardRulesPassWithReason("你好")
|
||||
if pass || reason != "too_short" {
|
||||
t.Fatalf("'你好' 期望被拒为 too_short(先于 chitchat 短路),实际 pass=%v reason=%q", pass, reason)
|
||||
}
|
||||
if got := bl.deltaRule("chitchat"); got != 0 {
|
||||
t.Fatalf("chitchat 桶不应+1(不可达),got %d", got)
|
||||
}
|
||||
if got := bl.deltaRule("too_short"); got != 1 {
|
||||
t.Fatalf("too_short 桶应+1,got %d", got)
|
||||
}
|
||||
}
|
||||
|
||||
// TestRejectCounterEveryBucket 从**计数器层**验证全部分桶(含不可达的 chitchat)
|
||||
// 的计数能力 + 并发安全:直调 RecordHardReject 对 7 个桶各 +1,读回并断言总数。
|
||||
// 这证明「即使某规则当前不可达,读到 rejected_by_rule_chitchat 也有真实语义」。
|
||||
func TestRejectCounterEveryBucket(t *testing.T) {
|
||||
bl := captureGateDelta()
|
||||
for _, b := range rejectBuckets {
|
||||
RecordHardReject(b, "probe-"+b)
|
||||
}
|
||||
_, _, byRule := GateStats()
|
||||
for _, b := range rejectBuckets {
|
||||
if byRule[b]-bl.byRule[b] != 1 {
|
||||
t.Fatalf("桶 %s delta=%d,期望 1", b, byRule[b]-bl.byRule[b])
|
||||
}
|
||||
}
|
||||
total := RejectedByRuleTotal()
|
||||
var sum uint64
|
||||
_, _, m := GateStats()
|
||||
for _, v := range m {
|
||||
sum += v
|
||||
}
|
||||
if total != sum {
|
||||
t.Fatalf("rejected 总数 %d ≠ 各桶之和 %d(读口自洽要成立)", total, sum)
|
||||
}
|
||||
}
|
||||
|
||||
// TestHardRulesRejectLogLine 拒绝至少打一行 [GATE][REJECT] rule=… 日志(AC1 验收)。
|
||||
// 本仓日志走 log 包 → 测试环境不可见,故改为回归日志格式串本身:
|
||||
// 断言通过 record 的组成满足「含 GATE/REJECT/rule=」,而不是靠抓测试日志。
|
||||
func TestHardRulesRejectReasonFormatMatchesLogContract(t *testing.T) {
|
||||
_, reason := HardRulesPassWithReason("[System note: you are a scheduled job]")
|
||||
expect := fmt.Sprintf("[GATE][REJECT] rule=%s content=", "sys_template")
|
||||
// 真实日志由 RecordHardReject 打印;这里验证分桶名确实在 reject 日志的规则白名单里
|
||||
ok := false
|
||||
for _, b := range rejectBuckets {
|
||||
if b == reason {
|
||||
ok = true
|
||||
break
|
||||
}
|
||||
}
|
||||
if !ok {
|
||||
t.Fatalf("reason=%q 不在 rejectBuckets 白名单,日志消费方无法对齐分桶。'\n %s'", reason, expect)
|
||||
}
|
||||
}
|
||||
|
||||
// TestGatePassEnteredQueue 通过闸门 → entered 分母 +1(入队计数)。
|
||||
func TestGatePassEnteredQueue(t *testing.T) {
|
||||
bl := captureGateDelta()
|
||||
pass, _ := HardRulesPassWithReason("牧尘决定明天把织忆记分牌跑一遍并归档结果。")
|
||||
if !pass {
|
||||
t.Fatal("正常长内容应通过硬规则")
|
||||
}
|
||||
// Enqueue 的 append 只算 entered(模拟:调用与 Enqueue 一致登记)
|
||||
RecordEnteredQueue()
|
||||
if en := bl.deltaEntered(); en != 1 {
|
||||
t.Fatalf("entered delta=%d,期望 1", en)
|
||||
}
|
||||
if rj := bl.deltaRule("empty"); rj != 0 {
|
||||
t.Fatalf("通过项不应计入任何拒绝分桶,got empty delta=%d", rj)
|
||||
}
|
||||
}
|
||||
|
||||
// TestGateCounterConcurrent 并发安全:N 个 goroutine 各拒 1 条,分桶/总数不丢。
|
||||
func TestGateCounterConcurrent(t *testing.T) {
|
||||
bl := captureGateDelta()
|
||||
const n = 200
|
||||
var wg sync.WaitGroup
|
||||
for i := 0; i < n; i++ {
|
||||
wg.Add(1)
|
||||
go func() {
|
||||
defer wg.Done()
|
||||
HardRulesPassWithReason("哦") // too_short
|
||||
}()
|
||||
}
|
||||
wg.Wait()
|
||||
if got := bl.deltaRule("too_short"); got != n {
|
||||
t.Fatalf("并发 after %d 次 too_short delta=%d,期望 %d(丢失计数)", n, got, n)
|
||||
}
|
||||
if bl.deltaAttempts() != n {
|
||||
t.Fatalf("并发 attempts delta=%d,期望 %d", bl.deltaAttempts(), n)
|
||||
}
|
||||
}
|
||||
|
||||
// genLong 生成 n 个字符的普通长文本(用于超长分桶)。
|
||||
// 必须内容多样(不同中文字 + 标点断句)以保住信息密度 ≥0.3,
|
||||
// 否则会先被「密度(<0.3)」拦截,到不了 too_long 桶。
|
||||
func genLong(n int) string {
|
||||
src := []rune("记织忆系统今日排查审计指标运行状态良好,数据写入读取均正常,召回延迟处于低位。")
|
||||
b := make([]rune, 0, n)
|
||||
for len(b) < n {
|
||||
b = append(b, src...)
|
||||
}
|
||||
return string(b[:n])
|
||||
}
|
||||
@@ -1,18 +1,40 @@
|
||||
// 织忆 MemoryWeave — 硬规则过滤
|
||||
// 蒸馏前筛选:跳过闲聊、纯知识问答、低密度内容
|
||||
//
|
||||
// t_a513b870:HardRulesPass 增加带原因的变体 HardRulesPassWithReason,并统一在此
|
||||
// 登记拒绝计数(RecordHardReject)——使「闸门拦掉多少」可观测,不再是黑洞。
|
||||
|
||||
package distill
|
||||
|
||||
import (
|
||||
"strings"
|
||||
"unicode/utf8"
|
||||
|
||||
"github.com/xiaoxue/memoryweave/internal/textfilter"
|
||||
)
|
||||
|
||||
// HardRulesPass 硬规则过滤 → true = 通过,可进入蒸馏队列
|
||||
// HardRulesPass 硬规则过滤 → true = 通过,可进入蒸馏队列。
|
||||
// 薄封装:委托 HardRulesPassWithReason,并登记计数。禁止新增逻辑在此(保持语义单点)。
|
||||
func HardRulesPass(content string) bool {
|
||||
pass, _ := HardRulesPassWithReason(content)
|
||||
return pass
|
||||
}
|
||||
|
||||
// HardRulesPassWithReason 硬规则过滤,返回 (是否通过, 拒绝原因分桶)。
|
||||
// 拒绝时登记计数 + 打 [GATE][REJECT] 日志(AC1)。规则顺序即判定优先级:
|
||||
// 空 → 系统样板 → 过短(含人侧短事实豁免)→ 闲聊 → 知识问答 → 密度 → 超长。
|
||||
func HardRulesPassWithReason(content string) (bool, string) {
|
||||
// 规则1: 无用户消息(纯系统消息) → 跳过
|
||||
if strings.TrimSpace(content) == "" {
|
||||
return false
|
||||
reject("empty", content)
|
||||
return false, "empty"
|
||||
}
|
||||
|
||||
// 规则1.5: 系统样板(t_a513b870 把原属 ClassifyAdmission 的 drop 提前到硬规则层,
|
||||
// 使 AC4(a)「drop 只在硬规则层发生」成立,并让「系统样板」成为可见拒绝分桶)
|
||||
if textfilter.IsSystemTemplate(content) {
|
||||
reject("sys_template", content)
|
||||
return false, "sys_template"
|
||||
}
|
||||
|
||||
// 规则2: 太短的消息 (< 10字符) → 跳过
|
||||
@@ -20,9 +42,11 @@ func HardRulesPass(content string) bool {
|
||||
// 不因字数被丢弃——否则"牧尘不在招商局工作"(9 字) 这类关键事实永远到不了 memories。
|
||||
if utf8.RuneCountInString(content) < 10 {
|
||||
if isSoulfulShortFact(content) {
|
||||
return true
|
||||
pass("too_short", content) // 豁免但记录一次 pass
|
||||
return true, ""
|
||||
}
|
||||
return false
|
||||
reject("too_short", content)
|
||||
return false, "too_short"
|
||||
}
|
||||
|
||||
// 规则3: 纯闲聊/问候 → 跳过
|
||||
@@ -33,7 +57,8 @@ func HardRulesPass(content string) bool {
|
||||
lower := strings.ToLower(strings.TrimSpace(content))
|
||||
for _, pattern := range chitchatPatterns {
|
||||
if strings.EqualFold(lower, pattern) || lower == pattern {
|
||||
return false
|
||||
reject("chitchat", content)
|
||||
return false, "chitchat"
|
||||
}
|
||||
}
|
||||
|
||||
@@ -41,22 +66,38 @@ func HardRulesPass(content string) bool {
|
||||
qaPrefixes := []string{"什么是", "怎么定义", "解释一下", "介绍一下"}
|
||||
for _, prefix := range qaPrefixes {
|
||||
if strings.HasPrefix(content, prefix) {
|
||||
return false
|
||||
reject("qa", content)
|
||||
return false, "qa"
|
||||
}
|
||||
}
|
||||
|
||||
// 规则5: 内容密度检查 (信息密度 < 0.3 → 跳过)
|
||||
density := contentDensity(content)
|
||||
if density < 0.3 {
|
||||
return false
|
||||
reject("low_density", content)
|
||||
return false, "low_density"
|
||||
}
|
||||
|
||||
// 规则6: 长度适中(太长可能是粘贴/日志,跳过蒸馏,交给 episode 保留)
|
||||
if utf8.RuneCountInString(content) > 5000 {
|
||||
return false
|
||||
reject("too_long", content)
|
||||
return false, "too_long"
|
||||
}
|
||||
|
||||
return true
|
||||
RecordGatePass()
|
||||
return true, ""
|
||||
}
|
||||
|
||||
// reject 拒绝分支的统一登记点(计数 + 日志)。
|
||||
func reject(rule string, content string) {
|
||||
RecordHardReject(rule, content)
|
||||
}
|
||||
|
||||
// pass 通过分支的计数登记(进入队列前由 Enqueue append 时再 RecordEnteredQueue)。
|
||||
func pass(rule string, content string) {
|
||||
// rule 仅用于豁免场景的调试定位(如 too_short 豁免),计数器不需分桶记录 pass,
|
||||
// 只记总评估次数。此处保留参数签名以明确「这条走了豁免通过」。
|
||||
RecordGatePass()
|
||||
}
|
||||
|
||||
// contentDensity 内容信息密度 = 有意义字符 / 总字符
|
||||
@@ -109,4 +150,4 @@ func ShouldDeepConsolidate(distilledSinceLast int, hoursSinceLast float64) bool
|
||||
// 条件: 队列 >= 10 或 距上次 > 5 分钟
|
||||
func ShouldBatchDistill(queueLen int, secondsSinceLast float64) bool {
|
||||
return queueLen >= 10 || secondsSinceLast > 300
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user