Files
memoryweave/go/internal/distill/write_ops_test.go
T
小唯 211d516e5f fix(distill): t_a0831457 P0 解耦——写时四操作门控不再劫持基础 InsertMemory(shadow/off 恒插入,门控只管标记)+ env 改名 ZHIYI_WRITE_SEMANTIC_OPS(旧名兼容一档)
根因:ApplyWriteOp 在 shadow(默认)/off 恒返回 shouldInsert=false ⇒ api/server.go 蒸馏写回路径
`if !shouldInsert { continue }` 把基础 InsertMemory 整个跳过 ⇒ 2026-10-14 起每日蒸馏事实
2053/1094/1559 → 384 → 0 全丢(shadow log 2189 条判定,2120 条该落库的被弃;episodes 原始层完整可重蒸)。
违背了门控自身注释声明的「默认 shadow ⇒ 零行为变化」硬要求(零变化=等价特性不存在,之前基础插入总是发生)。

改动(三模式语义表):
- shadow(默认) ⇒ 插入新条 ✓ + 不做任何标记 ✓ + 记 shadow log ✓
- apply        ⇒ 插入新条 ✓ + 做标记 ✓(NOOP 丢弃;apply 语义不变,回归测试守住)
- off          ⇒ 插入新条 ✓ + 不跑判定 ✓(零开销)
1) write_ops.go ApplyWriteOp:!writeOpsApply() 分支 false→true(门控不参与插入决策)
2) api/server.go 调用点:verdict!=nil 包一层;err/!shouldInsert 丢弃路径仅剩 apply+NOOP 与 apply 标记失败,均显式 warning(禁静默)
3) AC10:ZHIYI_WRITE_OPS → ZHIYI_WRITE_SEMANTIC_OPS(防「所有写操作开关」误读);旧名兼容一档+弃用日志(sync.Once 只打一次);默认值仍是 shadow
4) 回归测试 write_ops_regression_test.go(旧代码上先红已实证:shadow 4 判定/默认/off 5 项 FAIL):
   断言 shadow 下四操作均 shouldInsert=true 且 MarkSuperseded/MarkConflict 零调用(AC2 增补)
5) 旧测试 TestWriteOps_Noop 改写:其「shadow+NOOP 不插入」断言即 bug 语义本身(量具自证:该测试随修复必须改,否则回归门失效)

边界(AC6):不动 episodes 层、不删任何 memories、不改默认值(仍 shadow,改的是 shadow 的语义);
与 284584c(lancedb_ipc.go/usage_track.go)文件不重叠,合并部署=一次观察协议+一个回滚点。
未部署:按 AC3/AC9 交证据包(diff+测试红/绿+md5+回滚方案+观察协议)本体转呈牧尘拍板。
2026-10-15 22:53:03 +08:00

