fix: 7维置信度评分打通 — IPC持久化 + 时间衰减 + QualityScore融合
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 存储)
This commit is contained in:
@@ -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)})
|
||||
}
|
||||
|
||||
|
||||
@@ -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
|
||||
}
|
||||
|
||||
@@ -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,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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<u64, 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(table).execute())?;
|
||||
let fields: Vec<serde_json::Value> = 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<Vec<MemoryRecord>, Box<dyn std::error::Error>> {
|
||||
let db = rt().block_on(lancedb::connect(self.data_dir.to_str().unwrap()).execute())?;
|
||||
|
||||
@@ -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) => {
|
||||
|
||||
Reference in New Issue
Block a user