From 9bfe4c217fee282b4e4299f30550b95945512776 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=B0=8F=E5=94=AF?= Date: Thu, 8 Oct 2026 15:44:04 +0800 Subject: [PATCH] fix(p1-1): forget path - counting test + purge-invalid endpoint (t_37ac8a45) --- go/internal/api/routes/admin.go | 16 ++ go/internal/api/routes/admin_forget_test.go | 154 ++++++++++++++++++ .../api/routes/recall_error_shape_test.go | 1 + .../routes/zz_commit_conflict_gate_test.go | 1 + go/internal/api/server.go | 1 + go/internal/storage/lancedb.go | 3 + go/internal/storage/lancedb_ipc.go | 19 +++ go/internal/storage/memvector.go | 15 ++ .../storage/recall_write_buffer_test.go | 1 + go/internal/storage/sqlite.go | 30 ++++ go/internal/storage/sqlite_mem.go | 26 +++ rust/src/lancedb_ops.rs | 26 +++ rust/src/main.rs | 9 + 13 files changed, 302 insertions(+) create mode 100644 go/internal/api/routes/admin_forget_test.go diff --git a/go/internal/api/routes/admin.go b/go/internal/api/routes/admin.go index af67a55..0bfd18a 100644 --- a/go/internal/api/routes/admin.go +++ b/go/internal/api/routes/admin.go @@ -118,6 +118,22 @@ func (aa *AdminAPI) Forget(w http.ResponseWriter, r *http.Request) { }) } +// POST /api/v1/admin/purge-invalid +// P1-1 2026-10-08: 一次性清理 id 为空的垃圾行(DB 存在 id/content/source 全空的 2 行, +// 命中 <30 字碎片快速道 → SoftDelete("") 被 Rust 拒绝 → 每轮刷错误日志 + 遗忘计数虚高)。 +// 这些行无 id 无法按 id 软删,只能按 id='' 条件一次性软删(is_deleted=true)。 +// ⚠️ 由验收/决策者按需调用(本实现不自动触发),本端点只提供能力 + 返回受影响行数。 +func (aa *AdminAPI) PurgeInvalid(w http.ResponseWriter, r *http.Request) { + n, err := aa.LanceDB.PurgeInvalid() + if err != nil { + respondError(w, 500, "purge-invalid failed: "+err.Error()) + return + } + respond(w, 200, map[string]interface{}{ + "status": "ok", "purged": n, + }) +} + // POST /api/v1/admin/backup func (aa *AdminAPI) Backup(w http.ResponseWriter, r *http.Request) { timestamp := time.Now().Format("20060102-150405") diff --git a/go/internal/api/routes/admin_forget_test.go b/go/internal/api/routes/admin_forget_test.go new file mode 100644 index 0000000..7d979ef --- /dev/null +++ b/go/internal/api/routes/admin_forget_test.go @@ -0,0 +1,154 @@ +// 织忆 MemoryWeave — P1-1 遗忘路径计数修复单测(t_37ac8a45, 2026-10-08) +// +// 目标(AC3):SoftDelete 失败 → forgotten 不得增加(原实现失败照样 forgotten++ ⇒ 遗忘计数虚高)。 +// 量具铁律:正例(成功 → forgotten+1)与负例(失败 → forgotten 不 +1)都要有。 +package routes + +import ( + "encoding/json" + "fmt" + "net/http/httptest" + "strings" + "testing" + "time" + + "github.com/xiaoxue/memoryweave/internal/governance" + "github.com/xiaoxue/memoryweave/internal/models" +) + +// forgetMockLance 为 Forget 计数测试提供的 LanceDB 桩: +// GetCandidatesForForgetting 可配置候选列表;SoftDelete 可配置失败/成功。 +type forgetMockLance struct { + candidates []map[string]interface{} + softDeleteErr error + deletedIDs []string +} + +func (m *forgetMockLance) InsertEpisode(agentID, namespace, content, category string) (string, error) { + return "ep_test", nil +} +func (m *forgetMockLance) GetTopByQuality(agentID string, limit int) ([]models.MemoryRecord, error) { + return nil, nil +} +func (m *forgetMockLance) Stats() (map[string]interface{}, error) { + return map[string]interface{}{}, nil +} +func (m *forgetMockLance) SoftDelete(id, reason string) error { + if m.softDeleteErr != nil { + return m.softDeleteErr + } + m.deletedIDs = append(m.deletedIDs, id) + return nil +} +func (m *forgetMockLance) PurgeInvalid() (int64, error) { return 0, nil } +func (m *forgetMockLance) SoftDeleteBatch(table string, ids []string, updatedAt string) (int64, error) { + return int64(len(ids)), nil +} +func (m *forgetMockLance) GetVersionHistory(id string) ([]map[string]interface{}, error) { + return nil, nil +} +func (m *forgetMockLance) GetCandidatesForForgetting() ([]map[string]interface{}, error) { + return m.candidates, nil +} +func (m *forgetMockLance) GetSkillCandidates(minRecalls, limit int) ([]models.MemoryRecord, error) { + return nil, nil +} +func (m *forgetMockLance) Backup(path string) error { return nil } +func (m *forgetMockLance) GetAuditLog(limit int) ([]map[string]interface{}, error) { return nil, nil } +func (m *forgetMockLance) IncrementUseful(id string) error { return nil } +func (m *forgetMockLance) IncrementNotUseful(id string) error { return nil } +func (m *forgetMockLance) UpdateMemoryContent(id, newContent, source string) error { return nil } +func (m *forgetMockLance) InsertMemory(mem models.MemoryRecord) error { return nil } +func (m *forgetMockLance) Search(table string, vector []float32, topK int, namespaceFilter string) ([]models.MemoryRecord, error) { + return nil, nil +} +func (m *forgetMockLance) Scan(limit int, namespaceFilter string) ([]models.MemoryRecord, error) { + return nil, nil +} +func (m *forgetMockLance) Insert(table string, record any) error { return nil } +func (m *forgetMockLance) Update(table, id string, fields map[string]any) error { + return nil +} + +// fragment 构造一个命中「<30 字碎片快速道」的候选(content<30 字 + 20 天未访问)。 +func fragmentCandidate(id string) map[string]interface{} { + return map[string]interface{}{ + "id": id, + "content": "短碎片", // <30 字 + "category": "distilled", + "last_recalled_at": time.Now().Add(-30 * 24 * time.Hour).Format(time.RFC3339), + "recall_count": 0, + "tier": "normal", + } +} + +// forgetResp 解析 Forget 响应体。 +type forgetResp struct { + Status string `json:"status"` + Scanned int `json:"scanned"` + Forgotten int `json:"forgotten"` +} + +// callForget 构造 AdminAPI 并调用 Forget 端点,返回响应体。 +func callForget(t *testing.T, db *forgetMockLance) forgetResp { + t.Helper() + aa := NewAdminAPI(db, governance.NewForgetter(), governance.NewInMemoryGraph()) + req := httptest.NewRequest("POST", "/api/v1/admin/forget", strings.NewReader("")) + w := httptest.NewRecorder() + aa.Forget(w, req) + if w.Code != 200 { + t.Fatalf("Forget 期望 200,实得 %d:%s", w.Code, w.Body.String()) + } + var resp forgetResp + if err := json.Unmarshal(w.Body.Bytes(), &resp); err != nil { + t.Fatalf("解析响应失败: %v", err) + } + return resp +} + +// TestForget_SoftDeleteFailure_DoesNotIncrement 负例(AC3 核心): +// 有效 id 的候选命中碎片快速道,但 SoftDelete 失败 → forgotten 不得增加。 +// 修前:失败照样 forgotten++ ⇒ 遗忘计数虚高(每轮刷日志 + 计数失真)。 +func TestForget_SoftDeleteFailure_DoesNotIncrement(t *testing.T) { + db := &forgetMockLance{ + candidates: []map[string]interface{}{fragmentCandidate("mem_fail_1")}, + softDeleteErr: fmt.Errorf("ipc: simulated soft delete failure"), + } + resp := callForget(t, db) + if resp.Forgotten != 0 { + t.Fatalf("SoftDelete 失败时 forgotten 不得增加,实得 %d(计数 bug 未修)", resp.Forgotten) + } + t.Logf("✓ SoftDelete 失败 → forgotten=%d(不虚增)", resp.Forgotten) +} + +// TestForget_SoftDeleteSuccess_Increments 正例(量具铁律:证明量具能报阳性): +// 有效 id 候选 + SoftDelete 成功 → forgotten 必须 +1。 +func TestForget_SoftDeleteSuccess_Increments(t *testing.T) { + db := &forgetMockLance{ + candidates: []map[string]interface{}{fragmentCandidate("mem_ok_1")}, + } + resp := callForget(t, db) + if resp.Forgotten != 1 { + t.Fatalf("SoftDelete 成功时 forgotten 应 +1,实得 %d", resp.Forgotten) + } + if len(db.deletedIDs) != 1 || db.deletedIDs[0] != "mem_ok_1" { + t.Fatalf("SoftDelete 应被调用一次并传入 mem_ok_1,实得 %v", db.deletedIDs) + } + t.Logf("✓ SoftDelete 成功 → forgotten=%d(计数正确)", resp.Forgotten) +} + +// TestForget_EmptyIDSkipped 空 id 候选直接跳过(Step 2a 守卫): +// id 为空(id/content/source 全空的垃圾行)→ 不计数、不调用 SoftDelete。 +func TestForget_EmptyIDSkipped(t *testing.T) { + db := &forgetMockLance{ + candidates: []map[string]interface{}{fragmentCandidate("")}, + } + resp := callForget(t, db) + if resp.Forgotten != 0 { + t.Fatalf("空 id 候选不得计入 forgotten,实得 %d", resp.Forgotten) + } + if len(db.deletedIDs) != 0 { + t.Fatalf("空 id 候选不得调用 SoftDelete,实得 %v", db.deletedIDs) + } + t.Logf("✓ 空 id 候选跳过:forgotten=%d, SoftDelete 调用 0 次", resp.Forgotten) +} \ No newline at end of file diff --git a/go/internal/api/routes/recall_error_shape_test.go b/go/internal/api/routes/recall_error_shape_test.go index 63fb4ff..9e5177a 100644 --- a/go/internal/api/routes/recall_error_shape_test.go +++ b/go/internal/api/routes/recall_error_shape_test.go @@ -35,6 +35,7 @@ func (f *fakeLanceDB) Stats() (map[string]interface{}, error) { return map[string]interface{}{}, nil } func (f *fakeLanceDB) SoftDelete(id, reason string) error { return nil } +func (f *fakeLanceDB) PurgeInvalid() (int64, error) { return 0, nil } func (f *fakeLanceDB) SoftDeleteBatch(table string, ids []string, updatedAt string) (int64, error) { return 0, nil } diff --git a/go/internal/api/routes/zz_commit_conflict_gate_test.go b/go/internal/api/routes/zz_commit_conflict_gate_test.go index ae8a89c..e976582 100644 --- a/go/internal/api/routes/zz_commit_conflict_gate_test.go +++ b/go/internal/api/routes/zz_commit_conflict_gate_test.go @@ -65,6 +65,7 @@ func (m *mockLance) GetTopByQuality(agentID string, limit int) ([]models.MemoryR } func (m *mockLance) Stats() (map[string]interface{}, error) { return map[string]interface{}{}, nil } func (m *mockLance) SoftDelete(id, reason string) error { return nil } +func (m *mockLance) PurgeInvalid() (int64, error) { return 0, nil } func (m *mockLance) SoftDeleteBatch(table string, ids []string, updatedAt string) (int64, error) { return 0, nil } diff --git a/go/internal/api/server.go b/go/internal/api/server.go index fffa67c..e47000a 100644 --- a/go/internal/api/server.go +++ b/go/internal/api/server.go @@ -1070,6 +1070,7 @@ func NewServer() http.Handler { } }) mux.HandleFunc("/api/v1/admin/forget", adminAPI.Forget) + mux.HandleFunc("/api/v1/admin/purge-invalid", adminAPI.PurgeInvalid) mux.HandleFunc("/api/v1/admin/dedup", api.Dedup) mux.HandleFunc("/api/v1/admin/backup", adminAPI.Backup) mux.HandleFunc("/api/v1/admin/restore", adminAPI.Restore) diff --git a/go/internal/storage/lancedb.go b/go/internal/storage/lancedb.go index 236a953..810ae0f 100644 --- a/go/internal/storage/lancedb.go +++ b/go/internal/storage/lancedb.go @@ -38,4 +38,7 @@ type LanceDB interface { Scan(limit int, namespaceFilter string) ([]models.MemoryRecord, error) Insert(table string, record any) error Update(table, id string, fields map[string]any) error + // PurgeInvalid 清理 id 为空的垃圾行(P1-1):按 id='' 条件一次性软删(is_deleted=true)。 + // 返回受影响行数。这些行无 id 无法按 id 软删,只能走专用端点 /api/v1/admin/purge-invalid。 + PurgeInvalid() (int64, error) } diff --git a/go/internal/storage/lancedb_ipc.go b/go/internal/storage/lancedb_ipc.go index 5529c50..486a565 100644 --- a/go/internal/storage/lancedb_ipc.go +++ b/go/internal/storage/lancedb_ipc.go @@ -637,6 +637,25 @@ func (rc *RustLanceDBClient) SoftDeleteBatch(table string, ids []string, updated return updated, nil } +// PurgeInvalid 清理 id 为空的垃圾行(P1-1 2026-10-08)。 +// 走 Rust IPC lancedb_purge_invalid:按 id='' 条件一次性软删(is_deleted=true + updated_at=now)。 +// 这些行 id/content/source 全空、无法按 id 软删,只能按条件清。返回受影响行数。 +func (rc *RustLanceDBClient) PurgeInvalid() (int64, error) { + now := time.Now().Format(time.RFC3339) + resp, err := rc.rpc(ipcReq{Type: "lancedb_purge_invalid", TS: now}) + if err != nil { + return 0, fmt.Errorf("purge_invalid rpc: %w", err) + } + var out struct { + Purged int64 `json:"purged"` + } + if resp.ReportJSON != "" { + _ = json.Unmarshal([]byte(resp.ReportJSON), &out) + } + log.Printf("[ipc] PurgeInvalid: 软删 %d 行 id 为空垃圾记录", out.Purged) + return out.Purged, nil +} + func (rc *RustLanceDBClient) GetVersionHistory(id string) ([]map[string]interface{}, error) { return nil, nil } diff --git a/go/internal/storage/memvector.go b/go/internal/storage/memvector.go index afe9ba3..b541738 100644 --- a/go/internal/storage/memvector.go +++ b/go/internal/storage/memvector.go @@ -5,6 +5,7 @@ import ( "fmt" "math" "sort" + "strings" "sync" "time" @@ -322,6 +323,20 @@ func (mlc *MemLanceClient) Update(table, id string, fields map[string]any) error return nil } +// PurgeInvalid 清理 id 为空的垃圾行(P1-1 2026-10-08,内存兜底实现)。 +func (mlc *MemLanceClient) PurgeInvalid() (int64, error) { + mlc.mu.Lock() + defer mlc.mu.Unlock() + var n int64 + for id, e := range mlc.memories { + if strings.TrimSpace(id) == "" && !e.IsDeleted { + e.IsDeleted = true + n++ + } + } + return n, nil +} + // ─── SearchCache 兼容 ────────────────────────────────── func (mlc *MemLanceClient) SearchCompat(queryVec []float32, topK int, namespace string) ([]interface{}, error) { diff --git a/go/internal/storage/recall_write_buffer_test.go b/go/internal/storage/recall_write_buffer_test.go index 38915ce..a94ff61 100644 --- a/go/internal/storage/recall_write_buffer_test.go +++ b/go/internal/storage/recall_write_buffer_test.go @@ -61,6 +61,7 @@ func (f *fakeLDB) Update(table, id string, fields map[string]any) error { f.mu.Unlock() return nil } +func (f *fakeLDB) PurgeInvalid() (int64, error) { return 0, nil } // BatchRecallUpdater 实现(单事务批量) func (f *fakeLDB) UpdateRecallBatch(table string, items []RecallWriteItem, lastRecalledAt string) (int64, error) { diff --git a/go/internal/storage/sqlite.go b/go/internal/storage/sqlite.go index b254919..9153ca9 100644 --- a/go/internal/storage/sqlite.go +++ b/go/internal/storage/sqlite.go @@ -765,6 +765,36 @@ func (sc *SQLiteClient) Update(table, id string, fields map[string]any) error { return nil } +// PurgeInvalid 清理 id 为空的垃圾行(P1-1 2026-10-08,SQLite 兜底实现)。 +// 软删(is_deleted=1 + updated_at=now)而非硬删,语义与 Rust LanceDB 一致。 +// execWithArgs 只返回 error,受影响行数用前后 COUNT 差值近似(空 id 行必然 is_deleted=0 才被清, +// 且这些行不参与任何读取路径,直接用 UPDATE 前的空 id 存活计数作为「受影响行数」)。 +func (sc *SQLiteClient) PurgeInvalid() (int64, error) { + sc.mu.Lock() + defer sc.mu.Unlock() + + rows, err := sc.query("SELECT COUNT(*) as cnt FROM memories WHERE is_deleted=0 AND (id='' OR trim(id)='')") + if err != nil { + return 0, err + } + before := int64(0) + if len(rows) > 0 { + before, _ = rows[0]["cnt"].(int64) + } + if before == 0 { + return 0, nil + } + + now := time.Now().Format(time.RFC3339) + if err := sc.execWithArgs( + "UPDATE memories SET is_deleted=1, updated_at=? WHERE id='' OR trim(id)=''", + now, + ); err != nil { + return 0, err + } + return before, nil +} + // ─── helpers ────────────────────────────────────────── func strVal(row sqliteRow, key string) string { diff --git a/go/internal/storage/sqlite_mem.go b/go/internal/storage/sqlite_mem.go index 39c1ee8..0d505f0 100644 --- a/go/internal/storage/sqlite_mem.go +++ b/go/internal/storage/sqlite_mem.go @@ -266,6 +266,32 @@ func (sm *SQLiteMemClient) SoftDelete(id, reason string) error { return nil } +func (sm *SQLiteMemClient) PurgeInvalid() (int64, error) { + // P1-1 2026-10-08: 空 id 垃圾行不在内存 map(map 按 id 为键),需直清 sqlite 落库行。 + // 复用 SQLiteClient 的语义:软删(is_deleted=1)。行数用 UPDATE 前计数近似。 + sm.mu.RLock() + var before int64 + if err := sm.db.QueryRow( + "SELECT COUNT(*) FROM memories WHERE is_deleted=0 AND (id='' OR trim(id)='')", + ).Scan(&before); err != nil { + sm.mu.RUnlock() + return 0, err + } + sm.mu.RUnlock() + if before == 0 { + return 0, nil + } + sm.mu.Lock() + defer sm.mu.Unlock() + if _, err := sm.db.Exec( + "UPDATE memories SET is_deleted=1, updated_at=? WHERE id='' OR trim(id)=''", + time.Now().Format(time.RFC3339), + ); err != nil { + return 0, err + } + return before, nil +} + func (sm *SQLiteMemClient) UpdateMemoryContent(id, newContent, source string) error { if err := sm.MemLanceClient.UpdateMemoryContent(id, newContent, source); err != nil { return err diff --git a/rust/src/lancedb_ops.rs b/rust/src/lancedb_ops.rs index 57bcce0..a8b672a 100644 --- a/rust/src/lancedb_ops.rs +++ b/rust/src/lancedb_ops.rs @@ -549,6 +549,32 @@ impl LanceDBOps { Ok(total) } + /// 清理 id 为空的垃圾行(P1-1, 2026-10-08)。 + /// + /// 背景:DB 存在 id/content/source 全空的垃圾行 ⇒ 命中「<30 字碎片快速道」 + /// ⇒ SoftDelete("") 被 Rust IPC 拒绝("id required")⇒ 每轮刷错误日志 + 遗忘计数虚高。 + /// 这些行无 id 无法按 id 软删,只能按「id 为空」条件一次性软删(软删非硬删,is_deleted=true)。 + /// + /// 做法:一次 update 提交把 id 为空的存活行标记 is_deleted=true + updated_at=ts。 + /// 只匹配精确空串(id = '');不匹配纯空白(LanceDB SQL 的 trim 支持未验证, + /// 宁缺勿滥 —— 防御/计数代码已能安全跳过任何残留空 id,不会刷日志)。 + /// ts 由 Go 侧传入(与 soft_delete_batch 同构,避免 Rust 侧依赖时钟库)。 + pub fn purge_invalid(&self, ts: &str) -> Result> { + 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 esc = |s: &str| s.replace("\\'", "''"); + let ts_lit = format!("'{}'", esc(ts)); + let op = tbl + .update() + .only_if("id = ''") + .column("is_deleted", "true") + .column("updated_at", &ts_lit); + let updated = rt().block_on(op.execute())?; + eprintln!("[lancedb] PURGE INVALID DONE: rows={}", updated); + Ok(updated) + } + /// 全量扫描 memories 表(用于深整),上限 10000 条 // P2 2026-09-06 安全版遗忘候选全表扫描(替代 febc2c9 风暴版): // 1. 强制 limit(调用方传, main.rs 钳制硬上限 5000) diff --git a/rust/src/main.rs b/rust/src/main.rs index ad3b9bc..d4ea9f2 100644 --- a/rust/src/main.rs +++ b/rust/src/main.rs @@ -377,6 +377,15 @@ fn handle_client(mut stream: UnixStream, args: &Args, lancedb: LanceDBOps, state Err(e) => send_error(&mut stream, "lancedb_scan", &e.to_string()), } } + "lancedb_purge_invalid" => { + // P1-1 2026-10-08: 清理 id 为空的垃圾行(无法按 id 软删,按 id='' 条件一次性软删)。 + // ts 由 Go 侧传入(RFC3339),与 soft_delete_batch 同构。 + let ts = msg["ts"].as_str().unwrap_or(""); + match lancedb.purge_invalid(ts) { + Ok(n) => send_ok(&mut stream, &format!(r#"{{"purged":{}}}"#, n)), + Err(e) => send_error(&mut stream, "lancedb_purge_invalid", &e.to_string()), + } + } _ => { let req: ConsolidateRequest = match serde_json::from_value(msg) { Ok(r) => r, Err(e) => {