Compare commits

...
Author SHA1 Message Date
xiaoyi db0845306d fix(metrics): 计数器/率指标语义分清 + t8 阈值改由 Condition 承载(t_da03e910)
- 审计误读订正:deprecated_per_day 是计数器(无分母),不给 _samples/_valid 是对的
- 新增 deprecated_total:区分「今天 0 条」与「从未统计过」(0 的二义性)
- executor t8:原 Condition:0.1 从不生效(判据硬编码 >5)→ Condition:5.0 + 读 t.Condition,行为不变
- 单测钉住:RecordDeprecation 双计数、t8 阈值真的可配、计数器不带率键
- docs/metrics-semantics.md:counter/rate/mean 三种读法 + 0 的二义性铁律
2026-10-26 14:42:19 +08:00
xiaoyi e9760dddeb feat(selfcheck): pattern 段可见化 —— 零产出可被机器读到(写入端 0 生产者事故)
- 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 天日志才发现「实现了≠出过数」
2026-10-26 14:05:58 +08:00
xiaoyi 7c12107967 feat(selfcheck): /api/v1/selfcheck 统一取数端点 + tools/selfcheck_full.py 全量快照(牧尘批「三档」) 2026-10-26 13:23:03 +08:00
小唯 9123bdcbb5 fix(graph): SQLiteGraphStore.ExpandFromResults 恒 0 产出 — from/to 是节点ID却拿裸名比对(t_724f31ad)
816/819 行把 Navigate 返回的节点 ID(n_织忆)与裸实体名 entity 做 == ⇒ 恒不相等 ⇒ 路径全被 continue ⇒ 结构性 0 条附加。
修:比对改用 nodeID(normalizeEntityID(entity));附加结果补 Category=graph_expanded + ID=邻居节点ID(非空,修复 recall.go ID 去重与审计计数);Content 用可读显示名(displayNodeName)。
补单测:正向(n_织忆→n_图谱 链+1条recall ⇒ 补入 graph_expanded 且 ID 非空) + 反向(图外实体 ⇒ 0 补入不凭空加)。
2026-10-26 13:18:39 +08:00
小怡 0bfe182054 fix(peer): 画像推理器支持 peer 专用 LLM 端点,避免被全局 LLM_ENDPOINT 拖去鉴权腿
起因 t_a5ef04a5:zhiyid 的 LLM_ENDPOINT 由 90-llm.conf 定为 newapi 3000 + agnes-2.5-flash
(供蒸馏/skillgen/consolidate 共用),而 NewLocal2BReasoner 按设计不发 Authorization
⇒ peer refresh 必然 401、peers 表恒 0 行、peer 召回零产出。

不采用卡面建议的「把全局 LLM_ENDPOINT 改成 8081」——那会把蒸馏同时降级成 2B。
改法:新增 ZHIYI_PEER_LLM_ENDPOINT / ZHIYI_PEER_LLM_MODEL 优先读取,未设时行为与改动前逐位一致。
回滚:删 91-peer-llm.conf 即恢复旧行为。
2026-10-26 10:56:48 +08:00
小怡 7aa562c7c9 fix(recall): agent_id 派生作用域候选过少时补一次全库搜索(ZHIYI_NS_FALLBACK_MIN,默认20,0=关)
问题:请求带 agent_id ⇒ resolveRecallNamespace 派生 <agent>-main,实测该 ns 只有
default-main 6 / xiaoyi-main 6 / prof-cloud-main 7 条,不传 agent_id 则 200 条
⇒ 带 agent_id 的调用静默劣化到个位数,不报错(09-23 只修了调用方,没修被调用方)。

改法:新增 RecallWithMetaOpts(..., allowNSFallback);仅 agent_id 派生作用域传 true,
显式 namespace 调用方传 false(防跨域泄漏)。候选 < 阈值时补一次全库搜索并合并 + 打日志。
回滚:ZHIYI_NS_FALLBACK_MIN=0。单测 4 条锁死:兜底生效/显式ns不兜底/env关/候选充足不兜底。
2026-10-26 10:47:29 +08:00
小怡 c84d968b02 feat(recall): 新增 ZHIYI_FUSE_MODE=proof(第二槽改用证据条数质量)
对应 t_9acaa74d §5 A' 的 nouse 臂:融合第二槽 = QualityFromProof(确定性 x/(x+K)),
彻底不含 importance=recency×(1+ln(seen))/V —— 老卡实测 usage 特征单独是负资产
(imp-only 0.0579 / seen-only 0.0335 NDCG@5)。
默认关 ⇒ 逐位等价现状;开启需配合 FUSION_W<1,否则第二槽权重 0。
单测锁两条:默认必须 false;证据分只依赖证据条数(同一证据数下改 seen/时间不得变)。
2026-10-26 08:42:40 +08:00
小怡 f4417c2f4d fix(eval): 金标路径优先级 显式path > env > 内嵌(保留相对路径内嵌兜底)
旧顺序 env 优先 ⇒ ZHIYI_GOLDEN_SET 一设,请求里的 golden_path 全被静默忽略:
实测 7 个 chunk(304 条) 每块都报 53 条(env 那套),指标全 0 时极难察觉。
现:绝对路径读不到=报错(不许静默换题);相对路径读不到仍回落内嵌(AC5 既有行为)。
2026-10-26 01:53:50 +08:00
小怡 03cac702a8 fix(eval): 金标路径优先级改为 显式path > env > 内嵌
旧顺序 env 优先 ⇒ ZHIYI_GOLDEN_SET 一设,请求里传 golden_path 全部被静默忽略:
实测 7 个 chunk(304条) 每块都报 53 条(env 那套),且指标全 0 时极难察觉。
env 现在只作默认金标;显式路径读不到改为明确报错,不再静默回落内嵌。
2026-10-26 01:52:11 +08:00
小怡 0499c82965 feat(eval): RunGolden 支持 all_namespaces(跨 ns 评测)
旧逻辑 ns 为空强制 shared ⇒ 评的是「只看 shared 的召回」,与线上跨 ns 不是同一系统
(实测前 15 条金标里 15 条 top 结果不同)。新增 all_namespaces=true ⇒ ns=""(等同线上默认);
不传 = 旧行为,向后兼容。
2026-10-26 00:28:38 +08:00
小怡 d117102088 fix(recall): t_standing_recall 改严格相等匹配(上线即抓到换主语误命中)
留出集实测:「织忆的服务跑在哪个端口」被判为「出图的服务跑在哪个端口」的匹配
(Dice 0.82,仅主语两字之差),把 ComfyUI 8188 置顶成织忆端口——模板句换主语必错。
改为归一化后完全相等才返回;近似 ≥0.78 只打 near-miss 日志用于补变体;加回归测试。
2026-10-25 23:57:23 +08:00
小怡 1aaab764ba feat(recall): t_standing_recall 常设答案精确通道(默认关)
实测基线(53 条真实提问):correct@1 20.8% / useful@5 88.7%;6 条跑偏案例里
5 条目标文档不在向量 top-50 —— 语义通道对端口/数字/标识符类提问够不着,补精确通道。

- storage/standing_match.go:归一化+bigram Dice 匹配(阈值 0.78,宁漏勿错)、30s 快照、置顶注入
- storage/recall.go:RecallWithMeta 拆为 wrapper + inner,开关 ZHIYI_STANDING_ANSWER=1 才生效
- 关闭时与旧行为逐位一致(可一行回滚)
- 单测:归一化/相似度/阈值/置顶 4 组全 PASS
2026-10-25 23:53:26 +08:00
小唯 2ac7c9d5a1 feat(write-ops): t_writeops_llm_judge — 写时判定器改 LLM 三分类 + apply 硬保护
问题(离线回放实测,非推测):
- 规则基 defaultJudge 以 ZHIYI_WRITE_SIM_UPDATE=0.70 判 UPDATE,17179 条影子日志里
  14435 条(84%)被判「新事实应覆盖旧事实」
- 人工抽检 15 条低相似度样本,15/15 不是真覆盖(「用户查看知乎链接」vs「用户查看微信文章」
  都被判成覆盖);低档 LLM 判定精度同样不足(0.70-0.85 档 REPLACE 精度约 25%)
- 结论:相似度只反映「话题相关」,不反映「是否同一属性的新旧值」

改动:
- 新增 llm_judge.go:REPLACE/DUPLICATE/KEEP 三分类,仅 sim>=ZHIYI_WRITE_JUDGE_SIM(0.95)
  才问模型,低档短路 ADD;调用失败兜底 ADD(宁可不覆盖)
- JudgeWriteOp:judge 显式注入 > apply/llm 模式用 LLMJudge > 规则基
- writeOpsApply 硬保护:apply 强制要求 ZHIYI_WRITE_JUDGE=llm,否则降级 shadow 并留痕
  (防止规则基 84% UPDATE 在 apply 下误覆盖上万条)
- 单测 8 条 + 真实 LLM e2e 3 条(ZHIYI_LIVE_JUDGE=1 才跑)

验收:go test ./internal/distill/ 全绿;live e2e 真覆盖→UPDATE / 假覆盖→ADD / 重复→NOOP 3/3
部署:shadow 模式(不改库),观察 2-3 天后 op 分布应从 84% UPDATE 降到 5-15% 再考虑 apply
2026-10-25 23:06:42 +08:00
小唯 66d5049151 feat(feedback): t_11245d30 区分人机信号 — MarkUseful 支持 source=auto → 记 auto_feedback
人工点「有用」仍 user_feedback(行为不变);插件自动反馈(_auto_feedback_for_reply)
传 source=auto → 记 auto_feedback,让 zhiyi:vprop_decisions 可辨「牧尘认可 vs 机器自评」。

纯观测,零行为变化:不改 V 权重/语义闸阈值/_MAX_PER_TURN。待 Go toolchain 重建后生效。
2026-10-24 04:34:25 +08:00
小唯 f979bd6ffc feat(recall): 融合权重可配 ZHIYI_FUSION_W(默认0.7=零变化,1.0=纯向量)
t_5624c0ff → 牧尘 2026-10-21 批准「按推荐执行」。

