diff --git a/go/internal/storage/concurrent_commit_conflict_test.go b/go/internal/storage/concurrent_commit_conflict_test.go index 4a16147..ac9c4ff 100644 --- a/go/internal/storage/concurrent_commit_conflict_test.go +++ b/go/internal/storage/concurrent_commit_conflict_test.go @@ -176,26 +176,34 @@ func TestConcurrentCommitConflict_CrossPath(t *testing.T) { } t.Logf("fake 观测:并发提交 reqs=%d conflicts=%d(两路径重叠即冲突)", fs.reqs.Load(), fs.conflicts.Load()) - // 判据②:Update() 对冲突静默吞掉(返回 nil,仅打日志) + // 判据②(t_28aa278e 修复后):Update() 遇冲突不再静默吞错丢弃,而是有界指数退避重试到成功 + // ⇒ updErr==nil(首次成功或重试成功);计数增量得以保留。 + // (修复前:此断言处 updErr==nil 只代表「静默吞错、增量丢失」;修复后同样 nil 但语义变为 + // 「已重试到成功、增量已落库」。确定性「不丢计数」证明见 update_conflict_retry_test.go。) if updErr != nil { - t.Fatalf("Update() 应静默返回 nil(错误被吞),实际 updErr=%v", updErr) + t.Fatalf("修复后 Update() 应重试冲突到成功(返回 nil,增量不丢);实际 updErr=%v", updErr) } - t.Log("Update() 对 Commit conflict 返回 nil ⇒ 调用方(usage-track)无感知 ⇒ 冲突增量未落库") + // 冲突确被观测到,且每次冲突都触发了后续重试(reqs 增长覆盖 conflict 次数) + if fs.reqs.Load() < fs.conflicts.Load() { + t.Fatalf("每次冲突应至少触发一次重试请求,reqs=%d < conflicts=%d", fs.reqs.Load(), fs.conflicts.Load()) + } + t.Log("修复后:Update() 冲突 → 有界退避重试到成功 ⇒ 计数增量不静默丢弃(对比修复前:静默丢失)") - // 判据③:本地缓存已 +1(Update 在发 IPC 前先改缓存),但 DB 侧提交失败 → 缓存/库分叉 + // 判据③:本地缓存已 +1(Update 在发 IPC 前先改缓存),重试仅重放 rpc、不回改缓存 _local.mu.RLock() cached := _local.memories["mem_A"].RecallVerifiedCount _local.mu.RUnlock() if cached != 4 { t.Fatalf("本地缓存应已 +1 为 4,实际 %d(Update 先改缓存)", cached) } - t.Logf("本地缓存 recall_verified_count=3→%d,但该增量因冲突未落库 ⇒ 缓存/DB 分叉", cached) + t.Logf("本地缓存 recall_verified_count=3→%d,增量已随重试落库 ⇒ 缓存/DB 一致(修复前为分叉)", cached) } -// TestCheckCommittedForUse_ConsumesOnConflict —— AC4 反馈丢失复现: -// 即使 Update 冲突失败,usage_recall 行仍被置 consumed=1 ⇒ 该信号永久丢失(不重试)。 -func TestCheckCommittedForUse_ConsumesOnConflict(t *testing.T) { - // 恒冲突的 fakeServer(untilOK=-1):Update 恒 Commit conflict +// TestCheckCommittedForUse_NotConsumedOnExhaustion —— t_28aa278e 方案① 修复后行为(原 ConsumesOnConflict 缺陷反向验证): +// Update 恒冲突(重试耗尽)⇒ recall_verified_count 不落库,且 usage_recall 行**不再被消费** +// (consumed 保持 0,下轮 commit 重扫会重试)⇒ 计数增量不静默丢失。修复前此场景 consumed=1 永久丢失。 +func TestCheckCommittedForUse_NotConsumedOnExhaustion(t *testing.T) { + // 恒冲突的 fakeServer(untilOK=-1):Update 恒 Commit conflict ⇒ 重试耗尽返回错误 fk := newFakeServer(t, -1, "") defer fk.close() rc := fk.client() @@ -222,18 +230,23 @@ func TestCheckCommittedForUse_ConsumesOnConflict(t *testing.T) { t.Fatalf("insert recall row: %v", err) } - // Update 恒冲突 ⇒ recall_verified_count 不落库;但 consumed=1 无条件置位 + // 修复后:Update 恒冲突耗尽 ⇒ 该行不消费、不 append flag(continue) // 注:CJK 连续段整体作一个 token(DistinctiveTokens),故命中内容须与记忆内容逐字一致 flags := CheckCommittedForUse(rc, "agent", "ns", "牧尘今天要求处理看板任务验收") - if len(flags) != 1 { - t.Fatalf("应判定 1 条被用上,实际 %d", len(flags)) + if len(flags) != 0 { + t.Fatalf("Update 冲突耗尽应跳过消费与 flag(continue),实际 flags=%d", len(flags)) } - // 判据:usage_recall 行已 consumed=1(不会重试)即便 count 冲突失败 + // 判据:usage_recall 行**未**消费(consumed 保持 0,下轮可重试)⇒ 增量不静默丢失 var consumed int _ = db.QueryRow(`SELECT consumed FROM usage_recall WHERE memory_id='mem_A'`).Scan(&consumed) - if consumed != 1 { - t.Fatalf("Update 冲突后 usage_recall 行仍应 consumed=1(无条件消费),实际 %d", consumed) + if consumed != 0 { + t.Fatalf("Update 冲突耗尽后 usage_recall 行应 consumed=0(下轮重试),实际 %d", consumed) } - t.Log("AC4:Update 冲突失败后 usage_recall 行仍 consumed=1 ⇒ 该 recall_verified_count 增量永久丢失(不重试)") + // 冲突路径确实走满重试(1 首次 + updateMaxRetries 重试 = updateMaxRetries+1 次 lancedb_update) + // fk.calls 还含 AppendHitEvent 的 1 次,故 lancedb_update 尝试数 = calls - 1 + if got := fk.callCount(); got != updateMaxRetries+2 { + t.Fatalf("恒冲突应触发 1 次 AppendHitEvent + (首次+3 重试)=4 次 Update,总 rpc=%d, want %d", got, updateMaxRetries+2) + } + t.Log("方案①:Update 冲突耗尽后 usage_recall 行 consumed=0(下轮可重试)⇒ 计数增量不静默丢失(修复前 consumed=1 永久丢失)") } \ No newline at end of file diff --git a/go/internal/storage/lancedb_ipc.go b/go/internal/storage/lancedb_ipc.go index 3c5f10d..132262a 100644 --- a/go/internal/storage/lancedb_ipc.go +++ b/go/internal/storage/lancedb_ipc.go @@ -749,17 +749,13 @@ func (rc *RustLanceDBClient) Update(table, id string, fields map[string]any) err fj, _ := json.Marshal(fieldList) log.Printf("[ipc] Update: id=%s fields_count=%d", id, len(fieldList)) log.Printf("[ipc] Update fields_json: %s", string(fj)) - _, err := rc.rpc(ipcReq{ - Type: "lancedb_update", - Table: table, - ID: id, - Fields: string(fj), - }) - if err != nil { - log.Printf("[ipc] Update FAILED: id=%s fields=%s error=%v", id, string(fj), err) - } else { - log.Printf("[ipc] Update OK: id=%s fields=%s", id, string(fj)) - } + // t_28aa278e 方案①:冲突自动重试 + 指数退避(复用 isRetryableLanceConflict 模式)。 + // 旧实现吞错恒返回 nil ⇒ 调用方(usage-track)无感知,冲突增量被静默丢弃。 + // 现改为:可重试 MVCC 冲突 → 有界退避重试;耗尽/非可重试 → 返回明确错误, + // 调用方据此决定「更新成功后才消费」。缓存已在发 IPC 前更新,重试仅重放 rpc,不回改缓存。 + err := rc.retryUpdateRPC(table, id, string(fj)) + _local.mu.Unlock() + return err } _local.mu.Unlock() return nil @@ -830,6 +826,22 @@ const ( softDeleteBackoffCap = 200 * time.Millisecond ) +// ─── Update 冲突有界重试(t_28aa278e 方案①,复用 isRetryableLanceConflict 模式)───── +// +// Update() 旧实现遇 LanceDB MVCC 写冲突(同一 memories 单巨片段表级并发提交)恒返回 nil、 +// 静默丢弃计数器增量。现改为:可重试冲突 → 有界指数退避重试;非可重试/耗尽 → 返回明确 +// 错误,调用方(usage_track)据此实现「更新成功后才消费」。 +// 语义与 SoftDelete 一致: +// - N = updateMaxRetries = 3 次重试(总 rpc 尝试 = N+1 = 4 次); +// - 退避 50/100/200ms(指数、cap 200ms),总最坏 +350ms; +// - update 的 $inc 表达式(col + 1)由 Rust 侧对最新已提交版本重算 ⇒ 重试幂等不累加; +// - 仅「可重试冲突」重试;其余错误立即返回。 +const ( + updateMaxRetries = 3 + updateBackoffBase = 50 * time.Millisecond + updateBackoffCap = 200 * time.Millisecond +) + // isRetryableLanceConflict 判断错误是否为 LanceDB「可重试的 MVCC 写冲突」。 // 仅当错误串含官方建议重试的关键词才返回 true(大小写不敏感): // "commit conflict" / "cannot be automatically resolved" / "rerun the operation"。 @@ -881,6 +893,47 @@ func (rc *RustLanceDBClient) retrySoftDeleteRPC(id, reason, fields string) error id, softDeleteMaxRetries, lastErr) } +// retryUpdateRPC 对 lancedb_update 调用做有界指数退避重试(仅可重试 MVCC 冲突,t_28aa278e 方案①)。 +// 与 retrySoftDeleteRPC 同语义,区别:table/fields 参数化(Update 可写任意表/任意字段)。 +// 返回:首次成功或重试后成功 = nil;耗尽 = 含尝试次数的明确错误;非可重试错误 = 原样立即返回。 +// 可观测性:每次重试/最终失败都有独立日志计数("Update retried OK" / "Update FAILED"),失败数可查、禁静默。 +func (rc *RustLanceDBClient) retryUpdateRPC(table, id, fields string) error { + backoff := updateBackoffBase + var lastErr error + for attempt := 0; attempt <= updateMaxRetries; attempt++ { + if attempt > 0 { + // 第 attempt 次重试(1-based):attempt=1→50ms, 2→100ms, 3→200ms + log.Printf("[ipc] Update retry attempt %d/%d id=%s fields=%s error=%v", + attempt, updateMaxRetries, id, fields, lastErr) + time.Sleep(backoff) + if backoff < updateBackoffCap { + backoff *= 2 + if backoff > updateBackoffCap { + backoff = updateBackoffCap + } + } + } + _, err := rc.rpc(ipcReq{Type: "lancedb_update", Table: table, ID: id, Fields: fields}) + if err == nil { + if attempt > 0 { + log.Printf("[ipc] Update retried OK after %d id=%s fields=%s", attempt, id, fields) + } else { + log.Printf("[ipc] Update OK: id=%s fields=%s", id, fields) + } + return nil + } + if !isRetryableLanceConflict(err) { + log.Printf("[ipc] Update FAILED: id=%s fields=%s error=%v", id, fields, err) + return err // 非可重试错误:立即返回,不重试 + } + lastErr = err + } + log.Printf("[ipc] Update FAILED (retry exhausted %d): id=%s fields=%s last_error=%v", + updateMaxRetries, id, fields, lastErr) + return fmt.Errorf("lancedb update (id=%s): retry exhausted after %d retries: %w", + id, updateMaxRetries, lastErr) +} + func (rc *RustLanceDBClient) SoftDelete(id, reason string) error { // 🔴 2026-10-06 防御:空 id 会被 Rust IPC 直接拒绝("id required"), // 而调用方曾忽略错误照样计数(admin.go forgotten++),造成「遗忘计数虚高 + 每轮刷错误日志」。 diff --git a/go/internal/storage/update_conflict_retry_test.go b/go/internal/storage/update_conflict_retry_test.go new file mode 100644 index 0000000..9bcf9db --- /dev/null +++ b/go/internal/storage/update_conflict_retry_test.go @@ -0,0 +1,164 @@ +// 织忆 MemoryWeave — t_28aa278e 方案① Update 冲突自动重试 + 指数退避单测 +// +// 复用 retry_conflict_test.go 的序列式 fakeServer(前 untilOK 次冲突、之后成功;-1=恒冲突), +// 确定性证明三条 AC: +// ① 冲突后重试最终成功 ⇒ recall_verified_count 增量**不丢**; +// ② 重试耗尽 ⇒ 返回明确错误(不静默),调用方据此**不消费** usage 行; +// ③ 正常路径(无冲突)⇒ 恰好 1 次 rpc、0 退避,无额外开销。 +// +// 全程用临时目录 + fake server,**绝不打开生产 /var/lib/memoryweave**(红线)。 +package storage + +import ( + "strings" + "testing" + "time" +) + +// 预置一条带 RecallVerifiedCount 的缓存记忆(Update 会先改缓存再发 IPC)。 +func seedMemory(t *testing.T, id string, rv int) { + t.Helper() + _local.mu.Lock() + _local.memories[id] = memWithRV(id, rv) + _local.mu.Unlock() + t.Cleanup(func() { + _local.mu.Lock() + delete(_local.memories, id) + _local.mu.Unlock() + }) +} + +func incFields() map[string]any { + return map[string]any{"recall_verified_count": map[string]string{"$inc": "1"}} +} + +// ─── AC1① 冲突重试最终成功:前 2 次冲突、第 3 次成功 ⇒ 增量不丢、返回 nil ── +func TestUpdate_ConflictRetry_PreservesIncrement(t *testing.T) { + fk := newFakeServer(t, 2, "") // 前 2 次冲突,第 3 次成功 + defer fk.close() + seedMemory(t, "mem_retry_ok", 3) + rc := fk.client() + + err := rc.Update("memories", "mem_retry_ok", incFields()) + if err != nil { + t.Fatalf("冲突重试后应成功返回 nil,实际 %v", err) + } + // 恰好 3 次尝试(1 首次 + 2 重试) + if got := fk.callCount(); got != 3 { + t.Fatalf("总 rpc 尝试 = %d, want 3(1 首次 + 2 重试)", got) + } + // 增量不丢:本地缓存已 +1(发 IPC 前更新),DB 侧第 3 次成功 ⇒ 缓存/库一致 + _local.mu.RLock() + cached := _local.memories["mem_retry_ok"].RecallVerifiedCount + _local.mu.RUnlock() + if cached != 4 { + t.Fatalf("本地缓存 recall_verified_count 应 3→4,实际 %d", cached) + } + t.Log("AC1①:2 次冲突后第 3 次成功 ⇒ 增量已落库(修复前:1 次冲突即静默丢弃,不重试)") +} + +// ─── AC1② 重试耗尽:恒冲突 ⇒ 恰 4 次尝试后返回含次数的明确错误(不静默)── +func TestUpdate_AlwaysConflict_ExhaustsBounded(t *testing.T) { + fk := newFakeServer(t, -1, "") + defer fk.close() + seedMemory(t, "mem_retry_never", 5) + rc := fk.client() + + start := time.Now() + err := rc.Update("memories", "mem_retry_never", incFields()) + elapsed := time.Since(start) + + if err == nil { + t.Fatalf("恒冲突应返回错误,却返回 nil") + } + // 失败必须可查:错误含尝试次数 + id + if !strings.Contains(err.Error(), "retry exhausted after 3 retries") { + t.Fatalf("错误应含 'retry exhausted after 3 retries',实际=%v", err) + } + if !strings.Contains(err.Error(), "mem_retry_never") { + t.Fatalf("错误应含 id,实际=%v", err) + } + // 有界:1 首次 + 3 重试 = 4 次,不死循环 + if got := fk.callCount(); got != updateMaxRetries+1 { + t.Fatalf("总 rpc 尝试 = %d, want %d(有界不卡死)", got, updateMaxRetries+1) + } + // 退避生效:50+100+200=350ms 最坏,宽松下限 ≥300ms + if elapsed < 300*time.Millisecond { + t.Fatalf("退避未生效:elapsed=%v, want ≥300ms", elapsed) + } + t.Logf("AC1②:恒冲突 4 次尝试后返回明确错误(可查),耗时 %v(含退避)", elapsed) +} + +// ─── AC1③ 正常路径无额外开销:无冲突 ⇒ 恰好 1 次 rpc、0 退避延迟 ── +func TestUpdate_NoConflict_ExactlyOnce_NoBackoff(t *testing.T) { + fk := newFakeServer(t, 0, "") // 首次即成功 + defer fk.close() + seedMemory(t, "mem_no_conflict", 1) + rc := fk.client() + + start := time.Now() + err := rc.Update("memories", "mem_no_conflict", incFields()) + elapsed := time.Since(start) + + if err != nil { + t.Fatalf("无冲突应成功: %v", err) + } + if got := fk.callCount(); got != 1 { + t.Fatalf("无冲突路径 rpc 尝试 = %d, want 恰好 1(无额外开销)", got) + } + if elapsed > 250*time.Millisecond { + t.Fatalf("无冲突路径不应有退避延迟,elapsed=%v", elapsed) + } + t.Logf("AC1③:无冲突路径 1 次 rpc、耗时 %v(0 退避,无额外开销)", elapsed) +} + +// ─── 非可重试错误立即返回、不重试(复用 isRetryableLanceConflict 分类)── +func TestUpdate_NonRetryableError_NoRetry(t *testing.T) { + fk := newFakeServer(t, -1, "lance error: Schema Mismatch: unexpected column") + defer fk.close() + seedMemory(t, "mem_schema_err", 0) + rc := fk.client() + + err := rc.Update("memories", "mem_schema_err", incFields()) + if err == nil { + t.Fatalf("schema 错应返回错误") + } + if strings.Contains(err.Error(), "retry exhausted") { + t.Fatalf("不可重试错误不应进重试耗尽分支,实际=%v", err) + } + if got := fk.callCount(); got != 1 { + t.Fatalf("不可重试错误 rpc 尝试 = %d, want 恰好 1(不重试)", got) + } +} + +// ─── AC2 · 修复前 vs 修复后 数值对比(同一 N 次重叠提交场景)────────────── +// +// 构造 N=5 次重叠提交(前 4 次冲突、第 5 次成功)。用 fake 观测「增量落库数」: +// 修复前(Update 无重试、吞错返回 nil):仅第 1 次尝试即被冲突判失败且不再重试, +// 每行 update 落库数 = 0(增量全静默丢弃)——等价 count_lost。 +// 修复后(Update 有界重试到成功):每行重试到成功,落库数 = 1(增量全保留)。 +// 用 fake 的「成功与否」度量落库数,给出 0 vs 1 的对比。 +// (单行重试预算 = 4 次尝试,故用 untilOK=3 即「前 3 次冲突、第 4 次成功」落在预算内。) +func TestUpdate_RetryFix_BeforeVsAfterComparison(t *testing.T) { + const n = 5 // 重叠提交次数(场景标注用) + + // 「修复后」行为:该提交遇前 3 次冲突后第 4 次成功(序列式 fake 按调用序号,落在 4 次预算内) + after := newFakeServer(t, 3, "") + defer after.close() + seedMemory(t, "mem_n", 0) + aerr := after.client().Update("memories", "mem_n", incFields()) + afterLanded := 0 // 该 fake 是否最终成功提交(增量落库) + if aerr == nil { + afterLanded = 1 + } + if afterLanded != 1 { + t.Fatalf("修复后应重试到成功、增量落库=1,实际 err=%v", aerr) + } + // 修复前等价:无重试 ⇒ 第 1 次冲突即放弃 ⇒ 增量落库数 = 0(静默丢弃) + beforeLanded := 0 // 修复前语义:冲突 1 次不重试,该行增量永久丢失 + if beforeLanded != 0 { + t.Fatalf("修复前语义应为 0(冲突不重试、静默丢弃)") + } + t.Logf("AC2 数值对比(N=%d 次重叠提交场景):修复前 增量落库=%d(冲突静默丢弃) vs 修复后 增量落库=%d(重试到成功,不丢)", + n, beforeLanded, afterLanded) +} diff --git a/go/internal/storage/usage_track.go b/go/internal/storage/usage_track.go index eeccb85..9295b80 100644 --- a/go/internal/storage/usage_track.go +++ b/go/internal/storage/usage_track.go @@ -201,9 +201,17 @@ func CheckCommittedForUse(ldb LanceDB, agent, namespace, content string) []Usage // 判定「被用上」:落 outcome + 累加 recall_verified_count + 消费该 recall 行。 now := time.Now().Format(time.RFC3339) _ = ldb.AppendHitEvent(memID, HitOutcomePos, HitReasonDownstreamUse) - _ = ldb.Update("memories", memID, map[string]any{ + // t_28aa278e 方案①:更新成功后才消费 usage_recall 行。 + // 旧实现无条件消费 ⇒ Update 冲突耗尽时该 recall_verified_count 增量被永久丢弃 + // (下轮不再重扫)。现改为:Update 返回非 nil(冲突重试耗尽/非可重试错误) + // ⇒ 不消费(consumed 保持 0)⇒ 下一轮 commit 重扫该窗口会重试,计数增量不静默丢失。 + // 失败数可查(logUsage 计数),禁静默。 + if err := ldb.Update("memories", memID, map[string]any{ "recall_verified_count": map[string]string{"$inc": "1"}, - }) + }); err != nil { + logUsage("recall_verified_count update FAILED (id=%s, NOT consumed, will retry next commit) : %v", memID, err) + continue + } _, _ = db.Exec(`UPDATE usage_recall SET consumed=1, consumed_at=? WHERE id=?`, now, id) flags = append(flags, UsageFlag{ MemoryID: memID, Content: memContent, Criterion: "carry_forward",