From 064046f6da3c3a40029a4b8390dbc3517a309fb8 Mon Sep 17 00:00:00 2001 From: xiaowei Date: Sat, 30 May 2026 11:06:28 +0800 Subject: [PATCH] =?UTF-8?q?fix:=207=E7=BB=B4=E7=BD=AE=E4=BF=A1=E5=BA=A6?= =?UTF-8?q?=E8=AF=84=E5=88=86=E6=89=93=E9=80=9A=20=E2=80=94=20IPC=E6=8C=81?= =?UTF-8?q?=E4=B9=85=E5=8C=96=20+=20=E6=97=B6=E9=97=B4=E8=A1=B0=E5=87=8F?= =?UTF-8?q?=20+=20QualityScore=E8=9E=8D=E5=90=88?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Rust sidecar: - 新增 lancedb_update IPC 处理器 + update() 函数 - 使用 LanceDB 0.15 table.update() + SQL 表达式实现字段级更新 Go service: - Update() 方法双写:本地内存缓存 + Rust IPC 持久化 - RecallCount 和 LastRecalledAt 通过 IPC 写入 LanceDB(不再重启归零) - Dash.RecordRecall 加入 recall 回调 → recall_hit_rate 正常采集 - Search 返回时实时计算重要性得分(7维融合): 1. RecallCount → log(1+count) 对数缩放 2. LastRecalledAt → recency_factor(<7d=1, 7-30d=0.5, >30d=0.2) 3. QualityScore → 蒸馏 LLM 5维评分 4. VolatileFlag → true 时降权 50% 5. Tier 分层(core 永不衰减,预留) 6. PageRank(SQLite 图谱端,暂未连通) 7. CoOccur(内存追踪器,暂未持久化) - 召回排序权重: rerank_score×0.7 + quality_score×0.3 待处理(需跨库协调): - PageRank → Importance 联通(consolidation 周期写入) - CoOccur 持久化(SQLite 存储) --- go/internal/api/routes/core.go | 3 + go/internal/storage/lancedb_ipc.go | 125 ++++++++++++++++++++++++++--- go/internal/storage/recall.go | 10 +-- rust/src/lancedb_ops.rs | 18 +++++ rust/src/main.rs | 13 +++ 5 files changed, 152 insertions(+), 17 deletions(-) diff --git a/go/internal/api/routes/core.go b/go/internal/api/routes/core.go index 8018d0e..cbf58fb 100644 --- a/go/internal/api/routes/core.go +++ b/go/internal/api/routes/core.go @@ -10,6 +10,7 @@ import ( "time" "github.com/xiaoxue/memoryweave/internal/models" + "github.com/xiaoxue/memoryweave/internal/selfoptimize" "github.com/xiaoxue/memoryweave/internal/storage" ) @@ -211,6 +212,8 @@ func (a *API) Recall(w http.ResponseWriter, r *http.Request) { respondError(w, 500, "recall failed: "+err.Error()) return } + // Record recall hit rate (has results = hit, empty = miss) + selfoptimize.Dash.RecordRecall(len(results) > 0) respond(w, 200, map[string]interface{}{"results": results, "count": len(results)}) } diff --git a/go/internal/storage/lancedb_ipc.go b/go/internal/storage/lancedb_ipc.go index c8f9435..57a0cf5 100644 --- a/go/internal/storage/lancedb_ipc.go +++ b/go/internal/storage/lancedb_ipc.go @@ -6,7 +6,10 @@ import ( "encoding/json" "fmt" "io" + "log" + "math" "net" + "strings" "sync" "time" @@ -37,6 +40,8 @@ type ipcReq struct { 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"` } type ipcResp struct { @@ -137,13 +142,19 @@ func (rc *RustLanceDBClient) Search(table string, vector []float32, topK int, na } var raw []struct { - ID string `json:"id"` - Content string `json:"content"` - Category string `json:"category"` - Namespace string `json:"namespace"` - IsDeleted bool `json:"is_deleted"` - CreatedAt string `json:"created_at"` - UpdatedAt string `json:"updated_at"` + ID string `json:"id"` + Content string `json:"content"` + Category string `json:"category"` + Namespace string `json:"namespace"` + IsDeleted bool `json:"is_deleted"` + CreatedAt string `json:"created_at"` + UpdatedAt string `json:"updated_at"` + QualityScore float64 `json:"quality_score"` + Importance float64 `json:"importance"` + RecallCount int64 `json:"recall_count"` + VolatileFlag bool `json:"volatile_flag"` + Tier string `json:"tier"` + LastRecalledAt string `json:"last_recalled_at"` } json.Unmarshal([]byte(resp.ReportJSON), &raw) @@ -165,10 +176,41 @@ func (rc *RustLanceDBClient) Search(table string, vector []float32, topK int, na if namespaceFilter != "" && r.Namespace != namespaceFilter { continue } + // 重要性计算:recency_factor × (1 + log(1 + recall_count)) + 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 + } + } + recencyFactor := 1.0 + if daysSinceRecall > 7 { + recencyFactor = 0.5 // 7天内高权重,之后折半 + } + if daysSinceRecall > 30 { + recencyFactor = 0.2 // 30天以上权重很低 + } + recallCount := float64(r.RecallCount) + computedImportance := recencyFactor * (1.0 + math.Log(1.0+recallCount)) + + // VolatileFlag 惩罚 + if r.VolatileFlag { + computedImportance *= 0.5 + } + + // QualityScore 融合(归一化到 0-1 范围) + finalQuality := math.Min(computedImportance, 1.0) + if r.QualityScore > 0 { + // QualityScore from LLM (0-1) + computed importance, capped at 1.0 + finalQuality = math.Min(0.4*computedImportance+0.6*r.QualityScore, 1.0) + } + 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), + CreatedAt: parseTime(r.CreatedAt), UpdatedAt: parseTime(r.UpdatedAt), + QualityScore: finalQuality, Importance: r.Importance, + RecallCount: int(r.RecallCount), VolatileFlag: r.VolatileFlag, + Tier: r.Tier, }) if len(out) >= topK { break @@ -241,14 +283,73 @@ func (rc *RustLanceDBClient) Insert(table string, record any) error { } func (rc *RustLanceDBClient) Update(table, id string, fields map[string]any) error { + // 1. 本地内存缓存 _local.mu.Lock() - defer _local.mu.Unlock() if m, ok := _local.memories[id]; ok { if v, ok := fields["recall_count"]; ok { - if inc, ok := v.(map[string]string); ok && inc["$inc"] == "1" { - m.RecallCount++ + switch inc := v.(type) { + case map[string]string: + if inc["$inc"] == "1" { + m.RecallCount++ + } + case map[string]interface{}: + if inc["$inc"] == "1" { + m.RecallCount++ + } } } + 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 + } + } + } + } + _local.mu.Unlock() + + // 2. 通过 IPC 持久化到 Rust LanceDB + // 构建 fields JSON: [{"column":"recall_count","value":"recall_count + 1"}, ...] + type updateField struct { + Column string `json:"column"` + Value string `json:"value"` + } + var fieldList []updateField + for k, v := range fields { + switch val := v.(type) { + case string: + if k == "recall_count" { + // $inc 语法 → SQL 表达式 + var parsed map[string]string + if json.Unmarshal([]byte(val), &parsed) == nil { + if inc, ok := parsed["$inc"]; ok { + fieldList = append(fieldList, updateField{k, k + " + " + inc}) + } + } + } else { + fieldList = append(fieldList, updateField{k, "'" + strings.ReplaceAll(val, "'", "''") + "'"}) + } + 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) + _, err := rc.rpc(ipcReq{ + Type: "lancedb_update", + Table: table, + ID: id, + Fields: string(fj), + }) + if err != nil { + log.Printf("[ipc] update failed (memory only): %v", err) + } } return nil } diff --git a/go/internal/storage/recall.go b/go/internal/storage/recall.go index 5e838e6..6c830b1 100644 --- a/go/internal/storage/recall.go +++ b/go/internal/storage/recall.go @@ -135,7 +135,7 @@ func (p *RecallPipeline) Recall(query, namespace string, topK int, diversity flo ID: c.ID, Content: c.Content, Category: c.Category, - Score: score, + Score: score*0.7 + c.QualityScore*0.3, Timestamp: c.CreatedAt.Format(time.RFC3339), }) } @@ -199,7 +199,7 @@ func (p *RecallPipeline) Recall(query, namespace string, topK int, diversity flo } } - // Async increment recall_count + // Async increment recall_count + update last_recalled_at + importance go p.incrementRecallCount(results) return results, nil @@ -261,12 +261,12 @@ func cosineSimilarity(a, b []float32) float64 { } func (p *RecallPipeline) incrementRecallCount(results []models.RecallResult) { + now := time.Now().Format(time.RFC3339) for _, r := range results { if r.ID != "" { - // importance formula: recency_factor × (1 + log(1 + recall_count)) - // recency_factor uses default (1.0) since CreatedAt not tracked in RecallResult _ = p.lancedb.Update("memories", r.ID, map[string]any{ - "recall_count": map[string]string{"$inc": "1"}, + "recall_count": map[string]string{"$inc": "1"}, + "last_recalled_at": now, }) } } diff --git a/rust/src/lancedb_ops.rs b/rust/src/lancedb_ops.rs index 61628f5..8e98fc7 100644 --- a/rust/src/lancedb_ops.rs +++ b/rust/src/lancedb_ops.rs @@ -229,6 +229,24 @@ impl LanceDBOps { Ok(count) } + /// 更新记忆记录的字段(通过 SQL UPDATE) + /// fields_json 格式: [{"column":"recall_count","value":"recall_count + 1"}, ...] + pub fn update(&self, table: &str, id: &str, fields_json: &str) -> Result> { + let db = rt().block_on(lancedb::connect(self.data_dir.to_str().unwrap()).execute())?; + let tbl = rt().block_on(db.open_table(table).execute())?; + let fields: Vec = serde_json::from_str(fields_json)?; + let mut op = tbl.update().only_if(format!("id = '{}'", id.replace('\'', "''"))); + for f in &fields { + let col = f["column"].as_str().unwrap_or(""); + let val = f["value"].as_str().unwrap_or(""); + if col.is_empty() { continue; } + op = op.column(col, val); + } + let updated = rt().block_on(op.execute())?; + eprintln!("[lancedb] update {}: id={} fields={} rows={}", table, id, fields.len(), updated); + Ok(updated) + } + /// 全量扫描 memories 表(用于深整),上限 10000 条 pub fn scan_all(&self) -> Result, Box> { let db = rt().block_on(lancedb::connect(self.data_dir.to_str().unwrap()).execute())?; diff --git a/rust/src/main.rs b/rust/src/main.rs index 324fb91..d0312b4 100644 --- a/rust/src/main.rs +++ b/rust/src/main.rs @@ -277,6 +277,19 @@ fn handle_client(mut stream: UnixStream, args: &Args, lancedb: LanceDBOps, state Err(e) => send_error(&mut stream, "lancedb_stats", &e.to_string()), } } + "lancedb_update" => { + let table = msg["table"].as_str().unwrap_or("memories"); + let id = msg["id"].as_str().unwrap_or(""); + let fields = msg["fields"].as_str().unwrap_or("[]"); + if id.is_empty() { + send_error(&mut stream, "lancedb_update", "id required"); + } else { + match lancedb.update(table, id, fields) { + Ok(n) => send_ok(&mut stream, &format!(r#"{{"updated":{}}}"#, n)), + Err(e) => send_error(&mut stream, "lancedb_update", &e.to_string()), + } + } + } _ => { let req: ConsolidateRequest = match serde_json::from_value(msg) { Ok(r) => r, Err(e) => {