From b7fae4c23ba78e9cb65ce66bfcba0e78a591a6e3 Mon Sep 17 00:00:00 2001 From: xiaoyi Date: Mon, 21 Sep 2026 21:27:01 +0800 Subject: [PATCH] =?UTF-8?q?perf(distill):=20=E5=8D=95=E8=BD=AE=20flush=20?= =?UTF-8?q?=E5=86=85=E5=B9=B6=E5=8F=91=E8=92=B8=E9=A6=8F=EF=BC=88concurren?= =?UTF-8?q?cy=3D3=EF=BC=89+=20flushing=20=E5=AE=88=E5=8D=AB=E9=98=B2?= =?UTF-8?q?=E9=87=8D=E5=8F=A0=20+=20dailyUsed=20=E7=AB=9E=E6=80=81?= =?UTF-8?q?=E4=BF=AE=E5=A4=8D?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 实测瓶颈定位:摄入 ~132 条/min vs 蒸馏 11.6 条/min。 batchSize 只决定一轮取多少条(实测 batch 恒为 10、token 阈值从未触发), 真正瓶颈是 flush 内**串行**的 LLM 调用(每条 1 次 callLLM5D ≈ 5.2s)。 改:并发调用 LLM(写回仍串行)+ 防重叠守卫 + dailyUsed 原子累加。 测试:-race 下 peak=3、耗时 403ms vs 串行 1.2s、重叠触发不叠加并发、9/9 无丢条目。 未部署:等 09-23 织忆观察窗结束再上线(重启会重置日计数器污染判据)。 --- go/internal/distill/engine.go | 58 ++++++-- .../distill/engine_concurrency_test.go | 127 ++++++++++++++++++ 2 files changed, 176 insertions(+), 9 deletions(-) create mode 100644 go/internal/distill/engine_concurrency_test.go diff --git a/go/internal/distill/engine.go b/go/internal/distill/engine.go index 2f682c3..bcf4a68 100644 --- a/go/internal/distill/engine.go +++ b/go/internal/distill/engine.go @@ -12,6 +12,7 @@ import ( "net/http" "strings" "sync" + "sync/atomic" "time" "github.com/xiaoxue/memoryweave/internal/metrics" @@ -116,10 +117,24 @@ type Engine struct { dailyUsed int dailyReset time.Time + // 并发蒸馏(2026-09-21 加) + flushing atomic.Bool // 防多轮 flush 重叠:原来 go e.flush() 无互斥,队列一满就可能叠加并发打爆本地 2B + emitMu sync.Mutex // 串行化 emitResult(存储写回不并发;LLM 调用才并发) + // HTTP客户端 client *http.Client } +// distillConcurrency 单轮 flush 内并发蒸馏的条数上限。 +// +// 起因(2026-09-21 实测):摄入 ~132 条/min、蒸馏仅 11.6 条/min 且队列持续积压。 +// 逐条排查发现瓶颈**不是 batch 大小**(batchSize 只决定一轮取多少条, +// 实测 batch 恒为 10、token 阈值从未触发),而是 flush 内**串行**的 LLM 调用: +// 每条 1 次 callLLM5D ≈ 5.2s,10 条 = 52s,吞吐被单条延迟锁死。 +// 故真正的杠杆 = 让 LLM 调用并发(本地 2B 走 8081 代理,106 双槽); +// 写回 emitResult 仍串行,避免并发写存储。 +const distillConcurrency = 3 + func NewEngine(llmEndpoint, llmModel, apiKey string) *Engine { return &Engine{ LLMEndpoint: llmEndpoint, @@ -188,6 +203,13 @@ func (e *Engine) Enqueue(input DistillInput) { // flush 批量蒸馏 func (e *Engine) flush() { + // 互斥:队列一满就 go flush(),原实现允许多轮重叠 → 并发叠加打爆本地 2B 单/双槽。 + // 已有轮次在跑就直接返回,队列留给它(它 drain 时会连新来的条目一起取走)。 + if !e.flushing.CompareAndSwap(false, true) { + return + } + defer e.flushing.Store(false) + e.mu.Lock() if len(e.queue) == 0 { e.mu.Unlock() @@ -200,8 +222,8 @@ func (e *Engine) flush() { e.lastDistill = time.Now() e.mu.Unlock() - log.Printf("[distill] flush START: batch=%d items, dailyUsed=%d/%d, endpoint=%s, model=%s", - len(batch), e.dailyUsed, e.dailyLimit, e.LLMEndpoint, e.LLMModel) + log.Printf("[distill] flush START: batch=%d items, concurrency=%d, dailyUsed=%d/%d, endpoint=%s, model=%s", + len(batch), distillConcurrency, e.dailyUsed, e.dailyLimit, e.LLMEndpoint, e.LLMModel) // Phase F: 更新 LLM 调用计数 metrics.DistillLLMCallsToday.Set(float64(e.dailyUsed)) @@ -215,15 +237,33 @@ func (e *Engine) flush() { return } - // LLM 蒸馏 + // LLM 蒸馏:并发调用(吞吐杠杆),写回串行(emitMu) + var wg sync.WaitGroup + sem := make(chan struct{}, distillConcurrency) + var processed int64 for _, input := range batch { - result := e.distillOne(input) - log.Printf("[distill] distillOne done: episode=%s facts=%d entities=%d", - input.EpisodeID, len(result.Facts), len(result.Entities)) - e.dailyUsed++ - e.emitResult(input, result) + wg.Add(1) + sem <- struct{}{} // 取槽(满则阻塞,天然限流) + go func(in DistillInput) { + defer wg.Done() + defer func() { <-sem }() + result := e.distillOne(in) + log.Printf("[distill] distillOne done: episode=%s facts=%d entities=%d", + in.EpisodeID, len(result.Facts), len(result.Entities)) + atomic.AddInt64(&processed, 1) + e.emitMu.Lock() + e.emitResult(in, result) + e.emitMu.Unlock() + }(input) } - log.Printf("[distill] flush DONE: processed %d items", len(batch)) + wg.Wait() + + // dailyUsed 一次性累加(原实现每条 ++ 且无锁 = 数据竞争,/stats 读同一字段) + e.mu.Lock() + e.dailyUsed += int(atomic.LoadInt64(&processed)) + e.mu.Unlock() + + log.Printf("[distill] flush DONE: processed %d items (concurrency=%d)", len(batch), distillConcurrency) } // distillOne 蒸馏单条 diff --git a/go/internal/distill/engine_concurrency_test.go b/go/internal/distill/engine_concurrency_test.go new file mode 100644 index 0000000..83f7235 --- /dev/null +++ b/go/internal/distill/engine_concurrency_test.go @@ -0,0 +1,127 @@ +package distill + +import ( + "net/http" + "net/http/httptest" + "sync/atomic" + "testing" + "time" +) + +// 测试桩:LLM 返回一条合法的 5D + facts/entities JSON +const testLLMBody = `{"choices":[{"message":{"content":"{\"facts\":[\"用户今天买了咖啡\"],\"entities\":[\"咖啡\"],\"is\":0.9,\"su\":0.8,\"pa\":0.7,\"vd\":0.9,\"ru\":0.8}"}}]}` + +// TestFlushCallsLLMConcurrently 行为契约(2026-09-21): +// 单轮 flush 内的 LLM 调用必须**并发**(吞吐瓶颈是单条延迟 ~5.2s,串行 10 条 = 52s, +// 实测摄入 132 条/min vs 蒸馏 11.6 条/min)。 +// 判据:① 峰值并发 ≥2(并发真的生效)② 总耗时 < 条数×单条延迟(不是串行) +// ③ 峰值 ≤ distillConcurrency(限流真的生效,不会打爆本地 2B) +func TestFlushCallsLLMConcurrently(t *testing.T) { + var inflight, peak int32 + const delay = 200 * time.Millisecond + + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + n := atomic.AddInt32(&inflight, 1) + for { + p := atomic.LoadInt32(&peak) + if n <= p || atomic.CompareAndSwapInt32(&peak, p, n) { + break + } + } + time.Sleep(delay) + atomic.AddInt32(&inflight, -1) + w.Header().Set("Content-Type", "application/json") + _, _ = w.Write([]byte(testLLMBody)) + })) + defer srv.Close() + + e := NewEngine(srv.URL, "test-model", "test-key") + // 抑制 Enqueue 内的「超时自动 flush」(lastDistill 零值 → 立即超时), + // 让本轮完全由测试显式驱动,否则自动 flush 与手动 flush 竞争会让断言读到 0。 + e.lastDistill = time.Now() + const n = 6 + for i := 0; i < n; i++ { + e.Enqueue(DistillInput{ + EpisodeID: "ep_concurrency_test", + Content: "用户今天在鹤壁买了咖啡,下午读了一本关于马哲经济学的书,并讨论了剪辑软件的选型问题。", + Category: Category("fact"), + }) + } + + start := time.Now() + e.flush() // 同包测试:直接驱动一轮(避免依赖定时器) + elapsed := time.Since(start) + + gotPeak := atomic.LoadInt32(&peak) + if gotPeak < 2 { + t.Fatalf("并发未生效:LLM 峰值并发=%d(期望 ≥2)", gotPeak) + } + if gotPeak > int32(distillConcurrency) { + t.Fatalf("限流失效:峰值并发=%d > distillConcurrency=%d", gotPeak, distillConcurrency) + } + serial := time.Duration(n) * delay + if elapsed >= serial { + t.Fatalf("并发未生效:耗时 %v ≥ 串行基线 %v", elapsed, serial) + } + if q := e.QueueLen(); q != 0 { + t.Fatalf("一轮 flush 后队列应排空,实测 %d", q) + } + t.Logf("✅ peak=%d concurrency=%d elapsed=%v(串行基线 %v)", gotPeak, distillConcurrency, elapsed, serial) +} + +// TestFlushIsSerialized 契约:重叠触发不会叠加并发(原实现 go e.flush() 无互斥) +// 判据:连续多次触发后,LLM 峰值并发仍 ≤ distillConcurrency(而不是 N×concurrency) +func TestFlushIsSerialized(t *testing.T) { + var inflight, peak int32 + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + n := atomic.AddInt32(&inflight, 1) + for { + p := atomic.LoadInt32(&peak) + if n <= p || atomic.CompareAndSwapInt32(&peak, p, n) { + break + } + } + time.Sleep(120 * time.Millisecond) + atomic.AddInt32(&inflight, -1) + _, _ = w.Write([]byte(testLLMBody)) + })) + defer srv.Close() + + e := NewEngine(srv.URL, "test-model", "test-key") + e.lastDistill = time.Now() // 同上:本轮由测试显式驱动 + const total = 9 + for i := 0; i < total; i++ { + e.Enqueue(DistillInput{EpisodeID: "ep_serial_test", Content: "用户今天在鹤壁买了咖啡并读了一本关于马哲经济学的书,下午讨论了剪辑选型。"}) + } + // 手动叠加触发 5 次:只有第一轮应真正执行,其余被 flushing 守卫挡掉 + done := make(chan struct{}) + go func() { + for i := 0; i < 5; i++ { + e.flush() + time.Sleep(10 * time.Millisecond) + } + close(done) + }() + <-done + // 等本轮真正结束(队列排空 + 计数落地)——守卫只挡重叠触发,**不应丢条目** + deadline := time.Now().Add(5 * time.Second) + var used int + for time.Now().Before(deadline) { + e.mu.Lock() + used = e.dailyUsed + e.mu.Unlock() + if used == total && e.QueueLen() == 0 { + break + } + time.Sleep(20 * time.Millisecond) + } + + if used != total { + t.Fatalf("守卫丢条目:处理 %d/%d", used, total) + } + if p := atomic.LoadInt32(&peak); p > int32(distillConcurrency) { + t.Fatalf("重叠触发导致并发叠加:峰值=%d > %d", p, distillConcurrency) + } + t.Logf("✅ 重叠触发 5 次:峰值并发 %d(上限 %d)、无丢条目(%d/%d)", + atomic.LoadInt32(&peak), distillConcurrency, used, total) +}