301 lines
10 KiB
Go
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
// 织忆 MemoryWeave — 写时四操作 + 哈希去重 单测(t_3e98b65a)
package distill
import (
"os"
"path/filepath"
"testing"
"github.com/xiaoxue/memoryweave/internal/models"
)
// ─── 测试辅助 ─────────────────────────────────────────────
// fakeStore 内存版 WriteOpsStore(记录被标记的操作,供 apply 断言)。
type fakeStore struct {
superseded map[string]string // oldID → newID
conflicted map[string]bool
}
func newFakeStore() *fakeStore {
return &fakeStore{superseded: map[string]string{}, conflicted: map[string]bool{}}
}
func (f *fakeStore) MarkSuperseded(oldID, newID string) error {
f.superseded[oldID] = newID
return nil
}
func (f *fakeStore) MarkConflict(id string) error {
f.conflicted[id] = true
return nil
}
func mkMem(id, content string) models.MemoryRecord {
return models.MemoryRecord{ID: id, Content: content}
}
// 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) }
}
// withLogPath 临时把影子日志指到临时文件,返回清理函数。
func withLogPath(t *testing.T) func() {
p := filepath.Join(t.TempDir(), "shadow.log")
old := os.Getenv("ZHIYI_WRITE_OPS_LOG")
os.Setenv("ZHIYI_WRITE_OPS_LOG", p)
return func() { os.Setenv("ZHIYI_WRITE_OPS_LOG", old) }
}
// ─── AC2:写前哈希去重(同内容连写 3 次 → 库内 1 条)────────────────
func TestWriteOpHashDedup_ExactDuplicate(t *testing.T) {
candidate := "牧尘在招商局工作"
existing := []models.MemoryRecord{
{ID: "mem_1", Content: "牧尘在招商局工作。"}, // 多句号,归一化后等价
{ID: "mem_2", Content: "牧尘在别的公司"},
}
dupID, dup := WriteOpHashDedup(candidate, existing)
if !dup {
t.Fatalf("期望判为重复,实际不重复(candidate=%q)", candidate)
}
if dupID != "mem_1" {
t.Fatalf("期望命中 mem_1,实际 %s", dupID)
}
}
func TestWriteOpHashDedup_NotDuplicate(t *testing.T) {
candidate := "牧尘最近在学 Go"
existing := []models.MemoryRecord{
{ID: "mem_1", Content: "牧尘在招商局工作"},
}
if _, dup := WriteOpHashDedup(candidate, existing); dup {
t.Fatalf("期望不判为重复,实际判重(candidate=%q)", candidate)
}
}
func TestNormalizeContent_HashStable(t *testing.T) {
if ContentHash("牧尘在招商局工作") != ContentHash(" 牧尘在招商局工作 ") {
t.Fatalf("归一化哈希不稳定:首尾空白应被忽略")
}
}
// AC2 全链路:同内容连写 3 次 → 3 次都判同一重复 → 只该写 1 条
func TestWriteOps_ThreeWritesOneRow(t *testing.T) {
candidate := "X=true"
// 第一次写入:库里没有 → 不重复
if _, dup := WriteOpHashDedup(candidate, nil); dup {
t.Fatalf("首次写入不应判重")
}
// 第二、三次:已有第一条 → 判重复(拒绝写入)
existing := []models.MemoryRecord{mkMem("mem_1", candidate)}
for i := 0; i < 2; i++ {
if _, dup := WriteOpHashDedup(candidate, existing); !dup {
t.Fatalf("第 %d 次重复写入未拦截", i+2)
}
}
// 结论:库里始终只有 1 条(mem_1),新重复被源头堵住
if len(existing) != 1 {
t.Fatalf("库内应 1 条,实际 %d", len(existing))
}
}
// ─── AC4:四操作各 1 个单测 ────────────────────────────────
// 操作1:ADD —— 无语义等价 → 新建
func TestWriteOps_Add(t *testing.T) {
defer withMode("apply")()
candidate := "牧尘最近在学 Rust 异步"
similar := []SimilarMemory{
{ID: "mem_1", Content: "牧尘在招商局工作", Similarity: 0.4},
}
v := JudgeWriteOp(candidate, similar, nil, nil)
if v == nil {
t.Fatalf("JudgeWriteOp 返回 nil")
}
if v.Op != OpAdd {
t.Fatalf("期望 ADD,实际 %s(%s)", v.Op, v.Reason)
}
shouldInsert, err := ApplyWriteOp(*v, newFakeStore(), "mem_new")
if err != nil || !shouldInsert {
t.Fatalf("ADD 应插入:shouldInsert=%v err=%v", shouldInsert, err)
}
}
// 操作2:UPDATE —— 互补/更新 → 并入现有(supersede)
func TestWriteOps_Update(t *testing.T) {
defer withMode("apply")()
candidate := "牧尘在招商局工作 负责算法部门"
similar := []SimilarMemory{
{ID: "mem_1", Content: "牧尘在招商局工作", Similarity: 0.92},
}
v := JudgeWriteOp(candidate, similar, nil, nil)
if v == nil {
t.Fatalf("nil verdict")
}
if v.Op != OpUpdate {
t.Fatalf("期望 UPDATE,实际 %s(%s)", v.Op, v.Reason)
}
store := newFakeStore()
shouldInsert, err := ApplyWriteOp(*v, store, "mem_new")
if err != nil || !shouldInsert {
t.Fatalf("UPDATE 应插入:%v %v", shouldInsert, err)
}
// 旧条被标记 superseded_by=mem_new
if store.superseded["mem_1"] != "mem_new" {
t.Fatalf("旧条未标记 superseded_by=mem_new,实际 %q", store.superseded["mem_1"])
}
}
// 操作3:NOOP —— 无新增价值。
// t_a0831457 解耦修复后语义:apply 模式丢弃(特性预期去重行为);
// shadow/默认模式**不再拦基础插入**(门控只决定标记,不决定插入)——
// 旧断言「shadow+NOOP 不插入」正是 10-14 起蒸馏事实全丢的 bug 语义,已改写。
func TestWriteOps_Noop(t *testing.T) {
candidate := "牧尘在招商局工作"
similar := []SimilarMemory{
{ID: "mem_1", Content: "牧尘在招商局工作", Similarity: 0.99}, // 语义等价
}
t.Run("apply+NOOP_丢弃", func(t *testing.T) {
defer withMode("apply")()
v := JudgeWriteOp(candidate, similar, nil, nil)
if v == nil || v.Op != OpNoop {
t.Fatalf("期望 NOOP,实际 %v", v)
}
shouldInsert, err := ApplyWriteOp(*v, newFakeStore(), "mem_new")
if err != nil || shouldInsert {
t.Fatalf("apply+NOOP 应丢弃:shouldInsert=%v err=%v", shouldInsert, err)
}
})
t.Run("shadow+NOOP_基础插入照跑", func(t *testing.T) {
defer withMode("shadow")()
defer withLogPath(t)()
v := JudgeWriteOp(candidate, similar, nil, nil)
if v == nil || v.Op != OpNoop {
t.Fatalf("期望 NOOP,实际 %v", v)
}
store := newFakeStore()
shouldInsert, err := ApplyWriteOp(*v, store, "mem_new")
if err != nil || !shouldInsert {
t.Fatalf("P0:shadow+NOOP 不得拦基础插入:shouldInsert=%v err=%v", shouldInsert, err)
}
if len(store.superseded) != 0 || len(store.conflicted) != 0 {
t.Fatalf("shadow 不得做标记:%v %v", store.superseded, store.conflicted)
}
})
}
// 操作4:CONFLICT-MARK —— 矛盾 → 双方标记 conflict(不删),交人工
func TestWriteOps_ConflictMark(t *testing.T) {
defer withMode("apply")()
candidate := "牧尘不在招商局工作了"
similar := []SimilarMemory{
{ID: "mem_1", Content: "牧尘在招商局工作", Similarity: 0.85},
}
v := JudgeWriteOp(candidate, similar, nil, nil)
if v == nil {
t.Fatalf("nil verdict")
}
if v.Op != OpConflictMark {
t.Fatalf("期望 CONFLICT-MARK,实际 %s(%s)", v.Op, v.Reason)
}
store := newFakeStore()
shouldInsert, err := ApplyWriteOp(*v, store, "mem_new")
if err != nil || !shouldInsert {
t.Fatalf("CONFLICT 应插入(供人工复核):%v %v", shouldInsert, err)
}
// 旧条被标记 conflict
if !store.conflicted["mem_1"] {
t.Fatalf("旧条未标记 conflict")
}
}
// 矛盾判定:true/false 对立
func TestRuleContradiction_TrueFalse(t *testing.T) {
if !ruleContradiction("X=false", SimilarMemory{Content: "X=true"}) {
t.Fatalf("false/true 应判矛盾")
}
if ruleContradiction("X=1", SimilarMemory{Content: "Y=2"}) {
t.Fatalf("无关事实不应判矛盾")
}
}
// ─── AC1:写「X=true」后写「X=false」→ 旧条 conflict 标记 + 新条 active ──
func TestWriteOps_WriteTrueThenFalse(t *testing.T) {
defer withMode("apply")()
// 第一次:写 X=true(库里空 → ADD)
first := JudgeWriteOp("X=true", nil, nil, nil)
if first == nil || first.Op != OpAdd {
t.Fatalf("首次 X=true 应 ADD,实际 %+v", first)
}
// 第二次:写 X=false,库里已有 X=true → CONFLICT(矛盾)
second := JudgeWriteOp("X=false", []SimilarMemory{
{ID: "mem_1", Content: "X=true", Similarity: 0.9},
}, nil, nil)
if second == nil {
t.Fatalf("nil")
}
if second.Op != OpConflictMark {
t.Fatalf("X=false 与 X=true 矛盾,应 CONFLICT-MARK,实际 %s", second.Op)
}
store := newFakeStore()
shouldInsert, err := ApplyWriteOp(*second, store, "mem_2")
if err != nil || !shouldInsert {
t.Fatalf("CONFLICT 应插入新条:%v %v", shouldInsert, err)
}
// 旧条 conflict 标记 + 新条 active(插入)
if !store.conflicted["mem_1"] {
t.Fatalf("旧条 X=true 未标 conflict")
}
}
// ─── AC5:影子模式行为零变化(判定不改库)──────────────────────
// 影子模式:JudgeWriteOp 只记日志,不触碰 store;同 query 召回结果不受影响。
func TestWriteOps_ShadowModeNoMutation(t *testing.T) {
defer withMode("shadow")()
defer withLogPath(t)()
store := newFakeStore()
// 影子模式下连续判定 ADD/UPDATE/NOOP/CONFLICT
ops := []struct {
op WriteOp
candidate string
sim []SimilarMemory
}{
{OpAdd, "新事实A", []SimilarMemory{{"mem_1", "无关", 0.2}}},
{OpUpdate, "牧尘在招商局负责算法", []SimilarMemory{{"mem_1", "牧尘在招商局", 0.9}}},
{OpNoop, "牧尘在招商局", []SimilarMemory{{"mem_1", "牧尘在招商局", 0.99}}},
{OpConflictMark, "牧尘不在招商局", []SimilarMemory{{"mem_1", "牧尘在招商局", 0.8}}},
}
for _, o := range ops {
v := JudgeWriteOp(o.candidate, o.sim, nil, nil)
if v == nil || v.Op != o.op {
t.Fatalf("期望 %s,实际 %v", o.op, v)
}
// apply 到 store(验证影子模式语义下 store 不被改动)
_, _ = ApplyWriteOp(*v, store, "mem_new")
}
// 影子模式:store 应保持零变化(superseded/conflict 都空)
if len(store.superseded) != 0 || len(store.conflicted) != 0 {
t.Fatalf("影子模式改了 store:superseded=%v conflicted=%v", store.superseded, store.conflicted)
}
}
// 影子日志确实被写入(供 AC3 分布统计)
func TestWriteOps_ShadowLogWritten(t *testing.T) {
defer withMode("shadow")()
defer withLogPath(t)()
_ = JudgeWriteOp("测试事实", []SimilarMemory{{"mem_1", "无关", 0.1}}, nil, nil)
content, err := os.ReadFile(os.Getenv("ZHIYI_WRITE_OPS_LOG"))
if err != nil {
t.Fatalf("读影子日志失败: %v", err)
}
if len(content) == 0 {
t.Fatalf("影子日志为空,AC3 分布统计无源")
}
}