依据(strict n=134,golden-v4):
- 现状 fuse 0.1125 vs 纯向量 0.1898 ⇒ 现状是负收益,比纯向量低 39%
- 去 usage 0.2019 但逐 query worst −100%(12/134 从答对变彻底答错)
- MoA expert-panel 4 槽:3 槽指向止血 + intern-s2 指出根因是召回不足(相关文档在 pool#10-14)
- A/C 绝对差 0.0121 在 n=134 上不显著 ⇒ 不为它背 9% 硬失败率

改动:三处硬编码 0.7/0.3 参数化为 fusionW(candidates.QualityScore / reranked.Score / base 展示分)。
回滚:ZHIYI_FUSION_W=0.7 或删除该 env(逐位回到改动前)。
2026-10-21 20:35:30 +08:00
小唯andClaude Opus 4.8 8ea82fbec3 fix(storage): t_cf680fad SoftDelete 冲突耗尽静默丢 — 修「重试成功=0」+ 残留根治
根因(实证):runMerges O(n²) 软删 + 并发遗忘碎片器 在同一张 memories 单表上
制造 MVCC 写风暴;旧 3 次/~350ms 无 jitter 预算下每次重放都撞已推进的新版本
(单次 op 3 次重放 version 598346→598347→598348→598350 逐版推进仍耗尽),
失败软删被 consolidation_pipe.go:252 的 `_ =` 静默丢弃 ⇒ 源记录 is_deleted 停
false,每次重启窗口留新残留(检索重复命中)。

修(3 件,均 Go 侧 zhiyid):
① durable pending-softdelete 队列(softdelete_pending.go):MVCC 冲突耗尽 ⇒
   把 (id, reason) 追加进 /var/lib/memoryweave/pending-softdelete.jsonl
   (单写者 append + 原子 tmp/rename + 同 id 去重);zhiyid 启动 + 每 30s 触发器
   tick 各 drain 一次(SET is_deleted=true 幂等、重读最新已提交版本),风暴退去
   后重放必落盘 —— 根治「每次重启窗口都留新残留」。
② retrySoftDeleteRPC 预算 3→5 + 退避加 0~50% jitter:破 50+ 并发软删锁步雷群
   (锁步本身是冲突持续的主因),多两次机会跨风暴窗口。
③ consolidation_pipe.go:252 `_ =` → 显式 log(观测、禁静默);队列负责最终落盘。

测试:storage 全绿(耗尽入队 / 非可重试不入队 / 同 id 去重 / 风暴退去 drain 落盘
清空 / 风暴未退 drain 保留队列)。6 文件:2 新 + 4 改。

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-10-21 09:45:06 +08:00
小唯 2862f68631 feat(gate): 补提 t_bd63b641 门控复核资产 — quarantine 过滤 + junk 实体拒写 + ListPatterns 三返回值
- ListPatterns 改三返回值 (pats, skipped, err):单行 NULL/空 id 跳过计数不致全盘失败;
  排除 quarantine 名空间;COALESCE 防 NULL Scan 错误
- SQLiteGraphStore 增 isQuarantinedNode + Navigate/NavigateBiDir 过滤 quarantine 节点
- graph_auto.go 蒸馏写库前拒 junk 实体 (IsJunkName)
- 新增 entity_guard.go (实体名拒写门禁) + shadow_diff_test.go (影-复量具)
- docs/ac-evidence/t_bd63b641-shadow-gate/ 验收证据
- .gitignore 增 /go/tmp/ /verify.go,删 17.9M 编译二进制临时产物

build+test 均通过:go build ./... exit0;pattern+routes 两包 ok
2026-10-20 07:10:29 +08:00
小唯 b8d77547de chore: mark 79019bf (A10 huc 读侧+e2e) approved 2026-10-19 21:29:04 +08:00
小唯 79019bfc40 A10(t_d618dc7c): 补 human_useful_count 读侧接线 + 真实 LanceDB e2e 闸门
读侧静默 no-op 修复(t_4c810e02 同类:写进库但读不回):
- lancedb_ipc.go 读路径 unmarshal 结构体缺 human_useful_count 字段,
  导致 /recall、/memories 读回恒 null(列真实写入但读侧解包丢弃,无报错)。
  补 4 处:SearchWithTruncation 结构体+输出映射、Scan 结构体+输出映射、
  GetSkillCandidates(mapInt)、新增 mapIntPtr 可空整数映射(NULL≠0)。
- ScanAll/embedded-model 路径经 models.MemoryRecord 已带字段,无需改。

新增 human_useful_count_e2e_test.go(真实 sidecar 写→读回闸门,
仿 bitemporal_e2e 模式,未设 ZHIYI_HUC_E2E_SOCK 自动 skip):
- AC#4 读非空:存量行读回 NULL(nil);
- AC#5 同步+反例:人工 useful×2⇒huc=2/useful=2;机器 dedup 路径不污染 huc;
  人工 not-useful 只动 human_not_useful。

验证:go build 通过 + 全 storage 套件绿;真实 sidecar e2e 全绿
(AC4 读回 nil / AC5 huc=2 useful=2 / 反例隔离成立)。

git show --stat 212624a4341fac
2026-10-19 21:28:33 +08:00
小唯 a5bc27c3a4 feat(distill): 蒸馏落库前拒写空壳(t_e11207f8 治源①)— 共享判据 zhiyi_payload_guard_rules.json + Go payload_guard + OnDistillComplete 拦截 + /api/v1/payload-guard/stats + 3 单测;顺带修复 deploy-approved 清单坏行
- distill/payload_guard.go: 读共享 JSON(与 Python 同源),ShellCheck 带心跳/拦截计数
- api/server.go: OnDistillComplete fact 循环红act 后 ShellCheck 拒写空壳 + 启动加载 + stats 端点
- main_test.go: TestMain 加载共享规则供单测
- 修复 scripts/deploy-approved-commits.txt 尾行坏数据('appending:' 前缀 → 两条合法 SHA)
2026-10-19 21:16:57 +08:00
小唯 83c41963cf deploy: mark a293f7b+3533e55 (A10 human_useful_count) approved for deploy [t_d618dc7c] 2026-10-19 20:45:08 +08:00
小唯 3533e55801 feat(api): A10 recall/search 出口直通 human_useful_count(t_d618dc7c AC#4 读侧)
- models.RecallResult 加 HumanUsefulCount *int(nil=NULL=从未被人工点过,non-omitempty)
- storage/recall.go 主路径(800) + FTS词面通道(891) 两条 RecallResult 构造处接线 c.HumanUsefulCount
- api/routes/core.go supplement(shared 0.5 / notes 0.45) + keyword 通道三处接线 m/c.HumanUsefulCount
- 合成路径(graph_* / peer / pattern / graph fallback)无 MemoryRecord 来源,保持 nil(正确)
- 仅补『响应值==库值』显示缺口,不进排序公式(AC#6 排序零变化)
- 修复 t_4c810e02『加列不接 IPC=静默 no-op』同款坑:列现在真能读出
2026-10-19 20:06:12 +08:00
小唯 a293f7b784 feat(storage): A10 拆出人工有用 human_useful_count 单独列(t_d618dc7c)
- Rust lance schema 追加 human_useful_count (Int64, nullable);open() 自动加列
  迁移,存量回填 NULL(与 confidence/human_not_useful_count 迁移模式一致)
- MemoryRecord 读侧接线(get_by_id/search/scan_all/scan_deleted/record_from_batch)
  走 col_i64_opt(NULL 读回 None,区别于 0)
- insert_batch 写入侧:未声明/NULL → 写 NULL;显式整数 → 写值(与 confidence 同款)
- update() $inc 基数改 col_i64_opt(NULL 行按 0 起算,首次人工 useful NULL→1)
- Go IncrementUseful 同一次 Update 三 $inc:useful_count + recall_verified_count
  + human_useful_count(只有人工 feedback 路径调用,机器自评路径不写此列)
- Go MemoryRecord/memEntry 加 *int 字段(nil=NULL)
- 新增 human_useful_count_test.go:人工 useful 同时 +1、机器路径不动反例
- 排序公式/权重零改动(AC#6 排序零变化)
2026-10-19 19:42:29 +08:00
小唯 754976db52 deploy: mark c954aa2 (AC3/AC7 PosMode) approved for deploy [t_22b4e9d0] 2026-10-19 12:58:26 +08:00
小唯 c954aa2917 fix(storage): t_23b6a940 热度≠质量 — FeedbackScore pos 拆出 recall_verified_count(env ZHIYI_POS_MODE 四态, 默认 legacy 逐位一致)+ AC7 热门度运行时看门狗 + 5 Go 测试
金标 119 条离线 A/B(固定候选集 cands-119.json, 确定性 σ=0):
- baseline(pos含verified) MRR 0.7265
- champion(pos只信useful + importance w=0.15 + B=0.2) MRR 0.7699 (Δ+0.0434)
- 与 t_5d28ad74 已部署公式收敛(pos 去掉 recall_verified)
分层: chunk1 +0.0729 / chunk2 +0.0562 / chunk3 持平(无新增伤害)
门关(ZHIYI_FEEDBACK_BIAS=0)逐位等价; 回滚=置0零代码变更
AC4: 不读 deprecated not_useful_count ✓
5 Go 测试全 PASS: 门关delta=0 / 门开方向(none/weight/tiebreak) / 反向对照 / AC1 tiebreak同档
2026-10-19 03:33:01 +08:00
59 changed files with 4737 additions and 103 deletions
+4
View File
@@ -45,3 +45,7 @@ cron_raw.txt
# 探针/临时构建产物(2026-10-14 t_3e98b65a 调查时发现 17MB 残留未清)
/go/*-probe
/go/rulefirst-probe
# 临时构建/验证工件(t_5f822020 清理:quantify/test_one 二进制 + verify.go 探针)
/go/tmp/
/verify.go
@@ -0,0 +1,147 @@
# 【织忆·门控复核】PATTERN/PEER 影子 diff 量化 — 对照表与原始证据
卡: t_bd63b641 · 执行人: prof-dev · 2026-10-17 21:0x CST
方法: 不碰生产 env/二进制/服务(AC 硬边界)。开态用「独立离线评测」——
真实 PatternProvider/PeerAPI + 生产 graph.db(只读) + 实时 bge embedder(:8000),
等价于活服务开态注入路径;关态取活服务(:7821, PID 812251)实测。
────────────────────────────────────────────────────────────
## 结论
关态 vs 开态 diff = **空(当前态)**,且开态即使修 bug 也**无净收益/伤主路径**。
两个通道本卡判定 **「不开闸」**,如实回卡。理由:
- PEER: 无 peers 表(0 行),开态物理零注入,无产出。
- PATTERN: 当前 NULL-id bug 使 `ListPatterns` 恒报错 → 零注入;**即使修好 bug**,
85 行全是「图聚类摘要节点」(无 data/tools 内容,只有聚类键名),对金标余弦
0.675–0.715(≥0.6 阈值)会注入 ≤3 条**无召回价值的聚类键噪声/金标**,外加每
query ~85 次 embed(冷 ~1.4s)拉高 P95 + 稀释 top-5 ⇒ 伤主路径、无净收益。
- 原始阻塞理由(上游未落地)小怡已复核失效(t_3e98b65a/t_fcadee04 done),
但「上游 done ≠ 该开」—— 实测证明开了也净负收益(比图谱路「接线已证、收益未证」
更明确: PATTERN 有 NULL-id 读库 bug + 数据源本身不是行为 pattern)。
────────────────────────────────────────────────────────────
## 一、门控现状(关态坐实,双源独立)
- systemd unit 权威配置: `systemctl --user cat zhiyid | grep ZHIYI_` → 无
ZHIYI_PATTERN_RECALL / 无 ZHIYI_PEER_RECALL
- 运行进程 env: `/proc/812251/environ` → 无此二键(与 prof-cloud 异源复核一致)
- 结论: 两通道 env 均「未设/≠1」⇒ server.go 启动期 `if os.Getenv(...)=="1"` 不成立
⇒ `storage.PatternRecallProvider` / `storage.PeerRecallProvider` 均未注册 ⇒ 关态
## 二、影子 diff(关态 vs 开态,逐条对照)
固定 query 集: 14 金标(golden-set.json)+ 69 条真实 content-recall(usage_recall 表)
### PATTERN 通道(ZHIYI_PATTERN_RECALL)
开态注入结果: 当前 **0 条 / 14 金标**(`shadow-on-pattern-inject.json` = 空 `{}`)
根因(不是「没命中」而是「读不出来」):
- 生产 graph_nodes(type='pattern') 共 85 行,**id 列 85/85 全为 NULL**
(`sqlite3: sum(id IS NULL)=85`)
- `PatternProvider.Match` → `GraphPatternStore.ListPatterns` 读 `SELECT id,...`
为 string,遇 NULL 恒报 `sql: Scan error: converting NULL to string`
(影子测试实测抓到原文: `PATTERN_LISTERROR="sql: Scan error on column index 0,
name \"id\": converting NULL to string is unsupported"`,`PATTERNS_LOADED=0`)
- ⇒ `Match` 直接 return nil ⇒ **当前开态无任何 pattern 注入**
深层(修 bug 后会怎样 —— 已量化,证明「修了也不该开」):
- 这 85 行 properties **0 行有 `data` 键、0 行有 `tools` 键**(只有 20 行有
`description`),全是「图聚类摘要节点」(如 `hermes-main/entity 共 3867 节点…`),
**不是 L2 行为 pattern**。`Match` 里 `p.Data` 恒空 → 回退 `p.Name`(聚类键,
如 `topic:memory` / `pattern:default-main:entity`)。
- 余弦探针(绕过 NULL-id 直接 embed 85 个 pattern 名 + 金标,bge-m3:8000 实测):
5 条金标 maxcos = 0.6752 / 0.6891 / 0.6975 / 0.7038 / 0.7148,**全 ≥ 0.6 阈值
⇒ 若修好 NULL-id,开态会对每条金标注入 ≤3 条聚类键条目**(`offset-cosine-probe.txt`)。
- 注入内容 = 裸聚类键名(`topic:memory`、`pattern:learner-main:concept`),
**对「织忆是什么」这类 query 无召回价值,只会稀释 top-5**。
- 额外成本: 每 query 需 embed 85 个 pattern 名(冷调用 ~85×16.5ms≈1.4s,
探针 430 embed/7.12s 实测)⇒ **P95 主路径显著上升**(OFF p95=3177ms → 开态
叠加 ~1.4s)。
- 判读: 0.6 阈值对 bge-m3 余弦分布偏低(无关文本基线 0.67+),开态注入的多是
**假阳性噪声**。
- ⇒ 修 bug 后开态 = 「伤主路径 + 无净收益」,仍 **不开**。
### PEER 通道(ZHIYI_PEER_RECALL)
开态注入结果: **0 条 / 14 金标**
根因: 生产 graph.db **无 peers 表**(`SELECT count(*) FROM sqlite_master WHERE
name='peers'` = 0)。`PeerAPI.GetRecallResults` → `Store.List(200)` → 0 行 →
return nil(peer.go:305-308 源码)。⇒ **开态也无任何 peer 注入**。
### 对照表
| 维度 | 关态(活服务) | 开态(影子/离线) | diff |
|---|---|---|---|
| PATTERN 注入条数 | 0(未注册) | 当前 0(NULL-id bug);修 bug 后 ≤3 聚类键/金标 | **0(当前)/ 噪声(修后)** |
| PEER 注入条数 | 0(未注册) | 0(无 peers 表) | **0** |
| 召回结果 top5 id | 见 off-recall-14golden-live.json | 当前与关态逐条相同(无注入项可加) | **空(当前)** |
| /eval/golden keyword_pass | 14/14 | =关态(当前注入 0 不动);修后注入聚类键不改关键词判据 | **0(当前)** |
| /eval/golden recall@5 | 0.643 | =关态 | **0(当前)** |
| 开态额外成本 | — | 修 bug 后每 query ~85 embed(冷 ~1.4s)+ top-5 稀释 | 伤主路径 |
| 新增条目位置 | — | 追加在结果尾部(recall.go:901-932 append 到 deduped 之后) | — |
## 三、延迟 P50/P95(阈值从实测读,非拍脑袋)
关态(活服务 :7821):
- 69 真实 query(本卡 AC 要求的「≥50 query」集): **p50=1383.7ms, p95=3177.2ms**
(`off-69-queries-lat-ms.json`,一致单次 run 采集)
- 14 金标: 空载热态 p50=949.9/p95=2288.5ms;我在并发 69-query 压测后重跑
p50=3936.9/p95=5255.5ms(`off-recall-14golden-live.json` = 并发态)——
**绝对值随负载/缓存/8081 LLM 队列代理波动**(非本卡判据,不追服务性能)。
开态:
- **当前态(NULL-id bug 在)**: 注入 0 条,代码块 `if patternRecallEnabled() &&
Provider!=nil` 即便走进去也只 `for _, pr := range nil` ⇒ **开态延迟 = 关态延迟
(逐条相同,无新增 embed)**。
- **修 bug 后态**: 每 query 额外 embed 85 个 pattern 名(探针实测 430 embed/7.12s
≈16.5ms/embed,冷调用 ~1.4s),追加在结果尾部 ⇒ **P95 主路径上叠加 ~1.4s 冷成本
(冷 ≈ 关态 p95 翻倍量级)** ⇒ 伤主路径(超 AC 判据「P95 涨幅>20%」)。
判读: 延迟上「开 vs 关」的**决策相关量 = 修 bug 后每次召回 +~1.4s 冷成本**;
当前态(bug 在)开=关=0 差异。绝对基线随负载波动,不作为开闸判据。
## 四、AC#2: 开门是否需重启才注册 Provider?
**答案: 是,必须重启。**
- 源码证据: `go/internal/api/server.go:189-202` ——
`if os.Getenv("ZHIYI_PATTERN_RECALL")=="1" { storage.PatternRecallProvider =
patternProvider.Match }` / `if os.Getenv("ZHIYI_PEER_RECALL")=="1"
{ storage.PeerRecallProvider = peerAPI.GetRecallResults }`,均在 `NewServer()`
启动期执行;`storage.PatternRecallProvider` 是包级变量,仅在这两处赋值。
改运行中 env(不重启)无法注册 Provider。
- 实测证据: PID 812251 运行二进制 mtime=2026-10-17 01:18,其 /proc environ 无
此二键,当前 Provider 未注册(关态)。要开态只能: 在 systemd unit 加
`Environment=ZHIYI_*_RECALL=1` + `daemon-reload` + `restart zhiyid`。
- 开闸成本 = 一次重启(低)。但本卡结论「不开」基于净收益为负(见二),
重启成本本身不是拦路项——拦路的是「开了也伤主路径 + 无净收益」。
## 五、判据(按卡 AC)
- 当前态 diff 为空(PATTERN NULL-id bug → 0 注入;PEER 无表 → 0 注入)
⇒ 「开态无产出」判据满足 ⇒ **不开闸**。
- 修 bug 后态: 注入聚类键噪声 + P95 主路径涨幅 >20% ⇒ 「有产出但伤主路径」判据
也满足 ⇒ **仍不开**。两条判据各自独立支撑「不开」。
- 主路径未退化(关态 /eval/golden kw 14/14、recall@5=0.643;开态当前态=关态)。
────────────────────────────────────────────────────────────
## 原始 JSON(改前/改后,禁只贴结论)
- 关态活服务 14 金标逐条: `off-recall-14golden-live.json`
- 关态活服务 /eval/golden 汇总: `off-eval-golden-raw.json`
- 关态 69 真实 query 延迟: `off-69-queries-lat-ms.json`
- 开态影子 pattern 注入(当前态 = 空 `{}`): `shadow-on-pattern-inject.json`
- 开态影子 peer 表存在性: 0(`SHADOW_PEER_TABLE_EXISTS=0`,见 shadow_diff_test.go)
- 修 bug 后余弦探针(85 聚类键 vs 金标 maxcos): `offset-cosine-probe.txt`
+ 复现 `TestShadowPattern_CosineIfIDFixed`(`PATTERN_ROWS_LOADABLE_BYPASS_ID=85`)
复跑命令:
# 关态金标召回(活服务)
cd <ws> && python3 eval_off.py
# 关态 69 真实 query 延迟
cd <ws> && python3 latency_off.py # 注: stdout 混进度行,JSON 在尾部
# 开态影子注入 + peer 表 + 修 bug 后余弦探针(只读 graph.db + :8000 embedder,不改生产)
cd /home/muc/src/memoryweave/go && go test ./internal/pattern/ \
-run 'TestShadowPattern_Diff|TestShadowPeer_NoTable|TestShadowPattern_CosineIfIDFixed' \
-v -count=1
## 给审计脚本的「已明确决策」标记(消音用)
本卡对 PATTERN/PEER 门控的终态 = **已明确决策: 暂不开闸(证据: 开态零产出,见上)**。
若审计脚本下次再报「门控到期/上游 done 但门关」,应据此识别为「已决策不开」而非
「没人复核」。建议: 门控台账加 `decision` 字段(values: open/no-open/unknown),
本卡结论落 `no-open` + 证据指针,脚本对 no-open 态静默。
────────────────────────────────────────────────────────────
## 未决(需人拍板,本卡不越界执行)
1. PATTERN NULL-id 读库 bug: `GraphPatternStore.ListPatterns` 扫 NULL id 报错。
85 存量 pattern 行全是聚类摘要节点且 id=NULL——**这套数据本身可能就不该作为
L2 行为 pattern 召回源**。属「修数据还是修代码」的决策,交 hub/ops,不在本卡。
2. 开闸动作: 小怡终审 + 牧尘放行(本卡只出证据,AC 明令不开门)。
@@ -0,0 +1 @@
[-1.0, -1.0, -1.0, -1.0, -1.0, -1.0, -1.0, -1.0, -1.0, -1.0, -1.0, -1.0, -1.0, -1.0, -1.0, -1.0, -1.0, -1.0, -1.0, -1.0, -1.0, -1.0, -1.0, -1.0, -1.0, -1.0, -1.0, -1.0, -1.0, -1.0, 825.0, 952.6, 1123.0, 1376.9, 1383.7, 1544.4, 1583.8, 1592.2, 1635.1, 1680.3, 1685.1, 1691.0, 1726.0, 1754.9, 1794.7, 1851.8, 1874.3, 1878.2, 1901.0, 1909.9, 1924.8, 1937.8, 1954.0, 2037.1, 2053.7, 2058.2, 2154.6, 2174.1, 2287.7, 2355.2, 2718.2, 2789.6, 2791.9, 2832.9, 3109.5, 3222.3, 3507.6, 3534.9, 3906.4]
@@ -0,0 +1 @@
{"id":"20261017-205654","model":"golden-set","recall_at_5":0.6428571428571429,"precision_at_5":0.12857142857142856,"mean_reciprocal_rank":0.47619047619047616,"ndcg":0.5238095238095238,"query_details":[{"query":"织忆是什么","expected_ids":["mem_1791666702950691634"],"must_include_keywords":["织忆"],"hits":null,"misses":["mem_1791666702950691634"],"recall_at_5":0,"precision_at_5":0,"keyword_ok":true},{"query":"织忆的图谱扩展机制是什么","expected_ids":["mem_1791899478673190284"],"must_include_keywords":["图谱"],"hits":["mem_1791899478673190284"],"misses":null,"recall_at_5":1,"precision_at_5":0.2,"keyword_ok":true},{"query":"织忆如何通过 E1 提取和 MMR 实现多样去重","expected_ids":["mem_1791666890486125605"],"must_include_keywords":["MMR"],"hits":null,"misses":["mem_1791666890486125605"],"recall_at_5":0,"precision_at_5":0,"keyword_ok":true},{"query":"牧尘的偏好是什么","expected_ids":["mem_1790448247125520424"],"must_include_keywords":["牧尘"],"hits":["mem_1790448247125520424"],"misses":null,"recall_at_5":1,"precision_at_5":0.2,"keyword_ok":true},{"query":"牧尘喜欢什么样的工作方式","expected_ids":["mem_1790448247125520424"],"must_include_keywords":["牧尘"],"hits":["mem_1790448247125520424"],"misses":null,"recall_at_5":1,"precision_at_5":0.2,"keyword_ok":true},{"query":"如何根据牧尘的偏好调整记忆检索策略","expected_ids":["mem_1791747597032219499"],"must_include_keywords":["记忆"],"hits":["mem_1791747597032219499"],"misses":null,"recall_at_5":1,"precision_at_5":0.2,"keyword_ok":true},{"query":"当前项目的技术栈是什么","expected_ids":["mem_1790455676397796671"],"must_include_keywords":["技术栈"],"hits":["mem_1790455676397796671"],"misses":null,"recall_at_5":1,"precision_at_5":0.2,"keyword_ok":true},{"query":"织忆项目有哪些核心组件","expected_ids":["mem_1791906354849281414"],"must_include_keywords":["织忆"],"hits":null,"misses":["mem_1791906354849281414"],"recall_at_5":0,"precision_at_5":0,"keyword_ok":true},{"query":"织忆和其他记忆系统相比有什么架构优势","expected_ids":["mem_1791666702950691634"],"must_include_keywords":["织忆"],"hits":["mem_1791666702950691634"],"misses":null,"recall_at_5":1,"precision_at_5":0.2,"keyword_ok":true},{"query":"如何使用 recall 接口","expected_ids":["mem_1791796178328736793"],"must_include_keywords":["recall"],"hits":null,"misses":["mem_1791796178328736793"],"recall_at_5":0,"precision_at_5":0,"keyword_ok":true},{"query":"织忆有哪些管理工具","expected_ids":["mem_1791666702950691634"],"must_include_keywords":["织忆"],"hits":null,"misses":["mem_1791666702950691634"],"recall_at_5":0,"precision_at_5":0,"keyword_ok":true},{"query":"如何通过 API 扩展织忆功能","expected_ids":["mem_1791666188168772049"],"must_include_keywords":["织忆"],"hits":["mem_1791666188168772049"],"misses":null,"recall_at_5":1,"precision_at_5":0.2,"keyword_ok":true},{"query":"本地 llama 服务 8080 端口","expected_ids":["mem_1791423503359721152"],"must_include_keywords":["8080"],"hits":["mem_1791423503359721152"],"misses":null,"recall_at_5":1,"precision_at_5":0.2,"keyword_ok":true},{"query":"session-to-zhiyi.py 脚本名","expected_ids":["mem_1791688470278719760"],"must_include_keywords":["session-to-zhiyi"],"hits":["mem_1791688470278719760"],"misses":null,"recall_at_5":1,"precision_at_5":0.2,"keyword_ok":true}],"queries":14,"ran_at":"2026-10-17T20:56:54.195909811+08:00","keyword_pass":14,"keyword_fail":0,"keyword_total":14}
@@ -0,0 +1,319 @@
{
"state": "OFF",
"results": [
{
"i": 0,
"q": "织忆是什么",
"count": 5,
"top5_ids": [
"mem_1791899478673190284",
"mem_1792154287491185572",
"mem_1791912043093092663",
"mem_1792154287177190000",
"mem_1792154288142808071"
],
"top5_cats": [
"distilled",
"distilled",
"distilled",
"distilled",
"distilled"
],
"kw_ok": true,
"lat_ms": 3936.9
},
{
"i": 1,
"q": "织忆的图谱扩展机制是什么",
"count": 5,
"top5_ids": [
"mem_1791899478673190284",
"mem_1791725847707296273",
"mem_1792154287491185572",
"mem_1791770032575826407",
"mem_1792088552819764989"
],
"top5_cats": [
"distilled",
"distilled",
"distilled",
"distilled",
"distilled"
],
"kw_ok": true,
"lat_ms": 4225.2
},
{
"i": 2,
"q": "织忆如何通过 E1 提取和 MMR 实现多样去重",
"count": 5,
"top5_ids": [
"mem_1792088552818081545",
"mem_1791666890486125605",
"mem_1791520496931190142",
"mem_1791422985447662675",
"mem_1791498226924653975"
],
"top5_cats": [
"distilled",
"distilled",
"distilled",
"distilled",
"distilled"
],
"kw_ok": true,
"lat_ms": 3643.6
},
{
"i": 3,
"q": "牧尘的偏好是什么",
"count": 5,
"top5_ids": [
"mem_1791556229473565240",
"mem_1791376118421773238",
"mem_1790448247125520424",
"mem_1792088552818232071",
"mem_1792086639900350664"
],
"top5_cats": [
"distilled",
"distilled",
"distilled",
"distilled",
"distilled"
],
"kw_ok": true,
"lat_ms": 3367.5
},
{
"i": 4,
"q": "牧尘喜欢什么样的工作方式",
"count": 5,
"top5_ids": [
"mem_1790448247125520424",
"mem_1792086639900350664",
"mem_1791482493617981202",
"mem_1789063252280657787",
"mem_1792086640133724836"
],
"top5_cats": [
"distilled",
"distilled",
"distilled",
"distilled",
"distilled"
],
"kw_ok": true,
"lat_ms": 3511.3
},
{
"i": 5,
"q": "如何根据牧尘的偏好调整记忆检索策略",
"count": 5,
"top5_ids": [
"mem_1792091916993248722",
"mem_1791747597032219499",
"mem_1792088552824810016",
"mem_1792153987878359340",
"mem_1790137162828579293"
],
"top5_cats": [
"distilled",
"distilled",
"distilled",
"distilled",
"distilled"
],
"kw_ok": true,
"lat_ms": 3544.6
},
{
"i": 6,
"q": "当前项目的技术栈是什么",
"count": 5,
"top5_ids": [
"mem_1792088552817810427",
"mem_1790455676397796671",
"mem_1791665641471849057",
"mem_1790317738849661043",
"mem_1790425023223201421"
],
"top5_cats": [
"distilled",
"distilled",
"distilled",
"distilled",
"distilled"
],
"kw_ok": true,
"lat_ms": 4874.5
},
{
"i": 7,
"q": "织忆项目有哪些核心组件",
"count": 5,
"top5_ids": [
"mem_1792154287491185572",
"mem_1792154287177190000",
"mem_1791770032575826407",
"mem_1792154288142808071",
"mem_1791666702950691634"
],
"top5_cats": [
"distilled",
"distilled",
"distilled",
"distilled",
"distilled"
],
"kw_ok": true,
"lat_ms": 3811.5
},
{
"i": 8,
"q": "织忆和其他记忆系统相比有什么架构优势",
"count": 5,
"top5_ids": [
"mem_1791899478077693848",
"mem_1791666702950691634",
"mem_1792088552819764989",
"mem_1791770032575826407",
"mem_1792154287491185572"
],
"top5_cats": [
"distilled",
"distilled",
"distilled",
"distilled",
"distilled"
],
"kw_ok": true,
"lat_ms": 3254.5
},
{
"i": 9,
"q": "如何使用 recall 接口",
"count": 5,
"top5_ids": [
"mem_1791482321288100863",
"mem_1792153988391999660",
"ep_1785686577666177306",
"ep_1786452727331645773",
"mem_1788717420755520289"
],
"top5_cats": [
"distilled",
"distilled",
"distilled",
"distilled",
"distilled"
],
"kw_ok": true,
"lat_ms": 4110.9
},
{
"i": 10,
"q": "织忆有哪些管理工具",
"count": 5,
"top5_ids": [
"mem_1792154287491185572",
"mem_1791666855166846631",
"mem_1792144557208382006",
"mem_1792116217448228684",
"mem_1792154288142808071"
],
"top5_cats": [
"distilled",
"distilled",
"distilled",
"distilled",
"distilled"
],
"kw_ok": true,
"lat_ms": 5963.1
},
{
"i": 11,
"q": "如何通过 API 扩展织忆功能",
"count": 5,
"top5_ids": [
"mem_1791666188168772049",
"mem_1791818814047111008",
"ep_1785695216419714474",
"ep_1785702789193047009",
"ep_1786336919812827426"
],
"top5_cats": [
"distilled",
"distilled",
"distilled",
"distilled",
"distilled"
],
"kw_ok": true,
"lat_ms": 4222.9
},
{
"i": 12,
"q": "本地 llama 服务 8080 端口",
"count": 5,
"top5_ids": [
"mem_1791423503359721152",
"mem_1791440673318711992",
"mem_1788594533802527918",
"mem_1788620335517621905",
"mem_1788700944516696452"
],
"top5_cats": [
"distilled",
"distilled",
"distilled",
"distilled",
"distilled"
],
"kw_ok": false,
"lat_ms": 3803.5
},
{
"i": 13,
"q": "session-to-zhiyi.py 脚本名",
"count": 5,
"top5_ids": [
"mem_1791688470278719760",
"mem_1789152643785440562",
"mem_1790154887033667954",
"mem_1790001291060572107",
"mem_1789896720973833628"
],
"top5_cats": [
"distilled",
"distilled",
"distilled",
"distilled",
"distilled"
],
"kw_ok": true,
"lat_ms": 4078.1
}
],
"kw_pass": 13,
"kw_total": 14,
"p50_ms": 3936.9,
"p95_ms": 5255.5,
"all_lat_ms": [
3254.5,
3367.5,
3511.3,
3544.6,
3643.6,
3803.5,
3811.5,
3936.9,
4078.1,
4110.9,
4222.9,
4225.2,
4874.5,
5963.1
]
}
@@ -0,0 +1,6 @@
shadow_diff_test.go:200: PATTERN_ROWS_LOADABLE_BYPASS_ID=85
shadow_diff_test.go:224: COSINE_PROBE "织忆是什么" maxcos=0.7038 hit=true (thr=0.6) best=topic:memory
shadow_diff_test.go:224: COSINE_PROBE "牧尘的偏好是什么" maxcos=0.6975 hit=true (thr=0.6) best=pattern:default-main:entity
shadow_diff_test.go:224: COSINE_PROBE "如何使用 recall 接口" maxcos=0.6891 hit=true (thr=0.6) best=topic:replying
shadow_diff_test.go:224: COSINE_PROBE "本地 llama 服务 8080 端口" maxcos=0.6752 hit=true (thr=0.6) best=pattern:test-llm:entity
shadow_diff_test.go:224: COSINE_PROBE "织忆项目有哪些核心组件" maxcos=0.7148 hit=true (thr=0.6) best=pattern:learner-main:concept
@@ -0,0 +1,229 @@
package pattern
import (
"database/sql"
"encoding/json"
"os"
"testing"
_ "modernc.org/sqlite"
"github.com/xiaoxue/memoryweave/internal/models"
"github.com/xiaoxue/memoryweave/internal/storage"
)
// ── t_bd63b641 影-复:PATTERN/PEER 开门量具(不碰生产;只读 graph.db + 实时 embedder)──
// 量化「开 ZHIYI_PATTERN_RECALL / ZHIYI_PEER_RECALL」对 14 金标会注入什么。
// Provider 装配在 server.go 启动期由 env 决定 ⇒ 不重启无法在活服务上测开态;
// 故本测试直接构造真实 Provider + 生产 graph.db(只读)+ 实时 bge embedder,
// 跑出「开态会注入的条目」,与关态(=主召回原样)对比。
//
// 本测试只读、不落盘、不改库(AC:不碰生产二进制/不重启)。
type logRecord struct {
ID string
Category string
Content string
}
// runShadowWithDiag 返回:注入结果 + 诊断(pattern 装载数 / query 是否编码成功 / 各 query 最高余弦)。
// ⚠️ 关键发现:生产 graph_nodes(type='pattern') 的 id 全为 NULL(85/85),ListPatterns 读 id 为 string
// ⇒ 恒报 sql: Scan error (converting NULL to string),Match 直接 return nil。
// 故 runShadow 不把 ListPatterns 错误当失败 —— 它本身就是「开态也无法注入」的根因证据。
func runShadowWithDiag() (map[string][]logRecord, int, string, map[string]float64) {
endpoint := os.Getenv("VLLM_ENDPOINT")
if endpoint == "" {
endpoint = "http://localhost:8000/v1/embeddings"
}
emb := storage.NewEmbedder(endpoint)
store := NewGraphPatternStore("/var/lib/memoryweave/graph.db")
pp := NewPatternProvider(store, NewEmbedderProvider(emb))
// 装载 pattern 数(防「store 空 → 注入恒 0」的假阴性);记录 ListPatterns 错误原文
pats, _, lerr := store.ListPatterns(1000)
loaded := 0
listErr := ""
if lerr != nil {
listErr = lerr.Error() // 根因:id 全 NULL → Scan error
} else {
loaded = len(pats)
}
golden := []string{
"织忆是什么", "织忆的图谱扩展机制是什么",
"织忆如何通过 E1 提取和 MMR 实现多样去重", "牧尘的偏好是什么",
"牧尘喜欢什么样的工作方式", "如何根据牧尘的偏好调整记忆检索策略",
"当前项目的技术栈是什么", "织忆项目有哪些核心组件",
"织忆和其他记忆系统相比有什么架构优势", "如何使用 recall 接口",
"织忆有哪些管理工具", "如何通过 API 扩展织忆功能",
"本地 llama 服务 8080 端口", "session-to-zhiyi.py 脚本名",
}
out := make(map[string][]logRecord)
maxCos := make(map[string]float64)
// 预编码 14 query(若编码失败会记 0,便于区分「没命中」vs「编码挂了」)
for _, q := range golden {
qv, eerr := emb.EncodeSingle(q)
if eerr != nil || len(qv) == 0 {
maxCos[q] = -1 // 编码失败标记
continue
}
// 逐个 pattern 算余弦,取最高(复现 Provider.Match 内部逻辑)
best := -1.0
for _, p := range pats {
rep := p.Data
if rep == "" {
rep = p.Name
}
text := rep
for _, tl := range p.Tools {
if tl != "" {
text += " " + tl
}
}
pv, perr := emb.EncodeSingle(text)
if perr != nil || len(pv) == 0 {
continue
}
s := cosineF32(qv, pv)
if s > best {
best = s
}
}
maxCos[q] = best
}
// 真注入(走 Provider.Match,同 server 路径)
for _, g := range golden {
pat := pp.Match(g, "hermes-main", 3) // server.go:902 topK=3
for _, r := range pat {
out[g] = append(out[g], logRecord{ID: r.ID, Category: r.Category, Content: r.Content})
}
}
return out, loaded, listErr, maxCos
}
// TestShadowPattern_Diff —— 开态 pattern 注入量化(只读生产库)
func TestShadowPattern_Diff(t *testing.T) {
out, loaded, listErr, maxCos := runShadowWithDiag()
t.Logf("PATTERNS_LOADED=%d (防假阴性:store 有货才会注入)", loaded)
if listErr != "" {
t.Logf("PATTERN_LISTERROR=%q — 根因:pattern 行 id 全 NULL ⇒ Provider.Match 恒 return nil", listErr)
}
queries := []string{
"织忆是什么", "织忆的图谱扩展机制是什么",
"织忆如何通过 E1 提取和 MMR 实现多样去重", "牧尘的偏好是什么",
"牧尘喜欢什么样的工作方式", "如何根据牧尘的偏好调整记忆检索策略",
"当前项目的技术栈是什么", "织忆项目有哪些核心组件",
"织忆和其他记忆系统相比有什么架构优势", "如何使用 recall 接口",
"织忆有哪些管理工具", "如何通过 API 扩展织忆功能",
"本地 llama 服务 8080 端口", "session-to-zhiyi.py 脚本名",
}
totalInjected := 0
for _, q := range queries {
mc := maxCos[q]
if mc < 0 {
t.Logf("[EMB-FAIL] %q → 编码失败(不计命中)", q)
}
if n := len(out[q]); n > 0 {
totalInjected += n
t.Logf("[INJECT] %q → %d pattern (maxcos=%.3f)", q, n, mc)
for _, r := range out[q] {
t.Logf(" id=%s cat=%s content=%s", r.ID, r.Category, trunc(r.Content, 60))
}
} else {
t.Logf("[NO-INJECT] %q → 0 pattern (maxcos=%.3f, 阈值=0.6)", q, mc)
}
}
b, _ := json.MarshalIndent(out, "", " ")
t.Logf("SHADOW_PATTERN_TOTAL_INJECTED=%d", totalInjected)
os.WriteFile("/tmp/shadow-pattern-inject.json", b, 0644)
t.Logf("raw json → /tmp/shadow-pattern-inject.json (%d bytes)", len(b))
}
func trunc(s string, n int) string {
if len(s) <= n {
return s
}
return s[:n] + "…"
}
// ── peer 侧:生产 graph.db 无 peers 表 ⇒ 开态无数据可注入 ──
func TestShadowPeer_NoTable(t *testing.T) {
db, err := peerOpenReadOnly("/var/lib/memoryweave/graph.db")
if err != nil {
t.Fatalf("open graph.db: %v", err)
}
defer db.Close()
var cnt int
err = db.QueryRow("SELECT count(*) FROM sqlite_master WHERE type='table' AND name='peers'").Scan(&cnt)
if err != nil {
t.Fatalf("query peers table existence: %v", err)
}
t.Logf("SHADOW_PEER_TABLE_EXISTS=%d (0 ⇒ 开态 peer 无数据可注入)", cnt)
}
// peerOpenReadOnly 只读开 sqlite(WAL 兼容),避免 peer.Store 的写路径。
func peerOpenReadOnly(path string) (*sql.DB, error) {
return sql.Open("sqlite", "file:"+path+"?mode=ro&_pragma=busy_timeout(5000)")
}
// ── 深度根因:即使修好 NULL-id,85 行 pattern 无 data/tools 键(只有 description),
// Match 只能 embed 命名键(如 "pattern:hermes-main:entity")⇒ 对金标余弦 < 0.6 阈值。
// 本测试量化「修好 NULL-id 后开态到底能注入几类金标」—— 证明开态收益仍≈0。
func TestShadowPattern_CosineIfIDFixed(t *testing.T) {
endpoint := os.Getenv("VLLM_ENDPOINT")
if endpoint == "" {
endpoint = "http://localhost:8000/v1/embeddings"
}
emb := storage.NewEmbedder(endpoint)
// 绕过 NULL-id 的 ListPatterns:只读 name + properties(非 NULL 列)
db, err := peerOpenReadOnly("/var/lib/memoryweave/graph.db")
if err != nil {
t.Fatalf("open: %v", err)
}
defer db.Close()
rows, _ := db.Query(`SELECT name, properties FROM graph_nodes WHERE type='pattern'`)
type patText struct{ name, text string }
var pats []patText
for rows.Next() {
var name, props string
if serr := rows.Scan(&name, &props); serr != nil {
continue
}
// 复现 Match 的 text 构造:rep=data(无→空) 回退 name;无 tools
text := name
pats = append(pats, patText{name, text})
}
rows.Close()
t.Logf("PATTERN_ROWS_LOADABLE_BYPASS_ID=%d", len(pats))
if len(pats) == 0 {
t.Skip("无 pattern 行可载(NULL-id 未修前本就 0 注入,已在 TestShadowPattern_Diff 覆盖)")
}
golden := []string{"织忆是什么", "牧尘的偏好是什么", "如何使用 recall 接口",
"本地 llama 服务 8080 端口", "织忆项目有哪些核心组件"}
for _, q := range golden {
qv, qerr := emb.EncodeSingle(q)
if qerr != nil || len(qv) == 0 {
t.Logf("[EMBFAIL] %q → %v", q, qerr)
continue
}
best, bestName := -1.0, ""
for _, p := range pats {
pv, perr := emb.EncodeSingle(p.text)
if perr != nil || len(pv) == 0 {
continue
}
s := cosineF32(qv, pv)
if s > best {
best, bestName = s, p.name
}
}
hit := best >= 0.6
t.Logf("COSINE_PROBE %q maxcos=%.4f hit=%v (thr=0.6) best=%s", q, best, hit, bestName)
}
}
// 防 unused 误报
var _ = models.RecallResult{}
+30
View File
@@ -0,0 +1,30 @@
# 织忆指标语义:counter / rate / mean(`/api/v1/metrics`)
> 2026-10-26 建立。起因:有效性审计把 `deprecated_per_day`(计数器)当成率指标,
> 报出「0 样本却判 valid=None ⇒ 缺最小样本门」。计数器没有分母,「样本门」对它无定义
> —— 属**探针模型错配**,不是指标缺陷。本文件是给下游(审计脚本 / 看板 / 人)的唯一口径。
## 三类指标,三种读法
| 类型 | 命名特征 | 自带字段 | 怎么用 | 例子 |
|---|---|---|---|---|
| **counter 计数器** | `*_per_day` / `*_total` / `*_count` | **无** `_samples` / `_valid` | 直接读绝对值,跨时间比大小;不要算比率、不要报「样本不足」 | `deprecated_per_day`、`deprecated_total`、`distill_success_count` |
| **rate 比率** | `*_rate` | `_samples`(分母)+ `_valid`(1=可判 / 0=不可判 / -1=N/A) | `_valid != 1` 时**不得**当结论;`_samples` 小于门槛时只报「待积累」 | `auto_resolve_rate`、`recall_usefulness_rate` |
| **mean 均值** | `avg_*` | `_samples` + `_valid` | 同上:无分母就不下判断 | `avg_distill_loss` |
**铁律**:`0` 永远有两种含义 —— 「今天确实没有」和「根本没在统计」。
- 计数器必须配一个累计值来区分:`deprecated_per_day=0` + `deprecated_total=0` ⇒ 从未统计过;
`per_day=0` + `total=137` ⇒ 统计活着,只是今天没发生。
- 率指标必须配 `_valid`/`_samples`,分母退化时返回 `metricNA(-1)`,不给 1(给 1 会被读成满分)。
## 触发器阈值也用同一套语义
`internal/selfoptimize/executor.go` 的 `t8`(`TDecayCritical` → `archive_or_boost`):
- 判据读的是**计数器** `deprecated_per_day`(条/天),阈值由 `t8.Condition` 承载,**默认 5 条/天**。
- 2026-10-26 修正:原先 `Condition: 0.1` 但判据函数里硬编码 `> 5`,配置写了从不生效。
现改为 `Condition: 5.0` + 判据读 `t.Condition`(行为不变,但配置真的能被改)。
- 若要改成「率」语义,需要先有分母(当日活跃写入量),否则别动 —— 那会变成另一个探针错配。
## 已知遗留
- 审计脚本侧对计数器发「样本不足」告警的白名单修复,归 `t_44c07eca`(脚本侧统一处理,避免多处各改一遍)。
+6 -1
View File
@@ -249,7 +249,12 @@ func (cp *ConsolidationPipeline) mergeSimilar() (int, error) {
// 保留较新的
idI := strVal(mems[i]["id"])
idJ := strVal(mems[j]["id"])
_ = cp.ldb.SoftDelete(idJ, fmt.Sprintf("merged_into_%s", idI))
// t_cf680fad:不再 `_ =` 静默吞错。MVCC 冲突耗尽时 SoftDelete 内部会
// 把 (idJ, reason) 落 durable pending 队列(softdelete_pending.go),
// 启动/每 tick drain 重放必落盘;这里显式记日志做观测(禁静默)。
if err := cp.ldb.SoftDelete(idJ, fmt.Sprintf("merged_into_%s", idI)); err != nil {
log.Printf("[consolidation] merge-softdelete FAILED: src=%s → target=%s err=%v (pending-queue 将重放)", idJ, idI, err)
}
merged++
}
}
+18 -3
View File
@@ -545,6 +545,9 @@ func (a *API) Recall(w http.ResponseWriter, r *http.Request) {
req.Limit = 10
}
// 2026-09-21 五修(t_24eceed0 返修):无 ns 且无 agent_id → namespace="" → 全库跨 ns 召回
// 2026-10-26:区分「作用域来源」——只有 agent_id 派生的 ns 才允许兜底,
// 显式传 namespace 的调用方不兜底(避免跨域泄漏)。
nsDerivedFromAgent := req.Namespace == "" && req.AgentID != ""
req.Namespace = resolveRecallNamespace(req.Namespace, req.AgentID, req.Query)
// H4: Default diversity — balance relevance & diversity
@@ -582,7 +585,7 @@ func (a *API) Recall(w http.ResponseWriter, r *http.Request) {
// t_1c12e000:keyword 路径同样收进 RecallWithMeta(Pipeline.Recall 内部
// 走同一缓存键),只为把 cache_hit 带回响应——旧版用 Recall 丢掉了 meta。
var kwMeta storage.RecallMeta
kwResults, kwMeta, kwErr := a.Pipeline.RecallWithMeta(req.Query, req.Namespace, req.Limit, req.Diversity)
kwResults, kwMeta, kwErr := a.Pipeline.RecallWithMetaOpts(req.Query, req.Namespace, req.Limit, req.Diversity, nsDerivedFromAgent)
if kwErr != nil {
// 主路径硬错误(向量编码/rerank 依赖不可用):即便兜底能补结果,也按 502 上报,
// 调用方据此走失败路径而不是把依赖故障误判成"无匹配"
@@ -629,14 +632,14 @@ func (a *API) Recall(w http.ResponseWriter, r *http.Request) {
// Pure semantic — BM25 off (H1 skipped, Pipeline Recall has BM25 built in — handled by switch)
// t_949840b1:RecallWithMeta 额外返回候选池真实大小(ANN 粗检索池,非最终产出数)
var meta storage.RecallMeta
results, meta, err = a.Pipeline.RecallWithMeta(req.Query, req.Namespace, req.Limit, req.Diversity)
results, meta, err = a.Pipeline.RecallWithMetaOpts(req.Query, req.Namespace, req.Limit, req.Diversity, nsDerivedFromAgent)
annScanned = meta.CandidatesScanned
cacheHit = meta.CacheHit // t_1c12e000
truncated = meta.Truncated // t_3aa2a8c1
case "hybrid":
// BM25 + vector combined (H1: BM25 scoring inside Pipeline.Recall)
var meta storage.RecallMeta
results, meta, err = a.Pipeline.RecallWithMeta(req.Query, req.Namespace, req.Limit, req.Diversity)
results, meta, err = a.Pipeline.RecallWithMetaOpts(req.Query, req.Namespace, req.Limit, req.Diversity, nsDerivedFromAgent)
annScanned = meta.CandidatesScanned
cacheHit = meta.CacheHit // t_1c12e000
truncated = meta.Truncated // t_3aa2a8c1
@@ -699,6 +702,7 @@ func (a *API) Recall(w http.ResponseWriter, r *http.Request) {
Score: 0.5, // shared 结果降权,使用默认分
QualityScore: m.QualityScore,
VValue: vv,
HumanUsefulCount: m.HumanUsefulCount, // A10 (t_d618dc7c)
})
}
}
@@ -742,6 +746,7 @@ func (a *API) Recall(w http.ResponseWriter, r *http.Request) {
Score: 0.45, // 笔记知识降权:不挤掉主记忆,但能被看到
QualityScore: m.QualityScore,
VValue: vv,
HumanUsefulCount: m.HumanUsefulCount, // A10 (t_d618dc7c)
})
}
}
@@ -1001,6 +1006,7 @@ func (a *API) RecallDebug(w http.ResponseWriter, r *http.Request) {
results = append(results, models.RecallResult{
ID: c.ID, Content: c.Content, Category: c.Category,
Score: score, Timestamp: c.CreatedAt.Format(time.RFC3339),
HumanUsefulCount: c.HumanUsefulCount, // A10 (t_d618dc7c)
})
}
}
@@ -1459,3 +1465,12 @@ func (a *API) EdgeFeedback(w http.ResponseWriter, r *http.Request) {
_ = a.GraphStore.UpdateEdgeTrustScores()
respond(w, 200, map[string]string{"status": "ok"})
}
// GET /api/v1/popwatch — t_23b6a940 AC7:热门度看门狗快照(report-only 观测)。
// 服务端记录「最终 rank1 的 recall_verified_count 连续越 p95 阈值」计数
// (storage.PopWatch,观测点在 recallUncached 主路径漏斗末尾);本端点只读快照,
// 不改排序、不写库。传感器端脚本(zhiyi-popwatch.py)读它转既有告警通道;
// ZHIYI_POPWATCH=0 时 enabled=false(观测关闭)。
func (a *API) PopWatch(w http.ResponseWriter, r *http.Request) {
respond(w, 200, storage.PopWatchSnapshot())
}
+27 -12
View File
@@ -7,6 +7,7 @@ import (
"fmt"
"net/http"
"os"
"path/filepath"
"strings"
"sync"
"time"
@@ -55,22 +56,29 @@ type GoldenSet struct {
func LoadGoldenSet(path string) (*GoldenSet, error) {
var data []byte
usedSource := "env:ZHIYI_GOLDEN_SET"
if p := os.Getenv("ZHIYI_GOLDEN_SET"); p != "" {
// 2026-10-26 修正优先级:显式 path > env > 内嵌。
// 旧顺序(env 先)导致 ZHIYI_GOLDEN_SET 一旦设置,任何请求传 golden_path 都被静默忽略
// ⇒ 实测「传 7 个 chunk 却每块都报 53 条」(env 指向的 53 条集)—— 评测对象与预期不符,
// 且指标全是 0 时极难发现。env 现在只作「默认金标」,显式 path 必须能覆盖它。
if path != "" {
usedSource = "path:" + path
d, err := os.ReadFile(path)
if err == nil {
data = d
} else if filepath.IsAbs(path) {
// 绝对路径 = 明确指名要跑这套题 ⇒ 读不到必须报错,不许静默换题
return nil, fmt.Errorf("读 golden_path 失败(%s): %w", path, err)
} else {
// 相对路径在部署 CWD 下读不到 ⇒ 内嵌兜底(t_dfc93ad0 AC5 既有行为,保留)
data = embeddedGoldenSetJSON
usedSource = "embedded"
}
} else if p := os.Getenv("ZHIYI_GOLDEN_SET"); p != "" {
var err error
data, err = os.ReadFile(p)
if err != nil {
return nil, err
}
} else if path != "" {
usedSource = "path:" + path
d, err := os.ReadFile(path)
if err != nil {
// 相对路径在部署 CWD 下读不到 ⇒ 内嵌兜底(AC5 根因)
data = embeddedGoldenSetJSON
usedSource = "embedded"
} else {
data = d
}
} else {
data = embeddedGoldenSetJSON
usedSource = "embedded"
@@ -384,13 +392,20 @@ func (ea *EvalAPI) RunGolden(w http.ResponseWriter, r *http.Request) {
var req struct {
Namespace string `json:"namespace"`
GoldenPath string `json:"golden_path"` // 可选,默认 testdata/golden-set.json
// AllNamespaces(2026-10-26)跨 namespace 评测开关。
// 背景:旧逻辑 ns 为空 ⇒ 强制 "shared",而真实金标分散在 hermes-main/wiki/HUB 等多个 ns
// ⇒ 评测跑的是"只看 shared"的召回,与线上跨 ns 召回不是同一个系统(实测前 15 条里 15 条结果不同)。
// 语义:true ⇒ ns = ""(全库跨 ns,等同线上默认);false ⇒ 保持旧行为(默认 shared,向后兼容)。
AllNamespaces bool `json:"all_namespaces"`
}
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
respondError(w, 400, "invalid body")
return
}
ns := req.Namespace
if ns == "" {
if req.AllNamespaces {
ns = ""
} else if ns == "" {
ns = "shared"
}
gs, err := LoadGoldenSet(req.GoldenPath)
+11 -2
View File
@@ -23,6 +23,11 @@ func NewFeedbackAPI(ldb storage.LanceDB) *FeedbackAPI {
func (fa *FeedbackAPI) MarkUseful(w http.ResponseWriter, r *http.Request) {
var req struct {
MemoryID string `json:"memory_id"`
// 2026-10-24 (t_11245d30):区分人机信号。
// 空 = 人工点「有用」(保持 user_feedback,行为不变);
// "auto" = 插件自动反馈(_auto_feedback_for_reply)→ 记 auto_feedback,让 V 账可辨「牧尘认可 vs 机器自评」。
// 纯观测,不改 V 权重/阈值/上限。
Source string `json:"source"`
}
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
respondError(w, 400, "invalid body")
@@ -34,11 +39,15 @@ func (fa *FeedbackAPI) MarkUseful(w http.ResponseWriter, r *http.Request) {
}
selfoptimize.Dash.RecordFeedback(true)
// V 值:useful = success
// V 值:useful = success。action 名按来源区分(人工 user_feedback / 自动 auto_feedback)。
action := "user_feedback"
if req.Source == "auto" {
action = "auto_feedback"
}
selfoptimize.VProp.RecordDecision(
"useful_"+req.MemoryID,
[]string{req.MemoryID},
"user_feedback", "success", "",
action, "success", "",
)
if err := fa.LanceDB.IncrementUseful(req.MemoryID); err != nil {
log.Printf("[feedback] IncrementUseful failed %s: %v", req.MemoryID, err)
+1 -1
View File
@@ -57,7 +57,7 @@ func (pa *PatternAPI) List(w http.ResponseWriter, r *http.Request) {
limit = n
}
}
pats, err := pa.Store.ListPatterns(limit)
pats, _, err := pa.Store.ListPatterns(limit)
if err != nil {
respondError(w, 500, "list patterns: "+err.Error())
return
+327
View File
@@ -0,0 +1,327 @@
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
}
+99
View File
@@ -0,0 +1,99 @@
package routes
import (
"encoding/json"
"os"
"path/filepath"
"testing"
"time"
)
// 快照契约测试:/api/v1/selfcheck?level=full 依赖 tools/selfcheck_full.py 的产出格式。
// 这里钉住 schema_version 与关键字段,防止 python 侧改字段名后 Go 侧静默返回空。
func TestLoadQualitySnapshot(t *testing.T) {
dir := t.TempDir()
p := filepath.Join(dir, "zhiyi-quality.json")
body := `{
"schema_version": 1,
"generated_at": "2026-10-26T13:20:00+0800",
"source": {"db": "/var/lib/memoryweave", "table": "memories", "mode": "read_only_projection"},
"duration_ms": 1680,
"quality": {
"frag_len": 20, "total_rows": 39957, "live_rows": 39836,
"frag_rows_all": 313, "frag_rate_all": 0.0078,
"frag_rows_live": 313, "frag_rate_live": 0.0079,
"dup_groups": 34, "dup_extra_rows": 103, "dup_rate": 0.0026,
"new_rows_7d": 1176, "new_frag_rows_7d": 35, "new_frag_rate_7d": 0.0298
},
"write_volume": {
"days": [{"date": "2026-10-25", "rows": 1473, "live": 1471}],
"today": 332, "today_date": "2026-10-26", "last_7d": 7706, "nonzero_days": 60
}
}`
if err := os.WriteFile(p, []byte(body), 0o644); err != nil {
t.Fatal(err)
}
t.Setenv("ZHIYI_QUALITY_SNAPSHOT", p)
snap, err := loadQualitySnapshot()
if err != nil {
t.Fatalf("loadQualitySnapshot: %v", err)
}
if snap.SchemaVersion != 1 {
t.Fatalf("schema_version=%d want 1", snap.SchemaVersion)
}
var q struct {
TotalRows int `json:"total_rows"`
LiveRows int `json:"live_rows"`
DupRate float64 `json:"dup_rate"`
FragRowsAll int `json:"frag_rows_all"`
}
if err := json.Unmarshal(snap.Quality, &q); err != nil {
t.Fatalf("quality 段解析失败: %v", err)
}
if q.TotalRows != 39957 || q.LiveRows != 39836 {
t.Fatalf("quality 口径不符: %+v", q)
}
if q.FragRowsAll != 313 || q.DupRate != 0.0026 {
t.Fatalf("quality 数值不符: %+v", q)
}
var wv struct {
Today int `json:"today"`
Days []struct {
Date string `json:"date"`
Live int `json:"live"`
} `json:"days"`
}
if err := json.Unmarshal(snap.WriteVolume, &wv); err != nil {
t.Fatalf("write_volume 段解析失败: %v", err)
}
if wv.Today != 332 || len(wv.Days) != 1 || wv.Days[0].Live != 1471 {
t.Fatalf("write_volume 不符: %+v", wv)
}
// 新鲜度:刚写的文件 age 应 < 10s;人为改旧 → stale 判定为真
if age := snap.AgeSeconds(); age < 0 || age > 10 {
t.Fatalf("AgeSeconds=%d,本应接近 0", age)
}
old := time.Now().Add(-8 * time.Hour)
if err := os.Chtimes(p, old, old); err != nil {
t.Fatal(err)
}
snap2, err := loadQualitySnapshot()
if err != nil {
t.Fatal(err)
}
if snap2.AgeSeconds() <= qualityStaleAfter {
t.Fatalf("8h 前的快照应判 stale(>%d 秒),得到 %d", qualityStaleAfter, snap2.AgeSeconds())
}
}
// 快照缺失 ⇒ 必须报错(由 handler 转成 degraded),不能静默返回零值。
func TestLoadQualitySnapshotMissing(t *testing.T) {
t.Setenv("ZHIYI_QUALITY_SNAPSHOT", filepath.Join(t.TempDir(), "nope.json"))
if _, err := loadQualitySnapshot(); err == nil {
t.Fatal("缺失快照应返回 error")
}
}
@@ -80,10 +80,14 @@ func (m *mockLance) IncrementUseful(id string) error { r
func (m *mockLance) IncrementNotUseful(id string) error { return nil }
// GA-P0-1 (t_718d8707):拆分字段
func (m *mockLance) IncrementHumanNotUseful(id string) error { return nil }
func (m *mockLance) AppendHitEvent(memoryID, outcome, reason string) error { return nil }
func (m *mockLance) CountHitEvents(memoryID, outcome string, since time.Time) (int, error) { return 0, nil }
func (m *mockLance) GetHitEvents(memoryID string, limit int) ([]models.HitEvent, error) { return nil, nil }
func (m *mockLance) IncrementHumanNotUseful(id string) error { return nil }
func (m *mockLance) AppendHitEvent(memoryID, outcome, reason string) error { return nil }
func (m *mockLance) CountHitEvents(memoryID, outcome string, since time.Time) (int, error) {
return 0, nil
}
func (m *mockLance) GetHitEvents(memoryID string, limit int) ([]models.HitEvent, error) {
return nil, nil
}
func (m *mockLance) IncrementDedupDownweight(id string) error { return nil }
func (m *mockLance) UpdateMemoryContent(id, newContent, source string) error { return nil }
func (m *mockLance) InsertMemory(rec models.MemoryRecord) error { return nil }
@@ -116,6 +120,7 @@ func (mockGraph) ListNodesByType(nodeType string, namespace string) []map[string
}
func (mockGraph) ListNodes(namespace string) []map[string]interface{} { return nil }
func (mockGraph) Stats() (int, int, float64) { return 0, 0, 0 }
func (mockGraph) CountNodesByType(string) (int, int, string) { return 0, 0, "" }
func (mockGraph) Prune(minWeight float64) {}
func (mockGraph) ExpandFromResults(results []models.RecallResult, namespace string, maxHops int) []models.RecallResult {
return results
+56 -1
View File
@@ -93,7 +93,13 @@ func NewServer() http.Handler {
// 冲突检测器(E4.1: Commit 时矛盾检测依赖此实例)
// 2026-09-20:改用带持久化的构造 —— 此前 active 是纯内存 map,zhiyid 重启即丢
// (实测 17:17 重启后 pending 冲突全部消失)。落盘失败不致命,降级为内存模式并记日志。
conflictDetector, cdErr := governance.NewPersistentConflictDetector("/var/lib/memoryweave/conflicts.json")
// 2026-10-18 (t_23b6a940):ZHIYI_CONFLICTS_DIR 覆盖落盘目录(副本/评估场景隔离
// telemetry 写);未设 → 生产默认路径(行为不变)
confDir := os.Getenv("ZHIYI_CONFLICTS_DIR")
if confDir == "" {
confDir = "/var/lib/memoryweave"
}
conflictDetector, cdErr := governance.NewPersistentConflictDetector(filepath.Join(confDir, "conflicts.json"), filepath.Join(confDir, "conflict-seen.json"))
if cdErr != nil {
log.Printf("[conflict] 持久化加载失败,降级为内存模式: %v", cdErr)
}
@@ -133,6 +139,17 @@ func NewServer() http.Handler {
}
}()
// t_cf680fad:启动即 drain durable pending-softdelete 队列。
// 上一轮(尤其重启窗口 / 崩掉那轮)因 MVCC 写风暴耗尽而被入队的失败软删,
// 此刻风暴已退、sidecar 刚就绪,重放必落盘 —— 这是「不修则每次重启窗口都留新残留」的根治。
go func() {
time.Sleep(2 * time.Second) // 等 sidecar 完全就绪(比 metrics 的 1s 稍晚,避免抢首提交)
if n := storage.PendingSoftDeleteCount(); n > 0 {
log.Printf("[pending-softdelete] 启动发现 %d 条待重放,开始 drain", n)
storage.DrainPendingSoftDeletes(ldb)
}
}()
// 图谱(带 Navigate 结果缓存:TTL 5min,容量 500,热点实体缓存命中加速)
// 已在上面初始化
graphUpdater := governance.NewAutoGraphUpdater(graphStore)
@@ -221,6 +238,14 @@ func NewServer() http.Handler {
}
distillEngine := distill.NewEngine(llmEndpoint, llmModel, llmAPIKey)
routes.DistillEngineRef = distillEngine
// t_e11207f8 治源①:加载共享「空壳正文」判据(zhiyi_payload_guard_rules.json,Python/Go 同源)。
// 失败 ⇒ fail-open(distill 照跑、不拦空壳、不崩),/api/v1/payload-guard/stats 暴露 loaded=false。
if ok, lerr := distill.LoadPayloadGuard(""); ok {
_, _, _, rp := distill.PayloadGuardStats()
log.Printf("[distill][payload-guard] 空壳判据已加载 rules=%s", rp)
} else {
log.Printf("[distill][payload-guard] ⚠️ 共享判据未加载(fail-open,不拦空壳): %v", lerr)
}
// 蒸馏完成 → 自动图谱更新 + 冲突检测 + 被动验证 + 回写内存
distill.OnDistillComplete = func(input distill.DistillInput, result distill.DistillResult) {
entityNames := make([]string, len(result.Entities))
@@ -262,6 +287,13 @@ func NewServer() http.Handler {
// 这里再脱一次为幂等保险——防止任何中间层注入明文密钥。事故里泄漏进
// 镜像的记忆正是从这条路径入库的)。
fact = redact.RedactSecrets(fact)
// t_e11207f8 治源①:空壳拒写(单一判据 = 共享 zhiyi_payload_guard_rules.json,与 Python 同源)。
// 蒸馏 LLM 偶发把「只有溯源指针/占位/纯日期、无知识载荷」的碎片当 fact(如 `证据:文件:…|日期:…`),
// 长度/实体启发式(IsQualityFact)抓不住 ⇒ 落库前用 payload-guard 拦下(未加载时 fail-open)。
if distill.ShellCheck(fact) {
log.Printf("[distill][payload-guard] 拒写空壳蒸馏 fact episode=%s fact=%.40s", input.EpisodeID, fact)
continue
}
// 查重: 同 namespace 已存在**语义等价**记忆 → 跳过
// 必须用 cosine 近重复判据(≥0.98),不能只比字符串相等——
// 否则 "牧尘在招商局工作" 与 "牧尘在招商局工作。"(多一个句号)
@@ -487,6 +519,18 @@ func NewServer() http.Handler {
mux.HandleFunc("/health", routes.HandleHealth)
mux.HandleFunc("/api/v1/health", routes.HandleHealth)
// t_e11207f8 治源①:空壳拦截器「确实跑过」的取证端点。
// checks=每个蒸馏 fact 判一次的心跳计数(>0 即拦截器活着);blocks=实际拒写空壳条数;
// loaded=false 表示共享判据没加载上(fail-open,需排查 ZHIYI_PAYLOAD_GUARD_RULES 路径)。
mux.HandleFunc("/api/v1/payload-guard/stats", func(w http.ResponseWriter, r *http.Request) {
checks, blocks, loaded, rp := distill.PayloadGuardStats()
respondJSON(w, 200, map[string]interface{}{
"checks": checks,
"blocks": blocks,
"loaded": loaded,
"rules_path": rp,
})
})
// 图谱缓存统计 + 搜索缓存统计(t_1c12e000:并入 search_cache 段,
// 暴露 hits/misses/invalidated/size/ttl,写频对命中率的影响可观测)
mux.HandleFunc("/api/v1/cache/stats", func(w http.ResponseWriter, r *http.Request) {
@@ -558,6 +602,8 @@ func NewServer() http.Handler {
})
mux.HandleFunc("/api/v1/recall", api.Recall)
mux.HandleFunc("/api/v1/recall/debug", api.RecallDebug)
// t_23b6a940 AC7 热门度看门狗快照(report-only,传感器端读它转既有告警通道)
mux.HandleFunc("/api/v1/popwatch", api.PopWatch)
// 2026-10-13 (t_e9a4d18f P2) 常设答案直读/写入
mux.HandleFunc("/api/v1/standing-answers", routes.HandleStandingAnswers)
// ⑤使用追踪(t_5aa4dcac):上报 + 手动触发。env 门控 ZHIYI_USAGE_TRACK,默认关。
@@ -567,6 +613,10 @@ func NewServer() http.Handler {
// 反馈统一走 /api/v1/feedback/{useful,not-useful,deprecate,correct}(feedback.go,写拆分后新字段)。
mux.HandleFunc("/api/v1/bootstrap", api.Bootstrap)
mux.HandleFunc("/api/v1/stats", api.Stats)
// 2026-10-26(牧尘批「三档」):自检统一取数端点。
// 唯一契约 —— 自检脚本一律读这里,禁止再 lancedb.connect() 直连生产库。
// ?level=cheap(默认,内存态计数)| full(+读 tools/selfcheck_full.py 的全量快照:碎片/冗余/近7天质量/写量)
mux.HandleFunc("/api/v1/selfcheck", api.Selfcheck)
mux.HandleFunc("/api/v1/batch-commit", api.BatchCommit)
// 主症A(t_fa6c9104):显式写入直落 memories 表(嵌入 + 立刻可召回)。
// 纯新增路由:commit/recall/蒸馏路径零改动;旧服务端 404 时插件自动回落 commit。
@@ -1792,6 +1842,11 @@ func NewServer() http.Handler {
ticker := time.NewTicker(30 * time.Second)
defer ticker.Stop()
for range ticker.C {
// t_cf680fad:每个 tick 先 drain durable pending-softdelete 队列(风暴退去后的
// 相对静默窗口重放,必落盘)。队列空 = 廉价 no-op,不打日志;仅在有待处理时出声。
if n := storage.PendingSoftDeleteCount(); n > 0 {
storage.DrainPendingSoftDeletes(ldb)
}
for _, t := range []struct{ id, action string }{
{"t_distill", "distill"},
{"t_merge", "merge"},
+181
View File
@@ -0,0 +1,181 @@
// 织忆 MemoryWeave —— 写时四操作的 LLM 判定器(t_writeops_llm_judge,2026-10-25)
//
// 背景(离线回放实测,不是推测):
// · 规则基 defaultJudge 用 ZHIYI_WRITE_SIM_UPDATE=0.70 判 UPDATE,影子日志 11 天 17179 条里
// 14435 条(84%)被判「新事实应覆盖旧事实」;人工抽检 15 条低相似度样本,15/15 不是真覆盖
// (「用户查看知乎链接」vs「用户查看微信文章」都判成覆盖)。
// · 80 条分层回放(各相似度档 20 条,LLM 三分类):REPLACE 率 0.95+ 档 25%、0.90-0.95 档 35%、
// 0.85-0.90 档 35%、0.70-0.85 档 20% —— 与相似度**不单调**,说明相似度只反映「话题相关」,
// 不反映「是否同一属性的新旧值」。低档 LLM 同样会被话题带偏(0.70-0.85 档 REPLACE 精度约 25%)。
//
// 结论与实现:
// · 只有 sim >= ZHIYI_WRITE_JUDGE_SIM(默认 0.95)才调 LLM 判三分类;低于该档直接 ADD(不调 LLM,
// 省调用 + 该档不可信)。
// · REPLACE→UPDATE / DUPLICATE→NOOP / KEEP→ADD;判不准与调用失败一律兜底 ADD(宁可不覆盖)。
// · 默认 judge 模式仍是 rule(零行为变化);apply 模式强制要求 llm(见 write_ops.go 硬保护)。
package distill
import (
"encoding/json"
"fmt"
"io"
"log"
"net/http"
"os"
"strconv"
"strings"
"time"
)
const llmJudgeSystemPrompt = `你是记忆库的写入判定器。给你两条记忆:A=库里已有的旧事实,B=刚提取出的新事实。
判断 B 与 A 的关系,只回一个词,不要解释:
REPLACE = 同一主体的同一属性,B 是 A 的更新值/修正值(B 生效后 A 就过时了)
DUPLICATE= B 与 A 语义等价,B 没有新增信息
KEEP = B 补充/细化/扩展 A,或讲不同侧面/不同对象/不同阶段;两条都要保留
判不准时回 KEEP。`
// llmJudgeSimThreshold 低于此相似度直接 ADD(实测该档 LLM 判定精度不足,且省调用)。
const llmJudgeSimThresholdDefault = 0.95
// llmJudgeCall 可注入的 LLM 调用(单测替换,生产走 HTTP)。返回模型输出的原始文本。
var llmJudgeCall = callLLMJudgeModel
// LLMJudgeMode 当前 judge 模式:rule(默认)| llm。
func LLMJudgeMode() string {
m := strings.ToLower(strings.TrimSpace(os.Getenv("ZHIYI_WRITE_JUDGE")))
if m == "llm" {
return "llm"
}
return "rule"
}
// llmJudgeSimThreshold 判定相似度门槛(env 可调)。
func llmJudgeSimThreshold() float64 {
if v := strings.TrimSpace(os.Getenv("ZHIYI_WRITE_JUDGE_SIM")); v != "" {
if f, err := strconv.ParseFloat(v, 64); err == nil && f > 0 && f <= 1 {
return f
}
}
return llmJudgeSimThresholdDefault
}
// LLMJudge 用 LLM 判「B 是否应取代 A」。
// 返回的 WriteVerdict 与 defaultJudge 同构,调用方无需区分。
func LLMJudge(candidate string, similar []SimilarMemory) WriteVerdict {
v := WriteVerdict{
Op: OpAdd,
Candidate: candidate,
Reason: "llm:无相似候选 → 新建",
Timestamp: time.Now().Format(time.RFC3339),
}
if len(similar) == 0 {
return v
}
top := similar[0] // 调用方已按相似度排序(TopN)
v.Similarity = top.Similarity
// 归一化完全等价 → NOOP,不调 LLM
if NormalizeContent(top.Content) == NormalizeContent(candidate) {
v.Op = OpNoop
v.TargetID = top.ID
v.Reason = "llm:归一化等价 → 丢弃"
return v
}
// 相似度不足 → ADD(实测低档 LLM 判定不可信,且省钱)
if top.Similarity < llmJudgeSimThreshold() {
v.Reason = fmt.Sprintf("llm:sim %.3f < %.2f → 不判,新建", top.Similarity, llmJudgeSimThreshold())
return v
}
raw, err := llmJudgeCall(candidate, top.Content)
if err != nil {
// 调用失败兜底 ADD:宁可不覆盖(漏覆盖可事后补,误覆盖会丢事实)
v.Reason = "llm:调用失败兜底新建"
log.Printf("[write-ops][llm-judge] 调用失败,兜底 ADD: %v candidate=%.40s", err, candidate)
return v
}
verdict := parseLLMJudgeVerdict(raw)
switch verdict {
case "REPLACE":
v.Op = OpUpdate
v.TargetID = top.ID
v.Reason = "llm:同一属性更新 → 旧条标 superseded_by"
case "DUPLICATE":
v.Op = OpNoop
v.TargetID = top.ID
v.Reason = "llm:语义等价 → 丢弃"
default: // KEEP / 无法解析
v.Reason = "llm:保留(补充/不同侧面)→ 新建"
}
return v
}
// parseLLMJudgeVerdict 从模型输出里取三分类词;取不到返回 KEEP。
func parseLLMJudgeVerdict(raw string) string {
u := strings.ToUpper(raw)
for _, k := range []string{"REPLACE", "DUPLICATE", "KEEP"} {
if strings.Contains(u, k) {
return k
}
}
return "KEEP"
}
// callLLMJudgeModel 调判定模型,返回 message.content。配置项与对抗审计同构。
func callLLMJudgeModel(candidate, existing string) (string, error) {
endpoint := envStr("ZHIYI_WRITE_JUDGE_ENDPOINT", "http://127.0.0.1:3000/v1/chat/completions")
model := envStr("ZHIYI_WRITE_JUDGE_MODEL", "agnes-2.5-flash")
key := envStr("ZHIYI_WRITE_JUDGE_KEY", "")
if key == "" {
key = os.Getenv("LLM_API_KEY")
}
timeout := time.Duration(envFloat("ZHIYI_WRITE_JUDGE_TIMEOUT", 30)) * time.Second
body := map[string]interface{}{
"model": model,
"messages": []map[string]string{
{"role": "system", "content": llmJudgeSystemPrompt},
{"role": "user", "content": fmt.Sprintf("A(旧): %s\n\nB(新): %s", existing, candidate)},
},
"temperature": 0,
"max_tokens": 100,
"reasoning_effort": "none", // 实测:不给 none 时 reasoning 会吃光 max_tokens,content 返空
}
jsonBody, err := json.Marshal(body)
if err != nil {
return "", err
}
req, err := http.NewRequest("POST", endpoint, strings.NewReader(string(jsonBody)))
if err != nil {
return "", err
}
req.Header.Set("Content-Type", "application/json")
if key != "" {
req.Header.Set("Authorization", "Bearer "+key)
}
client := &http.Client{Timeout: timeout}
resp, err := client.Do(req)
if err != nil {
return "", err
}
defer resp.Body.Close()
raw, _ := io.ReadAll(io.LimitReader(resp.Body, 1<<16))
if resp.StatusCode != http.StatusOK {
return "", fmt.Errorf("judge HTTP %d: %.120s", resp.StatusCode, string(raw))
}
var parsed struct {
Choices []struct {
Message struct {
Content string `json:"content"`
} `json:"message"`
} `json:"choices"`
}
if err := json.Unmarshal(raw, &parsed); err != nil {
return "", fmt.Errorf("judge 响应解析失败: %w", err)
}
if len(parsed.Choices) == 0 {
return "", fmt.Errorf("judge 响应无 choices")
}
return parsed.Choices[0].Message.Content, nil
}
+159
View File
@@ -0,0 +1,159 @@
package distill
import (
"errors"
"os"
"sync/atomic"
"testing"
)
// withFakeLLMJudge 注入假 LLM 调用,返回调用次数计数器。
func withFakeLLMJudge(t *testing.T, reply string, err error) *int32 {
t.Helper()
var calls int32
orig := llmJudgeCall
llmJudgeCall = func(candidate, existing string) (string, error) {
atomic.AddInt32(&calls, 1)
return reply, err
}
t.Cleanup(func() { llmJudgeCall = orig })
return &calls
}
func similarTop(id, content string, sim float64) []SimilarMemory {
return []SimilarMemory{{ID: id, Content: content, Similarity: sim}}
}
// 低相似度档(实测 LLM 判定不可信)必须短路,不调 LLM。
func TestLLMJudge_LowSimilaritySkipsLLM(t *testing.T) {
calls := withFakeLLMJudge(t, "REPLACE", nil)
v := LLMJudge("新事实", similarTop("mem_1", "旧事实", 0.80))
if v.Op != OpAdd {
t.Fatalf("sim 0.80 应判 ADD,得到 %s", v.Op)
}
if got := atomic.LoadInt32(calls); got != 0 {
t.Fatalf("sim 低于门槛时不应调用 LLM,实际调用 %d 次", got)
}
}
func TestLLMJudge_Replace(t *testing.T) {
withFakeLLMJudge(t, "REPLACE", nil)
v := LLMJudge("executions.db 台账 max_rowid 为 185769",
similarTop("mem_x", "executions.db 台账 max_rowid 为 183371", 0.97))
if v.Op != OpUpdate {
t.Fatalf("REPLACE 应判 UPDATE,得到 %s", v.Op)
}
if v.TargetID != "mem_x" {
t.Fatalf("UPDATE 必须带 TargetID,得到 %q", v.TargetID)
}
}
func TestLLMJudge_Duplicate(t *testing.T) {
withFakeLLMJudge(t, "DUPLICATE", nil)
v := LLMJudge("该软件支持PDF与Word互转", similarTop("mem_y", "工具支持PDF与Word互转", 0.96))
if v.Op != OpNoop {
t.Fatalf("DUPLICATE 应判 NOOP,得到 %s", v.Op)
}
}
// KEEP=补充/不同侧面 → 必须新建,不能覆盖。
func TestLLMJudge_Keep(t *testing.T) {
withFakeLLMJudge(t, "KEEP", nil)
v := LLMJudge("用户查看微信文章", similarTop("mem_z", "用户查看知乎链接", 0.97))
if v.Op != OpAdd {
t.Fatalf("KEEP 应判 ADD,得到 %s", v.Op)
}
if v.TargetID != "" {
t.Fatalf("ADD 不应带 TargetID,得到 %q", v.TargetID)
}
}
// LLM 调用失败必须兜底 ADD(宁可不覆盖)。
func TestLLMJudge_CallErrorFallsBackToAdd(t *testing.T) {
withFakeLLMJudge(t, "", errors.New("503 Service Unavailable"))
v := LLMJudge("新事实", similarTop("mem_1", "旧事实", 0.99))
if v.Op != OpAdd {
t.Fatalf("调用失败应兜底 ADD,得到 %s", v.Op)
}
}
// 归一化完全等价 → NOOP,且不调 LLM。
func TestLLMJudge_NormalizedEqualSkipsLLM(t *testing.T) {
calls := withFakeLLMJudge(t, "KEEP", nil)
v := LLMJudge("用户喜欢喝咖啡。", similarTop("mem_1", "用户喜欢喝咖啡", 0.97))
if v.Op != OpNoop {
t.Fatalf("归一化等价应判 NOOP,得到 %s", v.Op)
}
if got := atomic.LoadInt32(calls); got != 0 {
t.Fatalf("归一化等价不应调用 LLM,实际 %d 次", got)
}
}
func TestParseLLMJudgeVerdict(t *testing.T) {
cases := map[string]string{
"REPLACE": "REPLACE",
"duplicate": "DUPLICATE",
"我认为应该 KEEP 两条": "KEEP",
"": "KEEP",
"无法判断": "KEEP",
"REPLACE\n因为同一属性更新": "REPLACE",
}
for in, want := range cases {
if got := parseLLMJudgeVerdict(in); got != want {
t.Errorf("parse(%q)=%q,期望 %q", in, got, want)
}
}
}
// apply 模式必须强制 llm 判定;规则基判定精度实测≈0%,不许放行改库。
func TestWriteOpsApply_RequiresLLMJudge(t *testing.T) {
t.Setenv("ZHIYI_WRITE_SEMANTIC_OPS", "apply")
t.Setenv("ZHIYI_WRITE_JUDGE", "rule")
if writeOpsApply() {
t.Fatal("apply + rule 必须被拒绝(会误覆盖上万条),实际放行")
}
t.Setenv("ZHIYI_WRITE_JUDGE", "llm")
if !writeOpsApply() {
t.Fatal("apply + llm 应放行")
}
t.Setenv("ZHIYI_WRITE_SEMANTIC_OPS", "shadow")
t.Setenv("ZHIYI_WRITE_JUDGE", "llm")
if writeOpsApply() {
t.Fatal("shadow 模式不应改库")
}
}
func TestLLMJudge_ModeDefaultIsRule(t *testing.T) {
t.Setenv("ZHIYI_WRITE_JUDGE", "")
if LLMJudgeMode() != "rule" {
t.Fatalf("默认 judge 模式必须是 rule(零行为变化),得到 %s", LLMJudgeMode())
}
}
// TestLLMJudgeLive 真实 LLM 端到端验证(默认跳过;ZHIYI_LIVE_JUDGE=1 才跑)。
// 三条样本取自 2026-10-25 影子日志回放,人类已判定正确答案。
func TestLLMJudgeLive(t *testing.T) {
if os.Getenv("ZHIYI_LIVE_JUDGE") != "1" {
t.Skip("live LLM 测试,设 ZHIYI_LIVE_JUDGE=1 才跑")
}
cases := []struct {
name string
cand string
existing string
want WriteOp
}{
{"真覆盖-同一指标新值", "executions.db台账的max_rowid为185769。", "executions.db台账的max_rowid为183371", OpUpdate},
{"假覆盖-不同对象", "用户要求查看 https://mp.weixin.qq.com/s/4nmTHWoK 这篇文章", "用户: https://www.zhihu.com/pin/2075233714007757230", OpAdd},
{"重复-同义改写", "该软件支持PDF与Word/Excel/图片互转功能。", "工具转换功能支持PDF与Word/Excel/图片互转", OpNoop},
}
for _, c := range cases {
v := LLMJudge(c.cand, similarTop("mem_x", c.existing, 0.97))
t.Logf("%-18s → op=%s reason=%s", c.name, v.Op, v.Reason)
if v.Op != c.want {
t.Errorf("%s: 期望 %s,实际 %s(%s)", c.name, c.want, v.Op, v.Reason)
}
}
}
+1
View File
@@ -15,5 +15,6 @@ import (
// 缓存本身的正确性由 score_cache_test.go 直接测结构体(不依赖全局实例)。
func TestMain(m *testing.M) {
scoreCacheDisabled = true
loadPayloadRulesForTests() // t_e11207f8 治源①:单测前确保 payload guard 规则已加载(共享 JSON 或内嵌兜底)
os.Exit(m.Run())
}
+231
View File
@@ -0,0 +1,231 @@
package distill
// 织忆 MemoryWeave — 蒸馏落库「空壳正文」拒写门禁(t_e11207f8 治源 ①)
//
// 背景:OnDistillComplete(api/server.go)把 LLM 蒸馏出的 fact 直接 InsertMemory 进
// memories(category=distilled)。蒸馏 LLM 偶发把「只有溯源指针 / 占位 / 纯日期、无知识
// 载荷」的碎片当 fact 输出(例:`证据:文件:小怡/工作笔记/已办.md|日期:2026-09-23`),
// 质量门槛 IsQualityFact 的长度/实体启发式抓不住它(>20 字)⇒ 库里持续长出新空壳。
//
// 单一真相源:判据的**规则值**读自共享 JSON(zhiyi_payload_guard_rules.json),与
// Python 侧 ~/.hermes/scripts/lib/zhiyi_payload_guard.py **读同一份文件**(不在此手抄,
// 防跨语言漂移)。改规则只改那一个 JSON。
//
// 铁律(与 Python 逐位一致,宁漏勿误删):
// · 含任一句读标点(clause_punct)⇒ 绝不判空壳(保真优先)
// · 仅 空串 / 占位变量 / 纯日期 / 溯源指针(来源/证据/文件/日期/source + 引用值) 判空壳
//
// 已知跨语言 nuance(文档,不改行为方向):refname 正则里的 \w,Go RE2 默认 ASCII、
// Python 默认 unicode ⇒ CJK-only 文件名 Go 不判引用 ⇒ Go **多保留**(安全向,宁漏勿误删)。
//
// 无缓存、无新增 Redis 键(只用原子计数),故不触及项目现成件清单的缓存条目。
import (
"encoding/json"
"os"
"path/filepath"
"regexp"
"strings"
"sync/atomic"
"unicode/utf8"
)
// defaultRulesPath — 与 Python 侧同一份共享规则文件(同机同用户 muc 可直读)。
// env ZHIYI_PAYLOAD_GUARD_RULES 可覆盖(测试/部署用)。
func defaultRulesPath() string {
if p := os.Getenv("ZHIYI_PAYLOAD_GUARD_RULES"); p != "" {
return p
}
if home, err := os.UserHomeDir(); err == nil && home != "" {
return filepath.Join(home, ".hermes", "scripts", "lib", "zhiyi_payload_guard_rules.json")
}
return "/home/muc/.hermes/scripts/lib/zhiyi_payload_guard_rules.json"
}
// payloadGuardRules 镜像共享 JSON(只取 Go 判据需要的字段;未知字段忽略)。
type payloadGuardRules struct {
ClausePunct string `json:"clause_punct"`
Placeholder struct {
Pattern string `json:"pattern"`
CaseInsensitive bool `json:"case_insensitive"`
} `json:"placeholder"`
BareDate struct {
Pattern string `json:"pattern"`
CaseInsensitive bool `json:"case_insensitive"`
} `json:"bare_date"`
ProvLabel struct {
Pattern string `json:"pattern"`
CaseInsensitive bool `json:"case_insensitive"`
} `json:"prov_label"`
Refname struct {
Pattern string `json:"pattern"`
CaseInsensitive bool `json:"case_insensitive"`
} `json:"refname"`
RefValueSubstrings []string `json:"ref_value_substrings"`
RefValueMaxLen int `json:"ref_value_max_len"`
RefValueMaxCJK int `json:"ref_value_max_cjk"`
CJKLo string `json:"cjk_lo"`
CJKHi string `json:"cjk_hi"`
}
type guard struct {
rules payloadGuardRules
placeH *regexp.Regexp
bareD *regexp.Regexp
provL *regexp.Regexp
refname *regexp.Regexp
loaded bool
path string
}
var (
g *guard
// shellChecks = 拦截器「确实跑过」的心跳计数(每个蒸馏 fact 判一次);
// shellBlocks = 实际拦下的空壳条数。二者配对即证拦截器活着(0 blocks 但 checks>0 也合法)。
shellChecks int64
shellBlocks int64
)
// LoadPayloadGuard 读共享规则 JSON 并编译正则。失败 ⇒ 未加载(fail-open:distill 照跑、
// 不拦空壳、不崩 zhiyid),并把 loaded=false 记给 /api/v1/payload-guard/stats 暴露。
func LoadPayloadGuard(explicitPath string) (loaded bool, err error) {
p := explicitPath
if p == "" {
p = defaultRulesPath()
}
raw, rerr := os.ReadFile(p)
if rerr != nil {
g = &guard{}
return false, rerr
}
var rc payloadGuardRules
if jerr := json.Unmarshal(raw, &rc); jerr != nil {
g = &guard{}
return false, jerr
}
compile := func(pat string, ci bool) (*regexp.Regexp, error) {
if ci {
pat = "(?i)" + pat
}
return regexp.Compile(pat)
}
gh := &guard{rules: rc, path: p, loaded: true}
if gh.placeH, err = compile(rc.Placeholder.Pattern, rc.Placeholder.CaseInsensitive); err != nil {
g = &guard{}
return false, err
}
if gh.bareD, err = compile(rc.BareDate.Pattern, rc.BareDate.CaseInsensitive); err != nil {
g = &guard{}
return false, err
}
if gh.provL, err = compile(rc.ProvLabel.Pattern, rc.ProvLabel.CaseInsensitive); err != nil {
g = &guard{}
return false, err
}
if gh.refname, err = compile(rc.Refname.Pattern, rc.Refname.CaseInsensitive); err != nil {
g = &guard{}
return false, err
}
if rc.RefValueMaxLen <= 0 {
rc.RefValueMaxLen = 24
}
if rc.RefValueMaxCJK <= 0 {
rc.RefValueMaxCJK = 12
}
gh.rules = rc
g = gh
return true, nil
}
// PayloadGuardStats 供 /metrics 与验收:拦截器心跳(checks) / 拦截数(blocks) / 是否加载 / 规则路径。
func PayloadGuardStats() (checks, blocks int64, loaded bool, path string) {
if g == nil {
return atomic.LoadInt64(&shellChecks), atomic.LoadInt64(&shellBlocks), false, ""
}
return atomic.LoadInt64(&shellChecks), atomic.LoadInt64(&shellBlocks), g.loaded, g.path
}
// IncShellCheck / IncShellBlock 供写路径在判定前后调用(相对增量,避免并发写竞态)。
func IncShellCheck() { atomic.AddInt64(&shellChecks, 1) }
func IncShellBlock() { atomic.AddInt64(&shellBlocks, 1) }
// ShellCheck 治源入口(带心跳计数):
// - 未加载 ⇒ fail-open(放行、checks 仍 +1,保证「拦截器跑过」可观测,不拦也不崩);
// - 已加载 ⇒ 用共享判据判定,命中空壳则 blocks +1 并返回 true(写路径据此 continue 拒写)。
func ShellCheck(content string) bool {
IncShellCheck()
if g == nil || !g.loaded {
return false
}
if g.isEmptyShell(content) {
IncShellBlock()
return true
}
return false
}
// IsEmptyShell 纯判据(无计数,供单测)。未加载时就地读一次默认路径兜底;失败则 fail-open。
func IsEmptyShell(content string) bool {
if g == nil {
if _, err := LoadPayloadGuard(""); err != nil {
return false
}
}
return g.isEmptyShell(content)
}
func (gr *guard) isEmptyShell(content string) bool {
c := strings.TrimSpace(content)
if c == "" {
return true
}
// 含任一句读标点 ⇒ 有知识断言 ⇒ 绝不当空壳(保真优先,优先于漏删)
for _, r := range []rune(gr.rules.ClausePunct) {
if strings.ContainsRune(c, r) {
return false
}
}
if gr.placeH.MatchString(c) {
return true
}
if gr.bareD.MatchString(c) {
return true
}
if gr.provL.MatchString(c) && gr.isRefValue(c) {
return true
}
return false
}
func (gr *guard) isRefValue(c string) bool {
s := strings.TrimSpace(c)
for _, sub := range gr.rules.RefValueSubstrings {
if strings.Contains(c, sub) {
return true
}
}
if gr.bareD.MatchString(s) || gr.refname.MatchString(s) {
return true
}
if utf8.RuneCountInString(s) <= gr.rules.RefValueMaxLen && gr.cjkCount(s) < gr.rules.RefValueMaxCJK {
return true
}
return false
}
// cjkCount 统计 [cjk_lo, cjk_hi] 区间的汉字数(与 Python re.findall(r"[一-鿿]") 等价)。
func (gr *guard) cjkCount(s string) int {
lo, hi := gr.rules.CJKLo, gr.rules.CJKHi
if lo == "" || hi == "" {
lo, hi = "一", "鿿" // U+4E00 / U+9FFF
}
loR, _ := utf8.DecodeRuneInString(lo)
hiR, _ := utf8.DecodeRuneInString(hi)
n := 0
for _, r := range s {
if r >= loR && r <= hiR {
n++
}
}
return n
}
+99
View File
@@ -0,0 +1,99 @@
package distill
// t_e11207f8 治源 ① Go 单测:
// ① 真样本(溯源指针)必判空壳;② 负控(真知识短句 / 含句读)必保留;③ 拦截计数。
// 判据值优先读【生产共享 JSON】(~/.hermes/scripts/lib/zhiyi_payload_guard_rules.json),
// 与 Python 同源;该文件缺失时用下方内嵌副本兜底(仅测试用,非运行时真相源)。
import (
"os"
"path/filepath"
"testing"
)
const embeddedRulesJSON = `{
"clause_punct": ",。、;!?",
"placeholder": {"pattern": "^[xX]=(?:true|false|\\\\d|[a-z_]{1,12})$", "case_insensitive": true},
"bare_date": {"pattern": "^(?:日期[::]?)?\\\\d{4}[-/]\\\\d{1,2}[-/]\\\\d{1,2}\\\\.?[。.\\\\s]*$"},
"prov_label": {"pattern": "^(?:来源|证据|文件|日期|source)[::]", "case_insensitive": true},
"refname": {"pattern": "^[\\\\w.-]+\\\\.(?:md|py|sh|json|yaml|log|txt)$", "case_insensitive": true},
"ref_value_substrings": ["|", "vault:", "/"],
"ref_value_max_len": 24, "ref_value_max_cjk": 12,
"cjk_lo": "一", "cjk_hi": "鿿"
}`
func loadPayloadRulesForTests() {
// 优先生产共享 JSON(与 Python 同源);缺失则落内嵌副本到临时目录再读(保证测试可独立跑)。
p := os.Getenv("ZHIYI_PAYLOAD_GUARD_RULES")
if p == "" {
if home, err := os.UserHomeDir(); err == nil && home != "" {
p = filepath.Join(home, ".hermes", "scripts", "lib", "zhiyi_payload_guard_rules.json")
}
}
if _, err := LoadPayloadGuard(p); err != nil {
tmp, merr := os.MkdirTemp("", "zhiyi-payload-rules-")
if merr != nil {
return
}
rp := filepath.Join(tmp, "rules.json")
if werr := os.WriteFile(rp, []byte(embeddedRulesJSON), 0o644); werr != nil {
return
}
LoadPayloadGuard(rp)
}
}
func TestIsEmptyShell_Positive_RealSample(t *testing.T) {
cases := []string{
"证据:文件:小怡/工作笔记/已办.md|日期:2026-09-23", // 蒸馏真样本(QA/小怡复现的那条)
"来源:vault:定义规范:106办公向优化方案-2026-09-18.md",
"证据:文件:小怡/工作笔记/已办.md",
"X=true",
"",
"2026-09-23",
}
for _, c := range cases {
if !IsEmptyShell(c) {
t.Errorf("应判空壳却放行: %q", c)
}
}
}
func TestIsEmptyShell_Negative_KeepRealKnowledge(t *testing.T) {
cases := []string{
"牧尘在招商局工作", // 负控:超短真断言,绝不当空壳
"活库直连写必须停服务", // 负控:真知识
"来源:t_cbc41a01 待办 #6 核销结果。", // 含句读(。)⇒ 必保留
"双向链接是 Obsidian 最核心的功能之一。", // 含句读
"决定将newapi平台中的付费key改为免费", // 真知识
"织忆端口7821", // 短但无句读、无溯源前缀、非占位 ⇒ 保守保留
}
for _, c := range cases {
if IsEmptyShell(c) {
t.Errorf("误判真知识为空壳(负控失败,违反宁漏勿误删): %q", c)
}
}
}
func TestShellCheck_Counters(t *testing.T) {
// ③ 拦截器计数:每个 fact 判一次(checks 增),命中空壳再 blocks 增。
c0, b0, loaded, _ := PayloadGuardStats()
if !loaded {
t.Fatalf("payload guard 未加载,无法验证拦截器")
}
good := "用户决定升级系统"
shell := "证据:文件:小怡/工作笔记/已办.md|日期:2026-09-23"
if ShellCheck(good) {
t.Errorf("真知识 fact 被误拦: %q", good)
}
if !ShellCheck(shell) {
t.Errorf("空壳蒸馏 fact 未被拦: %q", shell)
}
c1, b1, _, _ := PayloadGuardStats()
if c1-c0 != 2 {
t.Errorf("checks 增量应为 2(good+shell 各判一次),实得 %d", c1-c0)
}
if b1-b0 != 1 {
t.Errorf("blocks 增量应为 1(仅 shell 命中),实得 %d", b1-b0)
}
}
+21 -2
View File
@@ -181,9 +181,23 @@ func WriteOpsMode() string {
return writeOpsMode()
}
// writeOpsApply 是否真改库
// writeOpsApply 是否真改库(apply 模式)。
//
// 2026-10-25 硬保护:apply **强制要求 LLM 判定**。理由(离线回放实测,非推测):
// 规则基 defaultJudge 以 ZHIYI_WRITE_SIM_UPDATE=0.70 判 UPDATE,17179 条影子日志里
// 84%(14435 条)被判「应覆盖旧事实」;人工抽检低相似度样本 15/15 不是真覆盖
// (「用户查看知乎链接」vs「用户查看微信文章」都被判成覆盖)。放行 apply 会把上万条
// 记忆错误标记 superseded_by —— 规模是 2026-09-07 误删事故(67 条)的 200 倍。
// 因此未设 ZHIYI_WRITE_JUDGE=llm 时**降级为 shadow 并留痕**,不静默执行。
func writeOpsApply() bool {
return writeOpsMode() == "apply"
if writeOpsMode() != "apply" {
return false
}
if LLMJudgeMode() != "llm" {
log.Printf("[write-ops] 拒绝 apply:ZHIYI_WRITE_JUDGE != llm(规则基判定精度实测≈0%%,会误覆盖上万条)→ 本次按 shadow 处理")
return false
}
return true
}
// writeOpsLogPath 影子日志路径(env 可覆盖)
@@ -348,6 +362,11 @@ func JudgeWriteOp(candidate string, similar []SimilarMemory, judge JudgeFunc, co
var v WriteVerdict
if judge != nil {
v = judge(candidate, similar)
} else if writeOpsApply() || LLMJudgeMode() == "llm" {
// 2026-10-25:LLM 三分类判定。规则基 defaultJudge 的 UPDATE 精度实测约 0%
// (17179 条影子日志 84% 判 UPDATE,人工抽检 15/15 误判)⇒ apply 强制 llm;
// shadow 下也可用 ZHIYI_WRITE_JUDGE=llm 先观察新判定质量。judge 显式注入时优先注入。
v = LLMJudge(candidate, similar)
} else {
if contradict == nil {
contradict = ruleContradiction
+33 -8
View File
@@ -33,11 +33,36 @@ func mkMem(id, content string) models.MemoryRecord {
return models.MemoryRecord{ID: id, Content: content}
}
// fixedJudge 返回固定 verdict 的判定器。
// 2026-10-25:apply 模式改为强制 LLM 判定(规则基 UPDATE 精度实测≈0%),
// 单测注入确定性实现,避免依赖网络/模型。
func fixedJudge(op WriteOp) JudgeFunc {
return func(c string, s []SimilarMemory) WriteVerdict {
v := WriteVerdict{Op: op, Candidate: c}
if len(s) > 0 {
v.TargetID = s[0].ID
v.Similarity = s[0].Similarity
}
return v
}
}
// withMode 临时设 ZHIYI_WRITE_OPS 模式,返回恢复函数。
func withMode(mode string) func() {
old := os.Getenv("ZHIYI_WRITE_OPS")
os.Setenv("ZHIYI_WRITE_OPS", mode)
return func() { os.Setenv("ZHIYI_WRITE_OPS", old) }
old := os.Getenv("ZHIYI_WRITE_SEMANTIC_OPS")
oldJudge := os.Getenv("ZHIYI_WRITE_JUDGE")
os.Setenv("ZHIYI_WRITE_SEMANTIC_OPS", mode)
if mode == "apply" {
// 2026-10-25 硬保护:apply 强制 LLM 判定(规则基 UPDATE 精度实测≈0%)。
// apply 用例均已注入 fixedJudge,因此设置 llm 不会真调网络。
os.Setenv("ZHIYI_WRITE_JUDGE", "llm")
} else {
os.Setenv("ZHIYI_WRITE_JUDGE", "rule")
}
return func() {
os.Setenv("ZHIYI_WRITE_SEMANTIC_OPS", old)
os.Setenv("ZHIYI_WRITE_JUDGE", oldJudge)
}
}
// withLogPath 临时把影子日志指到临时文件,返回清理函数。
@@ -110,7 +135,7 @@ func TestWriteOps_Add(t *testing.T) {
similar := []SimilarMemory{
{ID: "mem_1", Content: "牧尘在招商局工作", Similarity: 0.4},
}
v := JudgeWriteOp(candidate, similar, nil, nil)
v := JudgeWriteOp(candidate, similar, fixedJudge(OpAdd), nil)
if v == nil {
t.Fatalf("JudgeWriteOp 返回 nil")
}
@@ -130,7 +155,7 @@ func TestWriteOps_Update(t *testing.T) {
similar := []SimilarMemory{
{ID: "mem_1", Content: "牧尘在招商局工作", Similarity: 0.92},
}
v := JudgeWriteOp(candidate, similar, nil, nil)
v := JudgeWriteOp(candidate, similar, fixedJudge(OpUpdate), nil)
if v == nil {
t.Fatalf("nil verdict")
}
@@ -159,7 +184,7 @@ func TestWriteOps_Noop(t *testing.T) {
}
t.Run("apply+NOOP_丢弃", func(t *testing.T) {
defer withMode("apply")()
v := JudgeWriteOp(candidate, similar, nil, nil)
v := JudgeWriteOp(candidate, similar, fixedJudge(OpNoop), nil)
if v == nil || v.Op != OpNoop {
t.Fatalf("期望 NOOP,实际 %v", v)
}
@@ -193,7 +218,7 @@ func TestWriteOps_ConflictMark(t *testing.T) {
similar := []SimilarMemory{
{ID: "mem_1", Content: "牧尘在招商局工作", Similarity: 0.85},
}
v := JudgeWriteOp(candidate, similar, nil, nil)
v := JudgeWriteOp(candidate, similar, fixedJudge(OpConflictMark), nil)
if v == nil {
t.Fatalf("nil verdict")
}
@@ -234,7 +259,7 @@ func TestWriteOps_WriteTrueThenFalse(t *testing.T) {
// 第二次:写 X=false,库里已有 X=true → CONFLICT(矛盾)
second := JudgeWriteOp("X=false", []SimilarMemory{
{ID: "mem_1", Content: "X=true", Similarity: 0.9},
}, nil, nil)
}, fixedJudge(OpConflictMark), nil)
if second == nil {
t.Fatalf("nil")
}
+189
View File
@@ -0,0 +1,189 @@
// 织忆 MemoryWeave — 实体名称拒写门禁(t_41f5ee7a 治源)
//
// 背景:在实体抽取写库前加拒绝规则,防止非法实体名(如过长、以数字开头、包含路径/后缀)
// 进入图谱。单一真相源:判据的规则值读自共享 JSON
// (~/.hermes/scripts/lib/graph_entity_guard.json),与 Python 侧
// graph_entity_guard.py 读同一份文件;改规则只改那一个 JSON。
//
// 铁律(与 Python 逐位一致):
// · 白名单内的名称直接放行(即使匹配判据)
// · 否则匹配 j1/j2/j3 之一即判为垃圾(应被拒绝)
//
// 无缓存、无新增 Redis 键(只用原子计数),故不触及项目现成件清单的缓存条目。
package governance
import (
"encoding/json"
"os"
"path/filepath"
"regexp"
"strings"
"sync/atomic"
)
// entityGuardG is the singleton guard instance.
var entityGuardG *guard
// defaultRulesPath — 与 Python 侧同一份共享规则文件(同机同用户 muc 可直读)。
// env GRAPH_ENTITY_GUARD_RULES 可覆盖(测试/部署用)。
func defaultRulesPath() string {
if p := os.Getenv("GRAPH_ENTITY_GUARD_RULES"); p != "" {
return p
}
if home, err := os.UserHomeDir(); err == nil && home != "" {
return filepath.Join(home, ".hermes", "scripts", "lib", "graph_entity_guard.json")
}
return "/home/muc/.hermes/scripts/lib/graph_entity_guard.json"
}
// entityGuardRules 镜像共享 JSON(只取 Go 判据需要的字段;未知字段忽略)。
type entityGuardRules struct {
Whitelist []string `json:"whitelist"`
Judgments struct {
J1LenGt14 struct {
Pattern string `json:"pattern"`
CaseInsensitive bool `json:"case_insensitive"`
} `json:"j1_len_gt_14"`
J2StartsWithDigit struct {
Pattern string `json:"pattern"`
CaseInsensitive bool `json:"case_insensitive"`
} `json:"j2_startswith_digit"`
J3PathOrExt struct {
Pattern string `json:"pattern"`
CaseInsensitive bool `json:"case_insensitive"`
} `json:"j3_path_or_ext"`
} `json:"judgments"`
}
type guard struct {
rules entityGuardRules
j1Regex *regexp.Regexp
j2Regex *regexp.Regexp
j3Regex *regexp.Regexp
loaded bool
path string
// 计数(可选,供监控)
checks int64
blocks int64
}
// LoadEntityGuard 读取并编译规则。首次成功后设置单例。
// 返回 (ok, error)。ok 表示是否成功加载。
func LoadEntityGuard(path string) (bool, error) {
if path == "" {
path = defaultRulesPath()
}
data, err := os.ReadFile(path)
if err != nil {
return false, err
}
var rc entityGuardRules
if err := json.Unmarshal(data, &rc); err != nil {
return false, err
}
// 編譯判據正則
j1Regex, err := regexp.Compile(rc.Judgments.J1LenGt14.Pattern)
if err != nil {
return false, err
}
if rc.Judgments.J1LenGt14.CaseInsensitive {
j1Regex = regexp.MustCompile("(?i)" + rc.Judgments.J1LenGt14.Pattern)
}
j2Regex, err := regexp.Compile(rc.Judgments.J2StartsWithDigit.Pattern)
if err != nil {
return false, err
}
if rc.Judgments.J2StartsWithDigit.CaseInsensitive {
j2Regex = regexp.MustCompile("(?i)" + rc.Judgments.J2StartsWithDigit.Pattern)
}
j3Regex, err := regexp.Compile(rc.Judgments.J3PathOrExt.Pattern)
if err != nil {
return false, err
}
if rc.Judgments.J3PathOrExt.CaseInsensitive {
j3Regex = regexp.MustCompile("(?i)" + rc.Judgments.J3PathOrExt.Pattern)
}
g := &guard{
rules: rc,
j1Regex: j1Regex,
j2Regex: j2Regex,
j3Regex: j3Regex,
path: path,
loaded: true,
}
// assign to package-level singleton
entityGuardG = g
return true, nil
}
// EntityGuardStats 供 /metrics 与验收:检查数 / 拦截数 / 是否加载 / 规则路径。
func EntityGuardStats() (checks, blocks int64, loaded bool, path string) {
if entityGuardG == nil {
return 0, 0, false, ""
}
return atomic.LoadInt64(&entityGuardG.checks), atomic.LoadInt64(&entityGuardG.blocks), entityGuardG.loaded, entityGuardG.path
}
// IncEntityGuardCheck / IncEntityGuardBlock 供写路径在判定前后调用(相对增量,避免并发写竞态)。
func IncEntityGuardCheck() {
if entityGuardG == nil {
return
}
atomic.AddInt64(&entityGuardG.checks, 1)
}
func IncEntityGuardBlock() {
if entityGuardG == nil {
return
}
atomic.AddInt64(&entityGuardG.blocks, 1)
}
// IsJunkName 治源入口(帶心跳計數):
// - 未加載 ⇒ fail-open(放行、checks 仍 +1,保證「拦截器跑過」可觀測,不拦也不崩);
// - 已加載 ⇒ 用共享判據判定,命中垃圾則 blocks +1 並返回 true(寫路径據此 continue 拒寫)。
func IsJunkName(name string) bool {
IncEntityGuardCheck()
if entityGuardG == nil || !entityGuardG.loaded {
return false
}
if entityGuardG.isJunkName(name) {
IncEntityGuardBlock()
return true
}
return false
}
// IsJunkNamePure 純判據(無計數,供單測)。未加載時就地讀一次默認路徑兜底;失敗則 fail-open。
func IsJunkNamePure(name string) bool {
if entityGuardG == nil {
if _, err := LoadEntityGuard(""); err != nil {
return false
}
}
return entityGuardG.isJunkName(name)
}
func (gr *guard) isJunkName(name string) bool {
// 先修剪空白(與 SQL trim 一致)
n := strings.TrimSpace(name)
// 白名單直接放行
for _, w := range gr.rules.Whitelist {
if w == n {
return false
}
}
// 判定垃圾:匹配 j1/j2/j3 之一
if gr.j1Regex.MatchString(n) {
return true
}
if gr.j2Regex.MatchString(n) {
return true
}
if gr.j3Regex.MatchString(n) {
return true
}
return false
}
+5
View File
@@ -115,6 +115,11 @@ func (agu *AutoGraphUpdater) UpdateFromDistill(distilled *DistillInput) {
entity, distilled.EpisodeID)
continue
}
cleaned := cleanEntityName(entity)
if IsJunkName(cleaned) {
log.Printf("[graph] skip-junk-entity=%q cleaned=%q", entity, cleaned)
continue
}
validEnts = append(validEnts, entity)
}
+17
View File
@@ -3,6 +3,7 @@ package governance
import (
"fmt"
"strings"
"sync"
)
@@ -295,6 +296,22 @@ func (g *InMemoryGraph) AllEdges(namespace string) []GraphEdge {
return out
}
// CountNodesByType 内存实现:无时间列,lastUpdated 恒为空(调用方按 unknown_age 处理)。
func (g *InMemoryGraph) CountNodesByType(typ string) (total, withID int, lastUpdated string) {
g.mu.RLock()
defer g.mu.RUnlock()
for _, n := range g.nodes {
if n.Type != typ {
continue
}
total++
if strings.TrimSpace(n.ID) != "" {
withID++
}
}
return
}
// Stats 返回图谱统计
func (g *InMemoryGraph) Stats() (nodeCount, edgeCount int, density float64) {
g.mu.RLock()
+87 -7
View File
@@ -216,11 +216,33 @@ func (gs *SQLiteGraphStore) AddEdge(id, source, target, relation, namespace stri
return execSQL(gs.db, sql)
}
func (gs *SQLiteGraphStore) isQuarantinedNode(nodeID string) (bool, error) {
sql := fmt.Sprintf(
"SELECT namespace, pagerank FROM graph_nodes WHERE id='%s'", escape(nodeID))
rows := queryRows(gs.db, sql)
if len(rows) == 0 {
// node not found; treat as not quarantined to avoid breaking existing flows
return false, nil
}
row := rows[0]
namespace, _ := row["namespace"].(string)
pagerankVal, _ := row["pagerank"].(float64)
return namespace == "quarantine" && pagerankVal == 0, nil
}
func (gs *SQLiteGraphStore) Navigate(entity string, maxHops int, namespace string, relFilter []string) ([]map[string]interface{}, error) {
// 单源 BFS:从 entity 展开到邻居,不找路径
// E1.4: relFilter 白名单过滤关系类型
gs.mu.RLock()
defer gs.mu.RUnlock()
if quarantined, err := gs.isQuarantinedNode(entity); err != nil {
// If we cannot determine, treat as not quarantined to avoid breaking existing flows.
if err != nil {
// Continue; assume not quarantined.
} else if quarantined {
return []map[string]interface{}{}, nil
}
}
nsClause := buildNamespaceClause(namespace)
relClause := buildRelationFilterClause(relFilter)
@@ -233,7 +255,7 @@ func (gs *SQLiteGraphStore) Navigate(entity string, maxHops int, namespace strin
var next []string
for _, node := range queue {
sql := fmt.Sprintf(
"SELECT e.id, e.target, e.relation, e.weight, n.name FROM graph_edges e JOIN graph_nodes n ON e.target = n.id WHERE e.source = '%s' AND %s AND %s",
"SELECT e.id, e.target, e.relation, e.weight, n.name FROM graph_edges e JOIN graph_nodes n ON e.target = n.id WHERE e.source = '%s' AND %s AND %s AND n.namespace != 'quarantine' AND n.pagerank > 0",
escape(node), nsClause, relClause)
edges := queryRows(gs.db, sql)
for _, edge := range edges {
@@ -269,6 +291,20 @@ func (gs *SQLiteGraphStore) NavigateBiDir(source, target string, maxHops int, na
gs.mu.RLock()
defer gs.mu.RUnlock()
if quarantinedSrc, err := gs.isQuarantinedNode(source); err != nil {
if err != nil {
// Continue; assume not quarantined.
} else if quarantinedSrc {
return []map[string]interface{}{}, nil
}
}
if quarantinedTgt, err := gs.isQuarantinedNode(target); err != nil {
if err != nil {
// Continue; assume not quarantined.
} else if quarantinedTgt {
return []map[string]interface{}{}, nil
}
}
nsClause := buildNamespaceClause(namespace)
@@ -310,7 +346,7 @@ func (gs *SQLiteGraphStore) NavigateBiDir(source, target string, maxHops int, na
var next []string
for _, node := range fwdQ {
sql := fmt.Sprintf(
"SELECT e.id, e.target, e.relation, e.weight FROM graph_edges e WHERE e.source = '%s' AND %s",
"SELECT e.id, e.target, e.relation, e.weight FROM graph_edges e JOIN graph_nodes n ON e.target = n.id WHERE e.source = '%s' AND %s AND n.namespace != 'quarantine' AND n.pagerank > 0",
escape(node), nsClause)
edges := queryRows(gs.db, sql)
for _, edge := range edges {
@@ -340,7 +376,7 @@ func (gs *SQLiteGraphStore) NavigateBiDir(source, target string, maxHops int, na
for _, node := range bwdQ {
// 反向要找所有指向 node 的边(target = node)
sql := fmt.Sprintf(
"SELECT e.id, e.source, e.relation, e.weight FROM graph_edges e WHERE e.target = '%s' AND %s",
"SELECT e.id, e.source, e.relation, e.weight FROM graph_edges e JOIN graph_nodes n ON e.source = n.id WHERE e.target = '%s' AND %s AND n.namespace != 'quarantine' AND n.pagerank > 0",
escape(node), nsClause)
edges := queryRows(gs.db, sql)
for _, edge := range edges {
@@ -548,6 +584,32 @@ func (gs *SQLiteGraphStore) Stats() (nodeCount, edgeCount int, density float64)
return
}
// CountNodesByType 返回某类节点的总量、id 非空量、最近一次更新时间(2026-10-26)。
//
// 存在的理由:selfcheck 需要暴露「pattern 召回有没有生产者」这一可观测事实。
// 事故背景:`POST /api/v1/patterns/detect` 是短命单发端点,全库 0 cron、0 调用方,
// 于是 graph_nodes(type='pattern') 恒 0 行、recall 恒 0 命中,而日志层面完全沉默。
// 零产出必须能被机器读到,不能靠人翻 7 天日志才发现。
func (gs *SQLiteGraphStore) CountNodesByType(typ string) (total, withID int, lastUpdated string) {
gs.mu.RLock()
defer gs.mu.RUnlock()
t := escape(typ)
total = queryInt(gs.db, fmt.Sprintf("SELECT COUNT(*) FROM graph_nodes WHERE type='%s'", t))
withID = queryInt(gs.db, fmt.Sprintf(
"SELECT COUNT(*) FROM graph_nodes WHERE type='%s' AND id IS NOT NULL AND TRIM(id)<>''", t))
rows := queryRows(gs.db, fmt.Sprintf(
"SELECT MAX(last_updated_at) AS m FROM graph_nodes WHERE type='%s'", t))
if len(rows) > 0 && rows[0]["m"] != nil {
if v, ok := rows[0]["m"].(string); ok {
lastUpdated = v
} else {
lastUpdated = fmt.Sprintf("%v", rows[0]["m"])
}
}
return
}
func (gs *SQLiteGraphStore) Prune(minWeight float64) {
gs.mu.Lock()
defer gs.mu.Unlock()
@@ -769,18 +831,20 @@ func (gs *SQLiteGraphStore) ExpandFromResults(results []models.RecallResult, nam
seenEntities[entity] = true
// SQLite 图谱节点 ID 格式: n_{entity_name},需 normalizeEntityID 转换
// Navigate 的 from/to 都是**节点 ID**(n_织忆),不能用裸名 entity 比对,
// 否则恒不相等 ⇒ 路径全被 continue ⇒ 结构性 0 条附加(t_be4d070a 诊断)。
nodeID := normalizeEntityID(entity)
paths, _ := gs.Navigate(nodeID, maxHops, namespace, nil)
for _, p := range paths {
// Navigate 返回字段: from, to, relation, weight, hop
// Navigate 返回字段: from, to, relation, weight, hop(均为节点 ID)
var neighbor, rel string
from, _ := p["from"].(string)
to, _ := p["to"].(string)
relVal, _ := p["relation"].(string)
if from == entity && to != "" {
if from == nodeID && to != "" {
neighbor = to
rel = relVal
} else if to == entity && from != "" {
} else if to == nodeID && from != "" {
neighbor = from
rel = "↩ " + relVal
}
@@ -792,7 +856,11 @@ func (gs *SQLiteGraphStore) ExpandFromResults(results []models.RecallResult, nam
}
seenEntities[neighbor] = true
expanded = append(expanded, models.RecallResult{
Content: fmt.Sprintf("[graph] %s --[%s]--> %s", entity, rel, neighbor),
// ID 用邻居节点 ID(n_<实体> 或 n_mem_<记忆id>),非空才不破坏 recall.go 的
// ID 去重(Step 5 按 r.ID==e.ID 判已存在);若邻居是记忆节点,ID 即真实记忆指针。
ID: neighbor,
Category: "graph_expanded",
Content: fmt.Sprintf("[graph] %s --[%s]--> %s", entity, rel, displayNodeName(neighbor)),
Score: r.Score * 0.5,
})
}
@@ -801,6 +869,18 @@ func (gs *SQLiteGraphStore) ExpandFromResults(results []models.RecallResult, nam
return expanded
}
// displayNodeName 把节点 ID 转成可读显示名(去 n_ / n_mem_ / mem_ 前缀)。
// 图节点 ID 形态:实体 n_织忆 / 概念 n_mem_<记忆id>(name 列才是 mem_<id>)。
// 仅用于格式化 Content 的可读展示,不做任何记忆正文编造。
func displayNodeName(nodeID string) string {
for _, p := range []string{"n_mem_", "n_", "mem_", "ep_"} {
if strings.HasPrefix(nodeID, p) {
return strings.TrimPrefix(nodeID, p)
}
}
return nodeID
}
// ExpandWithSummary BFS 扩展 + 生成汇总语句 — E1 图谱导航增强
// 从 recall 结果提取实体,进行多跳扩展,返回扩展关系列表和一句话汇总
func (gs *SQLiteGraphStore) ExpandWithSummary(results []models.RecallResult, namespace string, maxHops int) models.GraphBFSResult {
@@ -0,0 +1,95 @@
// 织忆 MemoryWeave — SQLiteGraphStore.ExpandFromResults 修复锁死测试(t_724f31ad)
//
// 背景:SQLiteGraphStore.ExpandFromResults(graph_sqlite.go:787)此前拿裸实体名 entity
// 与 Navigate 返回的节点 ID(n_织忆)做 == 比对 ⇒ 恒不相等 ⇒ 路径全被 continue ⇒ 结构性 0 条附加。
// 且附加结果 Category 空、ID 空(审计 graph_expanded 计数恒 0 + recall.go ID 去重失效)。
//
// 本文件两类断言:
// 1) 正向:构造 n_<实体> 节点 + 一条 recall 结果 ⇒ ExpandFromResults 返回 >len(results),
// 且新增项 Category=="graph_expanded" 且 ID!=""(ID 用邻居节点 ID)。
// 2) 反向:实体在图里不存在 ⇒ 结果条数不变(不得凭空加)。
package governance
import (
"path/filepath"
"testing"
"github.com/xiaoxue/memoryweave/internal/models"
)
// testNS724 SQLite 图的 namespace 须用 `-main` 全形态:SQLiteGraphStore.Navigate 经
// deriveNamespaceForGraph 会把裸名 ns 变 ns-main 再过滤(与生产 recall.go 传的 namespace 一致)。
const testNS724 = "t-ns-expand-sqlite-main"
// newTestSQLiteGraph 建临时 SQLiteGraphStore 并灌入一条链:n_织忆 -LINKS_TO-> n_图谱。
func newTestSQLiteGraph(t *testing.T) *SQLiteGraphStore {
t.Helper()
path := filepath.Join(t.TempDir(), "graph-test.db")
gs, err := NewSQLiteGraphStore(path)
if err != nil {
t.Fatalf("NewSQLiteGraphStore: %v", err)
}
t.Cleanup(func() { _ = gs.Close() })
if err := gs.AddNode("n_织忆", "织忆", "entity", testNS724); err != nil {
t.Fatalf("AddNode n_织忆: %v", err)
}
if err := gs.AddNode("n_图谱", "图谱", "entity", testNS724); err != nil {
t.Fatalf("AddNode n_图谱: %v", err)
}
if err := gs.AddEdge("e-ab", "n_织忆", "n_图谱", "LINKS_TO", testNS724, 1.0); err != nil {
t.Fatalf("AddEdge: %v", err)
}
return gs
}
// TestSQLiteGraphStore_ExpandFromResults_Inserts 正向:实体在图中 ⇒ 补入 graph_expanded 且 ID 非空。
func TestSQLiteGraphStore_ExpandFromResults_Inserts(t *testing.T) {
gs := newTestSQLiteGraph(t)
results := []models.RecallResult{{
ID: "mem_expand_1",
Content: "织忆 与 图谱 的扩展机制",
Category: "distilled",
Score: 0.9,
Namespace: testNS724,
}}
got := gs.ExpandFromResults(results, testNS724, 1)
if len(got) <= len(results) {
t.Fatalf("期望补入 >len(results)=%d,实际 %d 条(结构性 0 产出未修?)", len(results), len(got))
}
var added int
for _, e := range got[len(results):] {
if e.Category != "graph_expanded" {
t.Fatalf("补入结果 category=%q 期望 graph_expanded", e.Category)
}
if e.ID == "" {
t.Fatalf("补入结果 ID 为空(ID 去重会失效),Content=%q", e.Content)
}
added++
}
if added == 0 {
t.Fatal("没有任何 graph_expanded 补入")
}
t.Logf("SQLiteGraphStore: 1-recall 补入 %d 条 graph_expanded(ID 均非空)", added)
}
// TestSQLiteGraphStore_ExpandFromResults_NoFabrication 反向:实体不在图中 ⇒ 条数不变,不得凭空加。
func TestSQLiteGraphStore_ExpandFromResults_NoFabrication(t *testing.T) {
gs := newTestSQLiteGraph(t)
// content 只含一个图中不存在的实体「完全不存在的实体」(切分成 2~8 字中文串均无图节点)。
results := []models.RecallResult{{
ID: "mem_expand_2",
Content: "完全不存在的实体",
Category: "distilled",
Score: 0.9,
Namespace: testNS724,
}}
got := gs.ExpandFromResults(results, testNS724, 1)
if len(got) != len(results) {
t.Fatalf("实体不在图中却补入 %d 条(期望 0 补入,len=%d)", len(got)-len(results), len(results))
}
t.Logf("SQLiteGraphStore: 图外实体 ⇒ 0 补入(不凭空加)")
}
+3
View File
@@ -23,6 +23,9 @@ type GraphStore interface {
// 统计与维护
Stats() (nodeCount, edgeCount int, density float64)
// CountNodesByType 返回某类节点的总量、id 非空量、最近更新时间。
// 用途:让「写入端有没有产数」可被机器读到(pattern 召回曾恒 0 而日志沉默)。
CountNodesByType(typ string) (total, withID int, lastUpdated string)
Prune(minWeight float64)
// 边枚举(供社区发现用)
+11
View File
@@ -56,6 +56,12 @@ type MemoryRecord struct {
// 历史列(deprecated),新代码不再读它(见 AC#3)。
HumanNotUsefulCount int `json:"human_not_useful_count"` // 用户人工点「没用」的次数
DedupDownweightCount int `json:"dedup_downweight_count"` // dedup/合并流程自动降权的次数
// A10 (t_d618dc7c):把「人工有用」从 UsefulCount(人工+机器混写)拆出单独计数。
// 指针类型:nil = NULL(存量行/从未被人工点过),非 nil = 真实整数。
// 统计口径用时分母必须 WHERE human_useful_count IS NOT NULL(NULL≠0)。
// 只有人工 feedback(/api/v1/feedback/useful → IncrementUseful)会 ++,机器自评/
// 蒸馏质量路径走别的方法(IncrementDedupDownweight/IncrementHumanNotUseful/...)不写此列。
HumanUsefulCount *int `json:"human_useful_count"` // nil=NULL(从未被人工点过);非 nil=真实计数
NotUsefulCount int `json:"not_useful_count"` // [DEPRECATED] 历史混写列,勿再读
Version int `json:"version"` // 当前版本号
VersionHistory []VersionRecord `json:"version_history,omitempty"` // 完整修改链
@@ -192,6 +198,11 @@ type RecallResult struct {
// 仅当 stale 标记开启(ZHIYI_STALE_AFTER_HOURS>0)且 updated_at 超期时为 true;
// 默认关闭 ⇒ 恒 false 且 omitempty 不输出 ⇒ 行为零变化(向后兼容)。
Stale bool `json:"stale,omitempty"`
// A10 (t_d618dc7c):把「人工有用」单独计数直通给调用方。此前 RecallResult 缺它 ⇒
// 插件/调用方读不到(t_4c810e02「加列不接 IPC=静默 no-op」同款坑)。
// nil=该条从未被人工点过(库里 NULL);非 nil=真实人工 useful 次数(NULL≠0)。
// 仅观测口径,不进排序(AC#6 排序零变化)。
HumanUsefulCount *int `json:"human_useful_count"`
}
// RerankResult rerank 重排后的单条结果。
+1 -1
View File
@@ -65,7 +65,7 @@ func (pp *PatternProvider) Match(query, namespace string, topK int) []models.Rec
if pp == nil || pp.store == nil || topK <= 0 {
return nil
}
pats, err := pp.store.ListPatterns(topK * 3) // 多取些再按相似度截断
pats, _, err := pp.store.ListPatterns(topK * 3) // 多取些再按相似度截断
if err != nil || len(pats) == 0 {
return nil
}
+229
View File
@@ -0,0 +1,229 @@
package pattern
import (
"database/sql"
"encoding/json"
"os"
"testing"
_ "modernc.org/sqlite"
"github.com/xiaoxue/memoryweave/internal/models"
"github.com/xiaoxue/memoryweave/internal/storage"
)
// ── t_bd63b641 影-复:PATTERN/PEER 开门量具(不碰生产;只读 graph.db + 实时 embedder)──
// 量化「开 ZHIYI_PATTERN_RECALL / ZHIYI_PEER_RECALL」对 14 金标会注入什么。
// Provider 装配在 server.go 启动期由 env 决定 ⇒ 不重启无法在活服务上测开态;
// 故本测试直接构造真实 Provider + 生产 graph.db(只读)+ 实时 bge embedder,
// 跑出「开态会注入的条目」,与关态(=主召回原样)对比。
//
// 本测试只读、不落盘、不改库(AC:不碰生产二进制/不重启)。
type logRecord struct {
ID string
Category string
Content string
}
// runShadowWithDiag 返回:注入结果 + 诊断(pattern 装载数 / query 是否编码成功 / 各 query 最高余弦)。
// ⚠️ 关键发现:生产 graph_nodes(type='pattern') 的 id 全为 NULL(85/85),ListPatterns 读 id 为 string
// ⇒ 恒报 sql: Scan error (converting NULL to string),Match 直接 return nil。
// 故 runShadow 不把 ListPatterns 错误当失败 —— 它本身就是「开态也无法注入」的根因证据。
func runShadowWithDiag() (map[string][]logRecord, int, string, map[string]float64) {
endpoint := os.Getenv("VLLM_ENDPOINT")
if endpoint == "" {
endpoint = "http://localhost:8000/v1/embeddings"
}
emb := storage.NewEmbedder(endpoint)
store := NewGraphPatternStore("/var/lib/memoryweave/graph.db")
pp := NewPatternProvider(store, NewEmbedderProvider(emb))
// 装载 pattern 数(防「store 空 → 注入恒 0」的假阴性);记录 ListPatterns 错误原文
pats, _, lerr := store.ListPatterns(1000)
loaded := 0
listErr := ""
if lerr != nil {
listErr = lerr.Error() // 根因:id 全 NULL → Scan error
} else {
loaded = len(pats)
}
golden := []string{
"织忆是什么", "织忆的图谱扩展机制是什么",
"织忆如何通过 E1 提取和 MMR 实现多样去重", "牧尘的偏好是什么",
"牧尘喜欢什么样的工作方式", "如何根据牧尘的偏好调整记忆检索策略",
"当前项目的技术栈是什么", "织忆项目有哪些核心组件",
"织忆和其他记忆系统相比有什么架构优势", "如何使用 recall 接口",
"织忆有哪些管理工具", "如何通过 API 扩展织忆功能",
"本地 llama 服务 8080 端口", "session-to-zhiyi.py 脚本名",
}
out := make(map[string][]logRecord)
maxCos := make(map[string]float64)
// 预编码 14 query(若编码失败会记 0,便于区分「没命中」vs「编码挂了」)
for _, q := range golden {
qv, eerr := emb.EncodeSingle(q)
if eerr != nil || len(qv) == 0 {
maxCos[q] = -1 // 编码失败标记
continue
}
// 逐个 pattern 算余弦,取最高(复现 Provider.Match 内部逻辑)
best := -1.0
for _, p := range pats {
rep := p.Data
if rep == "" {
rep = p.Name
}
text := rep
for _, tl := range p.Tools {
if tl != "" {
text += " " + tl
}
}
pv, perr := emb.EncodeSingle(text)
if perr != nil || len(pv) == 0 {
continue
}
s := cosineF32(qv, pv)
if s > best {
best = s
}
}
maxCos[q] = best
}
// 真注入(走 Provider.Match,同 server 路径)
for _, g := range golden {
pat := pp.Match(g, "hermes-main", 3) // server.go:902 topK=3
for _, r := range pat {
out[g] = append(out[g], logRecord{ID: r.ID, Category: r.Category, Content: r.Content})
}
}
return out, loaded, listErr, maxCos
}
// TestShadowPattern_Diff —— 开态 pattern 注入量化(只读生产库)
func TestShadowPattern_Diff(t *testing.T) {
out, loaded, listErr, maxCos := runShadowWithDiag()
t.Logf("PATTERNS_LOADED=%d (防假阴性:store 有货才会注入)", loaded)
if listErr != "" {
t.Logf("PATTERN_LISTERROR=%q — 根因:pattern 行 id 全 NULL ⇒ Provider.Match 恒 return nil", listErr)
}
queries := []string{
"织忆是什么", "织忆的图谱扩展机制是什么",
"织忆如何通过 E1 提取和 MMR 实现多样去重", "牧尘的偏好是什么",
"牧尘喜欢什么样的工作方式", "如何根据牧尘的偏好调整记忆检索策略",
"当前项目的技术栈是什么", "织忆项目有哪些核心组件",
"织忆和其他记忆系统相比有什么架构优势", "如何使用 recall 接口",
"织忆有哪些管理工具", "如何通过 API 扩展织忆功能",
"本地 llama 服务 8080 端口", "session-to-zhiyi.py 脚本名",
}
totalInjected := 0
for _, q := range queries {
mc := maxCos[q]
if mc < 0 {
t.Logf("[EMB-FAIL] %q → 编码失败(不计命中)", q)
}
if n := len(out[q]); n > 0 {
totalInjected += n
t.Logf("[INJECT] %q → %d pattern (maxcos=%.3f)", q, n, mc)
for _, r := range out[q] {
t.Logf(" id=%s cat=%s content=%s", r.ID, r.Category, trunc(r.Content, 60))
}
} else {
t.Logf("[NO-INJECT] %q → 0 pattern (maxcos=%.3f, 阈值=0.6)", q, mc)
}
}
b, _ := json.MarshalIndent(out, "", " ")
t.Logf("SHADOW_PATTERN_TOTAL_INJECTED=%d", totalInjected)
os.WriteFile("/tmp/shadow-pattern-inject.json", b, 0644)
t.Logf("raw json → /tmp/shadow-pattern-inject.json (%d bytes)", len(b))
}
func trunc(s string, n int) string {
if len(s) <= n {
return s
}
return s[:n] + "…"
}
// ── peer 侧:生产 graph.db 无 peers 表 ⇒ 开态无数据可注入 ──
func TestShadowPeer_NoTable(t *testing.T) {
db, err := peerOpenReadOnly("/var/lib/memoryweave/graph.db")
if err != nil {
t.Fatalf("open graph.db: %v", err)
}
defer db.Close()
var cnt int
err = db.QueryRow("SELECT count(*) FROM sqlite_master WHERE type='table' AND name='peers'").Scan(&cnt)
if err != nil {
t.Fatalf("query peers table existence: %v", err)
}
t.Logf("SHADOW_PEER_TABLE_EXISTS=%d (0 ⇒ 开态 peer 无数据可注入)", cnt)
}
// peerOpenReadOnly 只读开 sqlite(WAL 兼容),避免 peer.Store 的写路径。
func peerOpenReadOnly(path string) (*sql.DB, error) {
return sql.Open("sqlite", "file:"+path+"?mode=ro&_pragma=busy_timeout(5000)")
}
// ── 深度根因:即使修好 NULL-id,85 行 pattern 无 data/tools 键(只有 description),
// Match 只能 embed 命名键(如 "pattern:hermes-main:entity")⇒ 对金标余弦 < 0.6 阈值。
// 本测试量化「修好 NULL-id 后开态到底能注入几类金标」—— 证明开态收益仍≈0。
func TestShadowPattern_CosineIfIDFixed(t *testing.T) {
endpoint := os.Getenv("VLLM_ENDPOINT")
if endpoint == "" {
endpoint = "http://localhost:8000/v1/embeddings"
}
emb := storage.NewEmbedder(endpoint)
// 绕过 NULL-id 的 ListPatterns:只读 name + properties(非 NULL 列)
db, err := peerOpenReadOnly("/var/lib/memoryweave/graph.db")
if err != nil {
t.Fatalf("open: %v", err)
}
defer db.Close()
rows, _ := db.Query(`SELECT name, properties FROM graph_nodes WHERE type='pattern'`)
type patText struct{ name, text string }
var pats []patText
for rows.Next() {
var name, props string
if serr := rows.Scan(&name, &props); serr != nil {
continue
}
// 复现 Match 的 text 构造:rep=data(无→空) 回退 name;无 tools
text := name
pats = append(pats, patText{name, text})
}
rows.Close()
t.Logf("PATTERN_ROWS_LOADABLE_BYPASS_ID=%d", len(pats))
if len(pats) == 0 {
t.Skip("无 pattern 行可载(NULL-id 未修前本就 0 注入,已在 TestShadowPattern_Diff 覆盖)")
}
golden := []string{"织忆是什么", "牧尘的偏好是什么", "如何使用 recall 接口",
"本地 llama 服务 8080 端口", "织忆项目有哪些核心组件"}
for _, q := range golden {
qv, qerr := emb.EncodeSingle(q)
if qerr != nil || len(qv) == 0 {
t.Logf("[EMBFAIL] %q → %v", q, qerr)
continue
}
best, bestName := -1.0, ""
for _, p := range pats {
pv, perr := emb.EncodeSingle(p.text)
if perr != nil || len(pv) == 0 {
continue
}
s := cosineF32(qv, pv)
if s > best {
best, bestName = s, p.name
}
}
hit := best >= 0.6
t.Logf("COSINE_PROBE %q maxcos=%.4f hit=%v (thr=0.6) best=%s", q, best, hit, bestName)
}
}
// 防 unused 误报
var _ = models.RecallResult{}
+20 -9
View File
@@ -229,27 +229,35 @@ func (s *GraphPatternStore) GetPattern(id string) (Pattern, error) {
// ListPatterns 列出 graph_nodes(type='pattern'),按 occurrence_count 降序取 top N。
// 0 / 空库 → 空列表不报错(AC1)。
func (s *GraphPatternStore) ListPatterns(limit int) ([]Pattern, error) {
// 单行 NULL/空 id 不致全盘失败:跳过并计数(见 AC1 差错容忍)。
// 名空间 quarantine 排除(AC2:stat-template/单句主题不视为真 pattern)。
func (s *GraphPatternStore) ListPatterns(limit int) ([]Pattern, int, error) {
if limit <= 0 {
limit = 10
}
db, oerr := s.open()
if oerr != nil {
return nil, oerr
return nil, 0, oerr
}
rows, qerr := db.Query(`SELECT id, name, properties FROM graph_nodes WHERE type='pattern' LIMIT ?`, limit*3)
// 使用 COALESCE 防止 NULL 导致 Scan 错误;同时排除 quarantine 名空间(AC2)
rows, qerr := db.Query(`SELECT COALESCE(id,''), COALESCE(name,''), COALESCE(properties,'') FROM graph_nodes WHERE type='pattern' AND COALESCE(namespace,'') != 'quarantine' LIMIT ?`, limit*3)
if qerr != nil {
return nil, qerr
return nil, 0, qerr
}
defer rows.Close()
type raw struct {
ID, Name, Props string
}
var all []raw
var skipped int
for rows.Next() {
var r raw
if serr := rows.Scan(&r.ID, &r.Name, &r.Props); serr != nil {
return nil, serr
return nil, 0, serr
}
if r.ID == "" {
skipped++
continue
}
all = append(all, r)
}
@@ -271,9 +279,6 @@ func (s *GraphPatternStore) ListPatterns(limit int) ([]Pattern, error) {
if c, ok := props["confidence"].(float64); ok {
p.Confidence = c
}
if o, ok := props["occurrence_count"].(float64); ok {
_ = o
}
if ts, ok := props["source_tasks"].([]interface{}); ok {
for _, v := range ts {
if s2, ok := v.(string); ok {
@@ -288,6 +293,12 @@ func (s *GraphPatternStore) ListPatterns(limit int) ([]Pattern, error) {
}
}
}
// occurrence_count 已在 props 中,但 ListPatterns 不再使用它做排序
// 保留该字段以免反序列化时丢失(若后续代码仍需)
if o, ok := props["occurrence_count"].(float64); ok {
// 暂不使用,仅保留
_ = o
}
}
out = append(out, p)
}
@@ -298,5 +309,5 @@ func (s *GraphPatternStore) ListPatterns(limit int) ([]Pattern, error) {
if len(out) > limit {
out = out[:limit]
}
return out, nil
return out, skipped, nil
}
+3 -3
View File
@@ -19,8 +19,8 @@ func newTestStore(t *testing.T) *GraphPatternStore {
// TestStore_EmptyList —— 空库 ListPatterns → 0 条不报错(AC1 判据:SELECT count ≥0 不报错)。
func TestStore_EmptyList(t *testing.T) {
s := newTestStore(t)
got, err := s.ListPatterns(10)
ts := newTestStore(t)
got, _, err := ts.ListPatterns(10)
if err != nil {
t.Fatalf("空库 List 不应报错: %v", err)
}
@@ -60,7 +60,7 @@ func TestStore_UpsertCreate(t *testing.T) {
if created != 1 || updated != 0 {
t.Fatalf("新 pattern 应 created=1/updated=0,实际 %d/%d", created, updated)
}
listed, _ := s.ListPatterns(10)
listed, _, _ := s.ListPatterns(10)
if len(listed) != 1 {
t.Fatalf("应 1 条,实际 %d", len(listed))
}
+17 -4
View File
@@ -19,10 +19,17 @@ import (
)
// Local2BReasoner 用本地 2B 生成四层推理画像。
// env:LLM_ENDPOINT(默认 http://127.0.0.1:8081/v1/chat/completions)
//
// LLM_MODEL (默认 local/minicpm5-2b)
// env 查找顺序(2026-10-26 加前两项,起因 t_a5ef04a5):
//
// ZHIYI_PEER_LLM_ENDPOINT(peer 专用,优先)→ LLM_ENDPOINT → 默认 8081 本地 2B
// ZHIYI_PEER_LLM_MODEL (peer 专用,优先)→ LLM_MODEL → 默认 local/minicpm5-2b
// LLM_TIMEOUT (默认 120s)
//
// 为什么要 peer 专用变量:LLM_ENDPOINT 是**全进程共享**的(蒸馏 llm_judge、
// adversarial_audit、skillgen、consolidate client 都读它,见 server.go:230)。
// 把全局指向 8081 会把蒸馏从 agnes-2.5-flash 顺手降级成 2B;而 newapi(3000)
// 需要鉴权、本 reasoner 按设计不发 Authorization ⇒ 必然 401。故只给 peer 开专用口子。
type Local2BReasoner struct {
endpoint string
model string
@@ -32,11 +39,17 @@ type Local2BReasoner struct {
// NewLocal2BReasoner 读 env 构造本地 2B 推理器。
func NewLocal2BReasoner() *Local2BReasoner {
endpoint := os.Getenv("LLM_ENDPOINT")
endpoint := os.Getenv("ZHIYI_PEER_LLM_ENDPOINT")
if endpoint == "" {
endpoint = os.Getenv("LLM_ENDPOINT")
}
if endpoint == "" {
endpoint = "http://127.0.0.1:8081/v1/chat/completions"
}
model := os.Getenv("LLM_MODEL")
model := os.Getenv("ZHIYI_PEER_LLM_MODEL")
if model == "" {
model = os.Getenv("LLM_MODEL")
}
if model == "" {
model = "local/minicpm5-2b"
}
@@ -0,0 +1,53 @@
package selfoptimize
import "testing"
// 2026-10-26(t_da03e910 终审):把「计数器语义」和「t8 阈值可配」钉住。
//
// 背景:审计曾把 deprecated_per_day 当成率指标报「0 样本却 valid=None ⇒ 缺样本门」,
// 实为探针模型错配(计数器无分母)。真正的缺陷是:
// ① 0 无法区分「今天没淘汰」与「从来没统计过」→ 加 DeprecatedTotal;
// ② executor t8 硬编码 >5 且无视 Condition(配置写 0.1 从不生效)。
func TestRecordDeprecation_CountsBothTodayAndTotal(t *testing.T) {
oldToday, oldTotal := Dash.DeprecatedToday, Dash.DeprecatedTotal
defer func() { Dash.DeprecatedToday, Dash.DeprecatedTotal = oldToday, oldTotal }()
Dash.DeprecatedToday, Dash.DeprecatedTotal = 0, 100
Dash.RecordDeprecation()
Dash.RecordDeprecation()
if Dash.DeprecatedToday != 2 || Dash.DeprecatedTotal != 102 {
t.Fatalf("today=%d total=%d,期望 2/102:累计值必须跨天保留,日值才归零",
Dash.DeprecatedToday, Dash.DeprecatedTotal)
}
m := Dash.Metrics()
if v, ok := m["deprecated_total"]; !ok || v != 102 {
t.Fatalf("metrics 缺 deprecated_total 或值不对: %v (ok=%v)", v, ok)
}
// 计数器不该带 _samples/_valid(有分母才有样本门)
for _, k := range []string{"deprecated_samples", "deprecated_valid"} {
if _, bad := m[k]; bad {
t.Fatalf("计数器不应用率语义键 %s", k)
}
}
}
func TestTDecayCritical_ReadsConditionNotHardcode(t *testing.T) {
te := &TriggerExecutor{}
th := TriggerDef{ID: "t8", Type: TDecayCritical, Condition: 5.0, Enabled: true}
if te.evaluate(&th, map[string]float64{"deprecated_per_day": 4}) {
t.Fatal("4 条/天不应触发(阈值 5)")
}
if !te.evaluate(&th, map[string]float64{"deprecated_per_day": 6}) {
t.Fatal("6 条/天应触发(阈值 5)")
}
// 配置必须真的生效:把阈值调到 10,同样 6 条就不该触发。
th.Condition = 10.0
if te.evaluate(&th, map[string]float64{"deprecated_per_day": 6}) {
t.Fatal("Condition=10 时 6 条不该触发 —— 说明仍在用硬编码阈值")
}
}
+8 -2
View File
@@ -63,7 +63,10 @@ func makeTriggers() []*TriggerDef {
{ID: "t5", Type: TGapDetected, Condition: true, Action: "gap_fill", Cooldown: 5 * time.Minute, Enabled: true},
{ID: "t6", Type: TConflict, Condition: 3, Action: "conflict_muchen", Cooldown: 10 * time.Minute, Enabled: true},
{ID: "t7", Type: TVValueLow, Condition: 0.2, Action: "mem_review", Cooldown: 12 * time.Hour, Enabled: true},
{ID: "t8", Type: TDecayCritical, Condition: 0.1, Action: "archive_or_boost", Cooldown: 6 * time.Hour, Enabled: true},
// t8 的 Condition 是「当天废弃条数」阈值(计数器语义,不是率)。
// 2026-10-26:原先这里写 0.1 但判据函数硬编码 >5 —— 配置值从不被读取,
// 改配置也改不动行为。现改为 Condition: 5(与硬编码等价,行为不变)+ 判据读 t.Condition。
{ID: "t8", Type: TDecayCritical, Condition: 5.0, Action: "archive_or_boost", Cooldown: 6 * time.Hour, Enabled: true},
}
}
@@ -145,7 +148,10 @@ func (te *TriggerExecutor) evaluate(t *TriggerDef, metrics map[string]float64) b
v, ok := metrics["recall_usefulness_rate"]
return ok && !IsNA(v) && v < threshold
case TDecayCritical:
return metrics["deprecated_per_day"] > 5
// counter 语义:deprecated_per_day 是「当天废弃条数」,阈值同单位(条/天)。
threshold, _ := t.Condition.(float64)
v, ok := metrics["deprecated_per_day"]
return ok && v > threshold
}
return false
}
+37 -21
View File
@@ -45,15 +45,19 @@ func dashboardLocalPath() string {
// 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"`
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"`
// DeprecatedTotal 累计淘汰条数(不跨天归零)。
// 2026-10-26:加它的唯一理由是把「今天 0 条」和「从来没统计过」分开 ——
// 与 pattern 召回那次的教训同型:0 永远有两种含义,指标必须能自证是哪一种。
DeprecatedTotal int `json:"deprecated_total"`
DeprecatedDate string `json:"deprecated_date"` // deprecated_today 的归属日期(跨天归零用)
DistillLossSum float64 `json:"distill_loss_sum"`
DistillLossCount int `json:"distill_loss_count"`
@@ -101,6 +105,7 @@ func loadDashboardLocal() error {
Dash.CascadeFixedTotal = st.CascadeFixedTotal
Dash.TotalFixes = st.TotalFixes
Dash.DeprecatedToday = st.DeprecatedToday
Dash.DeprecatedTotal = st.DeprecatedTotal
if st.DeprecatedDate != todayStr() { // "今日"计数跨天归零(进程跨零点不重置,下次加载时纠正)
Dash.DeprecatedToday = 0
}
@@ -132,6 +137,7 @@ func (d *Dashboard) persistLocalLocked() {
CascadeFixedTotal: d.CascadeFixedTotal,
TotalFixes: d.TotalFixes,
DeprecatedToday: d.DeprecatedToday,
DeprecatedTotal: d.DeprecatedTotal,
DeprecatedDate: todayStr(),
DistillLossSum: d.DistillLossSum,
DistillLossCount: d.DistillLossCount,
@@ -174,7 +180,7 @@ func (d *Dashboard) persist() {
_ = redisPersistence.HSet(dashboardRedisKey, "auto_resolved_conflicts", strconv.Itoa(d.AutoResolvedConflicts))
_ = redisPersistence.HSet(dashboardRedisKey, "total_conflicts", strconv.Itoa(d.TotalConflicts))
_ = redisPersistence.HSet(dashboardRedisKey, "dashboard_schema_version", dashboardSchemaV2) // t_e5997ca4:v2 标记常驻回写
_ = redisPersistence.Expire(dashboardRedisKey, 90*24*time.Hour) // 90 天 TTL
_ = redisPersistence.Expire(dashboardRedisKey, 90*24*time.Hour) // 90 天 TTL
}
// loadDashboard 从 Redis 加载 Dashboard 数据
@@ -244,16 +250,19 @@ func loadDashboard() error {
// ─── 自优化仪表盘 ────────────────────────────────────────
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"`
DeprecatedToday int `json:"deprecated_today"`
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"`
// DeprecatedTotal 累计淘汰条数(不跨天归零)—— 与「今天 0 条」区分开,
// 因为 0 有两种含义:今天没淘汰 / 从来没统计。指标必须能自证是哪一种。
DeprecatedTotal int `json:"deprecated_total"`
DistillLossSum float64 `json:"distill_loss_sum"`
DistillLossCount int `json:"distill_loss_count"`
DistillSuccessCount int `json:"distill_success_count"`
@@ -316,7 +325,11 @@ func b2f(b bool) float64 {
// Metrics 返回核心指标。
//
// 比率项在分母退化时返回 metricNA(-1) 而非 1;每项比率都配 *_valid / *_samples。
// 计数项(deprecated_per_day)与均值项(avg_distill_loss)同规则。
//
// 计数项(deprecated_per_day / deprecated_total)**不配** *_samples / *_valid:
// 它们没有分母,「样本不足」对它们无定义(2026-10-26 更正:旧注释写作「与均值项
// avg_distill_loss 同规则」是错的 —— 均值项有分母,故有 samples/valid;审计脚本
// 曾据此对计数器报「0 样本」告警,属探针模型错配,不是指标缺陷)。
func (d *Dashboard) Metrics() map[string]float64 {
d.mu.RLock()
defer d.mu.RUnlock()
@@ -391,7 +404,9 @@ func (d *Dashboard) Metrics() map[string]float64 {
"auto_resolve_samples": float64(d.TotalConflicts),
"auto_resolve_valid": autoValid,
// counter 语义:无分母 ⇒ 不给 _samples/_valid(给了会诱导下游当率用)。
"deprecated_per_day": float64(d.DeprecatedToday),
"deprecated_total": float64(d.DeprecatedTotal),
"distill_success_count": float64(d.DistillSuccessCount),
"avg_distill_loss": lossVal,
@@ -922,6 +937,7 @@ func (d *Dashboard) RecordDeprecation() {
d.mu.Lock()
defer d.mu.Unlock()
d.DeprecatedToday++
d.DeprecatedTotal++
d.persist()
}
@@ -0,0 +1,323 @@
package storage
// t_23b6a940:FeedbackScore 把「热度」(recall_verified_count) 当「质量」的修复。
// 金标 119 条 A/B 实测:legacy(verified 1:1 进 pos)⇒ MRR -22.2%。
// 本文件钉死:① 门关 delta=0 ② 门开方向正确(none/weight/tiebreak)③ 反向对照
// (负向项恒定性)+ AC4(不读 deprecated not_useful_count)。
// 测试基建(fbVec/newFbBiasPipeline/fbRun/fbBiasLance)复用 recall_feedback_bias_test.go。
import (
"math"
"testing"
"github.com/xiaoxue/memoryweave/internal/models"
)
// satRef 手工复刻 2026-10-13 原始实现(pos=useful+verified, K=3),作 legacy 逐位基准。
func satRef(pos, neg float64) float64 {
sat := func(x float64) float64 {
if x <= 0 {
return 0
}
return x / (x + 3) // K 默认 3(测试环境无 ZHIYI_FEEDBACK_K)
}
return sat(pos) - sat(neg)
}
func legacyScore(uc, vc, nuc, dd int) float64 {
return satRef(float64(uc+vc), float64(nuc+dd))
}
// TestPosModeDefaultIsLegacy — env 未设/设非法值 ⇒ legacy;且 legacy 与 10-13 原始
// 实现逐位一致(含大计数 max=389 与中位 3 两档,金标实测的两个代表点)。
func TestPosModeDefaultIsLegacy(t *testing.T) {
t.Setenv("ZHIYI_POS_MODE", "")
if got := posMode(); got != "legacy" {
t.Fatalf("默认 posMode()=%q,want legacy", got)
}
t.Setenv("ZHIYI_POS_MODE", "BOGUS")
if got := posMode(); got != "legacy" {
t.Fatalf("非法值 posMode()=%q,want legacy(回落默认)", got)
}
t.Setenv("ZHIYI_POS_MODE", "")
cases := []struct {
name string
rec models.MemoryRecord
want float64
}{
{"hot max=389", models.MemoryRecord{RecallVerifiedCount: 389}, 389 / 392},
{"median=3", models.MemoryRecord{RecallVerifiedCount: 3}, 3.0 / 6},
{"useful+verified 混合", models.MemoryRecord{UsefulCount: 5, RecallVerifiedCount: 62}, 67 / 70},
{"全零", models.MemoryRecord{}, 0},
{"纯负向", models.MemoryRecord{HumanNotUsefulCount: 2}, -0.4},
}
for _, c := range cases {
t.Setenv("ZHIYI_POS_MODE", "legacy")
if got := FeedbackScore(&c.rec); math.Abs(got-legacyScore(c.rec.UsefulCount, c.rec.RecallVerifiedCount, c.rec.HumanNotUsefulCount, c.rec.DedupDownweightCount)) > 1e-12 {
t.Fatalf("%s: legacy FeedbackScore=%.10f 与 10-13 原始实现不一致(必须逐位等价)", c.name, got)
}
}
}
// TestFeedbackScorePosModes — 四态数值单测(K=3、w=0.05 默认):
// 热度从「近满分」压到「有界小增量」;负向项各态恒 −0.4(反向对照基线)。
func TestFeedbackScorePosModes(t *testing.T) {
t.Setenv("ZHIYI_POS_WEIGHT", "0.05")
m := func(uc, vc int) models.MemoryRecord {
return models.MemoryRecord{UsefulCount: uc, RecallVerifiedCount: vc, HumanNotUsefulCount: 2}
}
type want struct {
legacy, none, weight, tiebreak float64
}
cases := []struct {
name string
rec models.MemoryRecord
w want
}{
// 热度 max=389:legacy +0.9924(金标实测的硬顶值)⇒ none 0 / weight 0.8664 / tiebreak +0.0398(均再扣 neg=2 的 -0.4)
{"hot389", m(0, 389), want{
legacy: 389/392.0 - 0.4,
none: -0.4,
weight: (19.45) / (19.45 + 3.0) - 0.4,
tiebreak: 0.05*(389.0/489.0) - 0.4,
}},
// 热度中位=3:legacy +0.5 ⇒ none 0 / weight sat(0.15)=0.04762 / tiebreak 0.001456
{"median3", m(0, 3), want{
legacy: 0.5 - 0.4,
none: -0.4,
weight: (0.15 / 3.15) - 0.4,
tiebreak: 0.05*(3.0/103.0) - 0.4,
}},
// 纯质量(useful=2、热度=0):四态同值(质量信号不受修法影响)
{"pure_quality", m(2, 0), want{
legacy: 0.4 - 0.4,
none: 0.4 - 0.4,
weight: 0.4 - 0.4,
tiebreak: 0.4 - 0.4,
}},
}
for _, mode := range []string{"legacy", "none", "weight", "tiebreak"} {
t.Setenv("ZHIYI_POS_MODE", mode)
for _, c := range cases {
var got float64
switch mode {
case "legacy":
got = legacyScore(c.rec.UsefulCount, c.rec.RecallVerifiedCount, 2, 0)
got = FeedbackScore(&c.rec) // 双校验:函数实值 == 手工 legacy 公式
default:
got = FeedbackScore(&c.rec)
}
var w float64
switch mode {
case "legacy":
w = c.w.legacy
case "none":
w = c.w.none
case "weight":
w = c.w.weight
case "tiebreak":
w = c.w.tiebreak
}
if math.Abs(got-w) > 1e-9 {
t.Fatalf("%s@%s: got=%.10f want=%.10f", c.name, mode, got, w)
}
}
}
// 跨态单调性(热度大值):legacy > weight > tiebreak > none
hot := m(0, 389)
for _, mode := range []string{"legacy", "weight", "tiebreak", "none"} {
t.Setenv("ZHIYI_POS_MODE", mode)
_ = FeedbackScore(&hot)
}
vals := map[string]float64{}
for _, mode := range []string{"legacy", "weight", "tiebreak", "none"} {
t.Setenv("ZHIYI_POS_MODE", mode)
vals[mode] = FeedbackScore(&hot)
}
if !(vals["legacy"] > vals["weight"] && vals["weight"] > vals["tiebreak"] && vals["tiebreak"] > vals["none"]) {
t.Fatalf("热度大值跨态单调性不成立: %v(want legacy>weight>tiebreak>none)", vals)
}
// AC4:deprecated 混写列 not_useful_count 任何模式都不读(GA-P0-1 已拆)——
// 只改 NotUsefulCount、其余字段(含 neg=2)相同的两条记录,四态 score 必须恒等。
// (四态全覆盖见 TestPosModeNegUnchanged;此处显式钉 legacy 默认态)
t.Setenv("ZHIYI_POS_MODE", "")
zeroRec := m(0, 0) // neg=2
base := FeedbackScore(&zeroRec)
depr := models.MemoryRecord{UsefulCount: 0, RecallVerifiedCount: 0, HumanNotUsefulCount: 2, NotUsefulCount: 99}
if got := FeedbackScore(&depr); math.Abs(got-base) > 1e-12 {
t.Fatalf("AC4 违反:只改 NotUsefulCount(99) 不应改变 FeedbackScore(base=%.4f got=%.4f),不得读 deprecated 列", base, got)
}
}
// TestPosGateClosedZeroDelta — AC3 判据①(门关 delta=0):
// ZHIYI_FEEDBACK_BIAS=0(生产现状)⇒ 偏置循环不执行 ⇒ 四种 POS_MODE 下召回
// 位次/分数逐位相同(门控逐位等价,模式切换零行为变化)。
func TestPosGateClosedZeroDelta(t *testing.T) {
oldBias := feedbackBias
feedbackBias = 0 // 生产现状 zhiyid.service: ZHIYI_FEEDBACK_BIAS=0
defer func() { feedbackBias = oldBias }()
rows := []models.MemoryRecord{
{ID: "m0", Content: "记忆甲 完全无关内容一", Category: "distilled", Source: "llm_distill", Vector: fbVec(0.95), RecallVerifiedCount: 389},
{ID: "m1", Content: "记忆乙 完全无关内容二", Category: "distilled", Source: "llm_distill", Vector: fbVec(0.90), UsefulCount: 2},
{ID: "m2", Content: "记忆丙 完全无关内容三", Category: "distilled", Source: "llm_distill", Vector: fbVec(0.85), RecallVerifiedCount: 3, HumanNotUsefulCount: 2},
{ID: "m3", Content: "记忆丁 完全无关内容四", Category: "distilled", Source: "llm_distill", Vector: fbVec(0.80)},
{ID: "m4", Content: "记忆戊 完全无关内容五", Category: "distilled", Source: "llm_distill", Vector: fbVec(0.75)},
}
var baseline map[string][2]float64
for i, mode := range []string{"", "none", "weight", "tiebreak"} {
t.Setenv("ZHIYI_POS_MODE", mode)
got := fbRun(t, rows)
if baseline == nil {
baseline = got
t.Logf("门关(bias=0) @%q 基准: m0(pos=%.0f,sc=%.4f) m1(pos=%.0f,sc=%.4f)",
mode, got["m0"][0], got["m0"][1], got["m1"][0], got["m1"][1])
continue
}
for id, b := range baseline {
a, ok := got[id]
if !ok {
t.Fatalf("门关时 @mode=%q 结果集合变了:%s 消失", mode, id)
}
if a[0] != b[0] || a[1] != b[1] {
t.Fatalf("AC3① 违反:bias=0 时 %s 模式位次/分数必须逐位相同(delta=0):before=(pos %.0f sc %.6f) @%s=(pos %.0f sc %.6f)",
id, b[0], b[1], mode, a[0], a[1])
}
}
_ = i
}
}
// TestPosModeNoneFlipsHeatWinner — AC3 判据②(门开方向正确):
// BIAS=1 时,legacy 下「热度 389、质量 0」的 hot 硬顶 rank1(金标 -22% 的机制);
// none 模式把它拆出去 ⇒ 质量信号(useful=2)的 good 反超 hot。方向翻转即修复生效。
func TestPosModeNoneFlipsHeatWinner(t *testing.T) {
oldBias := feedbackBias
feedbackBias = 1.0
defer func() { feedbackBias = oldBias }()
hot := func() []models.MemoryRecord {
return []models.MemoryRecord{
{ID: "hot", Content: "热门记忆 高频被召回", Category: "distilled", Source: "llm_distill", Vector: fbVec(0.90), RecallVerifiedCount: 389},
{ID: "good", Content: "优质记忆 人工认可", Category: "distilled", Source: "llm_distill", Vector: fbVec(0.88), UsefulCount: 2},
{ID: "p0", Content: "填充记忆 零", Category: "distilled", Source: "llm_distill", Vector: fbVec(0.60)},
{ID: "p1", Content: "填充记忆 一", Category: "distilled", Source: "llm_distill", Vector: fbVec(0.55)},
{ID: "p2", Content: "填充记忆 二", Category: "distilled", Source: "llm_distill", Vector: fbVec(0.50)},
}
}
// 对照臂:legacy(默认)门开 ⇒ hot rank1(复现金标 -22% 的机制)
t.Setenv("ZHIYI_POS_MODE", "")
legacy := fbRun(t, hot())
if legacy["hot"][0] > legacy["good"][0] {
t.Fatalf("对照臂异常:legacy 门开时 hot(热度389) 应压住 good(质量2),got hot pos=%.0f good pos=%.0f", legacy["hot"][0], legacy["good"][0])
}
t.Logf("对照臂 legacy: hot pos=%.0f (sc %.4f) 压住 good pos=%.0f (sc %.4f) —— 金标 -22%% 机制复现",
legacy["hot"][0], legacy["hot"][1], legacy["good"][0], legacy["good"][1])
// 修复臂:none ⇒ good 反超 hot
t.Setenv("ZHIYI_POS_MODE", "none")
none := fbRun(t, hot())
if none["good"][0] >= none["hot"][0] {
t.Fatalf("AC3② 违反:none 模式 good(useful=2) 应反超 hot(热度389),got good pos=%.0f hot pos=%.0f", none["good"][0], none["hot"][0])
}
// 填充行不受影响(方向正确 = 只动热度项,不动质量/负向)
for _, id := range []string{"p0", "p1", "p2"} {
if none[id][1] != legacy[id][1] {
t.Fatalf("填充行 %s 分数被误伤:legacy=%.6f none=%.6f", id, legacy[id][1], none[id][1])
}
}
t.Logf("修复臂 none: good pos=%.0f (sc %.4f) 反超 hot pos=%.0f (sc %.4f);填充行分数逐位不变 ✓",
none["good"][0], none["good"][1], none["hot"][0], none["hot"][1])
}
// TestPosModeTiebreakWithinClass — AC1 tiebreak 候选:热度增量有界(< w·1 = 0.05),
// 同档内保留热度顺序、不能跨档翻案;none 对照 = 热度零影响。
// 注:fbVec 只设 v[0],全部文档与查询同向 ⇒ cosine 恒 1 ⇒ 位次靠 tie-break;
// 这里用 fbVec2 给文档不同方向(cos(q=e0, (a,b)) = a/√(a²+b²))制造真实向量差。
func TestPosModeTiebreakWithinClass(t *testing.T) {
fbVec2 := func(v0, v1 float32) []float32 {
v := make([]float32, 1024)
v[0], v[1] = v0, v1
return v
}
oldBias := feedbackBias
feedbackBias = 1.0
defer func() { feedbackBias = oldBias }()
// 同档:warm cos=0.9138 > hot cos=0.8924(差 0.021 = 同相关性档),热度差 389 vs 3
// 跨档:low cos=0.4061;填充 p1/p2 cos≈0.32/0.20
rows := []models.MemoryRecord{
{ID: "hot", Content: "热门同档 高频被召回", Category: "distilled", Source: "llm_distill", Vector: fbVec2(0.89, 0.45), RecallVerifiedCount: 389},
{ID: "warm", Content: "微热同档 偶尔被召回", Category: "distilled", Source: "llm_distill", Vector: fbVec2(0.90, 0.40), RecallVerifiedCount: 3},
{ID: "low", Content: "低档填充", Category: "distilled", Source: "llm_distill", Vector: fbVec2(0.40, 0.90)},
{ID: "p1", Content: "填充记忆 一", Category: "distilled", Source: "llm_distill", Vector: fbVec2(0.30, 0.90)},
{ID: "p2", Content: "填充记忆 二", Category: "distilled", Source: "llm_distill", Vector: fbVec2(0.20, 0.98)},
}
// none 对照:同档两条 bias 恒 0 ⇒ 顺序 = 纯向量序(warm 0.90 > hot 0.89)
t.Setenv("ZHIYI_POS_MODE", "none")
noneRes := fbRun(t, rows)
if noneRes["warm"][0] > noneRes["hot"][0] {
t.Fatalf("none 对照异常:同档无热度差时应按向量序 warm(0.90) 在 hot(0.89) 前,got warm pos=%.0f hot pos=%.0f", noneRes["warm"][0], noneRes["hot"][0])
}
// tiebreak:hot 的热度小增量把它抬到 warm 之上(同档内热度序保留),
// 但增量有界(0.05·sat(389,100)≈0.040 < 跨档向量差 0.145)⇒ low 不得翻案进同档上方
t.Setenv("ZHIYI_POS_MODE", "tiebreak")
tb := fbRun(t, rows)
if tb["hot"][0] > tb["warm"][0] {
t.Fatalf("AC1 tiebreak 违反方向:同档内热度更高者应占优(hot 389 > warm 3),got hot pos=%.0f warm pos=%.0f", tb["hot"][0], tb["warm"][0])
}
if tb["low"][0] < tb["warm"][0] || tb["low"][0] < tb["hot"][0] {
t.Fatalf("AC1 tiebreak 违反有界性:热度小增量(<0.05)不得把低档 low(0.75) 翻案进同档(0.89/0.90) 上方:low pos=%.0f", tb["low"][0])
}
// 增量有界的数值核验(对 FeedbackScore 直接断言,不经 rerank)
t.Setenv("ZHIYI_POS_MODE", "tiebreak")
hotRow := &rows[0]
warmRow := &rows[1]
delta := FeedbackScore(hotRow) - FeedbackScore(warmRow) // 含 bias 系数 1.0
if delta <= 0 {
t.Fatalf("tiebreak 同档热度差应产生正增量:hot−warm=%.6f", delta)
}
if delta > 0.05 {
t.Fatalf("AC1 tiebreak 违反有界性:增量 %.4f 超过 w=0.05 上限(大-K 饱和设计目标)", delta)
}
t.Logf("AC1 tiebreak: 同档增量 hot−warm=%.4f (∈(0, 0.05],有界);none 对照=纯向量序;low 未翻案 ✓", delta)
}
// TestPosModeNegUnchanged — AC3 判据③(反向对照)+ AC4:
// 负向项(human_not_useful)在四种模式下逐位不变(修复只动 pos,不碰 neg 方向);
// 且任何模式都不读 deprecated NotUsefulCount。
func TestPosModeNegUnchanged(t *testing.T) {
oldBias := feedbackBias
feedbackBias = 1.0
defer func() { feedbackBias = oldBias }()
rows := []models.MemoryRecord{
{ID: "bad", Content: "被否定记忆 内容", Category: "distilled", Source: "llm_distill", Vector: fbVec(0.90), HumanNotUsefulCount: 2, NotUsefulCount: 7},
{ID: "clean", Content: "干净记忆 内容", Category: "distilled", Source: "llm_distill", Vector: fbVec(0.88)},
{ID: "p0", Content: "填充记忆 零", Category: "distilled", Source: "llm_distill", Vector: fbVec(0.60)},
{ID: "p1", Content: "填充记忆 一", Category: "distilled", Source: "llm_distill", Vector: fbVec(0.55)},
{ID: "p2", Content: "填充记忆 二", Category: "distilled", Source: "llm_distill", Vector: fbVec(0.50)},
}
wantNeg := float64(0) - 2.0/5.0 // -sat(2,3) = -0.4,四态同值
for _, mode := range []string{"", "none", "weight", "tiebreak"} {
t.Setenv("ZHIYI_POS_MODE", mode)
got := fbRun(t, rows)
if cleanPos, badPos := got["clean"][0], got["bad"][0]; cleanPos > badPos {
t.Fatalf("AC3③ 违反:neg 方向在模式 %q 下失效 —— clean(pos=%.0f) 未压住 bad(pos=%.0f)", mode, cleanPos, badPos)
}
_ = wantNeg
}
// 数值层:bad 行(verified=0,只有 neg)四态 FeedbackScore 必须逐位 == -0.4
for _, mode := range []string{"", "none", "weight", "tiebreak"} {
t.Setenv("ZHIYI_POS_MODE", mode)
badRow := &rows[0]
if got := FeedbackScore(badRow); math.Abs(got-wantNeg) > 1e-12 {
t.Fatalf("AC3③/AC4 违反:模式 %q 下 neg 项不恒定:bad score=%.10f want=%.10f(含 NotUsefulCount=7 干扰项仍必须 == -0.4)", mode, got, wantNeg)
}
}
t.Logf("AC3③ 反向对照: bad(human_not_useful=2, NotUsefulCount=7 干扰) 四态 score 恒 -0.4、位次恒被 clean 压住 ✓")
}
+62 -6
View File
@@ -1,11 +1,50 @@
package storage
import "github.com/xiaoxue/memoryweave/internal/models"
import (
"os"
"strings"
"github.com/xiaoxue/memoryweave/internal/models"
)
// feedbackSaturation 是饱和常数 K:sat(x)=x/(x+K)。
// 计数无上界(可被反复标记),必须压进 [0,1) 才能当加性偏置用。
var feedbackSaturation = envFloat("ZHIYI_FEEDBACK_K", 3)
// ── t_23b6a940:热度信号 recall_verified_count 如何进入正向质量项 ──
//
// 金标 119 条 A/B 实测(本卡卡体):legacy(verified 直入 pos)下 7413 条非零
// verified(max=389、中位 3)拿到近满分偏置(最大 +0.9924),热门记忆硬顶 rank1、
// 挤掉真正相关的 ⇒ MRR -22.2% / NDCG -17.7%(「热门≠正确」,与 t_34ec2b1f
// 「新鲜≠正确」同一族病:单一易得信号冒充质量)。
//
// 修法 = 把「热度」从质量项里拆出去,env ZHIYI_POS_MODE 切换(默认 legacy =
// 与当前生产逐位一致;回滚 = 置回 legacy 或 ZHIYI_FEEDBACK_BIAS=0,零代码变更):
//
// legacy = 现状(verified 1:1 进 pos,金标实测 -22%,仅作对照臂)
// none = 移除 verified,pos = useful_count(热度不是质量;MoA 复核行动①)
// weight = 独立小权重:pos = useful + w·verified,w=ZHIYI_POS_WEIGHT(默认 0.05)
// tiebreak = 纯 tiebreak(MoA 复核行动②):质量项只算 useful;verified 走独立
// 大 K(posTiebreakK=100) 饱和 × 小权重 w ⇒ 中位 v=3 ⇒ +0.0015、
// v=389 ⇒ +0.040,只在同相关性档内做有界增量、不能跨档
//
// 负向项(human_not_useful + dedup_downweight)与模式无关、恒定性,
// 各模式间逐位不变(反向对照判据)。
func posMode() string {
switch strings.ToLower(os.Getenv("ZHIYI_POS_MODE")) {
case "none", "weight", "tiebreak", "legacy":
return strings.ToLower(os.Getenv("ZHIYI_POS_MODE"))
default:
return "legacy" // 默认 = 与当前生产逐位一致
}
}
// posWeight 热度项权重(仅 weight/tiebreak 模式生效)。每次调用读 env,测试可 t.Setenv 翻转。
func posWeight() float64 { return envFloat("ZHIYI_POS_WEIGHT", 0.05) }
// posTiebreakK tiebreak 档独立饱和常数:verified=389 ⇒ sat≈0.80,×w(默认0.05) ⇒ 增量上限 +0.040。
const posTiebreakK = 100.0
// FeedbackScore 把 per-memory 反馈计数压成有界双向分 ∈ (-1, 1)。
//
// 设计(2026-10-13):排序此前只读 V 值(VValueProvider),而 V 值轴被 ep_*
@@ -13,8 +52,13 @@ var feedbackSaturation = envFloat("ZHIYI_FEEDBACK_K", 3)
// 本函数改读 DB 计数(干净、per-memory、双向),由 recall.go 以 env 门控
// 加性偏置的形式接入排序(ZHIYI_FEEDBACK_BIAS,默认 0 = 关闭)。
//
// 2026-10-18 (t_23b6a940):正向项按 ZHIYI_POS_MODE 分四态(见上方注释);
// legacy 态与 2026-10-13 原始实现**逐位一致**(verified 1:1 进 pos)——
// 该态已被金标 A/B 证明把「热度」当「质量」(MRR -22%),保留只为对照臂
// 与零变更回滚基线。
//
// 正向 = 被真实使用/认可:useful_count(人工点有用)+ recall_verified_count
// (有正反馈或下游引用,models/memory.go:69 定义的唯一正信号)。
// (legacy 态 1:1 计入;none/weight/tiebreak 态按 ZHIYI_POS_MODE 处理)。
// 负向 = 被真实否定/取代:human_not_useful_count(人工点没用)+
// dedup_downweight_count(去重降权)。
// 注意 not_useful_count 是 deprecated 混写列(GA-P0-1 已拆),本函数不读它。
@@ -22,13 +66,25 @@ func FeedbackScore(m *models.MemoryRecord) float64 {
if m == nil {
return 0
}
pos := float64(m.UsefulCount + m.RecallVerifiedCount)
useful := float64(m.UsefulCount)
verified := float64(m.RecallVerifiedCount)
neg := float64(m.HumanNotUsefulCount + m.DedupDownweightCount)
sat := func(x float64) float64 {
sat := func(x, k float64) float64 {
if x <= 0 {
return 0
}
return x / (x + feedbackSaturation)
return x / (x + k)
}
switch posMode() {
case "none":
return sat(useful, feedbackSaturation) - sat(neg, feedbackSaturation)
case "weight":
return sat(useful+posWeight()*verified, feedbackSaturation) - sat(neg, feedbackSaturation)
case "tiebreak":
return sat(useful, feedbackSaturation) - sat(neg, feedbackSaturation) +
posWeight()*sat(verified, posTiebreakK)
default: // legacy — 与 2026-10-13 实现逐位一致(pos = useful+verified)
pos := useful + verified
return sat(pos, feedbackSaturation) - sat(neg, feedbackSaturation)
}
return sat(pos) - sat(neg)
}
+4
View File
@@ -156,6 +156,10 @@ func (c *cachedGraphStore) AllEdges(namespace string) []governance.GraphEdge {
return c.inner.AllEdges(namespace)
}
func (c *cachedGraphStore) Stats() (int, int, float64) { return c.inner.Stats() }
func (c *cachedGraphStore) CountNodesByType(typ string) (int, int, string) {
return c.inner.CountNodesByType(typ)
}
func (c *cachedGraphStore) Prune(minWeight float64) { c.inner.Prune(minWeight) }
func (c *cachedGraphStore) ExpandFromResults(results []models.RecallResult, namespace string, maxHops int) []models.RecallResult {
return c.inner.ExpandFromResults(results, namespace, maxHops)
@@ -0,0 +1,137 @@
package storage_test
// human_useful_count_e2e_test.go — t_d618dc7c A10 人工有用列端到端回归闸门
//
// 为什么必须存在(防重犯 t_4c810e02 静默 no-op):加了列但 Go 读侧解包缺字段 / 输出映射缺行
// ⇒ 列真实写进 LanceDB,但 /recall、/memories 读出来恒 null(无报错、数值逐位不变)。
// 本测试经**真实 sidecar(Rust LanceDB)写→读回**,断言 human_useful_count 非空且等于写入值:
//
// AC#4 读非空:InsertMemory 后 Search 读回,从未人工点过 = nil;IncrementUseful×2 = 2。
// AC#5 反例 :机器 dedup/降权路径(IncrementDedupDownweight)跑后 human_useful_count 不变;
// 人工 not-useful(IncrementHumanNotUseful)只动 human_not_useful_count,不动本列。
//
// 跑法(需先起 sidecar;未设环境变量自动跳过,可安全留在 CI):
// zhiyi-consolidate --mode socket --socket /tmp/mw-huc.sock --data-dir /tmp/mw-hucdata
// ZHIYI_HUC_E2E_SOCK=/tmp/mw-huc.sock go test -run TestHumanUsefulCountE2E -v ./internal/storage/
import (
"os"
"testing"
"time"
"github.com/xiaoxue/memoryweave/internal/models"
"github.com/xiaoxue/memoryweave/internal/storage"
)
func TestHumanUsefulCountE2E(t *testing.T) {
sock := os.Getenv("ZHIYI_HUC_E2E_SOCK")
if sock == "" {
t.Skip("ZHIYI_HUC_E2E_SOCK 未设置,跳过(需要 sidecar 在跑)")
}
const ns = "huc-go-e2e"
rc := storage.NewRustLanceDBClient(sock, nil)
vec := make([]float32, 1024)
for i := range vec {
vec[i] = 0.05
}
now := time.Now().UTC()
// 读回:用 ScanAll(embedded model,useful_count 与 human_useful_count 都在),
// Search 路径不投影 useful_count(历史缺口,非本卡范围)⇒ 断言两者同步得走 ScanAll。
read := func(id string) *models.MemoryRecord {
rows, err := rc.ScanAll()
if err != nil {
t.Fatalf("ScanAll 失败: %v", err)
}
for i := range rows {
if rows[i].ID == id {
return &rows[i]
}
}
return nil
}
// ── AC#4:读非空 —— 从未人工点过的存量行 human_useful_count 必须读回 nil(NULL,非 0)──
t.Run("AC4_存量行读回NULL", func(t *testing.T) {
m := models.MemoryRecord{
ID: "huc-e2e-null", AgentID: "hermes-a06", Namespace: ns,
Content: "huc-e2e 从未人工点过样本", Category: "test", Vector: vec,
Tier: "normal", Importance: 1.0, QualityScore: 0.5,
Version: 1, Freshness: "fresh", EmbeddingModel: "bge-m3",
Source: "wiki:/tmp/huc-e2e.md", CreatedAt: now, UpdatedAt: now,
}
if err := rc.InsertMemory(m); err != nil {
t.Fatalf("InsertMemory huc-e2e-null 失败: %v", err)
}
got := read("huc-e2e-null")
if got == nil {
t.Fatalf("✗ 读不回 huc-e2e-null(写入链路断)")
}
if got.HumanUsefulCount != nil {
t.Fatalf("✗ AC4: 存量行 human_useful_count 应为 nil(NULL),got=%d(读侧解包/映射未接好或误填 0)", *got.HumanUsefulCount)
}
t.Log("✅ AC4: 存量行 human_useful_count 读回 = nil(NULL≠0 语义成立)")
})
// ── AC#4 + AC#5:人工 useful ×2 ⇒ human_useful_count nil→1→2 且 useful_count 同步 +2 ──
t.Run("AC5_人工useful两次同步+2", func(t *testing.T) {
m := models.MemoryRecord{
ID: "huc-e2e-inc", AgentID: "hermes-a06", Namespace: ns,
Content: "huc-e2e 连续人工点有用样本", Category: "test", Vector: vec,
Tier: "normal", Importance: 1.0, QualityScore: 0.5,
Version: 1, Freshness: "fresh", EmbeddingModel: "bge-m3",
Source: "wiki:/tmp/huc-e2e.md", CreatedAt: now, UpdatedAt: now,
}
if err := rc.InsertMemory(m); err != nil {
t.Fatalf("InsertMemory huc-e2e-inc 失败: %v", err)
}
if err := rc.IncrementUseful("huc-e2e-inc"); err != nil {
t.Fatalf("IncrementUseful #1 失败: %v", err)
}
g1 := read("huc-e2e-inc")
if g1 == nil {
t.Fatalf("读不回 huc-e2e-inc")
}
if g1.HumanUsefulCount == nil || *g1.HumanUsefulCount != 1 {
t.Fatalf("✗ AC5: 第 1 次人工 useful 后 human_useful_count 应 nil→1,got=%v", g1.HumanUsefulCount)
}
if err := rc.IncrementUseful("huc-e2e-inc"); err != nil {
t.Fatalf("IncrementUseful #2 失败: %v", err)
}
g2 := read("huc-e2e-inc")
if g2 == nil {
t.Fatalf("读不回 huc-e2e-inc (#2)")
}
if g2.HumanUsefulCount == nil || *g2.HumanUsefulCount != 2 {
t.Fatalf("✗ AC5: 第 2 次人工 useful 后 human_useful_count 应=2,got=%v(读非空失败=静默 no-op)", g2.HumanUsefulCount)
}
if g2.UsefulCount != 2 {
t.Fatalf("✗ AC5: useful_count 应与人工 useful 同步 =2,got=%d", g2.UsefulCount)
}
t.Logf("✅ AC5: 人工 useful ×2 ⇒ human_useful_count=%d useful_count=%d(同步、读非空)", *g2.HumanUsefulCount, g2.UsefulCount)
// ── 反例:机器 dedup 降权路径跑一次 ⇒ human_useful_count 不变(仍 2)──
if err := rc.IncrementDedupDownweight("huc-e2e-inc"); err != nil {
t.Fatalf("IncrementDedupDownweight 失败: %v", err)
}
g3 := read("huc-e2e-inc")
if g3.HumanUsefulCount == nil || *g3.HumanUsefulCount != 2 {
t.Fatalf("✗ AC5反例: 机器 dedup 路径不得污染 human_useful_count,want 2 got=%v", g3.HumanUsefulCount)
}
if g3.DedupDownweightCount != 1 {
t.Fatalf("机器 dedup 路径 dedup_downweight_count 应 +1,got=%d", g3.DedupDownweightCount)
}
// ── 人工 not-useful ⇒ human_not_useful_count +1,本列不变 ──
if err := rc.IncrementHumanNotUseful("huc-e2e-inc"); err != nil {
t.Fatalf("IncrementHumanNotUseful 失败: %v", err)
}
g4 := read("huc-e2e-inc")
if g4.HumanUsefulCount == nil || *g4.HumanUsefulCount != 2 {
t.Fatalf("✗ AC5反例: 人工 not-useful 不得动 human_useful_count,want 2 got=%v", g4.HumanUsefulCount)
}
if g4.HumanNotUsefulCount != 1 {
t.Fatalf("人工 not-useful 应 human_not_useful_count +1,got=%d", g4.HumanNotUsefulCount)
}
t.Logf("✅ AC5反例: 机器dedup + 人工not-useful 后 human_useful_count 仍=2(隔离成立)")
})
}
@@ -0,0 +1,80 @@
package storage
import "testing"
// TestHumanUsefulCountIsolation — A10 (t_d618dc7c) AC#3 反例测试
//
// 证明「只有人工 useful 才 +1 human_useful_count;机器自评/蒸馏质量路径不写此列」:
//
// 人工 useful ⇒ useful_count+1 且 human_useful_count+1 **同时发生**(同一次 IncrementUseful)
// 机器自评/降权(IncrementDedupDownweight / IncrementHumanNotUseful)⇒ human_useful_count 不变
//
// 用相对增量断言(绝对值会被其它路径干扰)。起点设 human_useful_count = nil(模拟
// 迁移后「从未被人工点过」的存量/NULL 行),验证首次人工 useful 从 NULL 起 +1 ⇒ 1。
func TestHumanUsefulCountIsolation(t *testing.T) {
mlc := NewMemLanceClient(nil)
mlc.mu.Lock()
// 起点:useful_count=0,human_useful_count=nil(NULL 存量语义),其它计数 0
mlc.memories["mem_huc_1"] = &memEntry{ID: "mem_huc_1", HumanUsefulCount: nil}
mlc.mu.Unlock()
e := mlc.memories["mem_huc_1"]
// ── 人工 useful ×2 ⇒ useful_count+2 且 human_useful_count nil→1→2 同时发生 ──
if err := mlc.IncrementUseful("mem_huc_1"); err != nil {
t.Fatalf("IncrementUseful #1 err: %v", err)
}
if e.UsefulCount != 1 {
t.Fatalf("人工 useful#1:useful_count 相对增量 +1,want 1 got %d", e.UsefulCount)
}
if e.HumanUsefulCount == nil || *e.HumanUsefulCount != 1 {
got := -1
if e.HumanUsefulCount != nil {
got = *e.HumanUsefulCount
}
t.Fatalf("人工 useful#1:human_useful_count NULL→1,want 1 got %d (nil=%v)", got, e.HumanUsefulCount == nil)
}
if err := mlc.IncrementUseful("mem_huc_1"); err != nil {
t.Fatalf("IncrementUseful #2 err: %v", err)
}
if e.UsefulCount != 2 || e.HumanUsefulCount == nil || *e.HumanUsefulCount != 2 {
huc := -1
if e.HumanUsefulCount != nil {
huc = *e.HumanUsefulCount
}
t.Fatalf("人工 useful#2:want useful=2 human=%d got useful=%d human=%d", 2, e.UsefulCount, huc)
}
// ── 反例:机器自评/dedup 降权路径 ⇒ human_useful_count 不变(仍 2),useful_count 不变 ──
if err := mlc.IncrementDedupDownweight("mem_huc_1"); err != nil {
t.Fatalf("IncrementDedupDownweight err: %v", err)
}
if e.HumanUsefulCount == nil || *e.HumanUsefulCount != 2 {
got := -1
if e.HumanUsefulCount != nil {
got = *e.HumanUsefulCount
}
t.Fatalf("机器 dedup 路径不得污染 human_useful_count,want 2 got %d", got)
}
if e.UsefulCount != 2 {
t.Fatalf("机器 dedup 路径不得污染 useful_count,want 2 got %d", e.UsefulCount)
}
if e.DedupDownweightCount != 1 {
t.Fatalf("dedup_downweight_count 相对增量 +1,want 1 got %d", e.DedupDownweightCount)
}
if err := mlc.IncrementHumanNotUseful("mem_huc_1"); err != nil {
t.Fatalf("IncrementHumanNotUseful err: %v", err)
}
if e.HumanUsefulCount == nil || *e.HumanUsefulCount != 2 {
got := -1
if e.HumanUsefulCount != nil {
got = *e.HumanUsefulCount
}
t.Fatalf("人工 not-useful 路径不得污染 human_useful_count,want 2 got %d", got)
}
if e.HumanNotUsefulCount != 1 {
t.Fatalf("human_not_useful_count 相对增量 +1,want 1 got %d", e.HumanNotUsefulCount)
}
}
+72 -5
View File
@@ -7,6 +7,7 @@ import (
"fmt"
"io"
"log"
"math/rand"
"net"
"os"
"path/filepath"
@@ -270,6 +271,8 @@ func (rc *RustLanceDBClient) SearchWithTruncation(table string, vector []float32
// 用 *float64 区分「NULL(存量未声明)」与「显式 0.0」。
Confidence *float64 `json:"confidence"`
ConfidenceSource string `json:"confidence_source"`
// A10 (t_d618dc7c):人工有用单独列(可空,NULL=从未人工点过)读侧投影——不补则静默 no-op。
HumanUsefulCount *int `json:"human_useful_count"`
// vector 必须解析:近重复去重(commit near_dup / 蒸馏写入 gate /
// admin/dedup 端点)全部依赖 records 携带向量做 cosine 比较。
// 此前缺失该字段 → Vector 恒为空 → 所有 len(Vector)>0 判定失败 →
@@ -350,6 +353,8 @@ func (rc *RustLanceDBClient) SearchWithTruncation(table string, vector []float32
// 端到端测试才抓得到)。
Confidence: r.Confidence,
ConfidenceSource: r.ConfidenceSource,
// A10 (t_d618dc7c):人工有用单独列输出映射(解包有 + 输出有,缺则 recall 恒 null)
HumanUsefulCount: r.HumanUsefulCount,
// 2026-10-14 (t_763e8701):bi-temporal 三列输出映射(缺 ⇒ 解包有、输出无,recall 拿不到)
ValidFrom: r.ValidFrom,
ValidTo: r.ValidTo,
@@ -411,6 +416,8 @@ func (rc *RustLanceDBClient) Scan(limit int, namespaceFilter string) ([]models.M
// 2026-10-08 (Gap#2):scan 路径同样要投影,否则该路径返回的 confidence 恒 nil
Confidence *float64 `json:"confidence"`
ConfidenceSource string `json:"confidence_source"`
// A10 (t_d618dc7c):人工有用单独列(可空)读侧投影
HumanUsefulCount *int `json:"human_useful_count"`
// 2026-10-14 (t_763e8701):bi-temporal 三列(scan 列表 / export 也需要)
ValidFrom string `json:"valid_from"`
ValidTo string `json:"valid_to"`
@@ -446,6 +453,7 @@ func (rc *RustLanceDBClient) Scan(limit int, namespaceFilter string) ([]models.M
// GA-P0-1 (t_718d8707):scan 读侧接线
NotUsefulCount: int(r.NotUsefulCount), HumanNotUsefulCount: int(r.HumanNotUsefulCount), DedupDownweightCount: int(r.DedupDownweightCount),
Confidence: r.Confidence, ConfidenceSource: r.ConfidenceSource, // 2026-10-08 (Gap#2)
HumanUsefulCount: r.HumanUsefulCount, // A10 (t_d618dc7c):人工有用单独列输出映射
// 2026-10-14 (t_763e8701):bi-temporal 三列输出映射(scan 列表 / export)
ValidFrom: r.ValidFrom,
ValidTo: r.ValidTo,
@@ -727,6 +735,27 @@ func (rc *RustLanceDBClient) Update(table, id string, fields map[string]any) err
m.UsefulCount = inc
}
}
// A10 (t_d618dc7c):人工有用单独计数 —— 本地读缓存同步(*int,NULL 时先置 0 再自增)
if v, ok := fields["human_useful_count"]; ok {
switch inc := v.(type) {
case map[string]string:
if inc["$inc"] == "1" {
if m.HumanUsefulCount == nil {
m.HumanUsefulCount = new(int)
}
*m.HumanUsefulCount++
}
case map[string]interface{}:
if inc["$inc"] == "1" {
if m.HumanUsefulCount == nil {
m.HumanUsefulCount = new(int)
}
*m.HumanUsefulCount++
}
case int:
m.HumanUsefulCount = &inc
}
}
if v, ok := fields["not_useful_count"]; ok {
switch inc := v.(type) {
case map[string]string:
@@ -884,8 +913,17 @@ func (rc *RustLanceDBClient) GetTopByQuality(agentID string, limit int) ([]model
// - 退避 50/100/200ms(指数、cap 200ms),总最坏 +350ms(背景软删按分钟/小时节奏,可忽略);
// - 更新是 SET is_deleted=true, updated_at=... 纯赋值 → 对最新已提交版本重放安全(幂等不累加);
// - 仅「可重试冲突」重试;其余错误(空 id / "id required" / schema 错)立即返回、不重试。
// t_cf680fad 机制修复:预算 3→5 + 退避加 jitter(破锁步雷群)。
// 根因:runMerges O(n²) 软删 + 并发遗忘碎片器 在同一张 memories 单表上制造 MVCC 写风暴;
// 旧 3 次/~350ms 预算下,风暴每 <100ms 推进一版 ⇒ 每次重放都撞新版本 ⇒ 4 次全败
// (实证:单次 op 的 3 次重放 version 598346→598347→598348→598350 逐版推进仍耗尽)。
// ① 预算 3→5:给单次 op 多两次机会跨过风暴窗口;
// ② jitter(退避上叠 0~50% 随机量):破 50+ 并发 SoftDelete 全在同一时刻重放的锁步雷群
// —— 锁步本身就是让冲突「持续」的主因(不 jitter,退避再长也齐步撞);
// ③ 耗尽 ⇒ 落 durable pending 队列(softdelete_pending.go),启动/每 tick 各 drain 一次,
// 风暴退去后重放必落盘(SET is_deleted=true 幂等)。
const (
softDeleteMaxRetries = 3
softDeleteMaxRetries = 5
softDeleteBackoffBase = 50 * time.Millisecond
softDeleteBackoffCap = 200 * time.Millisecond
)
@@ -924,16 +962,20 @@ func isRetryableLanceConflict(err error) bool {
}
// retrySoftDeleteRPC 对 lancedb_update 调用做有界指数退避重试(仅可重试冲突)。
// 返回:首次成功或重试后成功 = nil;耗尽 = 含尝试次数的明确错误;非可重试错误 = 原样立即返回。
// t_cf680fad:退避加 jitter(破锁步雷群)+ 耗尽落 durable pending 队列(风暴退去后必落盘)。
// 返回:首次成功或重试后成功 = nil;耗尽 = 已入 pending 队列 + 含尝试次数的明确错误;
// 非可重试错误 = 原样立即返回(不入队,那些是 schema/id 等真错误,入队无意义)。
func (rc *RustLanceDBClient) retrySoftDeleteRPC(id, reason, fields string) error {
backoff := softDeleteBackoffBase
var lastErr error
for attempt := 0; attempt <= softDeleteMaxRetries; attempt++ {
if attempt > 0 {
// 第 attempt 次重试(1-based):attempt=1→50ms, 2→100ms, 3→200ms
// 第 attempt 次重试(1-based):指数退避 + 0~50% jitter(破 50+ 并发软删锁步重放)
jitter := time.Duration(rand.Intn(int(backoff/2) + 1))
sleepDur := backoff + jitter
log.Printf("[ipc] SoftDelete retry attempt %d/%d id=%s reason=%s error=%v",
attempt, softDeleteMaxRetries, id, reason, lastErr)
time.Sleep(backoff)
time.Sleep(sleepDur)
if backoff < softDeleteBackoffCap {
backoff *= 2
if backoff > softDeleteBackoffCap {
@@ -949,10 +991,12 @@ func (rc *RustLanceDBClient) retrySoftDeleteRPC(id, reason, fields string) error
return nil
}
if !isRetryableLanceConflict(err) {
return err // 非可重试错误:立即返回,不重试
return err // 非可重试错误:立即返回,不重试(也无需入队)
}
lastErr = err
}
// t_cf680fad:MVCC 冲突耗尽 ⇒ 落 durable 队列,启动/每 tick drain 重放(SET 幂等,必落盘)。
EnqueuePendingSoftDelete(id, reason)
return fmt.Errorf("soft delete persist (id=%s): retry exhausted after %d retries: %w",
id, softDeleteMaxRetries, lastErr)
}
@@ -1354,6 +1398,22 @@ func mapInt(m map[string]interface{}, key string) int {
}
return 0
}
// mapIntPtr — A10 (t_d618dc7c):可空整数读侧映射(NULL=从未人工点过 ⇒ nil,区别于显式 0)。
// Rust 侧 human_useful_count 为 Option<i64>,serde 序列化后 null ⇒ 此处 v 缺失/nil ⇒ 返回 nil;
// 非 null ⇒ int。缺这层「NULL≠0」区分即静默 no-op(同 mapFloatPtr 之于 confidence)。
func mapIntPtr(m map[string]interface{}, key string) *int {
if v, ok := m[key]; ok {
if v == nil {
return nil // 显式 null(从未人工标记)
}
if f, ok := v.(float64); ok {
i := int(f)
return &i
}
}
return nil
}
func mapBool(m map[string]interface{}, key string) bool {
if v, ok := m[key]; ok {
if b, ok := v.(bool); ok {
@@ -1443,6 +1503,8 @@ func (rc *RustLanceDBClient) GetSkillCandidates(minRecalls, limit int) ([]models
// GA-P0-1 (t_718d8707):读侧接线拆分后的新字段(漏接线 ⇒ 加列也读不出,静默 no-op)
m.HumanNotUsefulCount = mapInt(r, "human_not_useful_count")
m.DedupDownweightCount = mapInt(r, "dedup_downweight_count")
// A10 (t_d618dc7c):人工有用单独列(可空,NULL=从未人工点过)读侧接线
m.HumanUsefulCount = mapIntPtr(r, "human_useful_count")
m.RecallCount = mapInt(r, "recall_count")
// GA-P0-2 (t_c6d41ac6):拆分字段读侧接线
m.RecallSeenCount = mapInt(r, "recall_seen_count")
@@ -1512,9 +1574,14 @@ func (rc *RustLanceDBClient) GetAuditLog(limit int) ([]map[string]interface{}, e
func (rc *RustLanceDBClient) IncrementUseful(id string) error {
// GA-P0-2 (t_c6d41ac6):正反馈 → useful_count+1 且 recall_verified_count+1。
// 不再碰 recall_count(冻结,保留历史值——虚高保命来源已被切断)。
// A10 (t_d618dc7c):同时把「人工有用」单独计到 human_useful_count($inc 1)。
// 本方法只被人工 feedback 路径调用(feedback.go MarkUseful /api/v1/feedback/useful);
// 机器自评/蒸馏质量路径走其它方法(IncrementDedupDownweight / IncrementHumanNotUseful /
// IncrementRecallVerified,均不写 human_useful_count)⇒ 只有人工 useful 才 +1 此列。
if err := rc.Update("memories", id, map[string]any{
"useful_count": map[string]string{"$inc": "1"},
"recall_verified_count": map[string]string{"$inc": "1"},
"human_useful_count": map[string]string{"$inc": "1"},
}); err != nil {
log.Printf("[ipc] IncrementUseful failed id=%s: %v", id, err)
return err
+9
View File
@@ -36,6 +36,8 @@ type memEntry struct {
// GA-P0-1 (t_718d8707):拆分字段
HumanNotUsefulCount int
DedupDownweightCount int
// A10 (t_d618dc7c):人工有用单独计数(指针:nil=NULL=从未被人工点过)
HumanUsefulCount *int
RecallCount int
// GA-P0-2 (t_c6d41ac6):拆分字段
RecallSeenCount int
@@ -277,6 +279,13 @@ func (mlc *MemLanceClient) IncrementUseful(id string) error {
e.UsefulCount++
// GA-P0-2 (t_c6d41ac6):正反馈 → recall_verified_count++;不再动 recall_count(冻结)
e.RecallVerifiedCount++
// A10 (t_d618dc7c):人工 useful ⇒ human_useful_count 同步 +1(与生产 IncrementUseful 的
// useful_count+recall_verified_count+human_useful_count 三 $inc 同一次 Update 一致)。
// 机器自评/蒸馏路径(IncrementDedupDownweight / IncrementHumanNotUseful)不碰此列。
if e.HumanUsefulCount == nil {
e.HumanUsefulCount = new(int)
}
*e.HumanUsefulCount++
}
return nil
}
+112
View File
@@ -0,0 +1,112 @@
package storage
import (
"log"
"os"
"strings"
"sync"
"time"
)
// t_23b6a940 AC7:热门度偏置的运行时看门狗(信号安全阈值兜底)。
//
// 背景:FeedbackScore legacy 态把 recall_verified_count(热度)当质量信号 ⇒
// 热门记忆硬顶 rank1(金标 119 条实测 MRR -22%)。离线 A/B 暴露问题的间隔
// 长(本次隔了一整晚)。本看门狗是**运行时兜底**:最终 rank1 记忆的
// recall_verified_count 连续 N 次超过全库 p95 阈值 ⇒ 打一条 ALERT 日志行
// (传感器通道),传感器端脚本(~/.hermes/scripts/tools/zhiyi-popwatch.py,
// 挂既有告警通道)把快照转成告警。
//
// 默认只报不改(report-only):
// - 不改排序、不写库、不发告警(告警由传感器端既有通道发);
// - 默认**开**(零排序影响、每 recall 一次 env 读 + 临界一次锁,开销可忽略),
// ZHIYI_POPWATCH=0 可完全关闭(关闭 ⇒ PopWatchRecord 立即返回,零行为变化)。
//
// 阈值按全库实测标定(47148 条,2026-10-18 复测):recall_verified_count
// 全库 p95=4、非零 p99=62(≈全库 top 1% 热层)、max=389、非零 7416 条:
//
// ZHIYI_POPWATCH_P95 = 62(触发阈值,rank1 verified 严格大于它才累计;
// = 非零 p99,MoA 复核标定值)
// ZHIYI_POPWATCH_N = 5 (连续多少个 query 触发 ALERT)
func PopWatchEnabled() bool {
switch strings.ToLower(os.Getenv("ZHIYI_POPWATCH")) {
case "0", "false", "off":
return false
default:
return true // 默认开(report-only)
}
}
func popWatchThreshold() int64 { return int64(envInt("ZHIYI_POPWATCH_P95", 62)) }
func popWatchN() int { return envInt("ZHIYI_POPWATCH_N", 5) }
// popWatchState 进程内观测状态(每实例一份;「连续 N 个 query」语义就是进程内的)。
type popWatchState struct {
mu sync.Mutex
consecutive int // rank1 verified > 阈值 的连续 query 数(否则清零)
lastRank1ID string // 最近一次 recall 的 rank1 记忆 id(审计用)
lastVerified int64 // 最近一次 recall 的 rank1 verified
lastSeenAt time.Time
alertsFired int // 本进程累计 ALERT 次数
lastAlertAt time.Time
}
// PopWatch 是全局观测器(GET /api/v1/popwatch 读快照;传感器端据此告警)。
var PopWatch = &popWatchState{}
// PopWatchRecord 观测一次 recall 的最终 rank1 的 recall_verified_count。
// 调用点:recallUncached 末尾(主路径漏斗——热度偏置恰好作用于此处)。
// 门关(ZHIYI_POPWATCH=0)⇒ 立即返回,零行为变化。
// 越阈连续满 N 个 query ⇒ 打一条 ALERT 日志行(同一连续段只在满 N 瞬间打一次;
// 之后继续越阈不刷屏,回落再爬升才再打)。
func PopWatchRecord(rank1ID string, rank1Verified int64) {
if !PopWatchEnabled() {
return
}
threshold := popWatchThreshold()
n := popWatchN()
PopWatch.mu.Lock()
defer PopWatch.mu.Unlock()
if rank1Verified > threshold {
PopWatch.consecutive++
} else {
PopWatch.consecutive = 0
}
PopWatch.lastRank1ID = rank1ID
PopWatch.lastVerified = rank1Verified
PopWatch.lastSeenAt = time.Now()
if PopWatch.consecutive == n {
PopWatch.alertsFired++
PopWatch.lastAlertAt = time.Now()
log.Printf("[popwatch] ALERT: rank1 recall_verified_count=%d > p95 阈值 %d 连续 %d 个 query(report-only:不改排序/不写库;回滚:ZHIYI_POS_MODE=legacy 或 ZHIYI_FEEDBACK_BIAS=0)",
rank1Verified, threshold, n)
}
}
// PopWatchSnapshot 供 GET /api/v1/popwatch(传感器端脚本读它转既有告警通道)。
func PopWatchSnapshot() map[string]any {
threshold := popWatchThreshold()
n := popWatchN()
PopWatch.mu.Lock()
defer PopWatch.mu.Unlock()
lastSeen := ""
if !PopWatch.lastSeenAt.IsZero() {
lastSeen = PopWatch.lastSeenAt.Format(time.RFC3339)
}
lastAlert := ""
if !PopWatch.lastAlertAt.IsZero() {
lastAlert = PopWatch.lastAlertAt.Format(time.RFC3339)
}
return map[string]any{
"enabled": PopWatchEnabled(),
"threshold_p95": threshold,
"consecutive_n": n,
"consecutive": PopWatch.consecutive,
"last_rank1_id": PopWatch.lastRank1ID,
"last_rank1_verified": PopWatch.lastVerified,
"last_seen_at": lastSeen,
"alerts_fired": PopWatch.alertsFired,
"last_alert_at": lastAlert,
"note": "report-only 观测:rank1 recall_verified_count 连续越 p95 阈值 = 热门度偏置行为证据;回滚 ZHIYI_POS_MODE=legacy / ZHIYI_FEEDBACK_BIAS=0",
}
}
+112 -5
View File
@@ -32,6 +32,19 @@ import (
var (
confidenceLambda = envFloat("ZHIYI_CONFIDENCE_LAMBDA", 0) // 0 = 关闭
confidenceMean = envFloat("ZHIYI_CONFIDENCE_MEAN", 0.7) // 去中心基准
// 2026-10-21(t_5624c0ff → 牧尘批准「按推荐执行」):融合权重可配。
// 1.0 = 纯向量(reranker 余弦分,不混 BM25/质量分);0.7 = 历史默认。
// 依据:MoA 四槽 + 实测 strict n=134 —— 现状 fuse 0.1125 vs 纯向量 0.1898(现状是负收益 39%),
// 且 A/C 绝对差 0.0121 在 n=134 上不显著 ⇒ 不值得为它背 9% 硬失败率(worst −100%)。
// 回滚:ZHIYI_FUSION_W=0.7(或删掉该 env)即逐位回到改动前。
fusionW = envFloat("ZHIYI_FUSION_W", 0.7)
// fuseModeProof 2026-10-26(Step3,对应 t_9acaa74d §5 A′ 的 nouse 臂):
// 融合第二槽改为 **QualityFromProof(证据条数,确定性)**,彻底不含
// importance=recency×(1+ln(seen)) 与 V 值 —— 老卡实测「usage 特征单独为负资产」
// (imp-only 0.0579 / seen-only 0.0335 NDCG@5,只有纯向量的 1/3)。
// 默认关 ⇒ 逐位等价现状;开启需同时把 FUSION_W 调<1(否则第二槽权重 0,等于没开)。
// 回滚 = 去掉 ZHIYI_FUSE_MODE。每次调用读 env(测试可 t.Setenv 翻转)。
// t_be3e958a 来源分层偏置:决策类来源(wiki:decision 等)在 MMR 之前加性加分,
// 让「我们定了什么/阈值怎么定的」这类问题召回出决定本体而非流水。0 = 关闭。
// 流水类(llm_distill/episode)不加分也不降权——偏置只抬决策,不动流水的相对位次。
@@ -305,6 +318,32 @@ func (p *RecallPipeline) SetMissRecorder(mr MissRecorder) {
// 诊断时置 ZHIYI_QSTRUST_VERBOSE=1。
var qstrustVerbose = os.Getenv("ZHIYI_QSTRUST_VERBOSE") == "1"
// nsFallbackMin 2026-10-26(牧尘令):ns 作用域兜底阈值 —— 作用域内候选少于此值就补一次
// 全库搜索。背景:agent_id 派生的 <agent>-main 里几乎没货(实测 6/7 条),
// 而不传 agent_id 是 200 条 ⇒ 带 agent_id 的调用静默劣化且不报错。
// 默认 20;**ZHIYI_NS_FALLBACK_MIN=0 即关闭**(回滚开关,逐位回到改动前)。
func nsFallbackMin() int {
if v := strings.TrimSpace(os.Getenv("ZHIYI_NS_FALLBACK_MIN")); v != "" {
if n, err := strconv.Atoi(v); err == nil && n >= 0 {
return n
}
}
return 20
}
// fuseModeProof 2026-10-26(Step3 / t_9acaa74d §5 A′ 的 nouse 臂):
// ZHIYI_FUSE_MODE=proof ⇒ 融合第二槽 = QualityFromProof(证据条数,确定性),
// 不含 importance(recency×seen)/V。默认关 ⇒ 零行为变化。
// 老卡实测:usage 特征单独为负资产(imp-only 0.0579 / seen-only 0.0335 @NDCG@5),
// 而 nouse 臂 strict 0.2019 > 纯向量 0.1898 ⇒ 方向对,但尾部仍需保位机制。
func fuseModeProof() bool {
switch strings.ToLower(os.Getenv("ZHIYI_FUSE_MODE")) {
case "proof", "nouse":
return true
}
return false
}
// RecallMeta RecallWithMeta 返回的召回元数据(t_949840b1:candidates_scanned 名实相符)。
// CandidatesScanned = 粗检索候选池真实大小(LanceDB ANN 检索返回 + 去重 +
// 原始对话过滤之后的候选数,在 rerank/MMR 截断之前捕获)。
@@ -324,6 +363,9 @@ type RecallMeta struct {
// true = 部分结果:candidates_scanned/count 反映截断后状态,调用方不得当作「全量」。
// 缓存命中路径 / 纯 Go 后端(无行数上限)⇒ false。
Truncated bool
// StandingAnswerHit(t_standing_recall, 2026-10-25):本次召回被常设答案精确通道
// 置顶注入时,记录命中的 question_id;未命中为空。仅观测用,不参与打分。
StandingAnswerHit string
}
// SearchTruncationReporter 可选扩展接口(t_3aa2a8c1):能报告「粗检索单次重读是否被
@@ -361,7 +403,32 @@ func DefaultMMRDiversity() float64 {
return 0.3
}
// RecallWithMeta 是召回的唯一外部入口:内部先走原有语义/词面管线,再叠加
// 「常设答案精确通道」(t_standing_recall,2026-10-25)。
// 通道默认关(ZHIYI_STANDING_ANSWER=1 才生效)⇒ 关闭时与旧行为逐位一致。
func (p *RecallPipeline) RecallWithMeta(query, namespace string, topK int, diversity float64) ([]models.RecallResult, RecallMeta, error) {
return p.RecallWithMetaOpts(query, namespace, topK, diversity, false)
}
// RecallWithMetaOpts 2026-10-26:allowNSFallback=true 时,若 namespace 作用域候选过少
// (ZHIYI_NS_FALLBACK_MIN,默认 20),补一次全库搜索并合并。
// 只有 **agent_id 派生** 的作用域才该传 true —— 显式传 namespace 的调用方传 false,
// 否则会跨域泄漏不该看到的记忆。
func (p *RecallPipeline) RecallWithMetaOpts(query, namespace string, topK int, diversity float64, allowNSFallback bool) ([]models.RecallResult, RecallMeta, error) {
results, meta, err := p.recallWithMetaInner(query, namespace, topK, diversity, allowNSFallback)
if err != nil {
return results, meta, err
}
if StandingAnswerEnabled() {
if sa := LookupStandingAnswer(query); sa != nil {
results = PrependStandingAnswer(results, sa, topK)
meta.StandingAnswerHit = sa.QuestionID
}
}
return results, meta, err
}
func (p *RecallPipeline) recallWithMetaInner(query, namespace string, topK int, diversity float64, allowNSFallback bool) ([]models.RecallResult, RecallMeta, error) {
// topK 先归一:缓存键必须与写入侧用的 topK 一致。recallUncached 内部也会归一,
// 若此处不先归一,topK<=0 的调用读到的是"归一前的键"、永远命中不了自己写的条目。
if topK <= 0 {
@@ -382,7 +449,7 @@ func (p *RecallPipeline) RecallWithMeta(query, namespace string, topK int, diver
}
}
}
return p.recallUncached(query, namespace, topK, diversity)
return p.recallUncached(query, namespace, topK, diversity, allowNSFallback)
}
// Recall 保持原签名(缓存 + 全量流程),行为不变。
@@ -393,7 +460,7 @@ func (p *RecallPipeline) Recall(query, namespace string, topK int, diversity flo
// recallUncached Recall 的非缓存路径。候选池大小在 Step 2.5 过滤后、
// Step 3 截断前捕获(真实粗检索池,不是最终产出数)。
func (p *RecallPipeline) recallUncached(query, namespace string, topK int, diversity float64) ([]models.RecallResult, RecallMeta, error) {
func (p *RecallPipeline) recallUncached(query, namespace string, topK int, diversity float64, allowFallback bool) ([]models.RecallResult, RecallMeta, error) {
if topK <= 0 {
topK = 10
}
@@ -450,6 +517,24 @@ func (p *RecallPipeline) recallUncached(query, namespace string, topK int, diver
candidates = append(candidates, nsResults...)
}
}
// 2026-10-26:**ns 作用域兜底**(牧尘令,可逆)。
// 背景:请求带 agent_id 时 resolveRecallNamespace 会派生 <agent>-main,
// 而该 ns 里几乎没有货 —— 实测 default-main 池 6 条 / xiaoyi-main 6 / prof-cloud-main 7,
// 不传 agent_id 则是 200 条。结果:召回静默劣化到个位数,不报错(见 note §M9)。
// 规则:仅当 allowFallback=true(= agent_id 派生作用域,**显式传 namespace 的调用方不兜底**,
// 避免跨域泄漏);候选数 < ZHIYI_NS_FALLBACK_MIN(默认 20,0=关闭)则补一次全库搜索并合并。
// 回滚:ZHIYI_NS_FALLBACK_MIN=0(或删该 env)即逐位回到改动前。
if allowFallback && namespace != "" {
if minN := nsFallbackMin(); minN > 0 && len(candidates) < minN {
fullLib, err := searchCoarse(200, "")
if err == nil && len(fullLib) > 0 {
log.Printf("[recall] ns 兜底:namespace=%q 仅 %d 条候选(<%d) ⇒ 合并全库 %d 条",
namespace, len(candidates), minN, len(fullLib))
candidates = append(candidates, fullLib...)
}
}
}
// 去重(按 ID)
seen := make(map[string]bool)
unique := make([]models.MemoryRecord, 0, len(candidates))
@@ -598,7 +683,7 @@ func (p *RecallPipeline) recallUncached(query, namespace string, topK int, diver
// 默认关 ⇒ 行为零变化。这是「兜底」不是「替换」——已有可信 quality 不受影响。
effQuality := ResolveQuality(&candidates[i], dbQuality[i])
if models.IsReliableQuality(effQuality) {
candidates[i].QualityScore = dbQuality[i]*0.7 + kwScore*0.3
candidates[i].QualityScore = dbQuality[i]*fusionW + kwScore*(1-fusionW)
} else {
// 存量分数不可信(0=未打分 / 0.755=历史常量 bug,见 models.IsReliableQuality)
// → 不拿假分数参与排序,权重全部让给关键词分。
@@ -670,7 +755,7 @@ func (p *RecallPipeline) recallUncached(query, namespace string, topK int, diver
continue
}
kw := ComputeBM25ScoreV2(query, candidates[idx].Content)
reranked[i].Score = reranked[i].Score*0.7 + kw*0.3
reranked[i].Score = reranked[i].Score*fusionW + kw*(1-fusionW)
}
}
@@ -776,7 +861,11 @@ func (p *RecallPipeline) recallUncached(query, namespace string, topK int, diver
conf := coalesceConfidence(c.Confidence)
// 2026-10-09 (P0 修正):λ 已在 Step 3.7 偏置进 reranked[i].Score,选择与展示
// 共用同一套分数;此处不再重复施加(否则 legacy 被双重扣分)。
base := score*0.7 + c.QualityScore*0.3
base := score*fusionW + c.QualityScore*(1-fusionW)
if fuseModeProof() {
// 第二槽换成确定性证据分:条数饱和 x/(x+K),无 seen/时间/V。
base = score*fusionW + QualityFromProof(&c)*(1-fusionW)
}
// 2026-10-11 (t_631ab13d):把库里的 quality_score / v_value 直通给调用方。
// 展示 DB 原值("响应值==库值"判据):优先用 RawQualityScore(LanceDB 原始列,
// 仅 Rust IPC 路径携带,json:"-" 不落库);否则退回 DB 捕获值 dbQuality[idx]
@@ -811,6 +900,8 @@ func (p *RecallPipeline) recallUncached(query, namespace string, topK int, diver
QualityScore: qsVal,
QualityScoreReliable: models.IsReliableQuality(qsVal),
VValue: vv,
// A10 (t_d618dc7c):人工有用单独计数直通(nil=NULL=从未被人工点过)
HumanUsefulCount: c.HumanUsefulCount,
// 2026-10-13 (t_e9a4d18f P0):过期标记(默认关闭 ⇒ 恒 false 不输出)
Stale: isStale(c.UpdatedAt, staleAfterHours),
})
@@ -898,6 +989,8 @@ func (p *RecallPipeline) recallUncached(query, namespace string, topK int, diver
QualityScore: rec.QualityScore,
QualityScoreReliable: false, // FTS 记录未经过质量融合 ⇒ 标不可信(审计可辨)
FtsBoosted: true,
// A10 (t_d618dc7c):人工有用单独计数直通(nil=NULL=从未被人工点过)
HumanUsefulCount: rec.HumanUsefulCount,
})
}
}
@@ -1020,6 +1113,20 @@ func (p *RecallPipeline) recallUncached(query, namespace string, topK int, diver
}
}()
// Step 8: 热门度观测点(t_23b6a940 AC7,report-only、零排序影响):
// 记录最终 rank1 的 recall_verified_count;连续越 p95 阈值满 N 个 query ⇒
// ALERT 日志行(传感器通道),传感器端 zhiyi-popwatch.py 转既有告警通道。
// 仅观测主 ANN 池出来的 rank1(图谱扩展/FTS 尾部位注入的 rank1 无池内计数,
// 跳过不记)——热度偏置的作用面恰在主池 rerank 漏斗。
if len(results) > 0 {
for i := range candidates {
if candidates[i].ID == results[0].ID {
PopWatchRecord(results[0].ID, int64(candidates[i].RecallVerifiedCount))
break
}
}
}
return results, RecallMeta{CandidatesScanned: poolSize, Truncated: truncated}, nil
}
@@ -0,0 +1,67 @@
package storage
import (
"math"
"testing"
"time"
"github.com/xiaoxue/memoryweave/internal/models"
)
// 2026-10-26 Step3:证明 ZHIYI_FUSE_MODE 的解析与证据分语义。
// 目的不是「跑通」,而是锁死两条:
// 1) 默认(未设/其它值)必须 false —— 零行为变化是上线前提;
// 2) QualityFromProof 必须只依赖证据条数(sat=x/(x+K)),与 recency/seen/V 无关。
func TestFuseModeProofParsing(t *testing.T) {
cases := []struct {
env string
want bool
}{
{"", false},
{"0", false},
{"off", false},
{"proof", true},
{"NOUSE", true}, // 大小写不敏感
{"Proof", true},
}
for _, c := range cases {
t.Setenv("ZHIYI_FUSE_MODE", c.env)
if got := fuseModeProof(); got != c.want {
t.Fatalf("ZHIYI_FUSE_MODE=%q → %v, want %v", c.env, got, c.want)
}
}
}
func TestQualityFromProofOnlyDependsOnEvidence(t *testing.T) {
K := proofSaturation // 默认 5
// 无证据 ⇒ 0
if got := QualityFromProof(&models.MemoryRecord{}); got != 0 {
t.Fatalf("无证据应为 0,得 %v", got)
}
// 5 条证据 ⇒ 5/(5+5) = 0.5
m := &models.MemoryRecord{SourceEvents: []string{"e1", "e2", "e3", "e4", "e5"}}
if got := QualityFromProof(m); math.Abs(got-5/(5+K)) > 1e-9 {
t.Fatalf("5 条证据应为 %.4f,得 %.4f", 5/(5+K), got)
}
// 去重:重复事件不虚增
dup := &models.MemoryRecord{SourceEvents: []string{"e1", "e1", "e1"}}
if got := QualityFromProof(dup); math.Abs(got-1/(1+K)) > 1e-9 {
t.Fatalf("重复证据应去重为 1 条(%.4f),得 %.4f", 1/(1+K), got)
}
// ★ 关键:同样的证据条数,不同 seen/时间 ⇒ 分数必须完全相同
// (若这里失败,说明证据分被 recency/seen 污染,Step3 的前提就不成立)
base := &models.MemoryRecord{SourceEvents: []string{"a", "b"}}
polluted := &models.MemoryRecord{
SourceEvents: []string{"a", "b"},
RecallSeenCount: 999, // 高频召回
LastRecalledAt: time.Now().AddDate(-3, 0, 0), // 三年前的最后一次召回
}
if QualityFromProof(base) != QualityFromProof(polluted) {
t.Fatalf("证据分被 recency/seen 污染:%v vs %v",
QualityFromProof(base), QualityFromProof(polluted))
}
}
@@ -0,0 +1,141 @@
package storage
import (
"fmt"
"testing"
"github.com/xiaoxue/memoryweave/internal/models"
)
// 2026-10-26(牧尘令)· ns 作用域兜底护栏的判据测试。
//
// 背景:请求带 agent_id 时 resolveRecallNamespace 派生 <agent>-main,而实测该 ns 里
// 只有 6~7 条货(default-main 6 / xiaoyi-main 6 / prof-cloud-main 7),不传 agent_id
// 则有 200 条 ⇒ 带 agent_id 的调用静默劣化到个位数、且不报错。
//
// 本组用例锁死四条不变量:
// 1) agent 派生作用域 + 候选过少 ⇒ 必须补一次全库搜索并合并(池变大)。
// 2) **显式 namespace 调用方不兜底**(allowNSFallback=false)⇒ 不得多发全库搜索,
// 否则跨域泄漏。
// 3) ZHIYI_NS_FALLBACK_MIN=0 ⇒ 关闭(回滚开关有效)。
// 4) 候选本来就够多 ⇒ 不兜底(避免每次多打一次 200 行的全库搜索)。
// nsFallbackLance 按 namespaceFilter 返回不同规模的候选:
// 全库("") → 100 条;hermes-main → 2 条;shared → 1 条。
type nsFallbackLance struct {
LanceDB
nsFilters []string
fullRowsN int
nsRowsN int
}
func (f *nsFallbackLance) Search(table string, vector []float32, topK int, namespaceFilter string) ([]models.MemoryRecord, error) {
f.nsFilters = append(f.nsFilters, namespaceFilter)
n := f.nsRowsN
if namespaceFilter == "" {
n = f.fullRowsN
}
out := make([]models.MemoryRecord, 0, n)
for i := 0; i < n; i++ {
ns := namespaceFilter
if ns == "" {
ns = "full"
}
out = append(out, models.MemoryRecord{
ID: fmt.Sprintf("%s-%03d", ns, i),
Content: fmt.Sprintf("%s 记忆 %d", ns, i),
Category: "distilled",
Namespace: ns,
})
}
return out, nil
}
// Update 覆写:后台 goroutine 会回写 recall_count,落到 nil 接口会 panic(见 recall_namespace_test.go 注释)。
func (f *nsFallbackLance) Update(table, id string, fields map[string]any) error { return nil }
// newNSFallbackPipeline 与 newNSTestPipeline 同构,但接受任意 LanceDB 实现
// (newNSTestPipeline 的形参是具体的 *nsRecordingLance)。
func newNSFallbackPipeline(t *testing.T, fake LanceDB) *RecallPipeline {
t.Helper()
saved := SearchCacheInstance
SearchCacheInstance = nil
t.Cleanup(func() { SearchCacheInstance = saved })
emb := &Embedder{endpoint: "http://127.0.0.1:1/never", dim: 1024}
vec := make([]float32, 1024)
for i := range vec {
vec[i] = 0.01
}
emb.cache.Store(nsTestQuery, vec) // 预置缓存 → 不走网络
return NewRecallPipeline(emb, fake, &Reranker{})
}
func (f *nsFallbackLance) countFullSearches() int {
n := 0
for _, ns := range f.nsFilters {
if ns == "" {
n++
}
}
return n
}
func TestNSFallbackMergesFullLibraryWhenScopeTooSmall(t *testing.T) {
fake := &nsFallbackLance{fullRowsN: 100, nsRowsN: 2}
p := newNSFallbackPipeline(t, fake)
_, meta, err := p.RecallWithMetaOpts(nsTestQuery, "hermes-main", 10, 0.3, true)
if err != nil {
t.Fatalf("Recall 出错: %v", err)
}
if fake.countFullSearches() != 1 {
t.Fatalf("✗ 应补 1 次全库搜索,实际 %d 次(调用序列 %v)", fake.countFullSearches(), fake.nsFilters)
}
if meta.CandidatesScanned < 50 {
t.Errorf("✗ 兜底后候选池仍只有 %d 条,应合并到接近全库 100 条", meta.CandidatesScanned)
}
t.Logf("✓ 兜底生效:作用域 2 条 → 合并后池 %d 条(搜索序列 %v)", meta.CandidatesScanned, fake.nsFilters)
}
func TestNSFallbackDisabledForExplicitNamespace(t *testing.T) {
fake := &nsFallbackLance{fullRowsN: 100, nsRowsN: 2}
p := newNSFallbackPipeline(t, fake)
if _, _, err := p.RecallWithMetaOpts(nsTestQuery, "hermes-main", 10, 0.3, false); err != nil {
t.Fatalf("Recall 出错: %v", err)
}
if n := fake.countFullSearches(); n != 0 {
t.Fatalf("✗ 显式 namespace 不得兜底,实际发起了 %d 次全库搜索(序列 %v)", n, fake.nsFilters)
}
t.Logf("✓ 显式 ns 不兜底(防跨域泄漏):搜索序列 %v", fake.nsFilters)
}
func TestNSFallbackCanBeTurnedOffByEnv(t *testing.T) {
fake := &nsFallbackLance{fullRowsN: 100, nsRowsN: 2}
p := newNSFallbackPipeline(t, fake)
t.Setenv("ZHIYI_NS_FALLBACK_MIN", "0") // 回滚开关
if _, _, err := p.RecallWithMetaOpts(nsTestQuery, "hermes-main", 10, 0.3, true); err != nil {
t.Fatalf("Recall 出错: %v", err)
}
if n := fake.countFullSearches(); n != 0 {
t.Fatalf("✗ ZHIYI_NS_FALLBACK_MIN=0 应完全关闭兜底,实际 %d 次", n)
}
t.Logf("✓ 回滚开关有效:ZHIYI_NS_FALLBACK_MIN=0 ⇒ 零全库搜索")
}
func TestNSFallbackSkippedWhenScopeAlreadyLarge(t *testing.T) {
// nsRowsN=30 ≥ 默认阈值 20 ⇒ 不该兜底(否则每次多打一次全库搜索)
fake := &nsFallbackLance{fullRowsN: 100, nsRowsN: 30}
p := newNSFallbackPipeline(t, fake)
_, meta, err := p.RecallWithMetaOpts(nsTestQuery, "hermes-main", 10, 0.3, true)
if err != nil {
t.Fatalf("Recall 出错: %v", err)
}
if n := fake.countFullSearches(); n != 0 {
t.Fatalf("✗ 候选已足够(%d 条)不该兜底,实际 %d 次全库搜索", meta.CandidatesScanned, n)
}
t.Logf("✓ 候选充足不兜底:池 %d 条,零全库搜索", meta.CandidatesScanned)
}
+7 -5
View File
@@ -4,6 +4,7 @@ package storage
import (
"encoding/binary"
"encoding/json"
"fmt"
"io"
"net"
"os"
@@ -143,18 +144,19 @@ func TestSoftDelete_AlwaysConflict_ExhaustsBounded(t *testing.T) {
if err == nil {
t.Fatalf("永远冲突应返回错误,却返回 nil")
}
// AC-2:含尝试次数(重试数)的明确错误
if !strings.Contains(err.Error(), "retry exhausted after 3 retries") {
t.Fatalf("错误应含 'retry exhausted after 3 retries',实际=%v", err)
// AC-2:含尝试次数(重试数)的明确错误(t_cf680fad:预算 3→5)
if want := fmt.Sprintf("retry exhausted after %d retries", softDeleteMaxRetries); !strings.Contains(err.Error(), want) {
t.Fatalf("错误应含 %q,实际=%v", want, err)
}
if !strings.Contains(err.Error(), "mem_retry_never_ok") {
t.Fatalf("错误应含 id,实际=%v", err)
}
// 有界:总 rpc 尝试 = 1 首次 + 3 重试 = 4 次,不死循环
// 有界:总 rpc 尝试 = 1 首次 + N 重试(t_cf680fad N=5)= 6 次,不死循环
if got := fk.callCount(); got != softDeleteMaxRetries+1 {
t.Fatalf("总 rpc 尝试 = %d, want %d(有界不卡死)", got, softDeleteMaxRetries+1)
}
// 退避:50+100+200 = 350ms 最坏,宽松下限断言 ≥300ms(证明睡了退避、非忙循环)
// 退避:jitter 后总时长随随机量浮动,但仍 ≥ 无 jitter 下限(50+100+200+200+200 的整数倍关系)
// 宽松下限断言 ≥300ms(证明睡了退避、非忙循环)
if elapsed < 300*time.Millisecond {
t.Fatalf("退避未生效:elapsed=%v, want ≥300ms", elapsed)
}
+143
View File
@@ -0,0 +1,143 @@
// 织忆 MemoryWeave — durable pending-softdelete 队列(t_cf680fad 机制修复)
//
// 背景 / 根因:
// runMerges O(n²) 软删 + 并发遗忘碎片器在同一张 memories 单表上制造 MVCC 写风暴;
// retrySoftDeleteRPC 旧预算 3 次/~350ms(且退避无 jitter,50+ 并发软删锁步重放)⇒
// 风暴下每次重放都撞已推进的新版本 ⇒ 4 次全败 ⇒ 失败软删被 consolidation_pipe.go:252
// 的 `_ =` 静默丢弃 ⇒ 源记录 is_deleted 停在 false,每次重启窗口都留新残留
// (检索里重复命中)。实证:单次 op 的 3 次重放 version 598346→598347→598348→598350
// 逐版推进仍耗尽;24h「重试成功=0」。
//
// 本文件提供的保证("重试必须能成功落盘"):
// ① EnqueuePendingSoftDelete:retrySoftDeleteRPC MVCC 冲突耗尽时把 (id, reason) 追加进
// durable JSONL(单写者 append + 原子 tmp/rename,同 id 去重)。
// ② DrainPendingSoftDeletes:zhiyid 启动 + 每 30s 触发器 tick 各调用一次,逐条重放
// SoftDelete(SET is_deleted=true 幂等、对最新已提交版本重读),成功后移除;
// 队列空/缺失 = 立即 no-op。风暴退去后(或下次重启窗口)重放必落盘。
package storage
import (
"bufio"
"encoding/json"
"log"
"os"
"path/filepath"
"sync"
"time"
)
// defaultPendingSoftDeletePath 生产路径。测试用 env ZHIYI_SOFTDELETE_PENDING 覆盖(不污染生产库)。
const defaultPendingSoftDeletePath = "/var/lib/memoryweave/pending-softdelete.jsonl"
func pendingSoftDeletePath() string {
if p := os.Getenv("ZHIYI_SOFTDELETE_PENDING"); p != "" {
return p
}
return defaultPendingSoftDeletePath
}
type pendingSoftDeleteEntry struct {
ID string `json:"id"`
Reason string `json:"reason"`
TS string `json:"ts"`
}
// pendingMu 单写者护栏:Go 侧 zhiyid 是唯一写者(Rust sidecar 不碰此文件)。
var pendingMu sync.Mutex
func readPendingEntries(p string) []pendingSoftDeleteEntry {
f, err := os.Open(p)
if err != nil {
return nil
}
defer f.Close()
var out []pendingSoftDeleteEntry
sc := bufio.NewScanner(f)
sc.Buffer(make([]byte, 1<<20), 1<<20)
for sc.Scan() {
var e pendingSoftDeleteEntry
if json.Unmarshal([]byte(sc.Text()), &e) == nil && e.ID != "" {
out = append(out, e)
}
}
return out
}
func rewritePendingFile(p string, entries []pendingSoftDeleteEntry) {
tmp := p + ".tmp"
f, err := os.OpenFile(tmp, os.O_CREATE|os.O_WRONLY|os.O_TRUNC, 0o644)
if err != nil {
log.Printf("[ipc] pending-softdelete rewrite open failed: %v", err)
return
}
w := bufio.NewWriter(f)
for _, e := range entries {
b, _ := json.Marshal(e)
_, _ = w.Write(b)
_, _ = w.Write([]byte{'\n'})
}
if err := w.Flush(); err != nil {
f.Close()
log.Printf("[ipc] pending-softdelete rewrite flush failed: %v", err)
return
}
f.Close()
if err := os.Rename(tmp, p); err != nil {
log.Printf("[ipc] pending-softdelete rewrite rename failed: %v", err)
}
}
// EnqueuePendingSoftDelete 追加一条待软删(幂等去重:同 id 只保留一条)。
// 由 retrySoftDeleteRPC 在 MVCC 冲突耗尽时调用;schema/空 id 等真错误不调(入队无意义)。
func EnqueuePendingSoftDelete(id, reason string) {
p := pendingSoftDeletePath()
if p == "" {
return
}
_ = os.MkdirAll(filepath.Dir(p), 0o755)
pendingMu.Lock()
defer pendingMu.Unlock()
entries := readPendingEntries(p)
for _, e := range entries {
if e.ID == id {
return // 已在队列,不重复(reason 保留最早一条)
}
}
entries = append(entries, pendingSoftDeleteEntry{ID: id, Reason: reason, TS: time.Now().Format(time.RFC3339)})
rewritePendingFile(p, entries)
log.Printf("[ipc] pending-softdelete ENQUEUED: id=%s reason=%s queue=%d", id, reason, len(entries))
}
// PendingSoftDeleteCount 返回队列当前条数(观测 / 测试用;缺失 = 0)。
func PendingSoftDeleteCount() int {
entries := readPendingEntries(pendingSoftDeletePath())
return len(entries)
}
// DrainPendingSoftDeletes 逐条重放待软删(幂等),成功后从队列移除。
// 启动 + 每 tick 各调用一次;队列空/缺失 = 立即 no-op(廉价 stat+read)。
// 参数取 LanceDB 接口(任意后端);内部调 rc.SoftDelete(RustLanceDBClient 走 IPC+重试+入队)。
// 返回 (成功条数, 仍失败条数);仍失败者保留在队列,下一 tick/下次启动再重放。
func DrainPendingSoftDeletes(ldb LanceDB) (ok, failed int) {
p := pendingSoftDeletePath()
entries := readPendingEntries(p)
if len(entries) == 0 {
return 0, 0
}
var remaining []pendingSoftDeleteEntry
for _, e := range entries {
if err := ldb.SoftDelete(e.ID, e.Reason); err != nil {
// 仍失败(仍在风暴内 / 真错误):保留在队列,下一轮再试。
// 注意:若这条 SoftDelete 内部又因 MVCC 耗尽触发 EnqueuePendingSoftDelete,
// 同 id 去重保证不会重复入队;此处 remaining 收口最终一致。
log.Printf("[ipc] pending-softdelete drain RETRY FAILED: id=%s reason=%s err=%v", e.ID, e.Reason, err)
remaining = append(remaining, e)
failed++
} else {
ok++
}
}
rewritePendingFile(p, remaining)
log.Printf("[ipc] pending-softdelete DRAIN: retried=%d ok=%d still_pending=%d", len(entries), ok, len(remaining))
return ok, failed
}
@@ -0,0 +1,119 @@
// 织忆 MemoryWeave — durable pending-softdelete 队列单测(t_cf680fad 机制修复 AC)
//
// 覆盖:
// ① MVCC 冲突耗尽 ⇒ 入 durable 队列(不再静默丢,残留根治)。
// ② 非可重试错误(schema/空 id)⇒ 不入队(入队无意义,避免污染)。
// ③ 幂等去重:同 id 只保留一条。
// ④ drain:风暴退去后(server 恒 OK)逐条重放 ⇒ 落盘 + 队列清空。
package storage
import (
"os"
"path/filepath"
"strings"
"testing"
)
func withTempPending(t *testing.T, fn func(pendingPath string)) {
t.Helper()
dir, err := os.MkdirTemp("", "pendingsdtest")
if err != nil {
t.Fatalf("mkdirtemp: %v", err)
}
defer os.RemoveAll(dir)
p := filepath.Join(dir, "pending-softdelete.jsonl")
_ = p
os.Setenv("ZHIYI_SOFTDELETE_PENDING", p)
defer os.Unsetenv("ZHIYI_SOFTDELETE_PENDING")
fn(p)
}
// ① MVCC 冲突耗尽 ⇒ 入 durable 队列
func TestSoftDelete_ExhaustConflicts_EnqueuesPending(t *testing.T) {
withTempPending(t, func(p string) {
fk := newFakeServer(t, -1, "") // 永远冲突
defer fk.close()
rc := fk.client()
if err := rc.SoftDelete("mem_exhaust_enq", "merged_into_mem_X"); err == nil {
t.Fatalf("永远冲突应返回错误")
}
if got := PendingSoftDeleteCount(); got != 1 {
t.Fatalf("耗尽后应入队 1 条,实际=%d", got)
}
// 文件里确实含该 id(durable,重启不丢)
b, _ := os.ReadFile(p)
if !strings.Contains(string(b), "mem_exhaust_enq") {
t.Fatalf("pending 文件未落盘该 id: %s", string(b))
}
})
}
// ② 非可重试错误 ⇒ 不入队
func TestSoftDelete_NonRetryable_NotEnqueued(t *testing.T) {
withTempPending(t, func(p string) {
fk := newFakeServer(t, -1, "lance error: Schema Mismatch: unexpected column")
defer fk.close()
rc := fk.client()
_ = rc.SoftDelete("mem_schema_err", "unit_test")
if got := PendingSoftDeleteCount(); got != 0 {
t.Fatalf("非可重试错误不应入队,实际=%d", got)
}
})
}
// ③ 幂等去重
func TestPendingSoftDelete_DedupSameID(t *testing.T) {
withTempPending(t, func(p string) {
EnqueuePendingSoftDelete("mem_dupe", "merged_into_a")
EnqueuePendingSoftDelete("mem_dupe", "merged_into_b") // 同 id 第二次
EnqueuePendingSoftDelete("mem_other", "merged_into_c")
if got := PendingSoftDeleteCount(); got != 2 {
t.Fatalf("同 id 去重后应 2 条,实际=%d", got)
}
})
}
// ④ drain:风暴退去(server 恒 OK)⇒ 逐条重放落盘 + 队列清空
func TestDrainPendingStormSettled_LandsAndClears(t *testing.T) {
withTempPending(t, func(p string) {
// 预置 2 条待软删(模拟上一轮风暴耗尽留下的残留)
EnqueuePendingSoftDelete("mem_pend_1", "merged_into_a")
EnqueuePendingSoftDelete("mem_pend_2", "merged_into_b")
if got := PendingSoftDeleteCount(); got != 2 {
t.Fatalf("预置后应 2 条,实际=%d", got)
}
// 风暴退去:sidecar 现在恒 OK
fk := newFakeServer(t, 0, "") // 首次即成功
defer fk.close()
rc := fk.client()
ok, failed := DrainPendingSoftDeletes(rc)
if ok != 2 || failed != 0 {
t.Fatalf("drain 应成功 2 条 失败 0,实际 ok=%d failed=%d", ok, failed)
}
if got := PendingSoftDeleteCount(); got != 0 {
t.Fatalf("drain 成功后队列应清空,实际=%d", got)
}
// 每条 SoftDelete 恰好 1 次 rpc(无冲突路径,无重试)
if fk.callCount() != 2 {
t.Fatalf("两条各 1 次 rpc,共应 2,实际=%d", fk.callCount())
}
})
}
// ④b drain 仍在风暴(恒冲突)⇒ 保留在队列、不误删、下轮再试(最终一致)
func TestDrainPendingStormStillOngoing_HoldsInQueue(t *testing.T) {
withTempPending(t, func(p string) {
EnqueuePendingSoftDelete("mem_hold", "merged_into_a")
fk := newFakeServer(t, -1, "") // 仍然冲突
defer fk.close()
rc := fk.client()
ok, failed := DrainPendingSoftDeletes(rc)
if ok != 0 || failed != 1 {
t.Fatalf("仍冲突时 drain 应 成功0 失败1,实际 ok=%d failed=%d", ok, failed)
}
// 关键:条目仍留在队列(未被误删),供下一 tick/启动再重放
if got := PendingSoftDeleteCount(); got != 1 {
t.Fatalf("仍失败者应保留在队列,实际=%d", got)
}
})
}
+193
View File
@@ -0,0 +1,193 @@
package storage
import (
"log"
"os"
"strings"
"sync"
"sync/atomic"
"time"
"unicode"
"github.com/xiaoxue/memoryweave/internal/models"
)
// 2026-10-25 (t_standing_recall) 常设答案 · 召回前置通道。
//
// 背景(实测,53 条真实提问基线):correct@1 = 20.8%,useful@5 = 88.7%;
// 6 条"完全跑偏"案例里 5 条的目标文档**根本不在向量 top-50 里**——不是排序问题,
// 是语义通道对"精确事实类"提问(端口/数字/标识符/专名)天然够不着。
// 故补一条**零检索、零 LLM**的精确通道:查询命中常设答案 → 直接置顶。
//
// 与既有 FTS 通道的区别:
// · FTS(t_2afae95e)只给尾部保证位,救不了 correct@1;
// · 本通道置顶,只匹配"已定型的精确事实",不做泛化,故误召回代价低(答错比答不上更糟,
// 所以阈值取保守值 + 只在环境开关开启时生效)。
//
// 开关:ZHIYI_STANDING_ANSWER=1 才生效(默认关 = 与旧行为逐位一致,便于 A/B 与一行回滚)。
// 回滚:删 drop-in 里该变量 + daemon-reload + restart。
// StandingAnswerEnabled 常设答案通道是否启用(默认关)。
func StandingAnswerEnabled() bool {
return os.Getenv("ZHIYI_STANDING_ANSWER") == "1"
}
// nearMissLogThreshold 近似命中日志阈值(**只用于日志**,不参与是否返回的决策)。
// 取 0.78:近似到这个程度说明"很像同一句但不是",正是该补 question 变体的信号。
const nearMissLogThreshold = 0.78
var (
standingCacheMu sync.RWMutex
standingCache []StandingAnswer
standingCacheAt time.Time
standingCacheTTL = 30 * time.Second
standingLookupHit atomic.Int64 // 观测:通道命中次数(/health 或日志复用)
)
// LookupStandingHitCount 返回本进程启动以来常设答案命中次数(观测用)。
func LookupStandingHitCount() int64 { return standingLookupHit.Load() }
// normalizeForMatch 归一化:小写 + 去掉所有非字母数字/非 CJK 字符(空格、标点、符号)。
func normalizeForMatch(s string) string {
var b strings.Builder
b.Grow(len(s))
for _, r := range strings.ToLower(s) {
if unicode.IsLetter(r) || unicode.IsDigit(r) {
b.WriteRune(r)
}
}
return b.String()
}
// bigrams 生成字符二元组集合(CJK 与拉丁一视同仁;长度 <2 时退化为单字符集合)。
func bigrams(s string) map[string]struct{} {
rs := []rune(s)
out := make(map[string]struct{}, len(rs))
if len(rs) < 2 {
if len(rs) == 1 {
out[string(rs)] = struct{}{}
}
return out
}
for i := 0; i+1 < len(rs); i++ {
out[string(rs[i:i+2])] = struct{}{}
}
return out
}
// diceSimilarity 字符二元组 Dice 系数(0..1)。
func diceSimilarity(a, b string) float64 {
if a == "" || b == "" {
return 0
}
if a == b {
return 1
}
ba, bb := bigrams(a), bigrams(b)
if len(ba) == 0 || len(bb) == 0 {
return 0
}
inter := 0
for g := range ba {
if _, ok := bb[g]; ok {
inter++
}
}
return 2 * float64(inter) / float64(len(ba)+len(bb))
}
// loadStandingAnswers 带 TTL 的常设答案快照(表极小,全量读;30s 内复用,避免热路径频繁查库)。
func loadStandingAnswers() []StandingAnswer {
standingCacheMu.RLock()
if time.Since(standingCacheAt) < standingCacheTTL {
cached := standingCache
standingCacheMu.RUnlock()
return cached
}
standingCacheMu.RUnlock()
standingCacheMu.Lock()
defer standingCacheMu.Unlock()
if time.Since(standingCacheAt) < standingCacheTTL { // 双检:并发下只读一次库
return standingCache
}
store := StandingStoreInstance
if store == nil {
return nil // 未初始化:通道静默失效,不影响召回
}
all, err := store.List()
if err != nil {
return standingCache
}
standingCache = all
standingCacheAt = time.Now()
return all
}
// LookupStandingAnswer 返回与 query 严格匹配的常设答案;无匹配返回 nil。
//
// 匹配口径 = **归一化后完全相等**(2026-10-25 实测修正):
// 先前用 bigram Dice 模糊匹配(阈值 0.78),上线后留出集立刻抓到真实误命中——
// 「织忆的服务跑在哪个端口」被判为「出图的服务跑在哪个端口」的匹配(仅主语两字之差,
// Dice≈0.82),把 ComfyUI 的 8188 当成织忆端口置顶。模板句 + 换主语 = 必错。
// 结论:常设答案只认**同一句话**;同义问法靠多行变体(question_id 不同)覆盖。
// 近似命中(Dice ≥ nearMissLogThreshold)只打日志不返回,用来发现该补哪些变体。
func LookupStandingAnswer(query string) *StandingAnswer {
q := normalizeForMatch(query)
if len([]rune(q)) < 2 {
return nil
}
all := loadStandingAnswers()
if len(all) == 0 {
return nil
}
var near *StandingAnswer
nearScore := 0.0
for i := range all {
cand := normalizeForMatch(all[i].Question)
if cand == "" {
continue
}
if cand == q {
return &all[i]
}
if s := diceSimilarity(q, cand); s > nearScore {
nearScore = s
near = &all[i]
}
}
// 近似但不等:只记日志(便于补变体),绝不返回——错答比不答更贵。
if near != nil && nearScore >= nearMissLogThreshold {
log.Printf("[standing] near-miss %.2f(不返回)query=%q 最接近=%q id=%s",
nearScore, query, near.Question, near.QuestionID)
}
return nil
}
// PrependStandingAnswer 把常设答案置顶注入召回结果(去重 + 遵守 topK)。
func PrependStandingAnswer(results []models.RecallResult, sa *StandingAnswer, topK int) []models.RecallResult {
if sa == nil {
return results
}
id := "standing:" + sa.QuestionID
out := make([]models.RecallResult, 0, len(results)+1)
out = append(out, models.RecallResult{
ID: id,
Content: sa.Answer,
Category: "standing_answer",
Score: 1.0,
Timestamp: sa.UpdatedAt.Format(time.RFC3339),
Source: "standing_answer",
})
for _, r := range results {
if r.ID == id {
continue
}
out = append(out, r)
}
if topK > 0 && len(out) > topK {
out = out[:topK]
}
standingLookupHit.Add(1)
return out
}
+116
View File
@@ -0,0 +1,116 @@
package storage
import (
"testing"
"time"
"github.com/xiaoxue/memoryweave/internal/models"
)
// 2026-10-25 (t_standing_recall) 常设答案通道的护栏测试。
// 关注点是"宁可漏,不可错":误置顶一条错答案比召回不到更糟。
func TestNormalizeForMatch(t *testing.T) {
cases := map[string]string{
"cron 任务的调度者是谁?": "cron任务的调度者是谁",
"Cron-Task 的 调度者": "crontask的调度者",
"织忆的向量维度是多少": "织忆的向量维度是多少",
" ": "",
}
for in, want := range cases {
if got := normalizeForMatch(in); got != want {
t.Errorf("normalize(%q)=%q want %q", in, got, want)
}
}
}
func TestDiceSimilarity(t *testing.T) {
same := diceSimilarity("cron任务的调度者是谁", "cron任务的调度者是谁")
if same != 1.0 {
t.Fatalf("同句相似度应为 1.0,实得 %v", same)
}
near := diceSimilarity("cron任务的调度者是谁", "cron调度者是谁")
if near < 0.7 || near > 1.0 {
t.Fatalf("近义句相似度异常:%v", near)
}
far := diceSimilarity("cron任务的调度者是谁", "织忆的向量维度是多少")
if far > 0.2 {
t.Fatalf("跨主题相似度应接近 0,实得 %v", far)
}
}
func TestLookupStandingAnswerThreshold(t *testing.T) {
seedStanding(t, []StandingAnswer{
{QuestionID: "cron-scheduler", Question: "cron 任务的调度者是谁", Answer: "kanban-daemon.service"},
{QuestionID: "zhiyi-dim", Question: "织忆的向量维度是多少", Answer: "1024 维(bge-m3)"},
})
// 命中:同句(归一化后相等)
if sa := LookupStandingAnswer("cron 任务的调度者是谁?"); sa == nil || sa.QuestionID != "cron-scheduler" {
t.Fatalf("同句应命中 cron-scheduler,实得 %+v", sa)
}
// 不命中:仅语序微调也不行(严格相等口径,防"模板句换主语"误命中)
if sa := LookupStandingAnswer("织忆向量维度是多少"); sa != nil {
t.Fatalf("非同一句不应命中(应靠变体行覆盖),实得 %+v", sa)
}
// 高相似但换主语 ⇒ 必须不命中(真实事故回归测试)
if sa := LookupStandingAnswer("织忆的服务跑在哪个端口"); sa != nil {
t.Fatalf("换主语的高相似句不得命中,实得 %+v", sa)
}
// 不命中:跨主题(防止"是谁"类短语乱命中)
if sa := LookupStandingAnswer("今天的天气怎么样"); sa != nil {
t.Fatalf("无关问题不应命中,实得 %+v", sa)
}
}
func TestPrependStandingAnswer(t *testing.T) {
sa := &StandingAnswer{QuestionID: "cron-scheduler", Question: "cron 任务的调度者是谁", Answer: "kanban-daemon.service"}
in := []models.RecallResult{
{ID: "mem_1", Content: "泛泛的 cron 描述", Score: 0.9},
{ID: "mem_2", Content: "另一条", Score: 0.8},
}
out := PrependStandingAnswer(in, sa, 2)
if len(out) != 2 {
t.Fatalf("topK=2 应截断到 2 条,实得 %d", len(out))
}
if out[0].ID != "standing:cron-scheduler" || out[0].Content != "kanban-daemon.service" {
t.Fatalf("常设答案应置顶,实得 %+v", out[0])
}
if out[1].ID != "mem_1" {
t.Fatalf("原有结果顺序应保持,实得 %+v", out[1])
}
// 关闭时不影响(Enabled 只由 env 控制,这里验 nil 安全)
if got := PrependStandingAnswer(in, nil, 2); len(got) != len(in) {
t.Fatalf("nil 常设答案应原样返回")
}
}
// seedStanding 注入隔离的常设答案表(临时 SQLite 文件,不碰生产库)。
func seedStanding(t *testing.T, rows []StandingAnswer) {
t.Helper()
dir := t.TempDir()
store, err := NewStandingStore(dir + "/standing_answers.db")
if err != nil {
t.Fatalf("建临时常设答案库失败: %v", err)
}
for _, r := range rows {
if _, err := store.Upsert(r.QuestionID, r.Question, r.Answer, nil); err != nil {
t.Fatalf("写入常设答案失败: %v", err)
}
}
prev := StandingStoreInstance
StandingStoreInstance = store
// 清缓存,确保读到本测试的数据
standingCacheMu.Lock()
standingCache = nil
standingCacheAt = time.Time{}
standingCacheMu.Unlock()
t.Cleanup(func() {
StandingStoreInstance = prev
standingCacheMu.Lock()
standingCache = nil
standingCacheAt = time.Time{}
standingCacheMu.Unlock()
store.Close()
})
}
+43 -1
View File
@@ -38,6 +38,13 @@ pub struct MemoryRecord {
// not_useful_count 保留(deprecated),新代码不再读它;human_not_useful_count 与
// dedup_downweight_count 是新写入点。arrow_schema 尾部新增列(nullable,存量补 NULL)。
pub human_not_useful_count: i64, pub dedup_downweight_count: i64,
// A10 (t_d618dc7c):把「人工有用」从 useful_count(人工+机器混写)拆出单独计数。
// Option<i64>(nullable)—— 与 confidence 同款「NULL≠0」语义:存量行/从未被人工
// 点过的行保持 NULL(迁移默认 CAST(NULL AS BIGINT)),一旦被人工点过才变真实整数。
// 统计口径用本列时分母必须 WHERE human_useful_count IS NOT NULL(NULL 是"未知"非"0 次")。
// #[serde(default)] ⇒ IPC 解包缺字段/NULL 读回 None(区别于显式 0),不漏这层即静默 no-op。
#[serde(default)]
pub human_useful_count: Option<i64>,
pub freshness: String, pub version: i64,
pub version_history: String, pub source: String,
// 2026-10-08 (t_7e3577c5):血缘字段
@@ -148,6 +155,10 @@ fn arrow_schema() -> Schema {
Field::new("valid_from", DataType::Utf8, true),
Field::new("valid_to", DataType::Utf8, true),
Field::new("provenance", DataType::Utf8, true),
// A10 (t_d618dc7c):人工有用单独计数。nullable Int64 —— 存量行由 open() schema 演进
// 迁移补 NULL(CAST(NULL AS BIGINT),与 confidence/human_not_useful_count 迁移模式一致);
// 人工点过后才变真实整数。只加观察口径,不进任何排序公式/权重(AC#6 排序零变化)。
Field::new("human_useful_count", DataType::Int64, true),
])
}
@@ -303,6 +314,8 @@ impl LanceDBOps {
// GA-P0-1 (t_718d8707):拆分字段读侧接线
human_not_useful_count: col_i64(&batch, i, "human_not_useful_count"),
dedup_downweight_count: col_i64(&batch, i, "dedup_downweight_count"),
// A10 (t_d618dc7c):读侧接线 —— human_useful_count 走可空读法(NULL 读回 None)
human_useful_count: col_i64_opt(&batch, i, "human_useful_count"),
freshness: col_str(&batch, i, "freshness"),
version: col_i64(&batch, i, "version"),
version_history: String::new(),
@@ -370,6 +383,8 @@ impl LanceDBOps {
// GA-P0-1 (t_718d8707):拆分字段读侧接线
human_not_useful_count: col_i64(&batch, i, "human_not_useful_count"),
dedup_downweight_count: col_i64(&batch, i, "dedup_downweight_count"),
// A10 (t_d618dc7c):读侧接线 —— human_useful_count 走可空读法(NULL 读回 None)
human_useful_count: col_i64_opt(&batch, i, "human_useful_count"),
freshness: col_str(&batch, i, "freshness"),
version: col_i64(&batch, i, "version"),
version_history: String::new(),
@@ -433,6 +448,8 @@ impl LanceDBOps {
// 2026-10-08 (Gap#2):nullable 列用 Option,未声明时写 None → 库里是 NULL
let mut confidences: Vec<Option<f64>> = Vec::new();
let mut confidence_sources: Vec<&str> = Vec::new();
// A10 (t_d618dc7c):人工有用单独计数(nullable,与 confidence 同款「未声明写 NULL」)
let mut human_useful_counts: Vec<Option<i64>> = Vec::new();
for r in &records {
ids.push(r["id"].as_str().unwrap_or(""));
@@ -455,6 +472,9 @@ impl LanceDBOps {
not_useful_counts.push(r["not_useful_count"].as_i64().unwrap_or(0));
human_not_useful_counts.push(r["human_not_useful_count"].as_i64().unwrap_or(0)); // GA-P0-1
dedup_downweight_counts.push(r["dedup_downweight_count"].as_i64().unwrap_or(0)); // GA-P0-1
// A10 (t_d618dc7c):未声明/NULL → None(写 NULL);显式给了整数 → Some(v)。
// 与 confidence 同款:库里 NULL = 「从未被人工点过」,非 0。
human_useful_counts.push(r["human_useful_count"].as_i64());
freshnesses.push(r["freshness"].as_str().unwrap_or("fresh"));
versions.push(r["version"].as_i64().unwrap_or(1));
version_histories.push(r["version_history"].as_str().unwrap_or("[]"));
@@ -540,6 +560,9 @@ impl LanceDBOps {
Arc::new(StringArray::from(valid_froms)),
Arc::new(StringArray::from(valid_tos)),
Arc::new(StringArray::from(provenances)),
// A10 (t_d618dc7c):human_useful_count 列(nullable,NULL=从未被人工点过),
// 追加在 arrow_schema() 尾字段 human_useful_count 之后,顺序严格一致。
Arc::new(Int64Array::from(human_useful_counts)),
];
let batch = RecordBatch::try_new(schema.clone(), columns)?;
@@ -584,7 +607,11 @@ impl LanceDBOps {
for f in &fields {
let col = f["column"].as_str().unwrap_or("");
if !col.is_empty() {
let val = col_i64(&batch, i, col);
// A10 (t_d618dc7c):NULL-aware 自增基数 —— 可空列(human_useful_count)
// 的 NULL 行「从未被人工点过」,$inc 时按 0 起算(NULL + 1 ⇒ 1)。
// 用 col_i64_opt(NULL→None)而非 col_i64(NULL→物理值 0),
// 不依赖 Arrow 物理缓冲约定,语义显式。非空列行为不变。
let val = col_i64_opt(&batch, i, col).unwrap_or(0);
current_values.insert(col.to_string(), val);
}
}
@@ -1031,6 +1058,8 @@ impl LanceDBOps {
not_useful_count: col_i64(batch, i, "not_useful_count"),
human_not_useful_count: col_i64(batch, i, "human_not_useful_count"),
dedup_downweight_count: col_i64(batch, i, "dedup_downweight_count"),
// A10 (t_d618dc7c):读侧接线 —— human_useful_count 走可空读法(NULL 读回 None)
human_useful_count: col_i64_opt(batch, i, "human_useful_count"),
freshness: col_str(batch, i, "freshness"),
version: col_i64(batch, i, "version"),
version_history: String::new(),
@@ -1071,6 +1100,7 @@ impl LanceDBOps {
"source", "volatile_flag", "is_deleted",
// GA-P0-1 (t_718d8707):scan_all 投影裁剪,漏加 ⇒ col_i64 取不到列 ⇒ 恒 0
"human_not_useful_count", "dedup_downweight_count",
"human_useful_count",
// GA-P0-2 (t_c6d41ac6):拆分字段投影,漏加 ⇒ col_i64 取不到列 ⇒ 恒 0
"recall_seen_count", "recall_verified_count",
"last_recalled_at", "created_at", "updated_at",
@@ -1108,6 +1138,8 @@ impl LanceDBOps {
// GA-P0-1 (t_718d8707):拆分字段读侧接线
human_not_useful_count: col_i64(&batch, i, "human_not_useful_count"),
dedup_downweight_count: col_i64(&batch, i, "dedup_downweight_count"),
// A10 (t_d618dc7c):读侧接线 —— human_useful_count 走可空读法(NULL 读回 None)
human_useful_count: col_i64_opt(&batch, i, "human_useful_count"),
freshness: col_str(&batch, i, "freshness"),
version: col_i64(&batch, i, "version"),
version_history: String::new(),
@@ -1156,6 +1188,7 @@ impl LanceDBOps {
"useful_count", "not_useful_count", "freshness", "version",
"source", "volatile_flag", "is_deleted",
"human_not_useful_count", "dedup_downweight_count",
"human_useful_count",
"recall_seen_count", "recall_verified_count",
"delete_reason", // GA-P0-3
"last_recalled_at", "created_at", "updated_at",
@@ -1190,6 +1223,8 @@ impl LanceDBOps {
not_useful_count: col_i64(&batch, i, "not_useful_count"),
human_not_useful_count: col_i64(&batch, i, "human_not_useful_count"),
dedup_downweight_count: col_i64(&batch, i, "dedup_downweight_count"),
// A10 (t_d618dc7c):读侧接线 —— human_useful_count 走可空读法(NULL 读回 None)
human_useful_count: col_i64_opt(&batch, i, "human_useful_count"),
freshness: col_str(&batch, i, "freshness"),
version: col_i64(&batch, i, "version"),
version_history: String::new(),
@@ -1341,6 +1376,13 @@ fn col_f64_opt(b: &RecordBatch, r: usize, c: &str) -> Option<f64> {
.and_then(|col| col.as_any().downcast_ref::<Float64Array>())
.and_then(|a| if a.is_null(r) { None } else { Some(a.value(r)) })
}
/// col_i64_opt (t_d618dc7c):可空 Int64 读法。列不存在或该行是 NULL 都返回 None(区别于 0)。
/// 用于 human_useful_count —— 存量行/从未被人工点过的是 NULL,要读回 None("未知")而非 0。
fn col_i64_opt(b: &RecordBatch, r: usize, c: &str) -> Option<i64> {
b.column_by_name(c)
.and_then(|col| col.as_any().downcast_ref::<Int64Array>())
.and_then(|a| if a.is_null(r) { None } else { Some(a.value(r)) })
}
fn col_i64(b: &RecordBatch, r: usize, c: &str) -> i64 {
b.column_by_name(c)
.and_then(|col| col.as_any().downcast_ref::<Int64Array>())
+5
View File
@@ -9,3 +9,8 @@ b8f7ddb53ce056a1ac86468a8e9a7557c71922f0
c57f557ab8d126c7ef031e63402abaa1f6602155
aaeaf2b7ec9304b851089cbe64ddda0a5916d99f
a2be088cba59c95901b22d855dea9b6df3bf3a80
4fb4705e6de8991e9863cf8902e4265ec412626e
212624a42541c41f10168e5a3834bd2304efcdb9
4341fac4c28a4f2825f7373ea0ec94d07c6452f0
b101b464471f6283c438f089e9ec269c8f2b1644
01d8f34
+200
View File
@@ -0,0 +1,200 @@
#!/usr/bin/env python3
"""织忆自检·全量取数器(唯一允许直连生产库的脚本)
为什么存在
----------
织忆相关的定时自检脚本曾有 ~20 个,其中两个直接 `lancedb.connect("/var/lib/memoryweave")`
绕过服务读全表。那种写法的病根不是"直连",而是**取数逻辑散落多处、与 schema 一起腐烂**:
pattern 自检写死 `type='pattern'`(库里其实是 `pattern_stat`)⇒ 连续数月静默 0 输出。
本文件把"全量取数"收成一处、放进仓库:改 schema 时同一个 commit 就能改它,且它有输出可复核。
判定/告警/投递**不在这里**(留在外部 cron)—— 观测者不能住在被观测者体内。
它产出 `~/.hermes/state/zhiyi-quality.json`,服务端 `GET /api/v1/selfcheck?level=full` 读这份快照。
口径(必须与历史 zhiyi-quality-watch.py 一致,改了就改告警语义)
------------------------------------------------------------
- 碎片:`len(content.strip()) < FRAG_LEN(20)`,按**字符数**(不是字节,中文按 1 算)
- 冗余:live 行内 content 完全相同;冗余行数 = Σ(组内行数-1)
- 近 7 天:created_at 在 7 天内(live)
- 写量:按 created_at 的**本地日期**分桶,同时给 rows(含已删)与 live(仅存活)
性能
----
只投影 3 列(content/created_at/is_deleted),不读 1024 维向量:
4 万行 0.06s(旧实现 `to_arrow()` 全列要数秒且吃 1G+ 内存)。
用法
----
python3 tools/selfcheck_full.py [--out PATH] [--json] [--days 60]
"""
from __future__ import annotations
import argparse
import datetime as dt
import json
import os
import sys
import time
from collections import Counter
DB_PATH = os.environ.get("ZHIYI_DB", "/var/lib/memoryweave")
FRAG_LEN = 20
OUT_DEFAULT = os.path.expanduser("~/.hermes/state/zhiyi-quality.json")
SCHEMA = 1
def _reexec_with_lancedb() -> None:
"""cron 默认解释器没有 lancedb 时,切到 lance-compact venv 再跑(一次性)。"""
try:
import lancedb # noqa: F401
return
except ImportError:
pass
venv_py = os.path.expanduser("~/.hermes/venvs/lance-compact/bin/python")
if os.path.exists(venv_py) and os.path.realpath(sys.prefix) != os.path.realpath(
os.path.dirname(os.path.dirname(venv_py))
):
os.execv(venv_py, [venv_py] + sys.argv)
sys.stderr.write("[selfcheck_full] lancedb 不可用(需 lance-compact venv)\n")
sys.exit(2)
def _as_bool(v) -> bool:
if v is None:
return False
if isinstance(v, bool):
return v
return str(v).strip().lower() in ("true", "1")
def collect(days: int = 60) -> dict:
import lancedb
t0 = time.time()
db = lancedb.connect(DB_PATH)
table = db.open_table("memories")
tbl = table.to_lance().to_table(columns=["content", "created_at", "is_deleted"])
contents = tbl.column("content").to_pylist()
created = tbl.column("created_at").to_pylist()
deleted = tbl.column("is_deleted").to_pylist()
total = len(contents)
frag_all = 0
live = 0
frag_live = 0
dup_counter: Counter[str] = Counter()
daily: dict[str, dict[str, int]] = {}
now = dt.datetime.now()
week_ago = now - dt.timedelta(days=7)
new_7d = 0
new_frag_7d = 0
for i in range(total):
raw = contents[i]
text = str(raw).strip() if raw is not None else ""
n = len(text)
is_frag = n < FRAG_LEN
if is_frag:
frag_all += 1
is_del = _as_bool(deleted[i] if i < len(deleted) else False)
# created_at:存量行有空串/畸形 → 归 unknown,不炸整批
day = "unknown"
ts = None
if i < len(created):
raw_ts = created[i]
if raw_ts:
try:
if isinstance(raw_ts, dt.datetime):
ts = raw_ts
else:
ts = dt.datetime.fromisoformat(str(raw_ts).replace("Z", "+00:00"))
if ts.tzinfo is not None:
ts = ts.astimezone().replace(tzinfo=None)
day = ts.strftime("%Y-%m-%d")
except Exception:
ts = None
slot = daily.setdefault(day, {"rows": 0, "live": 0})
slot["rows"] += 1
if is_del:
continue
live += 1
slot["live"] += 1
dup_counter[text] += 1
if is_frag:
frag_live += 1
if ts is not None and ts >= week_ago:
new_7d += 1
if is_frag:
new_frag_7d += 1
dup_groups = sum(1 for c in dup_counter.values() if c > 1)
dup_extra = sum(c - 1 for c in dup_counter.values() if c > 1)
# 只保留最近 days 天(含 unknown),按日期升序
keep = sorted(daily.keys())[-days:]
day_rows = [{"date": d, "rows": daily[d]["rows"], "live": daily[d]["live"]} for d in keep]
live_days = [x["live"] for x in day_rows if x["date"] != "unknown"]
today = now.strftime("%Y-%m-%d")
today_live = next((x["live"] for x in day_rows if x["date"] == today), 0)
return {
"schema_version": SCHEMA,
"generated_at": now.strftime("%Y-%m-%dT%H:%M:%S%z"),
"source": {"db": DB_PATH, "table": "memories", "mode": "read_only_projection"},
"duration_ms": int((time.time() - t0) * 1000),
"quality": {
"frag_len": FRAG_LEN,
"total_rows": total,
"live_rows": live,
"frag_rows_all": frag_all,
"frag_rate_all": round(frag_all / total, 4) if total else None,
"frag_rows_live": frag_live,
"frag_rate_live": round(frag_live / live, 4) if live else None,
"dup_groups": dup_groups,
"dup_extra_rows": dup_extra,
"dup_rate": round(dup_extra / live, 4) if live else None,
"new_rows_7d": new_7d,
"new_frag_rows_7d": new_frag_7d,
"new_frag_rate_7d": round(new_frag_7d / new_7d, 4) if new_7d else None,
},
"write_volume": {
"days": day_rows,
"today": today_live,
"today_date": today,
# 近 7 个完整日(不含今天/unknown)
"last_7d": sum(x["live"] for x in day_rows if x["date"] not in (today, "unknown")) if day_rows else 0,
"nonzero_days": sum(1 for x in live_days if x > 0),
},
}
def main() -> int:
ap = argparse.ArgumentParser(description="织忆自检全量取数(只读)")
ap.add_argument("--out", default=OUT_DEFAULT)
ap.add_argument("--json", action="store_true", help="打印到 stdout")
ap.add_argument("--days", type=int, default=60)
a = ap.parse_args()
_reexec_with_lancedb()
snap = collect(a.days)
if a.out:
os.makedirs(os.path.dirname(a.out), exist_ok=True)
tmp = a.out + ".tmp"
with open(tmp, "w", encoding="utf-8") as f:
json.dump(snap, f, ensure_ascii=False)
os.replace(tmp, a.out) # 原子替换:读方永不会看到半个文件
if a.json:
print(json.dumps(snap, ensure_ascii=False, indent=1))
return 0
if __name__ == "__main__":
sys.exit(main())