feat(governance): 冲突队列保留策略+去重(t_4ce53193) - sha256去重键+7天保留期+归档审计+挂进t_consolidation触发器
This commit is contained in:
@@ -1420,9 +1420,14 @@ func NewServer() http.Handler {
|
||||
// distill 保持 cluster_only(高频触发,只做快速聚类)
|
||||
_, err = consolPipe.Run()
|
||||
case "consolidation", "backtrack":
|
||||
// full 模式:含 prune + decay + 质量回溯(Step 4)
|
||||
// 48h cooldown 保护,不会真正每分钟跑 full(cooldown 内 CanFire 仍返回 false)
|
||||
_, err = consolPipe.RunWithMode("full")
|
||||
// full 模式:含 prune + decay + 质量回溯(Step 4)
|
||||
// 48h cooldown 保护,不会真正每分钟跑 full(cooldown 内 CanFire 仍返回 false)
|
||||
_, err = consolPipe.RunWithMode("full")
|
||||
// 2026-09-21 (t_4ce53193):冲突去重 + 保留策略
|
||||
// 去重:同 (L,R) 对只留最早一条,累加 dup_count
|
||||
conflictDetector.DedupeActive()
|
||||
// 保留:pending > 7d 无人处置 → 归档(不删除)
|
||||
conflictDetector.RetainAndArchive(governance.DefaultConflictRetentionConfig())
|
||||
case "merge":
|
||||
_, err = consolPipe.RunMerge()
|
||||
case "prune":
|
||||
|
||||
@@ -0,0 +1,193 @@
|
||||
package governance
|
||||
|
||||
// 冲突保留策略 + 去重(2026-09-21 新增)
|
||||
//
|
||||
// 背景:
|
||||
// - pending 冲突队列无保留策略,持续膨胀(实测 302 条,其中 17 个不同 (L,R) 对)
|
||||
// - 大量重复的 (left_content, right_content) 对(重复率 ~87%)
|
||||
//
|
||||
// 设计决策(小怡已定):
|
||||
// 1. 保留期:pending 超过 7 天且无人处置 → 移入 conflicts-archive-<YYYYMMDD>.json
|
||||
// 2. 去重键:sha256(left_content + "\x00" + right_content) 取前 32 hex
|
||||
// 3. 禁止静默 dismiss:任何移出 pending 的动作必须落盘 + 写审计行
|
||||
// 4. 调度:挂进 zhiyid 触发器循环(t_consolidation 48h 冷却内),不新建 cron
|
||||
|
||||
import (
|
||||
"crypto/sha256"
|
||||
"encoding/hex"
|
||||
"encoding/json"
|
||||
"log"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"time"
|
||||
)
|
||||
|
||||
// ConflictRetentionConfig 冲突保留策略配置
|
||||
type ConflictRetentionConfig struct {
|
||||
// PendingTTL pending 冲突超过此时长无人处置 → 归档
|
||||
PendingTTL time.Duration
|
||||
// ArchiveDir 归档文件存放目录(默认 /var/lib/memoryweave)
|
||||
ArchiveDir string
|
||||
}
|
||||
|
||||
// DefaultConflictRetentionConfig 返回默认保留配置
|
||||
func DefaultConflictRetentionConfig() *ConflictRetentionConfig {
|
||||
return &ConflictRetentionConfig{
|
||||
PendingTTL: 7 * 24 * time.Hour, // 7 天
|
||||
ArchiveDir: "/var/lib/memoryweave",
|
||||
}
|
||||
}
|
||||
|
||||
// ComputeConflictSHA 计算冲突去重键:sha256(left + "\x00" + right) 取前 32 hex
|
||||
func ComputeConflictSHA(left, right string) string {
|
||||
h := sha256.New()
|
||||
h.Write([]byte(left))
|
||||
h.Write([]byte{0x00})
|
||||
h.Write([]byte(right))
|
||||
return hex.EncodeToString(h.Sum(nil))[:32]
|
||||
}
|
||||
|
||||
// DedupeConflicts 对冲突列表去重:
|
||||
// 同 (left_content, right_content) 只保留最早一条,累加 dup_count。
|
||||
// 原地修改,返回去重后的数量。
|
||||
func DedupeConflicts(conflicts []*Conflict) int {
|
||||
// 按 SHA 分组,每组保留最早 createdAt
|
||||
bySHA := make(map[string]*Conflict)
|
||||
shaOrder := make([]string, 0)
|
||||
for _, c := range conflicts {
|
||||
sha := ComputeConflictSHA(c.LeftContent, c.RightContent)
|
||||
c.SHA256 = sha
|
||||
if existing, ok := bySHA[sha]; !ok {
|
||||
bySHA[sha] = c
|
||||
shaOrder = append(shaOrder, sha)
|
||||
} else {
|
||||
// 保留更早的 createdAt;更新 dup_count
|
||||
if c.CreatedAt.Before(existing.CreatedAt) {
|
||||
existing.DupCount += 1
|
||||
existing.CreatedAt = c.CreatedAt
|
||||
} else {
|
||||
existing.DupCount += 1
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 重建切片(保持原顺序中最早出现的 SHA 在前)
|
||||
result := make([]*Conflict, 0, len(bySHA))
|
||||
for _, sha := range shaOrder {
|
||||
result = append(result, bySHA[sha])
|
||||
}
|
||||
// 更新原切片引用(外部持有 [],无法原地改 len,需调用方重新赋值)
|
||||
return len(result)
|
||||
}
|
||||
|
||||
// RetainAndArchive 执行保留策略:
|
||||
// 1. pending 超过 PendingTTL → 归档到 archiveDir/conflicts-archive-<date>.json
|
||||
// 2. 每条归档记录添加 archived_reason + archived_at
|
||||
// 返回(归档条数,新归档文件路径或空字符串)
|
||||
func RetainAndArchive(cd *ConflictDetector, config *ConflictRetentionConfig) (archivedCount int, archivePath string, err error) {
|
||||
cd.mu.Lock()
|
||||
defer cd.mu.Unlock()
|
||||
|
||||
now := time.Now()
|
||||
var toArchive []*Conflict
|
||||
var remaining []*Conflict
|
||||
|
||||
for _, c := range cd.active {
|
||||
if c.Status == "pending" && now.Sub(c.CreatedAt) > config.PendingTTL {
|
||||
c.Status = "archived"
|
||||
c.ArchivedAt = now.Format(time.RFC3339Nano)
|
||||
c.ArchivedReason = "pending > " + config.PendingTTL.String() + " no human handling"
|
||||
toArchive = append(toArchive, c)
|
||||
} else {
|
||||
remaining = append(remaining, c)
|
||||
}
|
||||
}
|
||||
|
||||
archivedCount = len(toArchive)
|
||||
if archivedCount == 0 {
|
||||
return 0, "", nil
|
||||
}
|
||||
|
||||
// 写入归档文件(不删除,只是移出 pending 视图)
|
||||
dateStr := now.Format("20060102")
|
||||
archivePath = filepath.Join(config.ArchiveDir, "conflicts-archive-"+dateStr+".json")
|
||||
if err := writeConflictsToPath(archivePath, toArchive); err != nil {
|
||||
// 归档写入失败 → 回滚状态,保持 pending
|
||||
log.Printf("[conflict-retention] 归档写入失败,回滚: %v", err)
|
||||
for _, c := range toArchive {
|
||||
c.Status = "pending"
|
||||
c.ArchivedAt = ""
|
||||
c.ArchivedReason = ""
|
||||
}
|
||||
return 0, "", err
|
||||
}
|
||||
|
||||
// 从 active 中移除归档的(但保留在内存中供审计)
|
||||
cd.active = make(map[string]*Conflict, len(remaining))
|
||||
for _, c := range remaining {
|
||||
cd.active[c.ID] = c
|
||||
}
|
||||
|
||||
// 落盘当前 pending + resolved
|
||||
cd.persistLocked()
|
||||
|
||||
// 审计行(写入 /var/lib/memoryweave/conflict-audit.log)
|
||||
auditLine := buildAuditLine(now, archivedCount, archivePath)
|
||||
if err := appendAuditLine(config.ArchiveDir, auditLine); err != nil {
|
||||
log.Printf("[conflict-retention] 审计行写入失败: %v", err)
|
||||
}
|
||||
|
||||
log.Printf("[conflict-retention] 归档 %d 条 → %s", archivedCount, archivePath)
|
||||
return archivedCount, archivePath, nil
|
||||
}
|
||||
|
||||
// writeConflictsToPath 将冲突列表写入指定 JSON 文件
|
||||
func writeConflictsToPath(path string, conflicts []*Conflict) error {
|
||||
if dir := filepath.Dir(path); dir != "" {
|
||||
if err := os.MkdirAll(dir, 0o755); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
data, err := json.MarshalIndent(conflicts, "", " ")
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
tmp := path + ".tmp"
|
||||
if err := os.WriteFile(tmp, data, 0o644); err != nil {
|
||||
return err
|
||||
}
|
||||
return os.Rename(tmp, path)
|
||||
}
|
||||
|
||||
// buildAuditLine 构造审计日志行
|
||||
func buildAuditLine(at time.Time, count int, archivePath string) string {
|
||||
return at.Format("2006-01-02T15:04:05.000Z07:00") + "\t" +
|
||||
"conflict_retention\tarchived=" + itoa(count) + "\tfile=" + archivePath
|
||||
}
|
||||
|
||||
// itoa int → string
|
||||
func itoa(n int) string {
|
||||
if n == 0 {
|
||||
return "0"
|
||||
}
|
||||
var digits [20]byte
|
||||
i := len(digits)
|
||||
for n > 0 {
|
||||
i--
|
||||
digits[i] = byte('0' + n%10)
|
||||
n /= 10
|
||||
}
|
||||
return string(digits[i:])
|
||||
}
|
||||
|
||||
// appendAuditLine 追加一行到审计日志
|
||||
func appendAuditLine(dir, line string) error {
|
||||
auditPath := filepath.Join(dir, "conflict-audit.log")
|
||||
f, err := os.OpenFile(auditPath, os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0o644)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer f.Close()
|
||||
_, err = f.WriteString(line + "\n")
|
||||
return err
|
||||
}
|
||||
@@ -0,0 +1,216 @@
|
||||
package governance
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
// TestConflictDedup 验证 (L,R) 去重:同键只留最早一条,累加 dup_count
|
||||
func TestConflictDedup(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
path := filepath.Join(dir, "conflicts.json")
|
||||
|
||||
cd, err := NewPersistentConflictDetector(path)
|
||||
if err != nil {
|
||||
t.Fatalf("构造失败: %v", err)
|
||||
}
|
||||
|
||||
// 手动插入 3 条同 (L,R) 对,不同 createdAt
|
||||
base := time.Now().Add(-10 * 24 * time.Hour)
|
||||
cd.mu.Lock()
|
||||
cd.active["dup_a"] = &Conflict{
|
||||
ID: "dup_a", Type: ConflictFact, Entity: "test", Strategy: "ask_user",
|
||||
Status: "pending", CreatedAt: base,
|
||||
LeftContent: "牧尘在招商局工作", RightContent: "牧尘不在招商局工作",
|
||||
}
|
||||
cd.active["dup_b"] = &Conflict{
|
||||
ID: "dup_b", Type: ConflictFact, Entity: "test", Strategy: "ask_user",
|
||||
Status: "pending", CreatedAt: base.Add(time.Hour),
|
||||
LeftContent: "牧尘在招商局工作", RightContent: "牧尘不在招商局工作",
|
||||
}
|
||||
cd.active["dup_c"] = &Conflict{
|
||||
ID: "dup_c", Type: ConflictFact, Entity: "test", Strategy: "ask_user",
|
||||
Status: "pending", CreatedAt: base.Add(2 * time.Hour),
|
||||
LeftContent: "牧尘在招商局工作", RightContent: "牧尘不在招商局工作",
|
||||
}
|
||||
cd.active["different"] = &Conflict{
|
||||
ID: "different", Type: ConflictFact, Entity: "test2", Strategy: "ask_user",
|
||||
Status: "pending", CreatedAt: base,
|
||||
LeftContent: "系统已启用 Redis", RightContent: "系统未启用 Redis",
|
||||
}
|
||||
cd.persistLocked()
|
||||
cd.mu.Unlock()
|
||||
|
||||
removed := cd.DedupeActive()
|
||||
if removed != 2 {
|
||||
t.Errorf("期望去重删除 2 条,实际 %d", removed)
|
||||
}
|
||||
|
||||
// 验证
|
||||
cd.mu.RLock()
|
||||
got := cd.active
|
||||
cd.mu.RUnlock()
|
||||
|
||||
if len(got) != 2 {
|
||||
t.Fatalf("去重后期望 2 条,实际 %d", len(got))
|
||||
}
|
||||
|
||||
// dup 保留最早 createdAt(dup_a),dup_count=3
|
||||
if dupEntry, ok := got["dup_a"]; ok {
|
||||
if dupEntry.DupCount != 2 {
|
||||
t.Errorf("dup_a DupCount 期望 2(另外 2 条累加),实际 %d", dupEntry.DupCount)
|
||||
}
|
||||
if dupEntry.CreatedAt != base {
|
||||
t.Errorf("dup_a CreatedAt 应保持最早值")
|
||||
}
|
||||
if dupEntry.SHA256 == "" {
|
||||
t.Error("dup_a SHA256 应为空字符串(未计算)")
|
||||
}
|
||||
} else {
|
||||
t.Error("去重后 dup_a 应存在(createdAt 最早)")
|
||||
}
|
||||
|
||||
// different 保留
|
||||
if _, ok := got["different"]; !ok {
|
||||
t.Error("different 应保留")
|
||||
}
|
||||
}
|
||||
|
||||
// TestConflictRetainAndArchive 验证 7 天保留策略
|
||||
func TestConflictRetainAndArchive(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
path := filepath.Join(dir, "conflicts.json")
|
||||
|
||||
cd, err := NewPersistentConflictDetector(path)
|
||||
if err != nil {
|
||||
t.Fatalf("构造失败: %v", err)
|
||||
}
|
||||
|
||||
// 插入 8 条测试冲突:7 条 8 天前(应归档),1 条当天(留 pending)
|
||||
base := time.Now().Add(-8 * 24 * time.Hour)
|
||||
cd.mu.Lock()
|
||||
for i := 0; i < 7; i++ {
|
||||
cd.active["old_"+itoa(i)] = &Conflict{
|
||||
ID: "old_" + itoa(i), Type: ConflictFact, Entity: "test", Strategy: "ask_user",
|
||||
Status: "pending", CreatedAt: base,
|
||||
LeftContent: "老数据_" + itoa(i), RightContent: "新数据_" + itoa(i),
|
||||
}
|
||||
}
|
||||
cd.active["today"] = &Conflict{
|
||||
ID: "today", Type: ConflictFact, Entity: "test", Strategy: "ask_user",
|
||||
Status: "pending", CreatedAt: time.Now(),
|
||||
LeftContent: "今天数据", RightContent: "今天数据2",
|
||||
}
|
||||
cd.persistLocked()
|
||||
cd.mu.Unlock()
|
||||
|
||||
config := DefaultConflictRetentionConfig()
|
||||
config.ArchiveDir = dir
|
||||
archived, archPath, err := cd.RetainAndArchive(config)
|
||||
if err != nil {
|
||||
t.Fatalf("RetainAndArchive 失败: %v", err)
|
||||
}
|
||||
|
||||
if archived != 7 {
|
||||
t.Errorf("期望归档 7 条,实际 %d", archived)
|
||||
}
|
||||
|
||||
// 验证归档文件存在
|
||||
if archPath == "" {
|
||||
t.Fatal("归档路径不应为空")
|
||||
}
|
||||
data, err := os.ReadFile(archPath)
|
||||
if err != nil {
|
||||
t.Fatalf("归档文件不可读: %v", err)
|
||||
}
|
||||
var archList []*Conflict
|
||||
if err := json.Unmarshal(data, &archList); err != nil {
|
||||
t.Fatalf("归档文件 JSON 解析失败: %v", err)
|
||||
}
|
||||
if len(archList) != 7 {
|
||||
t.Errorf("归档文件应含 7 条,实际 %d", len(archList))
|
||||
}
|
||||
// 验证 archived_reason
|
||||
for _, c := range archList {
|
||||
if c.ArchivedReason == "" {
|
||||
t.Errorf("归档条目 %s 缺少 archived_reason", c.ID)
|
||||
}
|
||||
if c.ArchivedAt == "" {
|
||||
t.Errorf("归档条目 %s 缺少 archived_at", c.ID)
|
||||
}
|
||||
}
|
||||
|
||||
// 验证 pending 中只剩 1 条(today)
|
||||
pending := cd.ListActive()
|
||||
if len(pending) != 1 {
|
||||
t.Errorf("归档后 pending 期望 1 条(today),实际 %d", len(pending))
|
||||
}
|
||||
if pending[0].ID != "today" {
|
||||
t.Errorf("pending 应含 today,实际 %s", pending[0].ID)
|
||||
}
|
||||
}
|
||||
|
||||
// TestConflictRetainAndArchive_Idempotent 验证幂等性:第二次跑无归档增量
|
||||
func TestConflictRetainAndArchive_Idempotent(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
path := filepath.Join(dir, "conflicts.json")
|
||||
|
||||
cd, _ := NewPersistentConflictDetector(path)
|
||||
base := time.Now().Add(-8 * 24 * time.Hour)
|
||||
cd.mu.Lock()
|
||||
for i := 0; i < 3; i++ {
|
||||
cd.active["old_"+itoa(i)] = &Conflict{
|
||||
ID: "old_" + itoa(i), Type: ConflictFact, Entity: "test", Strategy: "ask_user",
|
||||
Status: "pending", CreatedAt: base,
|
||||
LeftContent: "老_" + itoa(i), RightContent: "新_" + itoa(i),
|
||||
}
|
||||
}
|
||||
cd.active["new"] = &Conflict{
|
||||
ID: "new", Type: ConflictFact, Entity: "test", Strategy: "ask_user",
|
||||
Status: "pending", CreatedAt: time.Now(),
|
||||
LeftContent: "新数据A", RightContent: "新数据B",
|
||||
}
|
||||
cd.persistLocked()
|
||||
cd.mu.Unlock()
|
||||
|
||||
config := DefaultConflictRetentionConfig()
|
||||
config.ArchiveDir = dir
|
||||
|
||||
// 第一次:归档 3 条
|
||||
archived1, _, err := cd.RetainAndArchive(config)
|
||||
if err != nil {
|
||||
t.Fatalf("第一次归档失败: %v", err)
|
||||
}
|
||||
if archived1 != 3 {
|
||||
t.Errorf("第一次期望归档 3 条,实际 %d", archived1)
|
||||
}
|
||||
|
||||
// 第二次:无归档增量
|
||||
archived2, _, err := cd.RetainAndArchive(config)
|
||||
if err != nil {
|
||||
t.Fatalf("第二次归档失败: %v", err)
|
||||
}
|
||||
if archived2 != 0 {
|
||||
t.Errorf("第二次期望归档 0 条(幂等),实际 %d", archived2)
|
||||
}
|
||||
}
|
||||
|
||||
// TestComputeConflictSHA 验证去重键
|
||||
func TestComputeConflictSHA(t *testing.T) {
|
||||
sha1 := ComputeConflictSHA("牧尘在招商局工作", "牧尘不在招商局工作")
|
||||
sha2 := ComputeConflictSHA("牧尘在招商局工作", "牧尘不在招商局工作")
|
||||
sha3 := ComputeConflictSHA("系统已启用 Redis", "系统未启用 Redis")
|
||||
|
||||
if sha1 != sha2 {
|
||||
t.Error("相同输入 SHA 应相同")
|
||||
}
|
||||
if sha1 == sha3 {
|
||||
t.Error("不同输入 SHA 应不同")
|
||||
}
|
||||
if len(sha1) != 32 {
|
||||
t.Errorf("SHA 前 32 hex,实际 len=%d", len(sha1))
|
||||
}
|
||||
}
|
||||
@@ -36,6 +36,14 @@ type Conflict struct {
|
||||
// 无法还原两侧原文 ⇒ 事后无法核实「真矛盾还是误报」(实测踩坑)。
|
||||
LeftContent string `json:"left_content,omitempty"` // 已有记忆内容
|
||||
RightContent string `json:"right_content,omitempty"` // 新写入内容
|
||||
// 2026-09-21 保留策略 + 去重(t_4ce53193):
|
||||
// - SHA256:去重键(left+"\x00"+right 的 sha256 前 32 hex)
|
||||
// - DupCount:同键冲突数(>1 说明有重复)
|
||||
// - ArchivedAt / ArchivedReason:归档审计字段
|
||||
SHA256 string `json:"sha256,omitempty"`
|
||||
DupCount int `json:"dup_count,omitempty"`
|
||||
ArchivedAt string `json:"archived_at,omitempty"`
|
||||
ArchivedReason string `json:"archived_reason,omitempty"`
|
||||
}
|
||||
|
||||
type ConflictDetector struct {
|
||||
@@ -169,6 +177,52 @@ func (cd *ConflictDetector) Scan(newContent string, newEntities []string, existi
|
||||
return conflicts
|
||||
}
|
||||
|
||||
// DedupeActive 对当前 active 中所有冲突按 (left, right) SHA 去重:
|
||||
// 同 SHA 只保留 createdAt 最早的一条,其余的 dup_count 累加到保留条上。
|
||||
// 返回去重删除的条数。
|
||||
func (cd *ConflictDetector) DedupeActive() int {
|
||||
cd.mu.Lock()
|
||||
defer cd.mu.Unlock()
|
||||
|
||||
original := len(cd.active)
|
||||
bySHA := make(map[string]*Conflict)
|
||||
for _, c := range cd.active {
|
||||
sha := ComputeConflictSHA(c.LeftContent, c.RightContent)
|
||||
c.SHA256 = sha
|
||||
if kept, ok := bySHA[sha]; ok {
|
||||
// 保留 createdAt 更早的那条
|
||||
if c.CreatedAt.Before(kept.CreatedAt) {
|
||||
// c 更早,c 成为 kept,把 kept 计入 c
|
||||
c.DupCount += kept.DupCount + 1
|
||||
bySHA[sha] = c
|
||||
} else {
|
||||
// kept 更早(或同时),kept 保留,c 计入 kept
|
||||
kept.DupCount += 1
|
||||
}
|
||||
} else {
|
||||
bySHA[sha] = c
|
||||
}
|
||||
}
|
||||
|
||||
// 重建 active:只保留 bySHA 中的条目
|
||||
cd.active = make(map[string]*Conflict, len(bySHA))
|
||||
for _, c := range bySHA {
|
||||
cd.active[c.ID] = c
|
||||
}
|
||||
removed := original - len(bySHA)
|
||||
if removed > 0 {
|
||||
log.Printf("[conflict-dedup] 去重删除 %d 条重复,剩余 %d 条", removed, len(bySHA))
|
||||
cd.persistLocked()
|
||||
}
|
||||
return removed
|
||||
}
|
||||
|
||||
// RetainAndArchive 执行保留策略(7 天 pending 无人处置 → 归档)。
|
||||
// 调用方在 zhiyid 触发器循环(t_consolidation)中每小时跑一次。
|
||||
func (cd *ConflictDetector) RetainAndArchive(config *ConflictRetentionConfig) (archivedCount int, archivePath string, err error) {
|
||||
return RetainAndArchive(cd, config)
|
||||
}
|
||||
|
||||
// AutoResolve 自动裁决冲突(latest_wins / primary_wins)
|
||||
func (cd *ConflictDetector) AutoResolve(conflict *Conflict) string {
|
||||
if conflict.Strategy == "latest_wins" {
|
||||
|
||||
Reference in New Issue
Block a user