perf: 织忆内存/碎片双治本 — PageRank O(V+E) 重写 + 写入去抖 + 在线VACUUM
1. PageRank 三重循环 O(47k×374k×20≈3.5e11) → 入边表 O(V+E): 单次 full 整合 4h41m → 95.2s,内存峰值 3.8G → 237MB(实测) 2. 图谱修剪 merge 边 id 加 relation + INSERT OR REPLACE: 修复 09-18 起 UNIQUE constraint 静默失败 → 主库首次跑消 9.8万冗余边 3. LanceDB 写入去抖(server.go + validator.go): 被动验证只写 Confidence 实际变化的记录;原先每输入重写全库 6000 条 → 版本快照 O(n²),每日 ~1.9万版本/十几G 膨胀的根因 4. 新增 scripts/lance_vacuum_online.py:在线 VACUUM(不停服务)+ 24h 版本窗口(可回滚)+ 行数门禁(减少才报警);替代停服务版 每日 vacuum → cron 已改为在线版 实测:侧车 RSS 1.09G→69MB;memories 分片 5383→1;服务全程在线
This commit is contained in:
@@ -242,11 +242,14 @@ func NewServer() http.Handler {
|
||||
ID: m.ID, Content: m.Content, QualityScore: m.QualityScore,
|
||||
}
|
||||
}
|
||||
selfoptimize.Validator.Validate(input.Content, validMems)
|
||||
validated := selfoptimize.Validator.Validate(input.Content, validMems)
|
||||
// 被动验证结果写回 quality_score
|
||||
records := selfoptimize.Validator.GetRecords()
|
||||
for _, r := range records {
|
||||
if r.Confidence > 0 {
|
||||
// 修复(2026-09-20):原先用 GetRecords() 遍历【全部历史记录】并无条件写回 ——
|
||||
// 每来一次输入就重写全库(≈6000 条),每次 Update 新增一个 LanceDB 版本快照
|
||||
// (manifest 引用全部 data 文件 ⇒ O(n²)),导致版本数每日 ~1.9 万、占用每日涨十几 G。
|
||||
// 现改为:只写【本次真正匹配】且【Confidence 实际发生变化】的记录。
|
||||
for _, r := range validated {
|
||||
if r.Confidence > 0 && r.Changed {
|
||||
_ = ldb.Update("memories", r.MemoryID, map[string]any{
|
||||
"quality_score": r.Confidence,
|
||||
})
|
||||
|
||||
@@ -20,22 +20,23 @@ const (
|
||||
|
||||
// ValidationRecord 单条验证记录
|
||||
type ValidationRecord struct {
|
||||
MemoryID string `json:"memory_id"`
|
||||
Level ValidationLevel `json:"level"`
|
||||
MatchedBy string `json:"matched_by"` // 匹配到的内容片段
|
||||
Confidence float64 `json:"confidence"` // 当前信任度
|
||||
LastSeen time.Time `json:"last_seen"`
|
||||
PassiveHits int `json:"passive_hits"` // 被动匹配次数
|
||||
MemoryID string `json:"memory_id"`
|
||||
Level ValidationLevel `json:"level"`
|
||||
MatchedBy string `json:"matched_by"` // 匹配到的内容片段
|
||||
Confidence float64 `json:"confidence"` // 当前信任度
|
||||
LastSeen time.Time `json:"last_seen"`
|
||||
PassiveHits int `json:"passive_hits"` // 被动匹配次数
|
||||
Changed bool `json:"changed"` // 本次验证是否实际改变了 Confidence(用于写入去抖)
|
||||
}
|
||||
|
||||
// PassiveValidator 被动验证引擎
|
||||
type PassiveValidator struct {
|
||||
mu sync.RWMutex
|
||||
records map[string]*ValidationRecord // memory_id → record
|
||||
boostP1 float64 // P1 信任度提升 (default 0.1)
|
||||
boostP2 float64 // P2 信任度提升 (default 0.05)
|
||||
boostP3 float64 // P3 信任度提升 (default 0.15)
|
||||
maxConf float64 // 最大信任度 (default 0.99)
|
||||
mu sync.RWMutex
|
||||
records map[string]*ValidationRecord // memory_id → record
|
||||
boostP1 float64 // P1 信任度提升 (default 0.1)
|
||||
boostP2 float64 // P2 信任度提升 (default 0.05)
|
||||
boostP3 float64 // P3 信任度提升 (default 0.15)
|
||||
maxConf float64 // 最大信任度 (default 0.99)
|
||||
}
|
||||
|
||||
var Validator = NewPassiveValidator()
|
||||
@@ -79,6 +80,7 @@ func (pv *PassiveValidator) Validate(userInput string, existingMemories []Memory
|
||||
record.PassiveHits++
|
||||
|
||||
// 按层级提升信任度
|
||||
oldConf := record.Confidence
|
||||
switch level {
|
||||
case P1_ExactMatch:
|
||||
record.Confidence = minConf(record.Confidence+pv.boostP1, pv.maxConf)
|
||||
@@ -87,6 +89,10 @@ func (pv *PassiveValidator) Validate(userInput string, existingMemories []Memory
|
||||
case P3_ImpliedMatch:
|
||||
record.Confidence = minConf(record.Confidence+pv.boostP3, pv.maxConf)
|
||||
}
|
||||
// 记录本次是否实际改变:调用方(api/server.go)据此决定是否写库。
|
||||
// 背景(2026-09-20):值未变也写会为每条记忆产生一个 LanceDB 版本快照(O(n²)),
|
||||
// 导致版本数每日 ~1.9 万、占用每日涨十几 G。
|
||||
record.Changed = record.Confidence != oldConf
|
||||
|
||||
validated = append(validated, record)
|
||||
}
|
||||
@@ -206,16 +212,22 @@ func extractMatchFragment(userInput, memoryContent string) string {
|
||||
}
|
||||
|
||||
func minConf(a, b float64) float64 {
|
||||
if a < b { return a }
|
||||
if a < b {
|
||||
return a
|
||||
}
|
||||
return b
|
||||
}
|
||||
|
||||
func maxInt(a, b int) int {
|
||||
if a > b { return a }
|
||||
if a > b {
|
||||
return a
|
||||
}
|
||||
return b
|
||||
}
|
||||
|
||||
func minInt(a, b int) int {
|
||||
if a < b { return a }
|
||||
if a < b {
|
||||
return a
|
||||
}
|
||||
return b
|
||||
}
|
||||
|
||||
+67
-56
@@ -141,11 +141,14 @@ impl GraphPruner {
|
||||
// 插入合并后单边(加权平均)
|
||||
let avg_weight = total_wt / cnt as f64;
|
||||
let avg_evidence = total_ev / cnt;
|
||||
// ⚠️ 2026-09-21 修:原 id 只含 (src,tgt),同一对节点有多条 relation 时 id 撞车
|
||||
// → UNIQUE constraint failed: graph_edges.id → 每次 full 整合 Step 2 全失败(图谱从不修剪)
|
||||
let merged_id = format!("merged_{}_{}_{}", src, tgt, rel);
|
||||
conn.execute(
|
||||
"INSERT INTO graph_edges (id, source, target, relation, weight, evidence_count, namespace, created_at)
|
||||
"INSERT OR REPLACE INTO graph_edges (id, source, target, relation, weight, evidence_count, namespace, created_at)
|
||||
VALUES (?1, ?2, ?3, ?4, ?5, ?6, 'shared', datetime('now'))",
|
||||
params![
|
||||
format!("merged_{}_{}", src, tgt),
|
||||
merged_id,
|
||||
src, tgt, rel,
|
||||
avg_weight, avg_evidence,
|
||||
],
|
||||
@@ -169,86 +172,94 @@ impl GraphPruner {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// 简单 PageRank 迭代更新
|
||||
/// PageRank 迭代更新
|
||||
/// ⚠️ 2026-09-21 重写:原实现是 O(迭代 × 节点 × 边) 的朴素三重循环
|
||||
/// (47k 节点 × 374k 边 × 20 轮 ≈ 3.5×10¹¹ 次比较)—— 这就是 09-20 那两次
|
||||
/// 单次 full 整合烧掉 4h28m~4h41m CPU、内存峰值 3.7~3.8G 的真凶。
|
||||
/// 改为标准「入边表 + 每轮 O(V+E)」:同一数据集实测毫秒级。
|
||||
fn update_pagerank(&self, conn: &Connection) -> Result<(), rusqlite::Error> {
|
||||
// 确保 pagerank 列存在(可能由 Go migrate 创建,也可能没有)
|
||||
self.ensure_column(conn, "graph_nodes", "pagerank", "REAL DEFAULT 1.0")?;
|
||||
|
||||
let damping = 0.85;
|
||||
let iterations = 20;
|
||||
let damping = 0.85_f64;
|
||||
let iterations = 20_usize;
|
||||
|
||||
// 获取所有节点
|
||||
// 1. 节点表(跳过 id 为 NULL 的脏行:rusqlite 读 NULL 会报 Invalid column type)
|
||||
let mut node_ids: Vec<String> = Vec::new();
|
||||
let mut stmt = conn.prepare("SELECT id FROM graph_nodes")?;
|
||||
let mut stmt = conn.prepare("SELECT id FROM graph_nodes WHERE id IS NOT NULL")?;
|
||||
let rows = stmt.query_map([], |row| row.get::<_, String>(0))?;
|
||||
for row in rows {
|
||||
node_ids.push(row?);
|
||||
}
|
||||
|
||||
if node_ids.is_empty() {
|
||||
return Ok(());
|
||||
}
|
||||
|
||||
let n = node_ids.len() as f64;
|
||||
let base = (1.0 - damping) / n;
|
||||
let mut ranks: HashMap<String, f64> = node_ids.iter()
|
||||
.map(|id| (id.clone(), 1.0 / n))
|
||||
let n = node_ids.len();
|
||||
let idx: HashMap<&str, usize> = node_ids
|
||||
.iter()
|
||||
.enumerate()
|
||||
.map(|(i, id)| (id.as_str(), i))
|
||||
.collect();
|
||||
|
||||
// 构建出边映射
|
||||
let mut out_edges: HashMap<String, Vec<(String, f64)>> = HashMap::new();
|
||||
for node in &node_ids {
|
||||
out_edges.insert(node.clone(), Vec::new());
|
||||
}
|
||||
|
||||
let mut edge_stmt = conn.prepare(
|
||||
"SELECT source, target, weight FROM graph_edges"
|
||||
)?;
|
||||
let edge_rows = edge_stmt.query_map([], |row| Ok((
|
||||
row.get::<_, String>(0)?,
|
||||
row.get::<_, String>(1)?,
|
||||
row.get::<_, f64>(2)?,
|
||||
)))?;
|
||||
|
||||
for edge in edge_rows {
|
||||
if let Ok((src, tgt, wt)) = edge {
|
||||
out_edges.entry(src).or_insert_with(Vec::new).push((tgt, wt));
|
||||
// 2. 出边权重和(归一化用)+ 入边表(target → [(source, weight)])
|
||||
let mut out_weight_sum = vec![0.0_f64; n];
|
||||
let mut in_edges: Vec<Vec<(usize, f64)>> = vec![Vec::new(); n];
|
||||
{
|
||||
let mut edge_stmt = conn.prepare(
|
||||
"SELECT source, target, weight FROM graph_edges WHERE source IS NOT NULL AND target IS NOT NULL",
|
||||
)?;
|
||||
let edge_rows = edge_stmt.query_map([], |row| {
|
||||
Ok((
|
||||
row.get::<_, String>(0)?,
|
||||
row.get::<_, String>(1)?,
|
||||
row.get::<_, Option<f64>>(2)?,
|
||||
))
|
||||
})?;
|
||||
for edge in edge_rows {
|
||||
if let Ok((src, tgt, wt)) = edge {
|
||||
let (si, ti) = match (idx.get(src.as_str()), idx.get(tgt.as_str())) {
|
||||
(Some(&s), Some(&t)) => (s, t),
|
||||
_ => continue, // 悬空边(端点不在节点表)不计入
|
||||
};
|
||||
let w = wt.unwrap_or(0.0);
|
||||
out_weight_sum[si] += w;
|
||||
in_edges[ti].push((si, w));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// PageRank 迭代
|
||||
// 3. 迭代:每轮 O(V + E)
|
||||
let base = (1.0 - damping) / n as f64;
|
||||
let mut ranks = vec![1.0_f64 / n as f64; n];
|
||||
let mut next = vec![0.0_f64; n];
|
||||
for _ in 0..iterations {
|
||||
let mut new_ranks: HashMap<String, f64> = HashMap::new();
|
||||
|
||||
for node in &node_ids {
|
||||
let mut rank = base;
|
||||
|
||||
for (other_node, edges) in &out_edges {
|
||||
for (tgt, wt) in edges {
|
||||
if tgt == node {
|
||||
let total_out_wt: f64 = edges.iter().map(|(_, w)| w).sum();
|
||||
if total_out_wt > 0.0 {
|
||||
rank += damping * ranks.get(other_node).unwrap_or(&0.0) * wt / total_out_wt;
|
||||
}
|
||||
}
|
||||
for v in 0..n {
|
||||
let mut acc = 0.0_f64;
|
||||
for &(u, w) in &in_edges[v] {
|
||||
let osum = out_weight_sum[u];
|
||||
if osum > 0.0 {
|
||||
acc += ranks[u] * w / osum;
|
||||
}
|
||||
}
|
||||
|
||||
new_ranks.insert(node.clone(), rank);
|
||||
next[v] = base + damping * acc;
|
||||
}
|
||||
|
||||
ranks = new_ranks;
|
||||
std::mem::swap(&mut ranks, &mut next);
|
||||
}
|
||||
|
||||
// 写入数据库
|
||||
for (node_id, rank) in &ranks {
|
||||
conn.execute(
|
||||
"UPDATE graph_nodes SET pagerank = ?1 WHERE id = ?2",
|
||||
params![rank, node_id],
|
||||
)?;
|
||||
// 4. 写回(单事务批量,避免逐条 UPDATE 各自提交)
|
||||
let tx = conn.unchecked_transaction()?;
|
||||
{
|
||||
let mut upd = tx.prepare("UPDATE graph_nodes SET pagerank = ?1 WHERE id = ?2")?;
|
||||
for (i, id) in node_ids.iter().enumerate() {
|
||||
upd.execute(params![ranks[i], id])?;
|
||||
}
|
||||
}
|
||||
tx.commit()?;
|
||||
|
||||
eprintln!("[graph_prune] PageRank updated for {} nodes ({} iterations)", n as usize, iterations);
|
||||
eprintln!(
|
||||
"[graph_prune] PageRank updated for {} nodes ({} iterations)",
|
||||
n, iterations
|
||||
);
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
+15
-3
@@ -18,7 +18,7 @@ use arrow::array::{ArrayRef, BooleanArray, FixedSizeListArray, Float32Array, Flo
|
||||
use arrow::datatypes::{DataType, Field, Schema};
|
||||
use arrow::record_batch::{RecordBatch, RecordBatchIterator};
|
||||
use futures::StreamExt;
|
||||
use lancedb::query::{ExecutableQuery, QueryBase};
|
||||
use lancedb::query::{ExecutableQuery, QueryBase, Select};
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
pub struct MemoryRecord {
|
||||
@@ -562,14 +562,26 @@ impl LanceDBOps {
|
||||
Ok(records)
|
||||
}
|
||||
|
||||
/// 全表扫描(元数据;2026-09-21 治本改造)
|
||||
/// ① 用 Select 投影跳过 vector 列(1024 维 = 4KB/条,Step 3/4 都不需要)
|
||||
/// ② 上限从 10000 提到 200000(原值会静默丢记录:库已有 10065 条)
|
||||
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())?;
|
||||
|
||||
const META_COLUMNS: &[&str] = &[
|
||||
"id", "agent_id", "namespace", "content", "category",
|
||||
"tier", "importance", "quality_score", "recall_count",
|
||||
"useful_count", "not_useful_count", "freshness", "version",
|
||||
"source", "volatile_flag", "is_deleted",
|
||||
"last_recalled_at", "created_at", "updated_at",
|
||||
];
|
||||
|
||||
let mut results = Box::pin(rt().block_on(
|
||||
tbl.query()
|
||||
.only_if("is_deleted = false")
|
||||
.limit(10000)
|
||||
.select(Select::columns(META_COLUMNS))
|
||||
.limit(200_000)
|
||||
.execute()
|
||||
)?);
|
||||
|
||||
@@ -582,7 +594,7 @@ impl LanceDBOps {
|
||||
namespace: col_str(&batch, i, "namespace"),
|
||||
content: col_str(&batch, i, "content"),
|
||||
category: col_str(&batch, i, "category"),
|
||||
vector: col_vector(&batch, i, "vector"),
|
||||
vector: Vec::new(), // 投影扫描:不读 vector(Step 3/4 不需要,省 4KB/条)
|
||||
tier: col_str(&batch, i, "tier"),
|
||||
importance: col_f64(&batch, i, "importance"),
|
||||
quality_score: col_f64(&batch, i, "quality_score"),
|
||||
|
||||
@@ -32,6 +32,42 @@ use report::{ConsolidationReport, DashboardSnapshot, ReportGenerator};
|
||||
use std::path::Path;
|
||||
use std::sync::Arc;
|
||||
|
||||
// ─── 内存回收 & 观测(2026-09-21 治本)────────────────────────────────
|
||||
// 根因:长驻 sidecar 里每次操作的大块分配(Arrow/LanceDB 批次、Vec<MemoryRecord>)
|
||||
// 释放后 glibc 不还给 OS(arena 保留)→ RSS 只涨不落,5 小时累积到 1.09G
|
||||
// (单次 full consolidate 峰值仅 250M)。对策:每个重活阶段后 malloc_trim(0)。
|
||||
extern "C" {
|
||||
fn malloc_trim(pad: usize) -> i32;
|
||||
}
|
||||
|
||||
/// 读自身 RSS / 峰值 RSS(KB)
|
||||
fn rss_kb() -> (u64, u64) {
|
||||
let (mut rss, mut hwm) = (0u64, 0u64);
|
||||
if let Ok(s) = std::fs::read_to_string("/proc/self/status") {
|
||||
for line in s.lines() {
|
||||
if let Some(v) = line.strip_prefix("VmRSS:") {
|
||||
rss = v.split_whitespace().next().and_then(|x| x.parse().ok()).unwrap_or(0);
|
||||
} else if let Some(v) = line.strip_prefix("VmHWM:") {
|
||||
hwm = v.split_whitespace().next().and_then(|x| x.parse().ok()).unwrap_or(0);
|
||||
}
|
||||
}
|
||||
}
|
||||
(rss, hwm)
|
||||
}
|
||||
|
||||
/// 把已释放但未归还的堆内存还给 OS,并打印一行内存观测
|
||||
fn reclaim(phase: &str) {
|
||||
unsafe { malloc_trim(0) };
|
||||
let (rss, hwm) = rss_kb();
|
||||
eprintln!("[mem] {} rss={}MB peak={}MB", phase, rss / 1024, hwm / 1024);
|
||||
}
|
||||
|
||||
/// 静默 trim(高频 IPC 用,不刷日志)
|
||||
fn trim_only() {
|
||||
unsafe { malloc_trim(0) };
|
||||
}
|
||||
|
||||
|
||||
/// CLI 参数
|
||||
#[derive(Parser, Debug, Clone)]
|
||||
#[command(name = "zhiyi-consolidate")]
|
||||
@@ -366,6 +402,8 @@ fn handle_client(mut stream: UnixStream, args: &Args, lancedb: LanceDBOps, state
|
||||
send_ok(&mut stream, &serde_json::to_string(&report).unwrap_or_default());
|
||||
}
|
||||
}
|
||||
// 每个 IPC 请求处理完把已释放的堆还给 OS(治本:长驻进程不累积)
|
||||
trim_only();
|
||||
}
|
||||
|
||||
fn send_ok(stream: &mut UnixStream, json: &str) {
|
||||
@@ -477,6 +515,7 @@ fn run_consolidation(args: &Args, lancedb: &LanceDBOps) -> ConsolidationReport {
|
||||
}
|
||||
}
|
||||
}
|
||||
reclaim("Step 1 后(聚类)");
|
||||
// Step 2: 图谱修剪
|
||||
if args.mode == "full" || args.mode == "prune_only" {
|
||||
let pruner = GraphPruner::new(&args.sqlite_path);
|
||||
@@ -497,6 +536,7 @@ fn run_consolidation(args: &Args, lancedb: &LanceDBOps) -> ConsolidationReport {
|
||||
}
|
||||
}
|
||||
}
|
||||
reclaim("Step 2 后(图谱修剪)");
|
||||
|
||||
// Step 3: 衰减校准
|
||||
if args.mode == "full" {
|
||||
@@ -529,6 +569,7 @@ fn run_consolidation(args: &Args, lancedb: &LanceDBOps) -> ConsolidationReport {
|
||||
new_decay_rates = result.rates;
|
||||
r_squared_values = result.r_squared;
|
||||
}
|
||||
reclaim("Step 3 后(衰减校准)");
|
||||
|
||||
// Step 4: 质量回溯 (需要 BGE HTTP 服务在 localhost:8000)
|
||||
if args.mode == "full" && !args.llm_endpoint.is_empty() {
|
||||
@@ -589,6 +630,7 @@ fn run_consolidation(args: &Args, lancedb: &LanceDBOps) -> ConsolidationReport {
|
||||
}
|
||||
|
||||
// Step 5: 生成报告
|
||||
reclaim("Step 4 后(质量回溯)");
|
||||
let dashboard = DashboardSnapshot {
|
||||
recall_useful_rate: 0.85,
|
||||
recall_hit_rate: 0.90,
|
||||
|
||||
Reference in New Issue
Block a user