fix(forgetting): P2 候选源升级 — Rust scan 全表替代纯缓存遍历
GetCandidatesForForgetting 原实现只遍历进程内 _local.memories 缓存
(commit/recall/search 才触碰), 重启后缓存空 → decay scanned=3 扫不全,
9-25 到期记忆若不在缓存则永远无法被遗忘(闭环断)。
安全版 scan_for_forgetting (防 febc2c9 风暴复发):
- 强制 limit (IPC 钳制硬上限 5000, decay 侧 2000)
- 不读 vector 列 (1024维×3000条≈12MB+, IPC JSON 会卡)
- 真读 last_recalled_at 列 (scan_all 旧实现 String::new() 恒空 → 遗忘判定失真)
- 消费方截断护栏已就位 (merge 桶500 / conflict 500 / sanity 1000)
- IPC 失败/空 → fallback 缓存遍历 (保持可用)
验证: [decay] scanned=3 → 2000 (重启即扫全表), CPU 0%, 无 panic
This commit is contained in:
@@ -488,6 +488,47 @@ func (rc *RustLanceDBClient) SoftDelete(id, reason string) error {
|
||||
|
||||
func (rc *RustLanceDBClient) GetVersionHistory(id string) ([]map[string]interface{}, error) { return nil, nil }
|
||||
func (rc *RustLanceDBClient) GetCandidatesForForgetting() ([]map[string]interface{}, error) {
|
||||
// P2 2026-09-06: 走 Rust 全表扫描(安全版: limit 2000 + 跳 vector + 真读 last_recalled_at)。
|
||||
// 替代纯缓存遍历 — 缓存只含近期 commit/recall/search 触碰的记忆, 到期旧记忆扫不到 → 9-25 遗忘闭环断。
|
||||
// IPC 失败/空 → fallback 缓存遍历(保持可用)。
|
||||
resp, err := rc.rpc(ipcReq{Type: "lancedb_scan", QueryLimit: 2000})
|
||||
if err == nil && resp.ReportJSON != "" {
|
||||
var raw []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"`
|
||||
LastRecalledAt string `json:"last_recalled_at"`
|
||||
CreatedAt string `json:"created_at"`
|
||||
}
|
||||
uerr := json.Unmarshal([]byte(resp.ReportJSON), &raw)
|
||||
if uerr == nil && len(raw) > 0 {
|
||||
log.Printf("[ipc] GetCandidatesForForgetting: Rust scan → %d candidates", len(raw))
|
||||
out := make([]map[string]interface{}, 0, len(raw))
|
||||
for _, r := range raw {
|
||||
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
|
||||
"last_recalled_at": r.LastRecalledAt,
|
||||
"created_at": r.CreatedAt,
|
||||
})
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
log.Printf("[ipc] GetCandidatesForForgetting: scan unmarshal empty (rpc=%v err=%v raw=%d) → fallback 缓存", err, uerr, len(raw))
|
||||
}
|
||||
_local.mu.RLock()
|
||||
defer _local.mu.RUnlock()
|
||||
var out []map[string]interface{}
|
||||
|
||||
@@ -351,6 +351,53 @@ impl LanceDBOps {
|
||||
}
|
||||
|
||||
/// 全量扫描 memories 表(用于深整),上限 10000 条
|
||||
// P2 2026-09-06 安全版遗忘候选全表扫描(替代 febc2c9 风暴版):
|
||||
// 1. 强制 limit(调用方传, main.rs 钳制硬上限 5000)
|
||||
// 2. 不读 vector 列(1024 维 × 3000 条 ≈ 12MB+,IPC JSON 会卡)
|
||||
// 3. 真读 last_recalled_at 列(scan_all 旧实现 String::new() 恒空 → 遗忘判定失真)
|
||||
pub fn scan_for_forgetting(&self, limit: usize) -> Result<Vec<MemoryRecord>, Box<dyn std::error::Error>> {
|
||||
let db = rt().block_on(lancedb::connect(self.data_dir.to_str().unwrap()).execute())?;
|
||||
let tbl = rt().block_on(db.open_table("memories").execute())?;
|
||||
let mut results = Box::pin(rt().block_on(
|
||||
tbl.query()
|
||||
.only_if("is_deleted = false")
|
||||
.limit(limit)
|
||||
.execute(),
|
||||
)?);
|
||||
let mut records = Vec::new();
|
||||
while let Some(Ok(batch)) = rt().block_on(results.next()) {
|
||||
for i in 0..batch.num_rows() {
|
||||
records.push(MemoryRecord {
|
||||
id: col_str(&batch, i, "id"),
|
||||
agent_id: col_str(&batch, i, "agent_id"),
|
||||
namespace: col_str(&batch, i, "namespace"),
|
||||
content: col_str(&batch, i, "content"),
|
||||
category: col_str(&batch, i, "category"),
|
||||
vector: Vec::new(), // ⚠️ 不读 vector — IPC 轻量, 遗忘候选不需要向量
|
||||
tier: col_str(&batch, i, "tier"),
|
||||
importance: col_f64(&batch, i, "importance"),
|
||||
quality_score: col_f64(&batch, i, "quality_score"),
|
||||
recall_count: col_i64(&batch, i, "recall_count"),
|
||||
useful_count: col_i64(&batch, i, "useful_count"),
|
||||
not_useful_count: col_i64(&batch, i, "not_useful_count"),
|
||||
freshness: col_str(&batch, i, "freshness"),
|
||||
version: col_i64(&batch, i, "version"),
|
||||
version_history: String::new(),
|
||||
source: col_str(&batch, i, "source"),
|
||||
volatile_flag: col_bool(&batch, i, "volatile_flag"),
|
||||
is_deleted: col_bool(&batch, i, "is_deleted"),
|
||||
depends_on: String::new(),
|
||||
derived_from: String::new(),
|
||||
last_recalled_at: col_str(&batch, i, "last_recalled_at"), // ✅ 真读(勿学 scan_all 的 String::new())
|
||||
created_at: col_str(&batch, i, "created_at"),
|
||||
updated_at: col_str(&batch, i, "updated_at"),
|
||||
});
|
||||
}
|
||||
}
|
||||
eprintln!("[lancedb] scan_for_forgetting → {} records (limit={})", records.len(), limit);
|
||||
Ok(records)
|
||||
}
|
||||
|
||||
pub fn scan_all(&self) -> Result<Vec<MemoryRecord>, Box<dyn std::error::Error>> {
|
||||
let db = rt().block_on(lancedb::connect(self.data_dir.to_str().unwrap()).execute())?;
|
||||
let tbl = rt().block_on(db.open_table("memories").execute())?;
|
||||
|
||||
@@ -312,6 +312,18 @@ fn handle_client(mut stream: UnixStream, args: &Args, lancedb: LanceDBOps, state
|
||||
Err(e) => send_error(&mut stream, "lancedb_query", &e.to_string()),
|
||||
}
|
||||
}
|
||||
"lancedb_scan" => {
|
||||
// P2 2026-09-06: 遗忘候选安全全表扫描 — 限长(硬上限 5000) + 跳 vector
|
||||
let mut limit = msg["limit"].as_u64().unwrap_or(2000) as usize;
|
||||
if limit > 5000 {
|
||||
limit = 5000;
|
||||
}
|
||||
eprintln!("[lancedb] scan_for_forgetting: limit={}", limit);
|
||||
match lancedb.scan_for_forgetting(limit) {
|
||||
Ok(r) => send_ok(&mut stream, &serde_json::to_string(&r).unwrap_or_default()),
|
||||
Err(e) => send_error(&mut stream, "lancedb_scan", &e.to_string()),
|
||||
}
|
||||
}
|
||||
_ => {
|
||||
let req: ConsolidateRequest = match serde_json::from_value(msg) {
|
||||
Ok(r) => r, Err(e) => {
|
||||
|
||||
Reference in New Issue
Block a user