Files
memoryweave/go/internal/storage/recall_write_buffer.go
T
小唯 7f7171ac14 feat(recall): 召回契约字段 + trace 回溯 + 生命周期/实体质量判据(工作树收口)
这批是 10-26~27 已在生产二进制(zhiyid-protectrails-20261027)里运行、
但一直留在工作树未提交的改动。收口原因:三件改造要开分支,工作树脏 =
分支基准与回滚点都不存在。

主要内容:
- api/routes/contract.go + trace.go:召回响应契约字段(trace_id/status/scope/
  continuation/channel)与 /api/v1/trace 回溯端点
- governance/entity_quality.go:实体质量闸
- storage/trace.go + recall.go/recall_write_buffer.go:召回写入缓冲与轨迹
- 测试:contract/recall_contract_fields/recall_lifecycle/stale_lifecycle/
  entity_quality/trace

同时修一个 flaky:recall_lifecycle_test 原本硬编码「今天 11:00 已过」,
凌晨跑就会把「已失效」fixture 当成仍有效。改成相对时间(过期=now-1h),
生命周期判据与运行时刻无关。修完 go test ./internal/api/routes ./internal/storage 全绿。
2026-10-28 02:09:19 +08:00

384 lines
14 KiB
Go
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
package storage
import (
"log"
"os"
"sort"
"strconv"
"strings"
"sync"
"sync/atomic"
"time"
)
// ─── 召回元数据「累积延迟更新」缓冲(2026-09-12 优化B)─────────────────────────
//
// 问题(根因):recall 读路径原先对**每条结果**同步调用 lancedb.Update
// (recall_count / last_recalled_at / freshness)。LanceDB 是 MVCC 存储——
// **每次 update 提交产生一个版本**。实测生产:15 版本/分钟、_versions 目录
// 膨胀到 17.72G(真实数据仅 22M,75,327 个 .manifest,放大 800 倍)。
//
// 方案:
//
// Record() 读路径只把增量写进内存缓冲;**同一记忆在一个窗口内多次命中合并成 1 条 delta**
// Flush() 后台按窗口(默认 300s)+ 阈值(默认 256 条不同记忆)批量提交一次;
// Rust 侧 lancedb_update_batch 把整批**按 delta 分组**,每组一次
// update(`recall_count + delta` + id IN (...)) 提交(lance 不支持 CASE WHEN)
// → 每批版本数 = 不同 delta 的个数(delta 绝大多数为 1,故通常 1 个版本;
// 旧实现:每行 1 个版本)
//
// 语义取舍(明确记录,便于日后审计):
// - last_recalled_at / freshness 最多延迟一个窗口(分钟级)。遗忘/衰减判定以「天」为单位,无影响。
// - 进程崩溃会丢最后一个窗口的增量(召回统计,不是记忆数据本身),可接受。
// - recall_count 由 Rust 侧「读库现值 + delta」计算(不是读 Go 缓存),顺带修掉旧实现里
// 「本地缓存 +1 后再 +1」导致的计数漂移。
type RecallWriteItem struct {
ID string `json:"id"`
Delta int `json:"delta"`
}
// BatchRecallUpdater 单事务批量更新接口。
// 由 Rust IPC 后端(RustLanceDBClient)实现;其他后端不支持时自动退化为逐条 Update。
type BatchRecallUpdater interface {
UpdateRecallBatch(table string, items []RecallWriteItem, lastRecalledAt string) (int64, error)
}
const (
defaultRecallFlushInterval = 300 * time.Second
// 2026-10-26 (t_0a54c12b):256 → 2048。
// 256 在搜索突发期每 1~2 秒就触发一次 flush(每次 flush = 2~4 个 delta 组 = 2~4 个
// LanceDB 版本),实测 20~200 版本/分钟。待写条目是「不同记忆 ID」,2048 只占几百 KB 内存,
// 把窗口内重复命中合并得更彻底、flush 次数降一个量级。
defaultRecallFlushMaxItems = 2048
// requeue 硬上限:IPC 长时间不可用时 pending 不能无限涨(召回计数是观测值,丢了可接受)。
recallRequeueHardCap = 16384
// 优雅停止窗口(t_fa797edd):Stop 内的「等后台协程退出 + 最终落盘」都必须有界。
// 否则 Rust/LanceDB 批量更新在活 IPC 流量下阻塞时,Stop 永远不返回 → 信号协程
// 到不了 srv.Shutdown → 进程跑满 systemd 90s TimeoutStopSec 被 SIGKILL
// (丢写风险 + 每次重启都变强杀 + 40s IPC 中断)。
defaultRecallStopLoopWait = 5 * time.Second // 等后台 flush 协程退出的上限
defaultRecallStopFlushWait = 8 * time.Second // 最终落盘的上限(召回统计,丢失可接受)
)
type pendingRecall struct {
delta int
lastAt time.Time
}
// RecallWriteBuffer 累积召回元数据写,延迟批量落盘。
type RecallWriteBuffer struct {
mu sync.Mutex
pending map[string]*pendingRecall
ldb LanceDB
batch BatchRecallUpdater
interval time.Duration
maxItems int
stopCh chan struct{}
doneCh chan struct{}
stopped bool
startOnce sync.Once
flushCount int64
flushItems int64
flushRows int64
flushErrors int64
fallbackRows int64
// requeuedItems: IPC 通道不可用时整批退回缓冲的条目数(t_0a54c12b 观测项)
requeuedItems int64
}
// RecallWriteBufferInstance 进程级单例(与 SearchCacheInstance / CoOccurTrackerInstance 同模式)
var RecallWriteBufferInstance *RecallWriteBuffer
// NewRecallWriteBuffer 创建缓冲并启动后台 flush 协程;interval<=0 表示只按阈值触发。
func NewRecallWriteBuffer(ldb LanceDB, interval time.Duration, maxItems int) *RecallWriteBuffer {
if maxItems <= 0 {
maxItems = defaultRecallFlushMaxItems
}
b := &RecallWriteBuffer{
pending: make(map[string]*pendingRecall),
ldb: ldb,
interval: interval,
maxItems: maxItems,
stopCh: make(chan struct{}),
doneCh: make(chan struct{}),
}
// Rust IPC 后端支持单事务批量更新(CASE WHEN 一次提交)
if bu, ok := ldb.(BatchRecallUpdater); ok {
b.batch = bu
}
go b.loop()
return b
}
// InitRecallWriteBuffer 初始化进程级单例(server 启动时调用一次)。
// 窗口可用环境变量 RECALL_WRITE_FLUSH_SECONDS 覆盖(运维/验证用)。
func InitRecallWriteBuffer(ldb LanceDB) *RecallWriteBuffer {
if RecallWriteBufferInstance != nil {
return RecallWriteBufferInstance
}
interval := defaultRecallFlushInterval
if v := os.Getenv("RECALL_WRITE_FLUSH_SECONDS"); v != "" {
if n, err := strconv.Atoi(v); err == nil && n >= 0 {
interval = time.Duration(n) * time.Second
}
}
b := NewRecallWriteBuffer(ldb, interval, defaultRecallFlushMaxItems)
RecallWriteBufferInstance = b
log.Printf("[recall-buffer] 已启用累积延迟更新: flush 窗口=%s, 阈值=%d 条, 单事务批量=%v",
interval, b.maxItems, b.batch != nil)
return b
}
// StopRecallWriteBuffer 停止单例并落盘最后一个窗口(进程优雅退出时调用)。
func StopRecallWriteBuffer() {
if b := RecallWriteBufferInstance; b != nil {
b.Stop()
}
}
func (b *RecallWriteBuffer) loop() {
defer close(b.doneCh)
if b.interval <= 0 {
<-b.stopCh
return
}
t := time.NewTicker(b.interval)
defer t.Stop()
for {
select {
case <-b.stopCh:
return
case <-t.C:
b.Flush()
}
}
}
// Record 累积一次召回命中的记忆 ID(同窗口内同 ID 合并 delta)。
// 返回当前待写条数;达到阈值时异步触发一次 flush(不阻塞读路径)。
func (b *RecallWriteBuffer) Record(ids []string) int {
now := time.Now()
b.mu.Lock()
for _, id := range ids {
if id == "" {
continue
}
p, ok := b.pending[id]
if !ok {
p = &pendingRecall{}
b.pending[id] = p
}
p.delta++
p.lastAt = now
}
n := len(b.pending)
b.mu.Unlock()
if n >= b.maxItems {
go b.Flush()
}
return n
}
// Flush 取出当前窗口的全部增量并批量提交(每批最多 1 个 LanceDB 版本)。
func (b *RecallWriteBuffer) Flush() (int, error) {
b.mu.Lock()
if len(b.pending) == 0 {
b.mu.Unlock()
return 0, nil
}
batch := make([]RecallWriteItem, 0, len(b.pending))
var lastAt time.Time
for id, p := range b.pending {
if p.delta <= 0 {
continue
}
batch = append(batch, RecallWriteItem{ID: id, Delta: p.delta})
if p.lastAt.After(lastAt) {
lastAt = p.lastAt
}
}
b.pending = make(map[string]*pendingRecall)
b.mu.Unlock()
if len(batch) == 0 {
return 0, nil
}
sort.Slice(batch, func(i, j int) bool { return batch[i].ID < batch[j].ID })
ts := lastAt.Format(time.RFC3339)
var rows int64
var err error
usedFallback := false
if b.batch != nil {
rows, err = b.batch.UpdateRecallBatch("memories", batch, ts)
if err != nil {
// 2026-10-26 (t_0a54c12b):**通道不可用**与**语句被拒**必须分开处置。
// 通道不可用(sidecar 重启/拒绝连接/超时)时逐条降级毫无收益:
// ① IPC 不可用 ⇒ 每条都失败,2026-10-26 21:16 实测 **9142 次失败拨号**(日志风暴);
// ② sidecar 恢复瞬间逐条成功 ⇒ **每条 = 1 个 LanceDB 版本**,正是 _versions 冲到 8.5k 的机制。
// 正确做法:整批退回 pending,下个窗口连同新命中一起批量重试(召回计数延迟可接受)。
if isRecallTransportErr(err) {
atomic.AddInt64(&b.flushErrors, 1)
atomic.AddInt64(&b.requeuedItems, int64(len(batch)))
n := b.requeue(batch, lastAt)
log.Printf("[recall-buffer] IPC 通道不可用(%v) → 整批 %d 条退回缓冲(pending=%d),下个窗口重试;不逐条降级(避免拨号风暴 + N 个版本)", err, len(batch), n)
return 0, err
}
log.Printf("[recall-buffer] 单事务批量提交失败(%v) → 退化逐条 Update(数据不丢,版本数不优化)", err)
atomic.AddInt64(&b.flushErrors, 1)
usedFallback = true
rows = b.fallbackRowUpdates(batch, ts)
}
} else {
usedFallback = true
rows = b.fallbackRowUpdates(batch, ts)
}
// 落盘成功后同步进程内缓存(缓存只是热数据,权威值在 LanceDB)
if rows > 0 {
_local.mu.Lock()
for _, it := range batch {
if m, ok := _local.memories[it.ID]; ok {
// GA-P0-2 (t_c6d41ac6):召回命中 → 进程内缓存同步到 recall_seen_count
m.RecallSeenCount += it.Delta
if !lastAt.IsZero() {
m.LastRecalledAt = lastAt
}
}
}
_local.mu.Unlock()
}
atomic.AddInt64(&b.flushCount, 1)
atomic.AddInt64(&b.flushItems, int64(len(batch)))
atomic.AddInt64(&b.flushRows, rows)
log.Printf("[recall-buffer] flush: 合并 %d 条记忆 → 落盘 %d 行, 单事务=%v, fallback=%v",
len(batch), rows, !usedFallback, usedFallback)
return int(rows), nil
}
// fallbackRowUpdates 逐条 Update(仅用于「批量语句被拒」或后端不支持批量的事务语义兜底)。
// 每条 = 1 个 LanceDB 版本,故**不得**在 IPC 通道不可用时走这里(见 Flush 里的通道判定)。
func (b *RecallWriteBuffer) fallbackRowUpdates(batch []RecallWriteItem, ts string) int64 {
var rows int64
for _, it := range batch {
// t_268b0353(2026-10-11 治根):召回只更新 recall_count / last_recalled_at,
// 不再写 freshness="verified"。freshness=verified 的语义是「经过校验/用户
// 反馈」;"被召回" ≠ "被验证"。此前每次召回都盖 verified → 越常被召回的
// 旧快照越"可信",时效判断全被污染(过期快照被当现状的机制根因之一)。
// GA-P0-2 (t_c6d41ac6):召回命中写 recall_seen_count;不再写 recall_count(冻结)。
if uerr := b.ldb.Update("memories", it.ID, map[string]any{
"recall_seen_count": map[string]string{"$inc": "1"},
"last_recalled_at": ts,
}); uerr != nil {
log.Printf("[recall-buffer] 逐条 Update 失败 id=%s: %v", it.ID, uerr)
continue
}
rows++
}
atomic.AddInt64(&b.fallbackRows, rows)
return rows
}
// requeue 把一批未落盘的增量退回 pending(IPC 通道不可用时用):delta 累加、时间取更晚者。
// 硬上限 recallRequeueHardCap:IPC 长期不可用时不能无限涨(召回计数是观测值,丢了可接受)。
func (b *RecallWriteBuffer) requeue(batch []RecallWriteItem, lastAt time.Time) int {
b.mu.Lock()
defer b.mu.Unlock()
for _, it := range batch {
if len(b.pending) >= recallRequeueHardCap {
if _, ok := b.pending[it.ID]; !ok {
continue // 满了且是新 ID:丢弃(观测值,可接受)
}
}
p, ok := b.pending[it.ID]
if !ok {
p = &pendingRecall{}
b.pending[it.ID] = p
}
p.delta += it.Delta
if lastAt.After(p.lastAt) {
p.lastAt = lastAt
}
}
return len(b.pending)
}
// isRecallTransportErr 判断是否为「IPC 通道不可用」类错误(可重试、且绝不能逐条降级)。
// 判据是**通道层**错误关键字,不是业务/谓词错误 —— 后者逐条降级有意义(换语句能成),
// 前者逐条只会制造拨号风暴 + 恢复后 N 个版本。
func isRecallTransportErr(err error) bool {
if err == nil {
return false
}
msg := strings.ToLower(err.Error())
for _, k := range []string{
"ipc dial", "connection refused", "connection reset", "broken pipe",
"i/o timeout", "context deadline exceeded", "unexpected eof",
"no such file or directory", // unix socket 文件不存在(sidecar 正在重启)
} {
if strings.Contains(msg, k) {
return true
}
}
return false
}
// Stop 停止后台 flush 协程,并把最后一个窗口落盘(进程优雅退出时调用)。
// 全程有界(t_fa797edd):等后台协程 ≤ defaultRecallStopLoopWait,最终落盘
// ≤ defaultRecallStopFlushWait。Rust/LanceDB 批量更新在活 IPC 流量下可能阻塞
// 数十秒;召回统计丢了可接受(源码注释「进程崩溃会丢最后一个窗口」),
// 因此超时即放弃落盘、放行退出,保证进程总在有限秒内到 srv.Shutdown。
func (b *RecallWriteBuffer) Stop() {
b.mu.Lock()
if b.stopped {
b.mu.Unlock()
return
}
b.stopped = true
b.mu.Unlock()
close(b.stopCh)
select {
case <-b.doneCh:
case <-time.After(defaultRecallStopLoopWait):
log.Printf("[recall-buffer] 后台 flush 协程停止超时(%s),直接进入最终落盘", defaultRecallStopLoopWait)
}
// 最终落盘有界:放到 goroutine 跑,到点不再等。若后台 ticker/阈值 flush
// 正持锁阻塞在 Rust IPC 上,本 goroutine 的 Flush 会先等 b.mu —— 同样被
// defaultRecallStopFlushWait 兜住,超时即放行进程退出。
flushDone := make(chan struct{})
go func() {
b.Flush()
close(flushDone)
}()
select {
case <-flushDone:
case <-time.After(defaultRecallStopFlushWait):
log.Printf("[recall-buffer] 最终落盘超时(%s),放弃剩余窗口(仅丢召回统计,进程照常退出)", defaultRecallStopFlushWait)
}
}
// Stats 观测用(flush 频率 / 合并率 / 版本写入行数)。
func (b *RecallWriteBuffer) Stats() map[string]interface{} {
b.mu.Lock()
pendingN := len(b.pending)
b.mu.Unlock()
return map[string]interface{}{
"pending": pendingN,
"flush_count": atomic.LoadInt64(&b.flushCount),
"flush_items": atomic.LoadInt64(&b.flushItems),
"flush_rows": atomic.LoadInt64(&b.flushRows),
"flush_errors": atomic.LoadInt64(&b.flushErrors),
"fallback_rows": atomic.LoadInt64(&b.fallbackRows),
"requeued_items": atomic.LoadInt64(&b.requeuedItems),
"window": b.interval.String(),
"max_items": b.maxItems,
"single_tx": b.batch != nil,
}
}