feat(governance): t_944344b5 自动遗忘(decay/auto_forget)保护守卫 — 命中保护规则的记忆禁止软删
- 新增 internal/memprotect:与 zhiyi_protection.py 同口径的 4 条保护规则
(category∈{decision,preference,pref}/distilled决策关键词, V值≥2.0,
freshness=verified, id∈zhiyi:protected_ids);Redis 宕机降级为纯行内规则。
- server.go decay 循环 + admin.go 自动遗忘路由:在 fragment/ShouldForget
两条 SoftDelete 道之前拦截,命中即 skip 并打 [decay|forget] protected skip 日志。
- redis.go 增补 SMembers/SIsMember(读 protected_ids)。
- lancedb_ipc.go:IPC 候选补 Freshness 列;forgetCursorPath 支持
ZHIYI_FORGET_CURSOR 环境变量覆盖(测试不碰生产游标);
抽出 unmarshalMemoryRecordsTolerant 统一 ScanAll/ScanDeleted 宽容解析
(修复 ScanDeleted 遇空时间列 time.Time 解析报错的潜在 bug)。
- 新增 memprotect 单测(8) + 端到端回归测试 forget_guard_e2e_test.go
(复制数据目录+独立 socket,未设 PROT_TEST_SOCK 自动跳过)。
AC1/AC2 已在副本 /tmp/mw-prot-copy-20261016-122000 上验证通过;
生产二进制已备份(zhiyid-new.bak-t_944344b5-20261016-115413, sha 7d9ed410…)
并另存 staged 二进制,**未**上活库(待 default 终审,AC5)。
This commit is contained in:
@@ -14,6 +14,7 @@ import (
|
||||
"time"
|
||||
|
||||
"github.com/xiaoxue/memoryweave/internal/governance"
|
||||
"github.com/xiaoxue/memoryweave/internal/memprotect"
|
||||
"github.com/xiaoxue/memoryweave/internal/storage"
|
||||
)
|
||||
|
||||
@@ -67,6 +68,10 @@ func (aa *AdminAPI) Forget(w http.ResponseWriter, r *http.Request) {
|
||||
}
|
||||
|
||||
forgotten := 0
|
||||
// 2026-10-16 (t_944344b5) 遗忘保护守卫:本批加载一次保护状态(Redis vprop + protected_ids),
|
||||
// 命中任一保护规则的候选永不自动软删(fragment 与 ShouldForget 两条道都拦截)。
|
||||
protState := memprotect.LoadState()
|
||||
protected := 0
|
||||
for _, mem := range results {
|
||||
lastAccess := parseTimeStr(mem["last_recalled_at"])
|
||||
// GA-P0-2 (t_c6d41ac6):衰减/遗忘只认 recall_verified_count(正反馈才是 V 值)。
|
||||
@@ -83,6 +88,15 @@ func (aa *AdminAPI) Forget(w http.ResponseWriter, r *http.Request) {
|
||||
if len([]rune(content)) > 200 {
|
||||
continue
|
||||
}
|
||||
// 🔒 2026-10-16 (t_944344b5) 遗忘保护守卫: 命中任一保护规则的候选
|
||||
// (category∈{decision,preference,pref} / V≥2.0 / freshness=verified /
|
||||
// protected_ids 名单 / 决策·偏好关键词) 永不自动软删。
|
||||
// 拦截 point 放在 fragment + ShouldForget 两条 SoftDelete 道之前。
|
||||
if isProt, protRule := memprotect.IsProtected(mem, protState); isProt {
|
||||
protected++
|
||||
log.Printf("[forget] protected skip id=%q rule=%s (遗忘保护守卫命中, 跳过自动遗忘)", strVal(mem["id"]), protRule)
|
||||
continue
|
||||
}
|
||||
// 2026-09-07 方案A 碎片快速道(与 server.go decay trigger 一致):
|
||||
// <30 字且 >20 天未访问 → 直接遗忘(碎片 recall_count 可能虚高, 绕过保命)
|
||||
if len([]rune(content)) < 30 && time.Since(lastAccess).Hours()/24 > 20 {
|
||||
@@ -117,6 +131,8 @@ func (aa *AdminAPI) Forget(w http.ResponseWriter, r *http.Request) {
|
||||
}
|
||||
respond(w, 200, map[string]interface{}{
|
||||
"status": "ok", "scanned": len(results), "forgotten": forgotten,
|
||||
// 2026-10-16 (t_944344b5):protected = 被遗忘保护守卫拦截、未软删的候选数
|
||||
"protected": protected,
|
||||
})
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,143 @@
|
||||
// Package routes — 遗忘保护守卫端到端回归测试(t_944344b5,AC1/AC2)。
|
||||
//
|
||||
// 2026-10-16 (t_944344b5):证明「decay/auto_forget 的判定道(admin Forget 路由)命中保护
|
||||
// 规则的候选**不被** SoftDelete,而非保护的衰减候选**照常**被软删」。
|
||||
//
|
||||
// 必须走**真实判定路径**(routes.NewAdminAPI.Forget),不能只测 memprotect.IsProtected,
|
||||
// 因为守卫是在 decay 循环 / admin Forget 路由里 SoftDelete 之前拦截的(见 server.go / admin.go)。
|
||||
//
|
||||
// 跑法(A/B 纪律:复制数据目录 + 独立 socket,绝不碰生产 /var/lib/memoryweave):
|
||||
// 1. cp -a /var/lib/memoryweave /tmp/mw-prot-copy-<ts>
|
||||
// 2. zhiyi-consolidate --mode socket --socket /tmp/mw-prot.sock \
|
||||
// --data-dir /tmp/mw-prot-copy-<ts> &
|
||||
// 3. PROT_TEST_SOCK=/tmp/mw-prot.sock \
|
||||
// go test ./internal/api/routes/ -run TestForgetGuardE2E -v -count=1
|
||||
//
|
||||
// 未设 PROT_TEST_SOCK → 自动跳过(可安全留在 CI)。
|
||||
package routes_test
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"os"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/xiaoxue/memoryweave/internal/governance"
|
||||
"github.com/xiaoxue/memoryweave/internal/models"
|
||||
"github.com/xiaoxue/memoryweave/internal/storage"
|
||||
|
||||
"github.com/xiaoxue/memoryweave/internal/api/routes"
|
||||
)
|
||||
|
||||
func TestForgetGuardE2E(t *testing.T) {
|
||||
sock := os.Getenv("PROT_TEST_SOCK")
|
||||
if sock == "" {
|
||||
t.Skip("PROT_TEST_SOCK 未设置,跳过(需先起 test sidecar 指向复制的数据目录)")
|
||||
}
|
||||
|
||||
// 让遗忘窗口游标指到临时文件(缺失 → 空游标 → 从最小 id 起轮转),
|
||||
// 保证我们构造的 `mem_0...` 行(id 最小)落在首个 2000 窗口内。
|
||||
// 不碰生产 /var/lib/memoryweave/forget-cursor.json。
|
||||
cursorDir := t.TempDir()
|
||||
cursorFile := cursorDir + "/test-forget-cursor.json"
|
||||
t.Setenv("ZHIYI_FORGET_CURSOR", cursorFile)
|
||||
|
||||
// embedder 传 nil:记录自带 1024 维 Vector,走不到编码分支(同 conf_e2e_test.go 做法)。
|
||||
rc := storage.NewRustLanceDBClient(sock, nil)
|
||||
f := governance.NewForgetter()
|
||||
aa := routes.NewAdminAPI(rc, f, nil) // GraphStore 传 nil:extractTopEntityDegree 空安全
|
||||
|
||||
// ── 构造 4 条测试记忆(id 都以 mem_0 开头 → 字典序最小 → 必在首窗口)──
|
||||
vec := make([]float32, 1024)
|
||||
for i := range vec {
|
||||
vec[i] = 0.001
|
||||
}
|
||||
now := time.Now().UTC()
|
||||
mk := func(id, category, content, freshness string, daysAgo int) models.MemoryRecord {
|
||||
lr := now.Add(-time.Duration(daysAgo) * 24 * time.Hour)
|
||||
return models.MemoryRecord{
|
||||
ID: id, AgentID: "hermes-a06", Namespace: "prot-test",
|
||||
Content: content, Category: category, Vector: vec,
|
||||
Tier: "normal", Importance: 0.5, QualityScore: 0.5,
|
||||
Version: 1, Freshness: freshness,
|
||||
Source: "wiki:/tmp/forget-guard-e2e.md",
|
||||
EmbeddingModel: "bge-m3", ScriptVersion: "forget-guard-e2e",
|
||||
CreatedAt: lr, UpdatedAt: lr, LastRecalledAt: lr,
|
||||
RecallVerifiedCount: 0,
|
||||
}
|
||||
}
|
||||
|
||||
// P1:规则3 freshness=verified 保护。content <30 字 + >20 天 ⇒ 本应走碎片快速道被删,
|
||||
// 但 freshness=verified ⇒ 守卫拦截 ⇒ 存活。
|
||||
p1 := mk("mem_0aaaa_p1", "distilled", "verified fact, kept", "verified", 30)
|
||||
// P2:规则1 category=decision 保护。
|
||||
p2 := mk("mem_0aaaa_p2", "decision", "short decision note", "fresh", 30)
|
||||
// P3:规则4 content 关键词「牧尘要求」保护。
|
||||
p3 := mk("mem_0aaaa_p3", "distilled", "牧尘要求:部署前必须先备份", "fresh", 30)
|
||||
// N1:不命中任何规则(distilled / fresh / 无关键词 / 低 V / 不在名单)⇒ 应被碎片快速道软删。
|
||||
n1 := mk("mem_0aaaa_n1", "distilled", "hi", "fresh", 45)
|
||||
|
||||
for _, m := range []models.MemoryRecord{p1, p2, p3, n1} {
|
||||
if err := rc.InsertMemory(m); err != nil {
|
||||
t.Fatalf("InsertMemory(%s) 失败: %v", m.ID, err)
|
||||
}
|
||||
}
|
||||
|
||||
// ── 跑真实判定路径:admin Forget 路由(= decay/auto_forget 决策 + 守卫 + SoftDelete)──
|
||||
req := httptest.NewRequest(http.MethodPost, "/api/v1/admin/forget", nil)
|
||||
w := httptest.NewRecorder()
|
||||
aa.Forget(w, req)
|
||||
if w.Code != http.StatusOK {
|
||||
t.Fatalf("admin forget expected 200, got %d: %s", w.Code, w.Body.String())
|
||||
}
|
||||
var resp map[string]interface{}
|
||||
json.Unmarshal(w.Body.Bytes(), &resp)
|
||||
t.Logf("admin forget 响应: %v", resp)
|
||||
|
||||
// ── 断言 ──
|
||||
// 读路径语义(rust lancedb_ops.rs):
|
||||
// scan_all → 仅 is_deleted=false(存活集,无 5000 上限)
|
||||
// scan_deleted → 仅 is_deleted=true(已删集,带 delete_reason)
|
||||
// 故 P1/P2/P3 应出现在 ScanAll 里;N1 应不在 ScanAll、而在 ScanDeleted 里。
|
||||
all, err := rc.ScanAll()
|
||||
if err != nil {
|
||||
t.Fatalf("ScanAll 失败: %v", err)
|
||||
}
|
||||
liveSet := map[string]bool{}
|
||||
for _, m := range all {
|
||||
liveSet[m.ID] = true // scan_all 只回 is_deleted=false
|
||||
}
|
||||
for _, id := range []string{p1.ID, p2.ID, p3.ID} {
|
||||
if !liveSet[id] {
|
||||
t.Errorf("❌ 受保护记忆 %s 应存活(ScanAll 命中),实际不在 —— 守卫失效", id)
|
||||
}
|
||||
}
|
||||
if liveSet[n1.ID] {
|
||||
t.Errorf("❌ 非保护衰减记忆 %s 应被软删(不在 ScanAll),实际仍存活 —— 回归异常", n1.ID)
|
||||
}
|
||||
|
||||
deleted, derr := rc.ScanDeleted()
|
||||
if derr != nil {
|
||||
t.Fatalf("ScanDeleted 失败: %v", derr)
|
||||
}
|
||||
deletedSet, n1Reason := map[string]bool{}, ""
|
||||
for _, m := range deleted {
|
||||
deletedSet[m.ID] = true
|
||||
if m.ID == n1.ID {
|
||||
n1Reason = m.DeleteReason
|
||||
}
|
||||
}
|
||||
if !deletedSet[n1.ID] {
|
||||
t.Errorf("❌ 非保护衰减记忆 %s 应出现在 ScanDeleted(is_deleted=true),实际不在", n1.ID)
|
||||
}
|
||||
if t.Failed() {
|
||||
return
|
||||
}
|
||||
// 受保护 3 条存活 + 非保护 1 条被删,打印结论
|
||||
t.Logf("✅ AC1 3 条命中保护规则(freshness=verified / category=decision / 关键词)全部存活于 ScanAll")
|
||||
t.Logf("✅ AC2 非保护衰减碎片 %s 照常软删(在 ScanDeleted)", n1.ID)
|
||||
// 取证:N1 的 delete_reason(auto_forget*/fragment 经 NormalizeDeleteReason → retention)
|
||||
t.Logf("取证: %s delete_reason=%q", n1.ID, n1Reason)
|
||||
}
|
||||
@@ -21,6 +21,7 @@ import (
|
||||
"github.com/xiaoxue/memoryweave/internal/api/routes"
|
||||
"github.com/xiaoxue/memoryweave/internal/distill"
|
||||
"github.com/xiaoxue/memoryweave/internal/governance"
|
||||
"github.com/xiaoxue/memoryweave/internal/memprotect"
|
||||
"github.com/xiaoxue/memoryweave/internal/metrics"
|
||||
"github.com/xiaoxue/memoryweave/internal/models"
|
||||
"github.com/xiaoxue/memoryweave/internal/pattern"
|
||||
@@ -1828,7 +1829,13 @@ func NewServer() http.Handler {
|
||||
memories, e := ldb.GetCandidatesForForgetting()
|
||||
decayScanned := 0
|
||||
decayForgotten := 0
|
||||
decayProtected := 0
|
||||
if e == nil {
|
||||
// 2026-10-16 (t_944344b5) 遗忘保护守卫:本 tick 加载一次保护状态
|
||||
// (Redis zhiyi:vprop_values + zhiyi:protected_ids),命中任一保护规则的
|
||||
// 候选永不自动软删(fragment 与 ShouldForget 两条道都拦截)。
|
||||
// Redis 宕机 → 降级为纯行内规则(category/freshness/关键词),不阻断衰减。
|
||||
protState := memprotect.LoadState()
|
||||
const maxDecayBatch = 2000
|
||||
if len(memories) > maxDecayBatch {
|
||||
sort.SliceStable(memories, func(a, b int) bool {
|
||||
@@ -1852,6 +1859,16 @@ func NewServer() http.Handler {
|
||||
continue
|
||||
}
|
||||
}
|
||||
// 🔒 2026-10-16 (t_944344b5) 遗忘保护守卫: 命中任一保护规则的候选
|
||||
// (category∈{decision,preference,pref} / V≥2.0 / freshness=verified /
|
||||
// protected_ids 名单 / 决策·偏好关键词) 永不自动软删。
|
||||
// 拦截 point 放在 fragment + ShouldForget 两条 SoftDelete 道之前。
|
||||
if isProt, protRule := memprotect.IsProtected(m, protState); isProt {
|
||||
gid, _ := m["id"].(string)
|
||||
decayProtected++
|
||||
log.Printf("[decay] protected skip id=%q rule=%s (遗忘保护守卫命中, 跳过自动遗忘)", gid, protRule)
|
||||
continue
|
||||
}
|
||||
// 解析 last_recalled_at
|
||||
lastAccessed := time.Now().Add(-30 * 24 * time.Hour) // 默认30天前
|
||||
if t, ok := m["last_recalled_at"].(string); ok && t != "" {
|
||||
@@ -1912,7 +1929,8 @@ func NewServer() http.Handler {
|
||||
}
|
||||
// AC-1 验收日志(P1 修复 type 断言后 last_recalled_at 可解析;batch<=2000)
|
||||
if decayScanned > 0 {
|
||||
log.Printf("[decay] scanned=%d forgotten=%d (batch<=2000, 最久未访问优先)", decayScanned, decayForgotten)
|
||||
// 2026-10-16 (t_944344b5):protected_skip = 被遗忘保护守卫拦截、未软删的候选数
|
||||
log.Printf("[decay] scanned=%d forgotten=%d protected_skip=%d (batch<=2000, 最久未访问优先)", decayScanned, decayForgotten, decayProtected)
|
||||
}
|
||||
case "gap_scan":
|
||||
// 检查已有缺口:过期 7 天的自动关闭
|
||||
|
||||
@@ -0,0 +1,148 @@
|
||||
// Package memprotect — 织忆 自动遗忘(衰减 decay / auto_forget)保护守卫。
|
||||
//
|
||||
// 2026-10-16 (t_944344b5):衰减/遗忘管线在 SoftDelete 前必须先过本守卫,
|
||||
// 命中任一保护规则的记忆**永不**被自动软删(人工删除、备份清理除外)。
|
||||
//
|
||||
// 本包是 **Go 侧同口径判定**,与 Python 参考实现
|
||||
// ~/.hermes/scripts/zhiyi_protection.py 的 ProtectionGuard 完全同规则:
|
||||
//
|
||||
// 规则1 protected_category : category ∈ {"decision","preference","pref"} → 保护
|
||||
// 规则2 high_v : vprop(Redis zhiyi:vprop_values 的 V)≥ 2.0 → 保护
|
||||
// 规则3 freshness_verified : freshness == "verified" → 保护
|
||||
// 规则4 explicit_protected : id ∈ protected_ids(Redis zhiyi:protected_ids)或
|
||||
// content 命中「决策/偏好」关键词 → 保护
|
||||
//
|
||||
// 口径要点(与 Python 一致,勿单独改动):
|
||||
// - protected_categories 含 "pref"(兼容 2026-05-14 迁移前旧数据)。
|
||||
// - 2026-08-24 牧尘裁定:「决策/偏好」内容关键词并入**同一条规则4**(explicit_protected),
|
||||
// 不拆新规则。关键词 7 个,中英文变体都要。
|
||||
//
|
||||
// 只读既有 Redis key(zhiyi:vprop_values / zhiyi:protected_ids),**不新建 key**
|
||||
// ⇒ 不触发 noeviction / TTL 约束(AGENTS.md 硬性纪律:maxmemory=0+noeviction,新建 key 必须 TTL)。
|
||||
package memprotect
|
||||
|
||||
import (
|
||||
"log"
|
||||
"strconv"
|
||||
"strings"
|
||||
|
||||
"github.com/xiaoxue/memoryweave/internal/storage"
|
||||
)
|
||||
|
||||
// ── 保护常量(与 Python ProtectionGuard 完全一致)──
|
||||
|
||||
// ProtectedCategories 规则1:这些 category 永不自动遗忘。
|
||||
// 含 "pref"(历史兼容,2026-05-14 迁移前的旧 category 值)。
|
||||
var ProtectedCategories = map[string]bool{
|
||||
"decision": true,
|
||||
"preference": true,
|
||||
"pref": true,
|
||||
}
|
||||
|
||||
// MinHighV 规则2:V 值 ≥ 此阈值 = 高价值,保护。
|
||||
const MinHighV = 2.0
|
||||
|
||||
// FreshnessVerified 规则3:被验证过的记忆,保护。
|
||||
const FreshnessVerified = "verified"
|
||||
|
||||
// DecisionKeywords 规则4(content 关键词分支):命中任一则视为「决策/偏好」,保护。
|
||||
// 2026-08-24 牧尘裁定并入 explicit_protected;7 个关键词,中英文变体都要。
|
||||
var DecisionKeywords = []string{
|
||||
"牧尘要求", "明确要求", "明确指示", "决策", "偏好", "preference", "decision",
|
||||
}
|
||||
|
||||
// Redis key 名(只读,勿改)。
|
||||
const (
|
||||
RedisKeyVPropValues = "zhiyi:vprop_values"
|
||||
RedisKeyProtectedIDs = "zhiyi:protected_ids"
|
||||
)
|
||||
|
||||
// State 一次 LoadState() 加载的保护状态快照。
|
||||
// 衰减 tick / admin forget 开始时 LoadState 一次,循环内对每条候选复用同一 State,
|
||||
// 避免每条记忆都 HGETALL/SMEMBERS 一次 Redis。
|
||||
type State struct {
|
||||
VProp map[string]float64 // id → V 值(解析失败的字段跳过,非 0 值)
|
||||
Protected map[string]bool // 显式豁免名单 zhiyi:protected_ids
|
||||
RedisDown bool // Redis 未连接:规则2/4 名单分支跳过,规则1/3/4 关键词分支仍生效
|
||||
}
|
||||
|
||||
// IsProtected 判断单条记忆是否受保护。row 为 GetCandidatesForForgetting()
|
||||
// 返回的候选 map(字段名与 LanceDB 列名一致:id/category/freshness/content/...)。
|
||||
// 命中任一规则返回 (true, 规则名);全不命中返回 (false, "")。
|
||||
//
|
||||
// 注意:规则3 依赖 row["freshness"]。遗忘候选曾长期漏 freshness(Go IPC 结构体丢字段),
|
||||
// 导致规则3 恒不触发——本卡已把 freshness 补进 Go 候选 map(见 storage/lancedb_ipc.go)。
|
||||
func IsProtected(row map[string]interface{}, st *State) (bool, string) {
|
||||
// 规则1:category 保护
|
||||
if cat, _ := row["category"].(string); cat != "" && ProtectedCategories[cat] {
|
||||
return true, "protected_category"
|
||||
}
|
||||
|
||||
if st != nil {
|
||||
// 规则2:V 值保护(Redis 宕机时 VProp 为空 map,自然跳过)
|
||||
id, _ := row["id"].(string)
|
||||
if st.VProp != nil && id != "" {
|
||||
if v, ok := st.VProp[id]; ok && v >= MinHighV {
|
||||
return true, "high_v"
|
||||
}
|
||||
}
|
||||
// 规则4:显式豁免(protected_ids 名单,Redis 宕机时空 set 跳过)
|
||||
if st.Protected != nil && id != "" && st.Protected[id] {
|
||||
return true, "explicit_protected"
|
||||
}
|
||||
}
|
||||
|
||||
// 规则3:freshness=verified(纯行内字段,不依赖 Redis)
|
||||
if fresh, _ := row["freshness"].(string); fresh == FreshnessVerified {
|
||||
return true, "freshness_verified"
|
||||
}
|
||||
|
||||
// 规则4:content 命中「决策/偏好」关键词(纯行内字段,不依赖 Redis)
|
||||
// 与 Python 参考实现同口径:`any(kw in content ...)` 大小写敏感("Decision" 不命中 "decision")。
|
||||
if content, _ := row["content"].(string); content != "" {
|
||||
for _, kw := range DecisionKeywords {
|
||||
if strings.Contains(content, kw) {
|
||||
return true, "explicit_protected"
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return false, ""
|
||||
}
|
||||
|
||||
// LoadState 从 Redis 加载保护状态快照。
|
||||
// 只读既有 key:HGETALL zhiyi:vprop_values(id→V)+ SMEMBERS zhiyi:protected_ids。
|
||||
// Redis 未连接时返回 RedisDown=true 的空 State(规则2/名单分支跳过,规则1/3/关键词仍生效),
|
||||
// 不阻断衰减循环(衰减照常跑,只是保护判断降级为纯行内规则)。
|
||||
func LoadState() *State {
|
||||
st := &State{
|
||||
VProp: map[string]float64{},
|
||||
Protected: map[string]bool{},
|
||||
}
|
||||
rc := storage.GetRedisClient()
|
||||
if rc == nil {
|
||||
st.RedisDown = true
|
||||
log.Printf("[memprotect] Redis 未连接 → 保护守卫降级:规则2(V)/名单跳过,规则1/3/关键词仍生效")
|
||||
return st
|
||||
}
|
||||
|
||||
raw, err := rc.HGetAll(RedisKeyVPropValues)
|
||||
if err != nil {
|
||||
log.Printf("[memprotect] HGETALL %s 失败: %v → V 规则降级", RedisKeyVPropValues, err)
|
||||
} else {
|
||||
for id, s := range raw {
|
||||
if v, perr := strconv.ParseFloat(s, 64); perr == nil {
|
||||
st.VProp[id] = v
|
||||
}
|
||||
// 解析失败的字段跳过(记一条,不当 0)
|
||||
}
|
||||
}
|
||||
|
||||
if ids := rc.SMembers(RedisKeyProtectedIDs); ids != nil {
|
||||
for _, id := range ids {
|
||||
st.Protected[id] = true
|
||||
}
|
||||
}
|
||||
|
||||
return st
|
||||
}
|
||||
@@ -0,0 +1,178 @@
|
||||
// Package memprotect — 遗忘保护守卫同口径判定测试。
|
||||
//
|
||||
// 2026-10-16 (t_944344b5):本测试用**合成 State + 合成候选 row** 验证 IsProtected
|
||||
// 的 4 条保护规则与 Python 参考实现(~/.hermes/scripts/zhiyi_protection.py 的
|
||||
// ProtectionGuard)完全同口径。不依赖 Redis / LanceDB —— 纯逻辑判定。
|
||||
//
|
||||
// 跑法:go test ./internal/memprotect/ -count=1 -v
|
||||
package memprotect
|
||||
|
||||
import (
|
||||
"testing"
|
||||
)
|
||||
|
||||
// mkRow 构造一条 GetCandidatesForForgetting() 返回形态的候选 map(字段值均为 string,
|
||||
// 与 Go IPC 主路径 / fallback 路径的实际类型一致)。
|
||||
func mkRow(id, category, content, freshness string) map[string]interface{} {
|
||||
return map[string]interface{}{
|
||||
"id": id,
|
||||
"category": category,
|
||||
"content": content,
|
||||
"freshness": freshness,
|
||||
}
|
||||
}
|
||||
|
||||
// synthState 构造合成保护状态(不碰 Redis):给定 vprop 与 protected_ids。
|
||||
func synthState(vprop map[string]float64, protected map[string]bool) *State {
|
||||
if vprop == nil {
|
||||
vprop = map[string]float64{}
|
||||
}
|
||||
if protected == nil {
|
||||
protected = map[string]bool{}
|
||||
}
|
||||
return &State{VProp: vprop, Protected: protected}
|
||||
}
|
||||
|
||||
func TestRule1_CategoryProtected(t *testing.T) {
|
||||
st := synthState(nil, nil) // 无 vprop / 无名单,纯行内规则
|
||||
for _, cat := range []string{"decision", "preference", "pref"} {
|
||||
row := mkRow("mem_x", cat, "随便一段普通内容", "fresh")
|
||||
ok, rule := IsProtected(row, st)
|
||||
if !ok {
|
||||
t.Fatalf("规则1: category=%s 应受保护,实际未保护", cat)
|
||||
}
|
||||
if rule != "protected_category" {
|
||||
t.Fatalf("规则1: category=%s 命中规则=%s,期望 protected_category", cat, rule)
|
||||
}
|
||||
}
|
||||
// 非保护 category 不命中规则1(其余字段也不触发 → 整体不保护)
|
||||
row := mkRow("mem_x", "distilled", "普通内容", "fresh")
|
||||
if ok, rule := IsProtected(row, st); ok {
|
||||
t.Fatalf("category=distilled 且无其他触发因素,不应保护,实际 rule=%s", rule)
|
||||
}
|
||||
}
|
||||
|
||||
func TestRule2_HighV(t *testing.T) {
|
||||
// V ≥ 2.0 → 保护;< 2.0 → 不保护(且其余字段不触发)
|
||||
cases := []struct {
|
||||
id string
|
||||
v float64
|
||||
want bool
|
||||
}{
|
||||
{"mem_high", 2.0, true},
|
||||
{"mem_high", 3.5, true},
|
||||
{"mem_low", 1.99, false},
|
||||
{"mem_low", 0.5, false},
|
||||
}
|
||||
for _, c := range cases {
|
||||
st := synthState(map[string]float64{c.id: c.v}, nil)
|
||||
row := mkRow(c.id, "distilled", "普通内容", "fresh")
|
||||
ok, rule := IsProtected(row, st)
|
||||
if ok != c.want {
|
||||
t.Fatalf("规则2: id=%s V=%.2f 期望 protected=%v,实际 %v (rule=%s)", c.id, c.v, c.want, ok, rule)
|
||||
}
|
||||
if c.want && rule != "high_v" {
|
||||
t.Fatalf("规则2: id=%s 命中规则=%s,期望 high_v", c.id, rule)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestRule3_FreshnessVerified(t *testing.T) {
|
||||
st := synthState(nil, nil)
|
||||
// freshness=verified → 保护(即使 category=distilled、无 vprop)
|
||||
row := mkRow("mem_v", "distilled", "普通内容", "verified")
|
||||
ok, rule := IsProtected(row, st)
|
||||
if !ok {
|
||||
t.Fatal("规则3: freshness=verified 应受保护,实际未保护")
|
||||
}
|
||||
if rule != "freshness_verified" {
|
||||
t.Fatalf("规则3: 命中规则=%s,期望 freshness_verified", rule)
|
||||
}
|
||||
// freshness 缺失(空串)→ 规则3 不触发
|
||||
row2 := mkRow("mem_v2", "distilled", "普通内容", "")
|
||||
if ok, _ := IsProtected(row2, st); ok {
|
||||
t.Fatalf("freshness 缺失不应触发规则3,实际 protected (其余字段也未触发却保护了)")
|
||||
}
|
||||
}
|
||||
|
||||
func TestRule4a_ExplicitProtectedIDs(t *testing.T) {
|
||||
// 名单内 id → 保护(即使 category=distilled、无 vprop、freshness 非 verified)
|
||||
st := synthState(nil, map[string]bool{"mem_exp": true})
|
||||
row := mkRow("mem_exp", "distilled", "普通内容", "fresh")
|
||||
ok, rule := IsProtected(row, st)
|
||||
if !ok {
|
||||
t.Fatal("规则4a: 名单内 id 应受保护,实际未保护")
|
||||
}
|
||||
if rule != "explicit_protected" {
|
||||
t.Fatalf("规则4a: 命中规则=%s,期望 explicit_protected", rule)
|
||||
}
|
||||
// 不在名单 → 不保护
|
||||
row2 := mkRow("mem_notin", "distilled", "普通内容", "fresh")
|
||||
if ok, _ := IsProtected(row2, st); ok {
|
||||
t.Fatalf("不在 protected_ids 名单且无其他触发,不应保护")
|
||||
}
|
||||
}
|
||||
|
||||
func TestRule4b_DecisionKeywords(t *testing.T) {
|
||||
st := synthState(nil, nil)
|
||||
// 每个关键词都应触发保护
|
||||
kws := []string{"牧尘要求", "明确要求", "明确指示", "决策", "偏好", "preference", "decision"}
|
||||
for _, kw := range kws {
|
||||
row := mkRow("mem_kw", "distilled", "这是一条关于"+kw+"的记录", "fresh")
|
||||
ok, rule := IsProtected(row, st)
|
||||
if !ok {
|
||||
t.Fatalf("规则4b: 关键词 %q 应触发保护,实际未保护", kw)
|
||||
}
|
||||
if rule != "explicit_protected" {
|
||||
t.Fatalf("规则4b: 关键词 %q 命中规则=%s,期望 explicit_protected", kw, rule)
|
||||
}
|
||||
}
|
||||
// 大小写敏感(与 Python `kw in content` 同口径):英文 "Decision" 不应命中 "decision"
|
||||
row := mkRow("mem_cs", "distilled", "This is a Decision record", "fresh")
|
||||
if ok, _ := IsProtected(row, st); ok {
|
||||
t.Fatalf("大小写敏感口径:'Decision' 不应命中关键词 'decision',实际保护了")
|
||||
}
|
||||
// 普通内容无关键词 → 不保护
|
||||
row2 := mkRow("mem_plain", "distilled", "普通蒸馏内容", "fresh")
|
||||
if ok, _ := IsProtected(row2, st); ok {
|
||||
t.Fatalf("无关键词、无触发因素,不应保护")
|
||||
}
|
||||
}
|
||||
|
||||
func TestNoRegression_PlainOldMemory(t *testing.T) {
|
||||
// 一条普通、旧、低价值、非保护 category 的记忆 → 不被任何规则保护(衰减可正常遗忘)
|
||||
st := synthState(nil, nil)
|
||||
row := map[string]interface{}{
|
||||
"id": "mem_plain_old",
|
||||
"category": "distilled",
|
||||
"content": "hi",
|
||||
"freshness": "fresh",
|
||||
}
|
||||
if ok, rule := IsProtected(row, st); ok {
|
||||
t.Fatalf("普通旧记忆不应受保护(回归):rule=%s", rule)
|
||||
}
|
||||
}
|
||||
|
||||
func TestMultipleRules_HighestWinsButAllProtect(t *testing.T) {
|
||||
// 同时命中多条规则 → 仍保护(任一命中即保护)
|
||||
st := synthState(map[string]float64{"mem_multi": 5.0}, map[string]bool{"mem_multi": true})
|
||||
row := mkRow("mem_multi", "decision", "牧尘要求:必须保护", "verified")
|
||||
ok, _ := IsProtected(row, st)
|
||||
if !ok {
|
||||
t.Fatal("多规则叠加应保护")
|
||||
}
|
||||
}
|
||||
|
||||
// TestLoadState_NoRedis_Panics 验证 LoadState 在 Redis 不可用时优雅降级(不 panic、
|
||||
// 不阻断),且行内规则仍生效。不依赖生产 Redis 的具体内容。
|
||||
func TestLoadState_NoRedis_Panics(t *testing.T) {
|
||||
st := LoadState() // 真实调用(可能连上生产 Redis,也可能连不上)——只要不 panic 即可
|
||||
if st == nil {
|
||||
t.Fatal("LoadState 不应返回 nil")
|
||||
}
|
||||
// 无论 Redis 是否可用,行内规则(category=decision)都应生效
|
||||
row := mkRow("mem_d", "decision", "任意内容", "fresh")
|
||||
if ok, _ := IsProtected(row, st); !ok {
|
||||
t.Fatalf("category=decision 无论 Redis 状态都应对保护")
|
||||
}
|
||||
}
|
||||
@@ -8,24 +8,25 @@ import (
|
||||
)
|
||||
|
||||
// resetForgetCursorPath 将游标路径指到临时目录,避免污染 /var/lib/memoryweave 真文件。
|
||||
// 2026-10-16 (t_944344b5):游标路径改为 env ZHIYI_FORGET_CURSOR 可覆盖(原为包级 var 直接赋值,
|
||||
// 现 var 改为 const + 解析函数),故测试改用 t.Setenv 设 env 指向临时文件。
|
||||
func resetForgetCursorPath(t *testing.T) string {
|
||||
t.Helper()
|
||||
dir := t.TempDir()
|
||||
old := forgetCursorPath
|
||||
forgetCursorPath = filepath.Join(dir, "forget-cursor.json")
|
||||
t.Cleanup(func() { forgetCursorPath = old })
|
||||
return forgetCursorPath
|
||||
p := filepath.Join(dir, "forget-cursor.json")
|
||||
t.Setenv("ZHIYI_FORGET_CURSOR", p)
|
||||
return p
|
||||
}
|
||||
|
||||
func TestForgetCursorPersistAndLoad(t *testing.T) {
|
||||
resetForgetCursorPath(t)
|
||||
path := resetForgetCursorPath(t)
|
||||
persistForgetCursor("mem_1791482426233375644")
|
||||
got := loadForgetCursor()
|
||||
if got != "mem_1791482426233375644" {
|
||||
t.Fatalf("persist→load 应一致, got=%q", got)
|
||||
}
|
||||
// 文件确实落盘
|
||||
if _, err := os.Stat(forgetCursorPath); err != nil {
|
||||
if _, err := os.Stat(path); err != nil {
|
||||
t.Fatalf("游标文件应存在: %v", err)
|
||||
}
|
||||
}
|
||||
@@ -39,16 +40,16 @@ func TestForgetCursorLoadMissing(t *testing.T) {
|
||||
}
|
||||
|
||||
func TestForgetCursorLoadCorrupt(t *testing.T) {
|
||||
resetForgetCursorPath(t)
|
||||
path := resetForgetCursorPath(t)
|
||||
// 损坏内容(非 mem_ 前缀)→ 返回 ""(降级从头轮转,不崩)
|
||||
if err := os.WriteFile(forgetCursorPath, []byte("not-a-cursor!!"), 0o644); err != nil {
|
||||
if err := os.WriteFile(path, []byte("not-a-cursor!!"), 0o644); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if got := loadForgetCursor(); got != "" {
|
||||
t.Fatalf("损坏游标应返回空串, got=%q", got)
|
||||
}
|
||||
// 空文件 → 返回 ""
|
||||
if err := os.WriteFile(forgetCursorPath, []byte(""), 0o644); err != nil {
|
||||
if err := os.WriteFile(path, []byte(""), 0o644); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if got := loadForgetCursor(); got != "" {
|
||||
@@ -58,9 +59,9 @@ func TestForgetCursorLoadCorrupt(t *testing.T) {
|
||||
|
||||
func TestForgetCursorPersistEmptySkips(t *testing.T) {
|
||||
// wrapped → 空串不落盘(缺文件=从头轮转)
|
||||
resetForgetCursorPath(t)
|
||||
path := resetForgetCursorPath(t)
|
||||
persistForgetCursor("")
|
||||
if _, err := os.Stat(forgetCursorPath); !os.IsNotExist(err) {
|
||||
if _, err := os.Stat(path); !os.IsNotExist(err) {
|
||||
t.Fatalf("空游标不应落盘文件, err=%v", err)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -423,6 +423,25 @@ func (rc *RustLanceDBClient) ScanAll() ([]models.MemoryRecord, error) {
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
out, err := unmarshalMemoryRecordsTolerant(resp.ReportJSON)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("scan_all unmarshal: %w", err)
|
||||
}
|
||||
// 同步到本地缓存(与 GetSkillCandidates 同款)
|
||||
_local.mu.Lock()
|
||||
for i := range out {
|
||||
cp := out[i]
|
||||
_local.memories[cp.ID] = &cp
|
||||
}
|
||||
_local.mu.Unlock()
|
||||
return out, nil
|
||||
}
|
||||
|
||||
// unmarshalMemoryRecordsTolerant 宽容解析 Rust 侧输出的内存记录 JSON 数组。
|
||||
// 时间列(last_recalled_at/created_at/updated_at)与血缘列(version_history/depends_on/…)
|
||||
// shadow 成 string 再解析:存量数据大量空串,直接 unmarshal 到 time.Time / []string 会炸。
|
||||
// ScanAll 早已如此;ScanDeleted 之前漏了这一步(遇空时间列即报错),本次统一收口到本 helper。
|
||||
func unmarshalMemoryRecordsTolerant(jsonText string) ([]models.MemoryRecord, error) {
|
||||
var raw []struct {
|
||||
models.MemoryRecord
|
||||
// 时间列:Rust 输出 RFC3339 字符串(存量为空串),shadow 成 string 宽容解析
|
||||
@@ -430,18 +449,16 @@ func (rc *RustLanceDBClient) ScanAll() ([]models.MemoryRecord, error) {
|
||||
CreatedAt string `json:"created_at"`
|
||||
UpdatedAt string `json:"updated_at"`
|
||||
// 血缘列:Rust 输出 JSON 数组字符串("[]" / "[\"ep_x\"]" / 空串),
|
||||
// Go 模型是 []string / []VersionRecord ⇒ 直接 unmarshal 到数组类型会炸
|
||||
// (实测 FTS 首建踩到 version_history),shadow 成 string 再解析
|
||||
// Go 模型是 []string / []VersionRecord ⇒ 直接 unmarshal 到数组类型会炸,shadow 成 string 再解析
|
||||
VersionHistory string `json:"version_history"`
|
||||
DependsOn string `json:"depends_on"`
|
||||
SourceEvents string `json:"source_events"`
|
||||
Supersedes string `json:"supersedes"`
|
||||
SupersededBy string `json:"superseded_by"`
|
||||
}
|
||||
if err := json.Unmarshal([]byte(resp.ReportJSON), &raw); err != nil {
|
||||
return nil, fmt.Errorf("scan_all unmarshal: %w", err)
|
||||
if err := json.Unmarshal([]byte(jsonText), &raw); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
out := make([]models.MemoryRecord, 0, len(raw))
|
||||
tolParse := func(s string) time.Time {
|
||||
if t, err := time.Parse(time.RFC3339, s); err == nil {
|
||||
return t
|
||||
@@ -470,6 +487,7 @@ func (rc *RustLanceDBClient) ScanAll() ([]models.MemoryRecord, error) {
|
||||
}
|
||||
return arr
|
||||
}
|
||||
out := make([]models.MemoryRecord, 0, len(raw))
|
||||
for i := range raw {
|
||||
rec := raw[i].MemoryRecord
|
||||
rec.LastRecalledAt = tolParse(raw[i].LastRecalledAt)
|
||||
@@ -482,13 +500,6 @@ func (rc *RustLanceDBClient) ScanAll() ([]models.MemoryRecord, error) {
|
||||
rec.SupersededBy = tolStrArray(raw[i].SupersededBy)
|
||||
out = append(out, rec)
|
||||
}
|
||||
// 同步到本地缓存(与 GetSkillCandidates 同款)
|
||||
_local.mu.Lock()
|
||||
for i := range out {
|
||||
cp := out[i]
|
||||
_local.memories[cp.ID] = &cp
|
||||
}
|
||||
_local.mu.Unlock()
|
||||
return out, nil
|
||||
}
|
||||
|
||||
@@ -499,11 +510,11 @@ func (rc *RustLanceDBClient) ScanDeleted() ([]models.MemoryRecord, error) {
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
var raw []models.MemoryRecord
|
||||
if err := json.Unmarshal([]byte(resp.ReportJSON), &raw); err != nil {
|
||||
out, err := unmarshalMemoryRecordsTolerant(resp.ReportJSON)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("scan_deleted unmarshal: %w", err)
|
||||
}
|
||||
return raw, nil
|
||||
return out, nil
|
||||
}
|
||||
|
||||
func (rc *RustLanceDBClient) localSearch(vec []float32, topK int, ns string) []models.MemoryRecord {
|
||||
@@ -1015,13 +1026,23 @@ func (rc *RustLanceDBClient) GetVersionHistory(id string) ([]map[string]interfac
|
||||
return nil, nil
|
||||
}
|
||||
|
||||
// forgetCursorPath 遗忘候选旋转窗口游标持久化文件(2026-10-11 t_a4b8fa52 方案 c′)。
|
||||
// defaultForgetCursorPath 遗忘候选旋转窗口游标持久化文件(2026-10-11 t_a4b8fa52 方案 c′)。
|
||||
// 游标 = 上一轮扫描窗口的末 id(mem_<unixnano>);文件缺失/损坏/库回滚 → 空串(从头轮转,降级不崩)。
|
||||
var forgetCursorPath = "/var/lib/memoryweave/forget-cursor.json"
|
||||
const defaultForgetCursorPath = "/var/lib/memoryweave/forget-cursor.json"
|
||||
|
||||
// forgetCursorFilePath 解析游标文件路径。
|
||||
// 2026-10-16 (t_944344b5):支持 env ZHIYI_FORGET_CURSOR 覆盖(测试/副本场景用独立游标文件,
|
||||
// 避免测试实例误读写生产 /var/lib/memoryweave/forget-cursor.json)。未设 env → 生产默认路径(行为不变)。
|
||||
func forgetCursorFilePath() string {
|
||||
if p := os.Getenv("ZHIYI_FORGET_CURSOR"); p != "" {
|
||||
return p
|
||||
}
|
||||
return defaultForgetCursorPath
|
||||
}
|
||||
|
||||
// loadForgetCursor 读取持久化游标。缺失/空/损坏 → 返回 ""(降级为从头轮转,不崩)。
|
||||
func loadForgetCursor() string {
|
||||
data, err := os.ReadFile(forgetCursorPath)
|
||||
data, err := os.ReadFile(forgetCursorFilePath())
|
||||
if err != nil {
|
||||
if os.IsNotExist(err) {
|
||||
return "" // 首次运行或文件被清,正常
|
||||
@@ -1045,17 +1066,18 @@ func persistForgetCursor(cursor string) {
|
||||
if cursor == "" {
|
||||
return // wrapped → 下轮从头,无需落盘空游标(缺文件=从头)
|
||||
}
|
||||
dir := filepath.Dir(forgetCursorPath)
|
||||
cursorFile := forgetCursorFilePath()
|
||||
dir := filepath.Dir(cursorFile)
|
||||
if err := os.MkdirAll(dir, 0o755); err != nil {
|
||||
log.Printf("[ipc] persistForgetCursor mkdir failed: %v", err)
|
||||
return
|
||||
}
|
||||
tmp := forgetCursorPath + ".tmp"
|
||||
tmp := cursorFile + ".tmp"
|
||||
if err := os.WriteFile(tmp, []byte(cursor), 0o644); err != nil {
|
||||
log.Printf("[ipc] persistForgetCursor write failed: %v", err)
|
||||
return
|
||||
}
|
||||
if err := os.Rename(tmp, forgetCursorPath); err != nil {
|
||||
if err := os.Rename(tmp, cursorFile); err != nil {
|
||||
log.Printf("[ipc] persistForgetCursor rename failed: %v", err)
|
||||
}
|
||||
}
|
||||
@@ -1088,6 +1110,9 @@ func (rc *RustLanceDBClient) GetCandidatesForForgetting() ([]map[string]interfac
|
||||
RecallVerifiedCount int64 `json:"recall_verified_count"`
|
||||
LastRecalledAt string `json:"last_recalled_at"`
|
||||
CreatedAt string `json:"created_at"`
|
||||
// 2026-10-16 (t_944344b5):补 freshness —— Rust MemoryRecord/forget_window 一直带该字段,
|
||||
// 但 Go IPC 结构体此前漏收 ⇒ 候选 map 无 freshness ⇒ 保护规则3(freshness=verified)恒不触发。
|
||||
Freshness string `json:"freshness"`
|
||||
} `json:"records"`
|
||||
NextCursor string `json:"next_cursor"`
|
||||
Wrapped bool `json:"wrapped"`
|
||||
@@ -1121,6 +1146,8 @@ func (rc *RustLanceDBClient) GetCandidatesForForgetting() ([]map[string]interfac
|
||||
"recall_verified_count": int(r.RecallVerifiedCount),
|
||||
"last_recalled_at": r.LastRecalledAt,
|
||||
"created_at": r.CreatedAt,
|
||||
// 2026-10-16 (t_944344b5):freshness 进候选 map ⇒ 保护守卫规则3 可判定
|
||||
"freshness": r.Freshness,
|
||||
})
|
||||
}
|
||||
return out, nil
|
||||
@@ -1145,6 +1172,8 @@ func (rc *RustLanceDBClient) GetCandidatesForForgetting() ([]map[string]interfac
|
||||
"recall_verified_count": m.RecallVerifiedCount,
|
||||
"tier": m.Tier,
|
||||
"importance": m.Importance,
|
||||
// 2026-10-16 (t_944344b5):fallback 缓存路径同样带 freshness(与主 IPC 路径对齐)
|
||||
"freshness": m.Freshness,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
@@ -221,6 +221,46 @@ func (rc *RedisClient) HGetAll(key string) (map[string]string, error) {
|
||||
return result, nil
|
||||
}
|
||||
|
||||
// SMembers 返回 SET 的全部成员(key 不存在 / 未连接 / 非 SET 响应 → 返回 nil,不报 error)。
|
||||
// 2026-10-16 (t_944344b5 遗忘保护守卫):读 zhiyi:protected_ids 显式豁免名单。
|
||||
// 只读既有 key,不新建 key ⇒ 不触发 noeviction/TTL 约束。
|
||||
func (rc *RedisClient) SMembers(key string) []string {
|
||||
if rc.conn == nil {
|
||||
return nil
|
||||
}
|
||||
v, err := rc.conn.Do("SMEMBERS", key)
|
||||
if err != nil {
|
||||
return nil
|
||||
}
|
||||
arr, ok := v.([]interface{})
|
||||
if !ok {
|
||||
return nil
|
||||
}
|
||||
out := make([]string, 0, len(arr))
|
||||
for _, e := range arr {
|
||||
if s, ok := e.(string); ok {
|
||||
out = append(out, s)
|
||||
}
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
// SIsMember 报告 member 是否在 SET 中(key 不存在 / 未连接 → false,不报 error)。
|
||||
// Redis SISMEMBER 返回整数 0/1(RESP : 行 → int64)。只读既有 key,不新建 key。
|
||||
func (rc *RedisClient) SIsMember(key, member string) bool {
|
||||
if rc.conn == nil {
|
||||
return false
|
||||
}
|
||||
v, err := rc.conn.Do("SISMEMBER", key, member)
|
||||
if err != nil {
|
||||
return false
|
||||
}
|
||||
if n, ok := v.(int64); ok {
|
||||
return n == 1
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
// ─── Pub/Sub ──────────────────────────────────────────
|
||||
|
||||
func (rc *RedisClient) Publish(channel, message string) error {
|
||||
|
||||
Reference in New Issue
Block a user