根因(实证):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>
1745 lines
71 KiB
Go
1745 lines
71 KiB
Go
// 织忆 MemoryWeave — LanceDB IPC 桥接(Go ↔ Rust Unix Socket)
|
||
package storage
|
||
|
||
import (
|
||
"encoding/binary"
|
||
"encoding/json"
|
||
"fmt"
|
||
"io"
|
||
"log"
|
||
"math/rand"
|
||
"net"
|
||
"os"
|
||
"path/filepath"
|
||
"strings"
|
||
"sync"
|
||
"time"
|
||
|
||
"github.com/xiaoxue/memoryweave/internal/metrics"
|
||
"github.com/xiaoxue/memoryweave/internal/models"
|
||
)
|
||
|
||
// RustLanceDBClient Unix Socket → zhiyi-consolidate
|
||
type RustLanceDBClient struct {
|
||
mu sync.Mutex
|
||
sockPath string
|
||
embedder *Embedder
|
||
}
|
||
|
||
// NewRustLanceDBClient 创建 Rust IPC 客户端
|
||
func NewRustLanceDBClient(sockPath string, emb *Embedder) *RustLanceDBClient {
|
||
if sockPath == "" {
|
||
sockPath = "/tmp/zhiyi-ipc.sock"
|
||
}
|
||
return &RustLanceDBClient{sockPath: sockPath, embedder: emb}
|
||
}
|
||
|
||
// ─── IPC 协议 ────────────────────────────────────────────
|
||
|
||
// t_576714de:单次重读被行数上限截断后,最重的一次响应(20000 行 JSON)在内存
|
||
// 紧张时实测 ~43s。读 deadline 取 120s(>> 任何合法操作,≪ 无限阻塞);侧车接受
|
||
// 连接后挂死/被 kill 时,旧实现 io.ReadFull 无 deadline ⇒ 客户端永久阻塞
|
||
// (「边车好了它还挂着」)。封顶后超时即返回错误,调用方降级(Search→本地兜底),
|
||
// 且每次 rpc 都是新 dial ⇒ 侧车恢复后下一次调用天然重连。
|
||
// 用 var(非 const)便于测试临时缩短读超时验证「挂死不被无限阻塞」。
|
||
var (
|
||
ipcDialTimeout = 5 * time.Second
|
||
ipcWriteTimeout = 30 * time.Second
|
||
ipcReadTimeout = 120 * time.Second
|
||
)
|
||
|
||
type ipcReq struct {
|
||
Type string `json:"type"`
|
||
Table string `json:"table,omitempty"`
|
||
Records string `json:"records,omitempty"`
|
||
Vector []float32 `json:"vector,omitempty"`
|
||
TopK int `json:"top_k,omitempty"`
|
||
Namespace string `json:"namespace,omitempty"`
|
||
ID string `json:"id,omitempty"`
|
||
Fields string `json:"fields,omitempty"`
|
||
MinRecall int `json:"min_recall,omitempty"`
|
||
QueryLimit int `json:"limit,omitempty"`
|
||
// 2026-10-11 (t_a4b8fa52 方案 c′): 遗忘候选旋转窗口游标(last processed id)
|
||
AfterID string `json:"after_id,omitempty"`
|
||
Items string `json:"items,omitempty"` // lancedb_update_batch: [{"id":..,"delta":N}]
|
||
TS string `json:"ts,omitempty"` // lancedb_update_batch: last_recalled_at
|
||
// GA-P0-4 (t_bb10e8bc):hits+/hits− outcome 事件 IPC 参数
|
||
Outcome string `json:"outcome,omitempty"` // hit_events: pos|neg
|
||
Reason string `json:"reason,omitempty"` // hit_events: human_feedback|contradiction|replacement|downstream_use
|
||
Source string `json:"source,omitempty"` // hit_events: 记录方标识
|
||
Since string `json:"since,omitempty"` // hit_events 周窗口起点 (RFC3339)
|
||
}
|
||
|
||
type ipcResp struct {
|
||
Status string `json:"status"`
|
||
ReportJSON string `json:"report_json"` // consolidator uses this
|
||
Result string `json:"result"` // lancedb search uses this
|
||
FailureStep string `json:"failure_step"`
|
||
ErrorDetail string `json:"error_detail"`
|
||
// t_576714de:单次重读被 Rust 侧行数上限截断时 = true(部分结果,非全量)。
|
||
// 旧 sidecar 无此字段 ⇒ 缺省 false,向后兼容。
|
||
Truncated bool `json:"truncated"`
|
||
}
|
||
|
||
// updateField lancedb_update 的单列更新项:Value 为 SQL 表达式
|
||
// (字符串需用单引号包裹并转义,布尔用 true/false 字面量,数值裸写)
|
||
type updateField struct {
|
||
Column string `json:"column"`
|
||
Value string `json:"value"`
|
||
}
|
||
|
||
func (rc *RustLanceDBClient) rpc(req ipcReq) (*ipcResp, error) {
|
||
// 每次调用都是新 dial:侧车不可用(socket 消失/无监听)⇒ 快速失败;
|
||
// 侧车恢复后下一次调用天然重连(t_576714de AC)。
|
||
conn, err := net.DialTimeout("unix", rc.sockPath, ipcDialTimeout)
|
||
if err != nil {
|
||
return nil, fmt.Errorf("ipc dial: %w", err)
|
||
}
|
||
defer conn.Close()
|
||
// 给已建立连接封顶读/写 deadline:侧车接受连接后挂死/被 kill ⇒ 旧实现
|
||
// io.ReadFull 无限阻塞(「边车好了它还挂着」)。现超时即降级,热路径 recall 不受阻。
|
||
now := time.Now()
|
||
_ = conn.SetWriteDeadline(now.Add(ipcWriteTimeout))
|
||
_ = conn.SetReadDeadline(now.Add(ipcReadTimeout))
|
||
|
||
body, _ := json.Marshal(req)
|
||
lenBuf := make([]byte, 4)
|
||
binary.BigEndian.PutUint32(lenBuf, uint32(len(body)))
|
||
if _, err := conn.Write(lenBuf); err != nil {
|
||
return nil, fmt.Errorf("ipc write len: %w", err)
|
||
}
|
||
if _, err := conn.Write(body); err != nil {
|
||
return nil, fmt.Errorf("ipc write body: %w", err)
|
||
}
|
||
|
||
if _, err := io.ReadFull(conn, lenBuf); err != nil {
|
||
return nil, fmt.Errorf("ipc read len (sidecar down/hung, read deadline %s): %w", ipcReadTimeout, err)
|
||
}
|
||
msgLen := binary.BigEndian.Uint32(lenBuf)
|
||
respBuf := make([]byte, msgLen)
|
||
if _, err := io.ReadFull(conn, respBuf); err != nil {
|
||
return nil, fmt.Errorf("ipc read body (sidecar down/hung, read deadline %s): %w", ipcReadTimeout, err)
|
||
}
|
||
|
||
var resp ipcResp
|
||
if err := json.Unmarshal(respBuf, &resp); err != nil {
|
||
return nil, err
|
||
}
|
||
if resp.Status != "ok" {
|
||
return nil, fmt.Errorf("ipc: %s", resp.ErrorDetail)
|
||
}
|
||
return &resp, nil
|
||
}
|
||
|
||
// ─── LanceDB 接口 ────────────────────────────────────────
|
||
|
||
// 本地内存缓冲(LanceDB IPC 只做向量存储,元数据本地缓存)
|
||
type memCache struct {
|
||
mu sync.RWMutex
|
||
memories map[string]*models.MemoryRecord
|
||
episodes []models.EpisodeRecord
|
||
auditLog []map[string]interface{}
|
||
}
|
||
|
||
var _local = &memCache{memories: make(map[string]*models.MemoryRecord)}
|
||
|
||
func (rc *RustLanceDBClient) InsertEpisode(agentID, namespace, content, category string) (string, error) {
|
||
id := fmt.Sprintf("ep_%d", time.Now().UnixNano())
|
||
now := time.Now()
|
||
// 本地缓存(保持原有行为)
|
||
_local.mu.Lock()
|
||
_local.episodes = append(_local.episodes, models.EpisodeRecord{
|
||
ID: id, AgentID: agentID, Namespace: namespace, Content: content, Category: category, CreatedAt: now,
|
||
})
|
||
_local.mu.Unlock()
|
||
|
||
// 持久化到 Rust LanceDB episodes 表(24 字段,重启不丢)
|
||
record := map[string]interface{}{
|
||
"id": id, "agent_id": agentID, "namespace": namespace,
|
||
"content": content, "category": category,
|
||
"tier": "episode", "importance": EffectiveEpisodeImportance(), "quality_score": 0.0,
|
||
"recall_count": 0, "useful_count": 0, "not_useful_count": 0,
|
||
// GA-P0-2 (t_c6d41ac6):拆分字段(episode 无召回/反馈,恒 0)
|
||
"recall_seen_count": 0, "recall_verified_count": 0,
|
||
// GA-P0-1 (t_718d8707):拆分字段(episode 无反馈,恒 0)
|
||
"human_not_useful_count": 0, "dedup_downweight_count": 0,
|
||
"freshness": "fresh", "version": 1, "version_history": "[]",
|
||
// t_268b0353:volatile_flag 插入路径恒 false;下方 *0.5 惩罚分支是预留
|
||
//(将来接「≥3 次修正自动置位」),当前不生效,勿依赖。
|
||
"source": "episode", "volatile_flag": false, "is_deleted": false,
|
||
"depends_on": "[]", "derived_from": "", "last_recalled_at": "",
|
||
"created_at": now.Format(time.RFC3339),
|
||
"updated_at": now.Format(time.RFC3339),
|
||
}
|
||
recJSON, _ := json.Marshal([]interface{}{record})
|
||
if _, err := rc.rpc(ipcReq{Type: "lancedb_insert", Table: "episodes", Records: string(recJSON)}); err != nil {
|
||
// 持久化失败不阻断请求(保持"总是写入"语义),但记日志便于发现
|
||
log.Printf("[ipc] InsertEpisode persist to LanceDB failed (id=%s): %v", id, err)
|
||
}
|
||
return id, nil
|
||
}
|
||
|
||
func (rc *RustLanceDBClient) InsertMemory(m models.MemoryRecord) error {
|
||
// 编码向量
|
||
if len(m.Vector) == 0 {
|
||
vec, err := rc.embedder.EncodeSingle(m.Content)
|
||
if err == nil {
|
||
m.Vector = vec
|
||
}
|
||
}
|
||
|
||
// 本地缓存
|
||
_local.mu.Lock()
|
||
cp := m
|
||
_local.memories[m.ID] = &cp
|
||
_local.mu.Unlock()
|
||
|
||
// 写入 Rust LanceDB(完整 24 字段)
|
||
record := map[string]interface{}{
|
||
"id": m.ID, "agent_id": m.AgentID, "namespace": m.Namespace,
|
||
"content": m.Content, "category": m.Category, "vector": m.Vector,
|
||
"tier": m.Tier, "importance": EffectiveMemoryImportance(m), "quality_score": m.QualityScore,
|
||
"recall_count": m.RecallCount, "useful_count": 0, "not_useful_count": 0,
|
||
// GA-P0-2 (t_c6d41ac6):拆分字段(新记忆按 model 携带,通常 0)
|
||
"recall_seen_count": m.RecallSeenCount, "recall_verified_count": m.RecallVerifiedCount,
|
||
// GA-P0-1 (t_718d8707):拆分字段(新记忆按 model 携带,通常 0)
|
||
"human_not_useful_count": m.HumanNotUsefulCount, "dedup_downweight_count": m.DedupDownweightCount,
|
||
"freshness": m.Freshness, "version": 1, "version_history": "[]",
|
||
// t_268b0353:volatile_flag 插入路径恒 false;下方 *0.5 惩罚分支是预留
|
||
//(将来接「≥3 次修正自动置位」),当前不生效,勿依赖。
|
||
"source": m.Source, "volatile_flag": false, "is_deleted": m.IsDeleted,
|
||
"depends_on": "[]", "derived_from": m.DerivedFrom, "last_recalled_at": "",
|
||
// 2026-10-13 (t_e9a4d18f P1) 证据链:全量来源 episode ID(JSON 数组字符串)
|
||
"source_events": seJSON(m.SourceEvents),
|
||
// 2026-10-13 (t_e9a4d18f P1) 矛盾保留:被取代的旧记忆 ID
|
||
"supersedes": seJSON(m.Supersedes),
|
||
// 2026-10-14 (t_3e98b65a) 被取代方标记:反向指针(新增时通常空)
|
||
"superseded_by": seJSON(m.SupersededBy),
|
||
// 2026-10-14 (t_3ada332b P3) bi-temporal 有效期三列:RFC3339;空 = 永久有效。
|
||
// 缺此三行 ⇒ Rust 侧 schema 无列 ⇒ 召回降权永不触发(本次事故根因,勿再删)。
|
||
"valid_from": m.ValidFrom, "valid_to": m.ValidTo, "provenance": m.Provenance,
|
||
"embedding_model": m.EmbeddingModel, "script_version": m.ScriptVersion, // 2026-10-08 (t_7e3577c5) 血缘
|
||
// 2026-10-08 (Gap#2):nil ⇒ JSON null ⇒ Rust 写 NULL(不伪装成 0.0)
|
||
"confidence": m.Confidence, "confidence_source": m.ConfidenceSource,
|
||
"created_at": m.CreatedAt.Format(time.RFC3339),
|
||
"updated_at": m.UpdatedAt.Format(time.RFC3339),
|
||
}
|
||
recJSON, _ := json.Marshal([]interface{}{record})
|
||
_, err := rc.rpc(ipcReq{Type: "lancedb_insert", Table: "memories", Records: string(recJSON)})
|
||
return err
|
||
}
|
||
|
||
// SearchWithTruncation 同 Search,但额外返回「本次结果是否被 Rust 侧单次重读行数上限
|
||
// 截断」(ipcResp.Truncated,t_576714de 引入)。t_3aa2a8c1:该标志此前只打日志不上抛
|
||
// (recall 调用方观测不到「结果被截断」),现透传出去供 /api/v1/recall 暴露。
|
||
// 本地兜底(IPC 错误 / 零结果走 localSearch)没有行数上限 ⇒ 恒 false。
|
||
func (rc *RustLanceDBClient) SearchWithTruncation(table string, vector []float32, topK int, namespaceFilter string) ([]models.MemoryRecord, bool, error) {
|
||
resp, err := rc.rpc(ipcReq{
|
||
Type: "lancedb_search", Vector: vector, TopK: topK * 2, Namespace: namespaceFilter,
|
||
})
|
||
if err != nil {
|
||
return rc.localSearch(vector, topK, namespaceFilter), false, nil
|
||
}
|
||
|
||
var raw []struct {
|
||
ID string `json:"id"`
|
||
Content string `json:"content"`
|
||
Category string `json:"category"`
|
||
Namespace string `json:"namespace"`
|
||
IsDeleted bool `json:"is_deleted"`
|
||
DeleteReason string `json:"delete_reason"` // GA-P0-3
|
||
CreatedAt string `json:"created_at"`
|
||
UpdatedAt string `json:"updated_at"`
|
||
QualityScore float64 `json:"quality_score"`
|
||
Importance float64 `json:"importance"`
|
||
RecallCount int64 `json:"recall_count"`
|
||
// GA-P0-2 (t_c6d41ac6):拆分字段读侧接线
|
||
RecallSeenCount int64 `json:"recall_seen_count"`
|
||
RecallVerifiedCount int64 `json:"recall_verified_count"`
|
||
VolatileFlag bool `json:"volatile_flag"`
|
||
Tier string `json:"tier"`
|
||
LastRecalledAt string `json:"last_recalled_at"`
|
||
// 2026-09-26:出处(笔记路径)—— 此前**解包结构缺该字段** → IPC 主路径 Source 恒空
|
||
// (本地兜底路径有 Source,主路径没有 → recall 永远拿不到出处,链路看似修好实则断在这一环)
|
||
Source string `json:"source"`
|
||
// 2026-10-14 (t_763e8701) bi-temporal 三列读回:Rust Search 已回传。
|
||
// 缺这几行 ⇒ 读回解包后仍是空串 ⇒ recall 降权判定拿不到 valid_to。
|
||
ValidFrom string `json:"valid_from"`
|
||
ValidTo string `json:"valid_to"`
|
||
Provenance string `json:"provenance"`
|
||
// 2026-10-08 (Gap#2):读侧投影 —— 不补这里,加列也读不出来(静默 no-op)。
|
||
// 用 *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 判定失败 →
|
||
// 去重静默退化为「只比字符串相等」,端点恒报 merged≈0(假阴性)。
|
||
Vector []float32 `json:"vector"`
|
||
}
|
||
json.Unmarshal([]byte(resp.ReportJSON), &raw)
|
||
if resp.Truncated {
|
||
// t_576714de:Rust 侧单次重读被行数上限截断(部分结果,非全量)—— 显式日志,禁静默。
|
||
log.Printf("[ipc] Search truncated: single-read cap applied, got %d rows (partial result)", len(raw))
|
||
}
|
||
if len(raw) == 0 {
|
||
log.Printf("[ipc] Search: resp.ReportJSON unmarshal gave 0 results, falling back to localSearch (Result=%q)", resp.Result)
|
||
return rc.localSearch(vector, topK, namespaceFilter), false, nil
|
||
}
|
||
log.Printf("[ipc] Search: got %d results from Rust IPC (Result=%q)", len(raw), resp.Result)
|
||
|
||
// 解析时间(Rust 返回 RFC3339 字符串 → time.Time)
|
||
parseTime := func(s string) time.Time {
|
||
t, err := time.Parse(time.RFC3339, s)
|
||
if err != nil {
|
||
return time.Now()
|
||
}
|
||
return t
|
||
}
|
||
|
||
// 客户端 namespace 过滤(Rust lancedb only_if 不可靠)
|
||
out := make([]models.MemoryRecord, 0, topK)
|
||
for _, r := range raw {
|
||
if r.IsDeleted {
|
||
continue
|
||
}
|
||
if namespaceFilter != "" && r.Namespace != namespaceFilter {
|
||
continue
|
||
}
|
||
// 重要性计算 + 质量融合 —— 纯函数在 quality_fusion.go(t_5028c14d)
|
||
daysSinceRecall := 30.0 // default for never-recalled
|
||
if r.LastRecalledAt != "" {
|
||
if lastT, err := time.Parse(time.RFC3339, r.LastRecalledAt); err == nil {
|
||
daysSinceRecall = time.Since(lastT).Hours() / 24.0
|
||
}
|
||
}
|
||
// GA-P0-2 (t_c6d41ac6):排序去偏用 recall_seen_count(观测/选择信号);
|
||
// recall_verified_count 只参与衰减/遗忘决策,不参与排序。
|
||
computedImportance := computeImportance(daysSinceRecall, r.RecallSeenCount, r.VolatileFlag)
|
||
|
||
// QualityScore 融合(归一化到 0-1 范围)
|
||
// t_631ab13d:先存原始 DB 值(r.QualityScore 是 LanceDB 列直接值),
|
||
// 融合后 finalQuality 写进 QualityScore(供排序),RawQualityScore 保留原值(供 recall 响应展示)
|
||
dbRawQS := r.QualityScore
|
||
// 2026-10-12:存量 quality_score 有 54.2% 不可信(0=未打分 / 0.755=历史常量 bug)。
|
||
// 修入口治不了存量 —— 消费端必须自己判定,不可信时把权重让给可信信号。
|
||
if !models.IsReliableQuality(r.QualityScore) && qstrustVerbose {
|
||
log.Printf("[qstrust-ipc] 不可信质量分已剔除 id=%s rawQS=%.6f → 仅用 importance %.4f",
|
||
r.ID, r.QualityScore, computedImportance)
|
||
}
|
||
var vVal float64
|
||
if VValueProvider != nil {
|
||
vVal = VValueProvider(r.ID)
|
||
}
|
||
finalQuality := fuseQuality(computedImportance, r.QualityScore, vVal)
|
||
|
||
out = append(out, models.MemoryRecord{
|
||
ID: r.ID, Content: r.Content, Category: r.Category, Namespace: r.Namespace,
|
||
CreatedAt: parseTime(r.CreatedAt), UpdatedAt: parseTime(r.UpdatedAt),
|
||
QualityScore: finalQuality, Importance: r.Importance,
|
||
RecallCount: int(r.RecallCount), VolatileFlag: r.VolatileFlag,
|
||
Tier: r.Tier,
|
||
// GA-P0-2 (t_c6d41ac6):拆分字段读侧接线
|
||
RecallSeenCount: int(r.RecallSeenCount),
|
||
RecallVerifiedCount: int(r.RecallVerifiedCount),
|
||
Source: r.Source, // 2026-09-26:出处透出(缺此行 → recall.source 恒空)
|
||
Vector: r.Vector, // 去重判据依赖,勿删
|
||
// t_631ab13d:DB 原值直通 —— RecallResult 展示用它,排序用 QualityScore(融合值)
|
||
RawQualityScore: &dbRawQS,
|
||
// 2026-10-08 (Gap#2):解包结构有 ≠ 输出有。缺这两行 ⇒ 加列、改 schema、
|
||
// 通 IPC 全做完,recall 拿到的 Confidence 仍是 nil(第 5 层静默断链,
|
||
// 端到端测试才抓得到)。
|
||
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,
|
||
Provenance: r.Provenance,
|
||
})
|
||
if len(out) >= topK {
|
||
break
|
||
}
|
||
}
|
||
return out, resp.Truncated, nil
|
||
}
|
||
|
||
// Search 旧签名(不报告截断)。截断标志的透传走 SearchWithTruncation(t_3aa2a8c1)。
|
||
func (rc *RustLanceDBClient) Search(table string, vector []float32, topK int, namespaceFilter string) ([]models.MemoryRecord, error) {
|
||
recs, _, err := rc.SearchWithTruncation(table, vector, topK, namespaceFilter)
|
||
return recs, err
|
||
}
|
||
|
||
// Scan 全表扫描存活记忆(走 Rust IPC `lancedb_scan`:is_deleted=false + namespace 下推)。
|
||
// 2026-09-21:为 /api/v1/memories 与 /api/v1/memories/export 提供正确底座。
|
||
// 修前这两个端点用 `Search(zeroVec, ...)` 冒充列表:零向量没有方向,
|
||
// ANN 返回的是存储序前 N 行再按 ns 过滤 ⇒ 实测 hermes-main 报 1 条(真实 139+),
|
||
// 计数完全失真、导出内容残缺。
|
||
// 注意:Rust 侧硬上限 5000;namespace 由 only_if 下推,limit 作用于**过滤后**结果集。
|
||
func (rc *RustLanceDBClient) Scan(limit int, namespaceFilter string) ([]models.MemoryRecord, error) {
|
||
if limit <= 0 {
|
||
limit = 100
|
||
}
|
||
if limit > 5000 {
|
||
limit = 5000
|
||
}
|
||
resp, err := rc.rpc(ipcReq{Type: "lancedb_scan", QueryLimit: limit, Namespace: namespaceFilter})
|
||
if err != nil {
|
||
return nil, err
|
||
}
|
||
|
||
var raw []struct {
|
||
ID string `json:"id"`
|
||
Content string `json:"content"`
|
||
Category string `json:"category"`
|
||
Namespace string `json:"namespace"`
|
||
IsDeleted bool `json:"is_deleted"`
|
||
DeleteReason string `json:"delete_reason"` // GA-P0-3
|
||
CreatedAt string `json:"created_at"`
|
||
UpdatedAt string `json:"updated_at"`
|
||
Importance float64 `json:"importance"`
|
||
QualityScore float64 `json:"quality_score"`
|
||
RecallCount int64 `json:"recall_count"`
|
||
// GA-P0-2 (t_c6d41ac6):拆分后的新字段,scan 也读
|
||
RecallSeenCount int64 `json:"recall_seen_count"`
|
||
RecallVerifiedCount int64 `json:"recall_verified_count"`
|
||
NotUsefulCount int64 `json:"not_useful_count"`
|
||
// GA-P0-1 (t_718d8707):拆分后的新字段,scan 也读(迁移脚本 / 列表需要)
|
||
HumanNotUsefulCount int64 `json:"human_not_useful_count"`
|
||
DedupDownweightCount int64 `json:"dedup_downweight_count"`
|
||
Tier string `json:"tier"`
|
||
Freshness string `json:"freshness"`
|
||
Source string `json:"source"`
|
||
// 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"`
|
||
Provenance string `json:"provenance"`
|
||
}
|
||
if err := json.Unmarshal([]byte(resp.ReportJSON), &raw); err != nil {
|
||
return nil, fmt.Errorf("scan unmarshal: %w", err)
|
||
}
|
||
parseTime := func(s string) time.Time {
|
||
if t, err := time.Parse(time.RFC3339, s); err == nil {
|
||
return t
|
||
}
|
||
return time.Time{}
|
||
}
|
||
out := make([]models.MemoryRecord, 0, limit)
|
||
for _, r := range raw {
|
||
if r.IsDeleted {
|
||
continue
|
||
}
|
||
// 兜底:Rust only_if 下推失效时客户端再过滤一次(同 Search 的做法)
|
||
if namespaceFilter != "" && r.Namespace != namespaceFilter {
|
||
continue
|
||
}
|
||
out = append(out, models.MemoryRecord{
|
||
ID: r.ID, Content: r.Content, Category: r.Category, Namespace: r.Namespace,
|
||
CreatedAt: parseTime(r.CreatedAt), UpdatedAt: parseTime(r.UpdatedAt),
|
||
Importance: r.Importance, QualityScore: r.QualityScore,
|
||
RecallCount: int(r.RecallCount), Tier: r.Tier, Source: r.Source,
|
||
// GA-P0-3 (t_f785d7f2):scan 读侧接线 delete_reason
|
||
DeleteReason: r.DeleteReason,
|
||
// GA-P0-2 (t_c6d41ac6):scan 读侧接线拆分字段
|
||
RecallSeenCount: int(r.RecallSeenCount), RecallVerifiedCount: int(r.RecallVerifiedCount),
|
||
// 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,
|
||
Provenance: r.Provenance,
|
||
})
|
||
if len(out) >= limit {
|
||
break
|
||
}
|
||
}
|
||
return out, nil
|
||
}
|
||
|
||
// ScanAll 全表扫描(仅存活行,无 5000 上限——Rust 侧 scan_all 上限 200000)。
|
||
// GA-P0-1 (t_718d7f01):供 not_useful_count 拆分迁移脚本读取全部行做统计。
|
||
// 2026-10-14 (t_2afae95e):时间列宽容解析 —— 存量行 created_at/last_recalled_at
|
||
// 可能为空串,time.Time 严格解析会把整批 2.6 万行全炸(FTS 建索引首建实测
|
||
// 踩到:scan_all unmarshal: parsing time "" ...)。空/畸形 ⇒ 零值,不阻塞。
|
||
func (rc *RustLanceDBClient) ScanAll() ([]models.MemoryRecord, error) {
|
||
resp, err := rc.rpc(ipcReq{Type: "lancedb_scan_all"})
|
||
if err != nil {
|
||
return nil, err
|
||
}
|
||
out, err := unmarshalMemoryRecordsTolerant(resp.ReportJSON)
|
||
if err != nil {
|
||
return nil, fmt.Errorf("scan_all unmarshal: %w", err)
|
||
}
|
||
if resp.Truncated {
|
||
// t_576714de:单次扫描被行数上限截断(部分结果)—— 显式日志,禁静默。
|
||
log.Printf("[ipc] ScanAll truncated: single-read cap applied, got %d rows (partial)", len(out))
|
||
}
|
||
// 同步到本地缓存(与 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 宽容解析
|
||
LastRecalledAt string `json:"last_recalled_at"`
|
||
CreatedAt string `json:"created_at"`
|
||
UpdatedAt string `json:"updated_at"`
|
||
// 血缘列:Rust 输出 JSON 数组字符串("[]" / "[\"ep_x\"]" / 空串),
|
||
// 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(jsonText), &raw); err != nil {
|
||
return nil, err
|
||
}
|
||
tolParse := func(s string) time.Time {
|
||
if t, err := time.Parse(time.RFC3339, s); err == nil {
|
||
return t
|
||
}
|
||
return time.Time{} // 空/畸形 ⇒ 零值(宽容,不炸整批)
|
||
}
|
||
tolStrArray := func(s string) []string {
|
||
s = strings.TrimSpace(s)
|
||
if s == "" || s == "[]" {
|
||
return nil
|
||
}
|
||
var arr []string
|
||
if err := json.Unmarshal([]byte(s), &arr); err != nil {
|
||
return nil // 畸形 JSON ⇒ 空(宽容)
|
||
}
|
||
return arr
|
||
}
|
||
tolVersionHistory := func(s string) []models.VersionRecord {
|
||
s = strings.TrimSpace(s)
|
||
if s == "" || s == "[]" {
|
||
return nil
|
||
}
|
||
var arr []models.VersionRecord
|
||
if err := json.Unmarshal([]byte(s), &arr); err != nil {
|
||
return nil // 畸形 JSON ⇒ 空(宽容)
|
||
}
|
||
return arr
|
||
}
|
||
out := make([]models.MemoryRecord, 0, len(raw))
|
||
for i := range raw {
|
||
rec := raw[i].MemoryRecord
|
||
rec.LastRecalledAt = tolParse(raw[i].LastRecalledAt)
|
||
rec.CreatedAt = tolParse(raw[i].CreatedAt)
|
||
rec.UpdatedAt = tolParse(raw[i].UpdatedAt)
|
||
rec.VersionHistory = tolVersionHistory(raw[i].VersionHistory)
|
||
rec.DependsOn = tolStrArray(raw[i].DependsOn)
|
||
rec.SourceEvents = tolStrArray(raw[i].SourceEvents)
|
||
rec.Supersedes = tolStrArray(raw[i].Supersedes)
|
||
rec.SupersededBy = tolStrArray(raw[i].SupersededBy)
|
||
out = append(out, rec)
|
||
}
|
||
return out, nil
|
||
}
|
||
|
||
// ScanDeleted 全表扫描**已删除**行(is_deleted=true)。GA-P0-3 (t_f785d7f2)。
|
||
// 供 delete_reason 回填脚本枚举存量已删行 + 出直方图。只读,不落库。
|
||
func (rc *RustLanceDBClient) ScanDeleted() ([]models.MemoryRecord, error) {
|
||
resp, err := rc.rpc(ipcReq{Type: "lancedb_scan_deleted"})
|
||
if err != nil {
|
||
return nil, err
|
||
}
|
||
out, err := unmarshalMemoryRecordsTolerant(resp.ReportJSON)
|
||
if err != nil {
|
||
return nil, fmt.Errorf("scan_deleted unmarshal: %w", err)
|
||
}
|
||
if resp.Truncated {
|
||
// t_576714de:单次扫描被行数上限截断(部分结果)—— 显式日志,禁静默。
|
||
log.Printf("[ipc] ScanDeleted truncated: single-read cap applied, got %d rows (partial)", len(out))
|
||
}
|
||
return out, nil
|
||
}
|
||
|
||
func (rc *RustLanceDBClient) localSearch(vec []float32, topK int, ns string) []models.MemoryRecord {
|
||
_local.mu.RLock()
|
||
defer _local.mu.RUnlock()
|
||
|
||
type sc struct {
|
||
mem *models.MemoryRecord
|
||
score float64
|
||
}
|
||
var cs []sc
|
||
for _, m := range _local.memories {
|
||
if m.IsDeleted || (ns != "" && m.Namespace != ns) {
|
||
continue
|
||
}
|
||
cs = append(cs, sc{mem: m, score: cosineSim(vec, m.Vector)})
|
||
}
|
||
// 选择排序 topK
|
||
for i := 0; i < len(cs) && i < topK; i++ {
|
||
best := i
|
||
for j := i + 1; j < len(cs); j++ {
|
||
if cs[j].score > cs[best].score {
|
||
best = j
|
||
}
|
||
}
|
||
cs[i], cs[best] = cs[best], cs[i]
|
||
}
|
||
if topK > len(cs) {
|
||
topK = len(cs)
|
||
}
|
||
out := make([]models.MemoryRecord, topK)
|
||
for i := 0; i < topK; i++ {
|
||
out[i] = *cs[i].mem
|
||
}
|
||
return out
|
||
}
|
||
|
||
func (rc *RustLanceDBClient) Stats() (map[string]interface{}, error) {
|
||
resp, err := rc.rpc(ipcReq{Type: "lancedb_stats"})
|
||
if err != nil {
|
||
return map[string]interface{}{"backend": "lancedb (Rust IPC offline)", "error": err.Error()}, nil
|
||
}
|
||
var s map[string]interface{}
|
||
json.Unmarshal([]byte(resp.ReportJSON), &s)
|
||
s["backend"] = "lancedb (Rust IPC)"
|
||
// Rust sidecar 统计 memories/tombstones/episodes(episodes 已持久化到 LanceDB)
|
||
// 若 Rust 返回的 total_episodes 计数缺失(旧 sidecar),回退到本地进程内缓存。
|
||
// 回退值标记为 episodes_cached(非 total_episodes),避免消费者误以为是真实总量。
|
||
// 真实总量以 Rust count_rows 结果为准(total_episodes);episodes_cached 仅反映
|
||
// 本进程生命周期内 Insert 过的条数(重启即清零)。
|
||
if _, ok := s["total_episodes"]; !ok {
|
||
_local.mu.RLock()
|
||
s["episodes_cached"] = len(_local.episodes) // ← 缓存值,改名标注
|
||
_local.mu.RUnlock()
|
||
}
|
||
return s, nil
|
||
}
|
||
|
||
func (rc *RustLanceDBClient) Insert(table string, record any) error {
|
||
if r, ok := record.(models.MemoryRecord); ok {
|
||
return rc.InsertMemory(r)
|
||
}
|
||
if r, ok := record.(models.EpisodeRecord); ok {
|
||
_local.mu.Lock()
|
||
_local.episodes = append(_local.episodes, r)
|
||
_local.mu.Unlock()
|
||
return nil
|
||
}
|
||
return fmt.Errorf("unknown type")
|
||
}
|
||
|
||
// helper: get a counter field's current value from cache, returns cache+1 or 1 if not cached
|
||
func getIncCachedValue(id, field string, cache map[string]*models.MemoryRecord) int {
|
||
if m, ok := cache[id]; ok {
|
||
switch field {
|
||
case "recall_count":
|
||
return m.RecallCount + 1
|
||
// GA-P0-2 (t_c6d41ac6):拆分字段
|
||
case "recall_seen_count":
|
||
return m.RecallSeenCount + 1
|
||
case "recall_verified_count":
|
||
return m.RecallVerifiedCount + 1
|
||
case "useful_count":
|
||
return m.UsefulCount + 1
|
||
case "not_useful_count":
|
||
return m.NotUsefulCount + 1
|
||
case "human_not_useful_count":
|
||
return m.HumanNotUsefulCount + 1
|
||
case "dedup_downweight_count":
|
||
return m.DedupDownweightCount + 1
|
||
}
|
||
}
|
||
return 1
|
||
}
|
||
|
||
// Update 同步执行:整个操作在锁内(cache read + IPC call)
|
||
// 保证并发调用时不会 read stale value 再写回
|
||
func (rc *RustLanceDBClient) Update(table, id string, fields map[string]any) error {
|
||
_local.mu.Lock()
|
||
|
||
// 1. 更新本地内存缓存
|
||
if m, ok := _local.memories[id]; ok {
|
||
// GA-P0-2 (t_c6d41ac6):recall_count 冻结,召回命中走 recall_seen_count,正反馈走 recall_verified_count。
|
||
if v, ok := fields["recall_seen_count"]; ok {
|
||
switch inc := v.(type) {
|
||
case map[string]string:
|
||
if inc["$inc"] == "1" {
|
||
m.RecallSeenCount++
|
||
}
|
||
case map[string]interface{}:
|
||
if inc["$inc"] == "1" {
|
||
m.RecallSeenCount++
|
||
}
|
||
case int:
|
||
m.RecallSeenCount = inc
|
||
}
|
||
}
|
||
if v, ok := fields["recall_verified_count"]; ok {
|
||
switch inc := v.(type) {
|
||
case map[string]string:
|
||
if inc["$inc"] == "1" {
|
||
m.RecallVerifiedCount++
|
||
}
|
||
case map[string]interface{}:
|
||
if inc["$inc"] == "1" {
|
||
m.RecallVerifiedCount++
|
||
}
|
||
case int:
|
||
m.RecallVerifiedCount = inc
|
||
}
|
||
}
|
||
if v, ok := fields["recall_count"]; ok {
|
||
switch inc := v.(type) {
|
||
case map[string]string:
|
||
if inc["$inc"] == "1" {
|
||
m.RecallCount++
|
||
}
|
||
case map[string]interface{}:
|
||
if inc["$inc"] == "1" {
|
||
m.RecallCount++
|
||
}
|
||
case int:
|
||
m.RecallCount = inc
|
||
}
|
||
}
|
||
if v, ok := fields["useful_count"]; ok {
|
||
switch inc := v.(type) {
|
||
case map[string]string:
|
||
if inc["$inc"] == "1" {
|
||
m.UsefulCount++
|
||
}
|
||
case map[string]interface{}:
|
||
if inc["$inc"] == "1" {
|
||
m.UsefulCount++
|
||
}
|
||
case int:
|
||
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:
|
||
if inc["$inc"] == "1" {
|
||
m.NotUsefulCount++
|
||
}
|
||
case map[string]interface{}:
|
||
if inc["$inc"] == "1" {
|
||
m.NotUsefulCount++
|
||
}
|
||
case int:
|
||
m.NotUsefulCount = inc
|
||
}
|
||
}
|
||
// GA-P0-1 (t_718d8707):拆分后的新字段也要同步更新本地缓存
|
||
if v, ok := fields["human_not_useful_count"]; ok {
|
||
switch inc := v.(type) {
|
||
case map[string]string:
|
||
if inc["$inc"] == "1" {
|
||
m.HumanNotUsefulCount++
|
||
}
|
||
case map[string]interface{}:
|
||
if inc["$inc"] == "1" {
|
||
m.HumanNotUsefulCount++
|
||
}
|
||
case int:
|
||
m.HumanNotUsefulCount = inc
|
||
}
|
||
}
|
||
if v, ok := fields["dedup_downweight_count"]; ok {
|
||
switch inc := v.(type) {
|
||
case map[string]string:
|
||
if inc["$inc"] == "1" {
|
||
m.DedupDownweightCount++
|
||
}
|
||
case map[string]interface{}:
|
||
if inc["$inc"] == "1" {
|
||
m.DedupDownweightCount++
|
||
}
|
||
case int:
|
||
m.DedupDownweightCount = inc
|
||
}
|
||
}
|
||
if v, ok := fields["last_recalled_at"]; ok {
|
||
if s, ok := v.(string); ok {
|
||
if t, err := time.Parse(time.RFC3339, s); err == nil {
|
||
m.LastRecalledAt = t
|
||
}
|
||
}
|
||
}
|
||
}
|
||
|
||
// 2. 通过 IPC 持久化到 Rust LanceDB(仍在锁内,防止并发写同一行)
|
||
var fieldList []updateField
|
||
for k, v := range fields {
|
||
switch val := v.(type) {
|
||
case string:
|
||
fieldList = append(fieldList, updateField{k, "'" + strings.ReplaceAll(val, "'", "''") + "'"})
|
||
case map[string]string:
|
||
if val["$inc"] == "1" {
|
||
// 交给 Rust 侧做**真自增**:Rust 的 update() 识别 "col + N"
|
||
// 表达式时会先查该行当前值再计算(lancedb_ops.rs has_arith 分支)。
|
||
// ⚠️不要改回用 getIncCachedValue 在 Go 侧算绝对值——
|
||
// _local.memories 只在 Insert 路径填充、Search 不填,
|
||
// 缓存未命中时它返回 1,会把已有计数(如 5)**重置为 1**,
|
||
// 造成「越降权计数越小」的静默数据损坏。
|
||
fieldList = append(fieldList, updateField{k, k + " + 1"})
|
||
}
|
||
case map[string]interface{}:
|
||
if val["$inc"] == float64(1) || val["$inc"] == 1 {
|
||
fieldList = append(fieldList, updateField{k, k + " + 1"})
|
||
}
|
||
case float64:
|
||
fieldList = append(fieldList, updateField{k, fmt.Sprintf("%f", val)})
|
||
case bool:
|
||
if val {
|
||
fieldList = append(fieldList, updateField{k, "true"})
|
||
} else {
|
||
fieldList = append(fieldList, updateField{k, "false"})
|
||
}
|
||
}
|
||
}
|
||
if len(fieldList) > 0 {
|
||
fj, _ := json.Marshal(fieldList)
|
||
log.Printf("[ipc] Update: id=%s fields_count=%d", id, len(fieldList))
|
||
log.Printf("[ipc] Update fields_json: %s", string(fj))
|
||
// t_28aa278e 方案①:冲突自动重试 + 指数退避(复用 isRetryableLanceConflict 模式)。
|
||
// 旧实现吞错恒返回 nil ⇒ 调用方(usage-track)无感知,冲突增量被静默丢弃。
|
||
// 现改为:可重试 MVCC 冲突 → 有界退避重试;耗尽/非可重试 → 返回明确错误,
|
||
// 调用方据此决定「更新成功后才消费」。缓存已在发 IPC 前更新,重试仅重放 rpc,不回改缓存。
|
||
err := rc.retryUpdateRPC(table, id, string(fj))
|
||
_local.mu.Unlock()
|
||
return err
|
||
}
|
||
_local.mu.Unlock()
|
||
return nil
|
||
}
|
||
|
||
// UpdateRecallBatch 单事务批量更新召回元数据(2026-09-12 优化B)。
|
||
// Rust 侧把整批按 delta 分组,每组一次 update(`recall_count + delta` + id IN (...))提交
|
||
// (lance 不支持 CASE WHEN)→ 整批版本数 = 不同 delta 的个数,通常 1 个(旧实现:每行 1 个)。
|
||
// 注:Rust 侧固定操作 memories 表,table 参数暂未使用。
|
||
func (rc *RustLanceDBClient) UpdateRecallBatch(table string, items []RecallWriteItem, lastRecalledAt string) (int64, error) {
|
||
if len(items) == 0 {
|
||
return 0, nil
|
||
}
|
||
fj, err := json.Marshal(items)
|
||
if err != nil {
|
||
return 0, err
|
||
}
|
||
resp, err := rc.rpc(ipcReq{
|
||
Type: "lancedb_update_batch",
|
||
Table: table,
|
||
Items: string(fj),
|
||
TS: lastRecalledAt,
|
||
})
|
||
if err != nil {
|
||
return 0, err
|
||
}
|
||
var out struct {
|
||
Updated int64 `json:"updated"`
|
||
Items int `json:"items"`
|
||
}
|
||
if resp.ReportJSON != "" {
|
||
_ = json.Unmarshal([]byte(resp.ReportJSON), &out)
|
||
}
|
||
log.Printf("[ipc] UpdateRecallBatch: 合并 %d 条记忆 → 落盘 %d 行(单事务)", len(items), out.Updated)
|
||
return out.Updated, nil
|
||
}
|
||
|
||
func (rc *RustLanceDBClient) GetTopByQuality(agentID string, limit int) ([]models.MemoryRecord, error) {
|
||
_local.mu.RLock()
|
||
defer _local.mu.RUnlock()
|
||
var out []models.MemoryRecord
|
||
for _, m := range _local.memories {
|
||
if m.IsDeleted {
|
||
continue
|
||
}
|
||
out = append(out, *m)
|
||
if len(out) >= limit {
|
||
break
|
||
}
|
||
}
|
||
return out, nil
|
||
}
|
||
|
||
// ─── 有界冲突重试(2026-10-11 t_5b5a83de 方案 a)────────────────────────
|
||
//
|
||
// LanceDB MVCC 写冲突(同一表并发提交)时返回 "Commit conflict ... rerun the operation"。
|
||
// 旧实现 SoftDelete 遇冲突直接失败返回、无重试 ⇒ 那次 soft-delete 未落库(静默丢失),
|
||
// 靠下一轮轮转重扫兜底 → 遗忘/合并延迟 + 日志刷错误。方案(a):识别可重试错误 → 有界退避重试。
|
||
//
|
||
// 重试语义:
|
||
// - N = softDeleteMaxRetries = 3 次重试(总 rpc 尝试 = N+1 = 4 次);
|
||
// - 退避 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 = 5
|
||
softDeleteBackoffBase = 50 * time.Millisecond
|
||
softDeleteBackoffCap = 200 * time.Millisecond
|
||
)
|
||
|
||
// ─── Update 冲突有界重试(t_28aa278e 方案①,复用 isRetryableLanceConflict 模式)─────
|
||
//
|
||
// Update() 旧实现遇 LanceDB MVCC 写冲突(同一 memories 单巨片段表级并发提交)恒返回 nil、
|
||
// 静默丢弃计数器增量。现改为:可重试冲突 → 有界指数退避重试;非可重试/耗尽 → 返回明确
|
||
// 错误,调用方(usage_track)据此实现「更新成功后才消费」。
|
||
// 语义与 SoftDelete 一致:
|
||
// - N = updateMaxRetries = 3 次重试(总 rpc 尝试 = N+1 = 4 次);
|
||
// - 退避 50/100/200ms(指数、cap 200ms),总最坏 +350ms;
|
||
// - update 的 $inc 表达式(col + 1)由 Rust 侧对最新已提交版本重算 ⇒ 重试幂等不累加;
|
||
// - 仅「可重试冲突」重试;其余错误立即返回。
|
||
const (
|
||
updateMaxRetries = 3
|
||
updateBackoffBase = 50 * time.Millisecond
|
||
updateBackoffCap = 200 * time.Millisecond
|
||
)
|
||
|
||
// isRetryableLanceConflict 判断错误是否为 LanceDB「可重试的 MVCC 写冲突」。
|
||
// 仅当错误串含官方建议重试的关键词才返回 true(大小写不敏感):
|
||
// "commit conflict" / "cannot be automatically resolved" / "rerun the operation"。
|
||
// 其他错误(空 id、id required、schema 错、网络错等)一律 false,立即返回不重试。
|
||
func isRetryableLanceConflict(err error) bool {
|
||
if err == nil {
|
||
return false
|
||
}
|
||
msg := strings.ToLower(err.Error())
|
||
for _, kw := range []string{"commit conflict", "cannot be automatically resolved", "rerun the operation"} {
|
||
if strings.Contains(msg, kw) {
|
||
return true
|
||
}
|
||
}
|
||
return false
|
||
}
|
||
|
||
// retrySoftDeleteRPC 对 lancedb_update 调用做有界指数退避重试(仅可重试冲突)。
|
||
// 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):指数退避 + 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(sleepDur)
|
||
if backoff < softDeleteBackoffCap {
|
||
backoff *= 2
|
||
if backoff > softDeleteBackoffCap {
|
||
backoff = softDeleteBackoffCap
|
||
}
|
||
}
|
||
}
|
||
_, err := rc.rpc(ipcReq{Type: "lancedb_update", Table: "memories", ID: id, Fields: fields})
|
||
if err == nil {
|
||
if attempt > 0 {
|
||
log.Printf("[ipc] SoftDelete retried OK after %d id=%s reason=%s", attempt, id, reason)
|
||
}
|
||
return nil
|
||
}
|
||
if !isRetryableLanceConflict(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)
|
||
}
|
||
|
||
// retryUpdateRPC 对 lancedb_update 调用做有界指数退避重试(仅可重试 MVCC 冲突,t_28aa278e 方案①)。
|
||
// 与 retrySoftDeleteRPC 同语义,区别:table/fields 参数化(Update 可写任意表/任意字段)。
|
||
// 返回:首次成功或重试后成功 = nil;耗尽 = 含尝试次数的明确错误;非可重试错误 = 原样立即返回。
|
||
// 可观测性:每次重试/最终失败都有独立日志计数("Update retried OK" / "Update FAILED"),失败数可查、禁静默。
|
||
func (rc *RustLanceDBClient) retryUpdateRPC(table, id, fields string) error {
|
||
backoff := updateBackoffBase
|
||
var lastErr error
|
||
for attempt := 0; attempt <= updateMaxRetries; attempt++ {
|
||
if attempt > 0 {
|
||
// 第 attempt 次重试(1-based):attempt=1→50ms, 2→100ms, 3→200ms
|
||
log.Printf("[ipc] Update retry attempt %d/%d id=%s fields=%s error=%v",
|
||
attempt, updateMaxRetries, id, fields, lastErr)
|
||
time.Sleep(backoff)
|
||
if backoff < updateBackoffCap {
|
||
backoff *= 2
|
||
if backoff > updateBackoffCap {
|
||
backoff = updateBackoffCap
|
||
}
|
||
}
|
||
}
|
||
_, err := rc.rpc(ipcReq{Type: "lancedb_update", Table: table, ID: id, Fields: fields})
|
||
if err == nil {
|
||
if attempt > 0 {
|
||
log.Printf("[ipc] Update retried OK after %d id=%s fields=%s", attempt, id, fields)
|
||
} else {
|
||
log.Printf("[ipc] Update OK: id=%s fields=%s", id, fields)
|
||
}
|
||
return nil
|
||
}
|
||
if !isRetryableLanceConflict(err) {
|
||
log.Printf("[ipc] Update FAILED: id=%s fields=%s error=%v", id, fields, err)
|
||
return err // 非可重试错误:立即返回,不重试
|
||
}
|
||
lastErr = err
|
||
}
|
||
log.Printf("[ipc] Update FAILED (retry exhausted %d): id=%s fields=%s last_error=%v",
|
||
updateMaxRetries, id, fields, lastErr)
|
||
return fmt.Errorf("lancedb update (id=%s): retry exhausted after %d retries: %w",
|
||
id, updateMaxRetries, lastErr)
|
||
}
|
||
|
||
// ─── AppendHitEvent 冲突有界重试(t_7793a484 残差缺口:命中事件写路径)─────
|
||
//
|
||
// 修复前:AppendHitEvent 一次发 `lancedb_append_hit_event`,冲突(Rust 内部 20 次
|
||
// commit 重试耗尽)⇒ 终态丢 ⇒ outcome 事件(V 轴信号:hits+/hits−)永久丢失。
|
||
// 10-16 实测当日 42 条 `AppendHitEvent failed` 全为终态丢(均 "Commit conflict ...
|
||
// after 20 retries"),来源 = usage_track 下游使用判定(usage_track.go 旧 `_ =` 吞错)
|
||
// + 人工 feedback 端点。
|
||
//
|
||
// 重试安全性(幂等):Rust 侧 append_hit_event 是 append-only INSERT(hit_events 表
|
||
// tbl.add,行 id = memory_id+"-"+unix微秒,每次调用唯一)——MVCC commit conflict 时
|
||
// **整个提交原子不生效**(不产生版本,数据文件成孤儿),重放追加**不产生重复行**
|
||
// (与 t_28aa278e update col+1「对最新已提交版本重算」同语义,官方 "rerun the operation")。
|
||
// 规格与 Update 同(t_28aa278e):N=3 次重试 + 50/100/200ms 指数退避;耗尽/非可重试
|
||
// ⇒ 返回明确错误(可查、禁静默);无冲突路径恰好 1 次 rpc、0 退避(AC4 行为等价)。
|
||
const (
|
||
appendHitEventMaxRetries = 3
|
||
appendHitEventBackoffBase = 50 * time.Millisecond
|
||
appendHitEventBackoffCap = 200 * time.Millisecond
|
||
)
|
||
|
||
// retryAppendHitEventRPC 对 lancedb_append_hit_event 调用做有界指数退避重试(仅可重试
|
||
// MVCC 冲突,t_7793a484)。与 retryUpdateRPC 同语义,区别:append_hit_event 参数化
|
||
// (id/outcome/reason/source 整 req 重放,Rust 侧 ts 未传时按当前时间重算——同逻辑事件、
|
||
// 不同行 id,重试不重复)。
|
||
// 返回:首次成功或重试后成功 = nil;耗尽 = 含尝试次数的明确错误;非可重试错误 = 原样立即返回。
|
||
// 可观测性:终态失败打 "AppendHitEvent FAILED"(独立日志计数 + Prometheus 计数器
|
||
// zhiyi_hit_event_append_failed_total,AC3 双口径对齐)。
|
||
func (rc *RustLanceDBClient) retryAppendHitEventRPC(req ipcReq) error {
|
||
backoff := appendHitEventBackoffBase
|
||
var lastErr error
|
||
for attempt := 0; attempt <= appendHitEventMaxRetries; attempt++ {
|
||
if attempt > 0 {
|
||
// 第 attempt 次重试(1-based):attempt=1→50ms, 2→100ms, 3→200ms
|
||
log.Printf("[ipc] AppendHitEvent retry attempt %d/%d id=%s outcome=%s reason=%s error=%v",
|
||
attempt, appendHitEventMaxRetries, req.ID, req.Outcome, req.Reason, lastErr)
|
||
time.Sleep(backoff)
|
||
if backoff < appendHitEventBackoffCap {
|
||
backoff *= 2
|
||
if backoff > appendHitEventBackoffCap {
|
||
backoff = appendHitEventBackoffCap
|
||
}
|
||
}
|
||
}
|
||
_, err := rc.rpc(req)
|
||
if err == nil {
|
||
if attempt > 0 {
|
||
log.Printf("[ipc] AppendHitEvent retried OK after %d id=%s outcome=%s reason=%s",
|
||
attempt, req.ID, req.Outcome, req.Reason)
|
||
} else {
|
||
log.Printf("[ipc] AppendHitEvent OK id=%s outcome=%s reason=%s", req.ID, req.Outcome, req.Reason)
|
||
}
|
||
return nil
|
||
}
|
||
if !isRetryableLanceConflict(err) {
|
||
log.Printf("[ipc] AppendHitEvent FAILED: id=%s outcome=%s error=%v", req.ID, req.Outcome, err)
|
||
metrics.HitEventAppendFailedTotal.Inc()
|
||
return err // 非可重试错误:立即返回,不重试
|
||
}
|
||
lastErr = err
|
||
}
|
||
log.Printf("[ipc] AppendHitEvent FAILED (retry exhausted %d): id=%s outcome=%s last_error=%v",
|
||
appendHitEventMaxRetries, req.ID, req.Outcome, lastErr)
|
||
metrics.HitEventAppendFailedTotal.Inc()
|
||
return fmt.Errorf("lancedb append_hit_event (id=%s): retry exhausted after %d retries: %w",
|
||
req.ID, appendHitEventMaxRetries, lastErr)
|
||
}
|
||
|
||
func (rc *RustLanceDBClient) SoftDelete(id, reason string) error {
|
||
// 🔴 2026-10-06 防御:空 id 会被 Rust IPC 直接拒绝("id required"),
|
||
// 而调用方曾忽略错误照样计数(admin.go forgotten++),造成「遗忘计数虚高 + 每轮刷错误日志」。
|
||
// 根因:DB 里存在 id/content 全空的垃圾行 → 命中 <30 字碎片快速道 → SoftDelete("")。
|
||
// 在入口直接挡掉,返回可辨识错误(调用方据此跳过、不计数)。
|
||
if strings.TrimSpace(id) == "" {
|
||
return fmt.Errorf("soft delete: empty id rejected (reason=%s)", reason)
|
||
}
|
||
_local.mu.Lock()
|
||
if m, ok := _local.memories[id]; ok {
|
||
m.IsDeleted = true
|
||
}
|
||
_local.mu.Unlock()
|
||
|
||
// 持久化 tombstone 到 Rust LanceDB(值按 SQL 表达式传递:true=布尔字面量,'...'=字符串字面量)
|
||
// GA-P0-3 (t_f785d7f2):同批写入 delete_reason(归一化枚举),让 is_deleted=true 可分原因。
|
||
dr := NormalizeDeleteReason(reason)
|
||
fj, _ := json.Marshal([]updateField{
|
||
{Column: "is_deleted", Value: "true"},
|
||
{Column: "updated_at", Value: "'" + time.Now().Format(time.RFC3339) + "'"},
|
||
{Column: "delete_reason", Value: "'" + dr + "'"},
|
||
})
|
||
if err := rc.retrySoftDeleteRPC(id, reason, string(fj)); err != nil {
|
||
log.Printf("[ipc] SoftDelete persist FAILED: id=%s reason=%s error=%v", id, reason, err)
|
||
return fmt.Errorf("soft delete persist (id=%s): %w", id, err)
|
||
}
|
||
log.Printf("[ipc] SoftDelete persisted: id=%s reason=%s", id, reason)
|
||
return nil
|
||
}
|
||
|
||
// TODO: 需要 Rust 侧支持 lancedb_update 才能持久化 SoftDelete
|
||
// 当前仅标记内存,重启后失效。测试数据已直接通过 Python LanceDB API 清理。
|
||
|
||
// SoftDeleteBatch 批量软删(真实落库)。
|
||
//
|
||
// 2026-09-20 修复:此前**只改内存缓存 `_local.memories`,完全不写 LanceDB**,
|
||
// 缓存又只在 Insert 路径填充、Search 不填 → 批量软删实际静默失效
|
||
// (调用方拿到 updated=N 却无一行落库)。与 SoftDelete() 的区别仅在批量语义,
|
||
// 因此这里逐个委托给已验证的 SoftDelete()(它走 SoftDeleteWriteBuffer,
|
||
// 5 分钟窗口 / 256 条阈值攒批 → 单事务提交,避免每条一个 MVCC 版本)。
|
||
//
|
||
// 注:Rust 侧的 lancedb_update_batch 只支持 recall_count 累加
|
||
// (Item{id, delta}),不支持 is_deleted 批量置位,故不能下沉到那里。
|
||
func (rc *RustLanceDBClient) SoftDeleteBatch(table string, ids []string, updatedAt string) (int64, error) {
|
||
if table != "memories" {
|
||
return 0, fmt.Errorf("unsupported table: %s", table)
|
||
}
|
||
var updated int64
|
||
for _, id := range ids {
|
||
if err := rc.SoftDelete(id, "batch:"+updatedAt); err != nil {
|
||
log.Printf("[ipc] SoftDeleteBatch persist FAILED: id=%s error=%v", id, err)
|
||
continue
|
||
}
|
||
updated++
|
||
}
|
||
return updated, nil
|
||
}
|
||
|
||
// PurgeInvalid 清理 id 为空的垃圾行(P1-1 2026-10-08)。
|
||
// 走 Rust IPC lancedb_purge_invalid:按 id=” 条件一次性软删(is_deleted=true + updated_at=now)。
|
||
// 这些行 id/content/source 全空、无法按 id 软删,只能按条件清。返回受影响行数。
|
||
func (rc *RustLanceDBClient) PurgeInvalid() (int64, error) {
|
||
now := time.Now().Format(time.RFC3339)
|
||
resp, err := rc.rpc(ipcReq{Type: "lancedb_purge_invalid", TS: now})
|
||
if err != nil {
|
||
return 0, fmt.Errorf("purge_invalid rpc: %w", err)
|
||
}
|
||
var out struct {
|
||
Purged int64 `json:"purged"`
|
||
}
|
||
if resp.ReportJSON != "" {
|
||
_ = json.Unmarshal([]byte(resp.ReportJSON), &out)
|
||
}
|
||
log.Printf("[ipc] PurgeInvalid: 软删 %d 行 id 为空垃圾记录", out.Purged)
|
||
return out.Purged, nil
|
||
}
|
||
|
||
func (rc *RustLanceDBClient) GetVersionHistory(id string) ([]map[string]interface{}, error) {
|
||
return nil, nil
|
||
}
|
||
|
||
// defaultForgetCursorPath 遗忘候选旋转窗口游标持久化文件(2026-10-11 t_a4b8fa52 方案 c′)。
|
||
// 游标 = 上一轮扫描窗口的末 id(mem_<unixnano>);文件缺失/损坏/库回滚 → 空串(从头轮转,降级不崩)。
|
||
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(forgetCursorFilePath())
|
||
if err != nil {
|
||
if os.IsNotExist(err) {
|
||
return "" // 首次运行或文件被清,正常
|
||
}
|
||
log.Printf("[ipc] loadForgetCursor read failed: %v → 降级从头轮转", err)
|
||
return ""
|
||
}
|
||
s := strings.TrimSpace(string(data))
|
||
if s == "" {
|
||
return ""
|
||
}
|
||
if !strings.HasPrefix(s, "mem_") {
|
||
log.Printf("[ipc] loadForgetCursor corrupt (not mem_ prefix): %q → 降级从头轮转", s)
|
||
return ""
|
||
}
|
||
return s
|
||
}
|
||
|
||
// persistForgetCursor 原子写游标(tmp+rename,复用 conflict-seen 的原子写模式)。
|
||
func persistForgetCursor(cursor string) {
|
||
if cursor == "" {
|
||
return // wrapped → 下轮从头,无需落盘空游标(缺文件=从头)
|
||
}
|
||
cursorFile := forgetCursorFilePath()
|
||
dir := filepath.Dir(cursorFile)
|
||
if err := os.MkdirAll(dir, 0o755); err != nil {
|
||
log.Printf("[ipc] persistForgetCursor mkdir failed: %v", err)
|
||
return
|
||
}
|
||
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, cursorFile); err != nil {
|
||
log.Printf("[ipc] persistForgetCursor rename failed: %v", err)
|
||
}
|
||
}
|
||
|
||
// GetCandidatesForForgetting 取遗忘候选:走 Rust `lancedb_forget_window` 旋转窗口扫描。
|
||
//
|
||
// 2026-10-11 t_a4b8fa52 方案 c′:修复「固定 2000 窗口不轮转」。
|
||
// 旧实现 lancedb_scan 无 ORDER BY ⇒ 返回物理存储序前 2000 条(compact/merge 后非创建序)
|
||
// ⇒ 新记忆落物理序后部 ⇒ 永不进遗忘候选池。方案 c′:Rust 列投影取全部存活 id →
|
||
// 内排序 → 连续窗口 → 区间过滤还原全字段;游标=窗口末 id,本函数持久化到 forget-cursor.json。
|
||
// 每轮只评估一个 2000 窗口,全库覆盖上界 = ceil(live/2000)×6h(实测 ~72h 全覆盖,吞吐余量见卡 AC-7)。
|
||
// IPC 失败/空 → fallback 缓存遍历(保持可用,回归安全)。
|
||
func (rc *RustLanceDBClient) GetCandidatesForForgetting() ([]map[string]interface{}, error) {
|
||
// 读游标(缺失/损坏 → 空串 = 从头轮转)
|
||
cursor := loadForgetCursor()
|
||
resp, err := rc.rpc(ipcReq{Type: "lancedb_forget_window", QueryLimit: 2000, AfterID: cursor})
|
||
if err == nil && resp.ReportJSON != "" {
|
||
var win struct {
|
||
Records []struct {
|
||
ID string `json:"id"`
|
||
Content string `json:"content"`
|
||
Namespace string `json:"namespace"`
|
||
Category string `json:"category"`
|
||
Tier string `json:"tier"`
|
||
IsDeleted bool `json:"is_deleted"`
|
||
Importance float64 `json:"importance"`
|
||
RecallCount int64 `json:"recall_count"`
|
||
// GA-P0-2 (t_c6d41ac6):拆分字段读侧接线
|
||
RecallSeenCount int64 `json:"recall_seen_count"`
|
||
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"`
|
||
LiveTotal int `json:"live_total"`
|
||
}
|
||
uerr := json.Unmarshal([]byte(resp.ReportJSON), &win)
|
||
if uerr == nil && (len(win.Records) > 0 || win.LiveTotal > 0) {
|
||
// 持久化新游标(wrapped → 空串,下轮从头)
|
||
persistForgetCursor(win.NextCursor)
|
||
// 覆盖度与吞吐日志(AC-7 判据源:live_total 应随轮转被消耗,写入率 142/h < 窗口率 2000/6h≈333/h)
|
||
if win.LiveTotal > 0 {
|
||
log.Printf("[ipc] GetCandidatesForForgetting: window n=%d live_total=%d wrapped=%v next_cursor=%s(池内覆盖累计进度)",
|
||
len(win.Records), win.LiveTotal, win.Wrapped, truncID(win.NextCursor))
|
||
}
|
||
log.Printf("[ipc] GetCandidatesForForgetting: Rust forget_window → %d candidates", len(win.Records))
|
||
out := make([]map[string]interface{}, 0, len(win.Records))
|
||
for _, r := range win.Records {
|
||
if r.IsDeleted || r.Tier == "core" {
|
||
continue
|
||
}
|
||
out = append(out, map[string]interface{}{
|
||
"id": r.ID,
|
||
"content": r.Content,
|
||
"namespace": r.Namespace,
|
||
"category": r.Category,
|
||
"tier": r.Tier,
|
||
"importance": r.Importance,
|
||
"recall_count": int(r.RecallCount), // decay 侧 .(int) 断言 — int64 会恒 0
|
||
// GA-P0-2 (t_c6d41ac6):衰减/遗忘决策读 recall_verified_count
|
||
"recall_seen_count": int(r.RecallSeenCount),
|
||
"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
|
||
}
|
||
log.Printf("[ipc] GetCandidatesForForgetting: forget_window unmarshal empty (rpc=%v err=%v raw=%d) → fallback 缓存", err, uerr, len(win.Records))
|
||
}
|
||
_local.mu.RLock()
|
||
defer _local.mu.RUnlock()
|
||
var out []map[string]interface{}
|
||
for id, m := range _local.memories {
|
||
if !m.IsDeleted && m.Tier != "core" {
|
||
out = append(out, map[string]interface{}{
|
||
"id": id,
|
||
"content": m.Content,
|
||
"namespace": m.Namespace,
|
||
"category": m.Category,
|
||
"last_recalled_at": fmtTimeRFC3339(m.LastRecalledAt),
|
||
"created_at": fmtTimeRFC3339(m.CreatedAt),
|
||
"recall_count": m.RecallCount,
|
||
// GA-P0-2 (t_c6d41ac6):衰减/遗忘决策读 recall_verified_count
|
||
"recall_seen_count": m.RecallSeenCount,
|
||
"recall_verified_count": m.RecallVerifiedCount,
|
||
"tier": m.Tier,
|
||
"importance": m.Importance,
|
||
// 2026-10-16 (t_944344b5):fallback 缓存路径同样带 freshness(与主 IPC 路径对齐)
|
||
"freshness": m.Freshness,
|
||
})
|
||
}
|
||
}
|
||
return out, nil
|
||
}
|
||
|
||
// fmtTimeRFC3339 统一时间输出契约:RFC3339 字符串;零值输出 ""。
|
||
// 2026-09-06 P1 修复:此前直接放 time.Time → server.go decay 的 .(string) 断言
|
||
// 恒失败 → lastAccessed 永远"默认30天前" → 遗忘判定失真(叠加数据年龄未到)。
|
||
// 调用方一律按 string 解析(parseTimeStr / time.Parse RFC3339)。
|
||
func fmtTimeRFC3339(t time.Time) string {
|
||
if t.IsZero() {
|
||
return ""
|
||
}
|
||
return t.Format(time.RFC3339)
|
||
}
|
||
|
||
// truncID 截断长 id 用于日志(mem_<unixnano> 19 位+前缀,全打印太长)
|
||
func truncID(id string) string {
|
||
if len(id) > 16 {
|
||
return id[:8] + "…" + id[len(id)-6:]
|
||
}
|
||
return id
|
||
}
|
||
|
||
func mapStr(m map[string]interface{}, key string) string {
|
||
if v, ok := m[key]; ok {
|
||
if s, ok := v.(string); ok {
|
||
return s
|
||
}
|
||
}
|
||
return ""
|
||
}
|
||
func mapFloat(m map[string]interface{}, key string) float64 {
|
||
if v, ok := m[key]; ok {
|
||
if f, ok := v.(float64); ok {
|
||
return f
|
||
}
|
||
}
|
||
return 0
|
||
}
|
||
|
||
// mapFloatPtr 2026-10-08 (Gap#2):可空浮点。JSON null / 缺键 → nil(区别于显式 0.0)。
|
||
// 用于 confidence:nil 表示「该条未声明信任等级」(存量行),调用方 COALESCE 到 1.0。
|
||
func mapFloatPtr(m map[string]interface{}, key string) *float64 {
|
||
if v, ok := m[key]; ok {
|
||
if f, ok := v.(float64); ok {
|
||
return &f
|
||
}
|
||
}
|
||
return nil
|
||
}
|
||
func mapInt(m map[string]interface{}, key string) int {
|
||
if v, ok := m[key]; ok {
|
||
if f, ok := v.(float64); ok {
|
||
return int(f)
|
||
}
|
||
}
|
||
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 {
|
||
return b
|
||
}
|
||
}
|
||
return false
|
||
}
|
||
|
||
// seJSON 2026-10-13 (t_e9a4d18f P1):SourceEvents → JSON 数组字符串。
|
||
// nil/空 → "[]"(Rust 读路径 col_str 兜底)。显式转,避免 []string 直接进
|
||
// map 后 json.Marshal 的嵌套转义([]string → 已是 JSON 数组)。
|
||
func seJSON(events []string) string {
|
||
if len(events) == 0 {
|
||
return "[]"
|
||
}
|
||
b, _ := json.Marshal(events)
|
||
return string(b)
|
||
}
|
||
|
||
// parseSourceEvents 2026-10-13 (t_e9a4d18f P1):JSON 数组字符串 → []string。
|
||
// 解析失败回退 nil(存量 NULL/空 ⇒ 无证据链)。
|
||
func parseSourceEvents(raw string) []string {
|
||
if raw == "" || raw == "[]" || raw == "null" {
|
||
return nil
|
||
}
|
||
var out []string
|
||
if err := json.Unmarshal([]byte(raw), &out); err != nil {
|
||
return nil
|
||
}
|
||
return out
|
||
}
|
||
|
||
func (rc *RustLanceDBClient) GetSkillCandidates(minRecalls, limit int) ([]models.MemoryRecord, error) {
|
||
resp, err := rc.rpc(ipcReq{
|
||
Type: "lancedb_query",
|
||
MinRecall: minRecalls,
|
||
QueryLimit: limit,
|
||
})
|
||
if err != nil {
|
||
return nil, fmt.Errorf("lancedb_query: %w", err)
|
||
}
|
||
raw := resp.ReportJSON
|
||
if raw == "" {
|
||
return []models.MemoryRecord{}, nil
|
||
}
|
||
|
||
// 用 raw JSON 反序列化,避免 time.Time 空字符串报错
|
||
var rawRecords []map[string]interface{}
|
||
if err := json.Unmarshal([]byte(raw), &rawRecords); err != nil {
|
||
return nil, fmt.Errorf("parse lancedb_query result: %w", err)
|
||
}
|
||
if len(rawRecords) == 0 {
|
||
return []models.MemoryRecord{}, nil
|
||
}
|
||
|
||
records := make([]models.MemoryRecord, 0, len(rawRecords))
|
||
for _, r := range rawRecords {
|
||
m := models.MemoryRecord{
|
||
ID: mapStr(r, "id"),
|
||
AgentID: mapStr(r, "agent_id"),
|
||
Namespace: mapStr(r, "namespace"),
|
||
Content: mapStr(r, "content"),
|
||
Category: mapStr(r, "category"),
|
||
Tier: mapStr(r, "tier"),
|
||
Source: mapStr(r, "source"),
|
||
Freshness: mapStr(r, "freshness"),
|
||
DerivedFrom: mapStr(r, "derived_from"),
|
||
SourceEvents: parseSourceEvents(mapStr(r, "source_events")), // 2026-10-13 P1
|
||
Supersedes: parseSourceEvents(mapStr(r, "supersedes")), // 2026-10-13 P1
|
||
SupersededBy: parseSourceEvents(mapStr(r, "superseded_by")), // 2026-10-14 t_3e98b65a(补读回,缺则反向指针丢)
|
||
// 2026-10-14 (t_3ada332b P3) bi-temporal 有效期三列:写侧已补(见 ~185),
|
||
// 读回侧必须同步接线,否则 AC1 回环读回为空(本次事故同款:只写不读=no-op)。
|
||
ValidFrom: mapStr(r, "valid_from"),
|
||
ValidTo: mapStr(r, "valid_to"),
|
||
Provenance: mapStr(r, "provenance"),
|
||
VersionHistory: nil,
|
||
DependsOn: nil,
|
||
}
|
||
m.QualityScore = mapFloat(r, "quality_score")
|
||
m.Importance = mapFloat(r, "importance")
|
||
// 2026-10-08 (Gap#2):读侧接线(不补 ⇒ 加列也读不出来)
|
||
m.Confidence = mapFloatPtr(r, "confidence")
|
||
m.ConfidenceSource = mapStr(r, "confidence_source")
|
||
m.UsefulCount = mapInt(r, "useful_count")
|
||
m.NotUsefulCount = mapInt(r, "not_useful_count")
|
||
// 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")
|
||
m.RecallVerifiedCount = mapInt(r, "recall_verified_count")
|
||
m.Version = mapInt(r, "version")
|
||
m.VolatileFlag = mapBool(r, "volatile_flag")
|
||
m.IsDeleted = mapBool(r, "is_deleted")
|
||
// 时间字段:空字符串 → 零值 time.Time
|
||
if t := mapStr(r, "last_recalled_at"); t != "" {
|
||
if pt, err := time.Parse(time.RFC3339, t); err == nil {
|
||
m.LastRecalledAt = pt
|
||
}
|
||
}
|
||
if t := mapStr(r, "created_at"); t != "" {
|
||
if pt, err := time.Parse(time.RFC3339, t); err == nil {
|
||
m.CreatedAt = pt
|
||
}
|
||
}
|
||
if t := mapStr(r, "updated_at"); t != "" {
|
||
if pt, err := time.Parse(time.RFC3339, t); err == nil {
|
||
m.UpdatedAt = pt
|
||
}
|
||
}
|
||
records = append(records, m)
|
||
}
|
||
|
||
// 同步到本地缓存
|
||
_local.mu.Lock()
|
||
for _, m := range records {
|
||
cp := m
|
||
_local.memories[m.ID] = &cp
|
||
}
|
||
_local.mu.Unlock()
|
||
return records, nil
|
||
}
|
||
|
||
// Backup 备份存储。
|
||
//
|
||
// 2026-09-20:此前是 `return nil` 空实现 —— 任何人调用它都会拿到"成功",
|
||
// 而实际没有任何备份发生(与 IncrementNotUseful 同类:静默假成功)。
|
||
// 当前 Rust sidecar 未提供 backup 能力,也无调用方(全仓 grep .Backup( 为 0),
|
||
// 因此这里改为**显式报错**:一旦将来有人调用,会立刻发现而不是以为备份成功。
|
||
// 需要备份时正确做法是外部对 /var/lib/memoryweave 做文件级快照
|
||
// (见 scripts/dual-backup-push.sh)。
|
||
func (rc *RustLanceDBClient) Backup(path string) error {
|
||
return fmt.Errorf("RustLanceDBClient.Backup: not supported by Rust sidecar; "+
|
||
"snapshot the data dir instead (requested path=%s)", path)
|
||
}
|
||
func (rc *RustLanceDBClient) GetAuditLog(limit int) ([]map[string]interface{}, error) {
|
||
_local.mu.RLock()
|
||
defer _local.mu.RUnlock()
|
||
if limit > len(_local.auditLog) {
|
||
limit = len(_local.auditLog)
|
||
}
|
||
return _local.auditLog[:limit], nil
|
||
}
|
||
|
||
// IncrementUseful 递增 useful_count + recall_count(用户标记"有用")。
|
||
//
|
||
// 2026-09-20 修复(双重 bug):
|
||
//
|
||
// ① 此前只改内存缓存、不落库 → 与 IncrementNotUseful 同类的假成功;
|
||
// ② 此前改的是 RecallCount,**完全没碰 UsefulCount** → 用户点"有用"
|
||
// 时 V 值评分的分子永远不涨,同时把"有用反馈"错记成一次"召回",
|
||
// 污染召回统计(召回率/新鲜度衰减都基于 recall_count)。
|
||
// 对照 MemLanceClient.IncrementUseful:UsefulCount++ 且 RecallCount++。
|
||
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
|
||
}
|
||
return nil
|
||
}
|
||
|
||
// IncrementNotUseful [DEPRECATED] 递增 not_useful_count(GA-P0-1 t_718d8707)。
|
||
//
|
||
// 历史(2026-09-20 修复):此前是**空实现** `{}`,导致 feedback/not-useful 端点与
|
||
// 一切降权类清理(zhiyi-dedup.py 等)全是**假成功**——HTTP 200 返回正常,
|
||
// 但 not_useful_count 从未落库。实测:dedup --apply 报「已降权 34 条,
|
||
// 失败 0」,回读 32 条 dropped 记录的 not_useful_count 全为 0。
|
||
//
|
||
// 2026-10-12 (GA-P0-1 t_718d8707):not_useful_count 曾把两种语义混写——
|
||
// 人工点「没用」(feedback.go)与 dedup 自动降权(core.go dedup 路径)都写它。
|
||
// 现拆分为 human_not_useful_count / dedup_downweight_count 两个字段,
|
||
// 两个写入点各写各的(IncrementHumanNotUseful / IncrementDedupDownweight)。
|
||
// 本方法仅向后兼容,**新代码不再调用它**。
|
||
func (rc *RustLanceDBClient) IncrementNotUseful(id string) error {
|
||
if err := rc.Update("memories", id, map[string]any{
|
||
"not_useful_count": map[string]string{"$inc": "1"},
|
||
}); err != nil {
|
||
log.Printf("[ipc] IncrementNotUseful failed id=%s: %v", id, err)
|
||
return err
|
||
}
|
||
return nil
|
||
}
|
||
|
||
// IncrementHumanNotUseful 递增 human_not_useful_count(用户人工点「没用」,GA-P0-1)。
|
||
func (rc *RustLanceDBClient) IncrementHumanNotUseful(id string) error {
|
||
if err := rc.Update("memories", id, map[string]any{
|
||
"human_not_useful_count": map[string]string{"$inc": "1"},
|
||
}); err != nil {
|
||
log.Printf("[ipc] IncrementHumanNotUseful failed id=%s: %v", id, err)
|
||
return err
|
||
}
|
||
return nil
|
||
}
|
||
|
||
// IncrementDedupDownweight 递增 dedup_downweight_count(dedup/合并流程自动降权,GA-P0-1)。
|
||
func (rc *RustLanceDBClient) IncrementDedupDownweight(id string) error {
|
||
if err := rc.Update("memories", id, map[string]any{
|
||
"dedup_downweight_count": map[string]string{"$inc": "1"},
|
||
}); err != nil {
|
||
log.Printf("[ipc] IncrementDedupDownweight failed id=%s: %v", id, err)
|
||
return err
|
||
}
|
||
return nil
|
||
}
|
||
|
||
// AppendHitEvent 追加一条真实 outcome 事件(GA-P0-4 t_bb10e8bc,走 Rust IPC)。
|
||
func (rc *RustLanceDBClient) AppendHitEvent(memoryID, outcome, reason string) error {
|
||
outcome = NormalizeHitOutcome(outcome)
|
||
if !ValidHitOutcomes[outcome] {
|
||
return fmt.Errorf("AppendHitEvent: invalid outcome %q (must be pos/neg); dedup-demote/recall-appearance are NOT outcomes", outcome)
|
||
}
|
||
reason = NormalizeHitReason(reason)
|
||
// t_7793a484:冲突有界退避重试(与 Update 同规格:3 次 + 50/100/200ms)。
|
||
// 修复前单次即终态丢(Rust 内部 20 次 commit 重试耗尽后不重发);无冲突路径不变(1 次 rpc、0 退避)。
|
||
req := ipcReq{
|
||
Type: "lancedb_append_hit_event",
|
||
ID: memoryID,
|
||
Outcome: outcome,
|
||
Reason: reason,
|
||
Source: "append_hit_event",
|
||
}
|
||
return rc.retryAppendHitEventRPC(req)
|
||
}
|
||
|
||
// CountHitEvents 统计某 memory 在某窗口起点的 outcome 事件数(周窗口聚合,P2 自适应阈值用)。
|
||
func (rc *RustLanceDBClient) CountHitEvents(memoryID, outcome string, since time.Time) (int, error) {
|
||
outcome = NormalizeHitOutcome(outcome)
|
||
if !ValidHitOutcomes[outcome] {
|
||
return 0, fmt.Errorf("CountHitEvents: invalid outcome %q", outcome)
|
||
}
|
||
resp, err := rc.rpc(ipcReq{
|
||
Type: "lancedb_count_hit_events",
|
||
ID: memoryID,
|
||
Outcome: outcome,
|
||
Since: since.Format(time.RFC3339),
|
||
})
|
||
if err != nil {
|
||
return 0, err
|
||
}
|
||
var out struct {
|
||
Count int `json:"count"`
|
||
}
|
||
if err := json.Unmarshal([]byte(resp.Result), &out); err != nil {
|
||
return 0, err
|
||
}
|
||
return out.Count, nil
|
||
}
|
||
|
||
// GetHitEvents 读回某 memory 的事件明细(read-back 取证,非只看函数返回)。
|
||
func (rc *RustLanceDBClient) GetHitEvents(memoryID string, limit int) ([]models.HitEvent, error) {
|
||
if limit <= 0 {
|
||
limit = 100
|
||
}
|
||
resp, err := rc.rpc(ipcReq{
|
||
Type: "lancedb_get_hit_events",
|
||
ID: memoryID,
|
||
QueryLimit: limit,
|
||
})
|
||
if err != nil {
|
||
return nil, err
|
||
}
|
||
var events []models.HitEvent
|
||
if err := json.Unmarshal([]byte(resp.Result), &events); err != nil {
|
||
return nil, err
|
||
}
|
||
return events, nil
|
||
}
|
||
|
||
// UpdateMemoryContent 修正记忆内容(重新编码向量)并**持久化**。
|
||
//
|
||
// 2026-09-20 修复:此前只改内存缓存 `_local.memories`,不写 LanceDB,
|
||
// 且缓存只在 Insert 路径填充 → 修正后的内容重启即丢、且大多数情况下
|
||
// 根本没生效(缓存未命中直接 return nil)。同时补齐 MemLanceClient
|
||
// 版本所具有的语义:Version 递增、VersionHistory 追加、Source 更新。
|
||
func (rc *RustLanceDBClient) UpdateMemoryContent(id, newContent, source string) error {
|
||
_local.mu.Lock()
|
||
var newVec []float32
|
||
if m, ok := _local.memories[id]; ok {
|
||
m.Version++
|
||
m.VersionHistory = append(m.VersionHistory, models.VersionRecord{
|
||
Version: m.Version,
|
||
Content: newContent,
|
||
Source: source,
|
||
Reason: "corrected",
|
||
Trigger: "update_memory_content",
|
||
UpdatedBy: source,
|
||
Timestamp: time.Now(),
|
||
})
|
||
m.Content = newContent
|
||
m.Source = source
|
||
if rc.embedder != nil {
|
||
if vec, err := rc.embedder.EncodeSingle(newContent); err == nil {
|
||
m.Vector = vec
|
||
newVec = vec
|
||
}
|
||
}
|
||
}
|
||
_local.mu.Unlock()
|
||
|
||
// 持久化内容(及向量,若已重编码)
|
||
vecJSON, _ := json.Marshal(newVec)
|
||
fields := map[string]any{
|
||
"content": newContent,
|
||
"source": source,
|
||
}
|
||
if len(newVec) > 0 {
|
||
fields["vector"] = string(vecJSON)
|
||
}
|
||
if err := rc.Update("memories", id, fields); err != nil {
|
||
log.Printf("[ipc] UpdateMemoryContent persist FAILED: id=%s error=%v", id, err)
|
||
return fmt.Errorf("update memory content (id=%s): %w", id, err)
|
||
}
|
||
return nil
|
||
}
|