Files
memoryweave/go/internal/distill/engine_flush_ticker_test.go
T
小唯 886c0c20e2 style(gofmt): 全仓 66 文件对齐 gofmt 1.25
gofmt -l 实测 66 文件不合规(历史遗留+gofmt 1.25 规范化:
单行 if/for/case 展开成块、Go1.19+ doc 注释 // 与段落 // 空行)。
本 commit 只含格式化,零逻辑改动:
- 66/66 文件「去注释+去空白+分号归一」后 token 流与 HEAD 完全一致
- go build ./... exit 0;go vet ./... exit 0(改前后一致)
- go test ./... 17 包全 ok(改前后一致)
验收: gofmt -l . 为空;git diff -w 非空系 gofmt 1.25 非纯空白特性,
非逻辑改动(等价性以 token 流 + test 兜底)。
2026-10-10 15:51:25 +08:00

134 lines
5.2 KiB
Go
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
package distill
import (
"net/http"
"net/http/httptest"
"sync/atomic"
"testing"
"time"
)
// ─── 2026-10-06 修复回归测试:flush 兜底 ticker ────────────────────────
//
// 修复的 bug:flush 触发原先**只挂在 Enqueue 入口** —— shouldFlush / timeout 两者
// 都只在「有新条目入队」时求值,全仓无任何 ticker 驱动。叠加守卫静默丢弃后永久冻结:
// ① 大批量入队撞上正在跑的 flush ⇒ flushing.CompareAndSwap 失败 ⇒ 直接 return(无补偿)
// ② flush 入口即整批取走队列(batch := e.queue; e.queue = nil)⇒ 后来条目不在快照里
// —— 源码注释「留给它 drain 时一起取走」的假设不成立
// ③ 此后生产者停止(无新 Enqueue)⇒ 积压永不触发
//
// 线上实测:2026-10-06 13:26:09 ~ 14:20:27 冻结 **57 分钟 / 61 条**,
// 直到一条新条目入队才解冻(journal 证据:flush START batch=70 → 57min 空档 → batch=61)。
//
// 本组测试的判据核心:**不依赖任何 Enqueue 触发**,只有 ticker 能救活队列。
// tickerTestEngine 构造一个 ticker 周期被压到 period 的引擎。
// 不经 NewEngine —— 它的 batchTimeout 固定 5min,跑测试太慢。
func tickerTestEngine(t *testing.T, period time.Duration, propsHits *int32) *Engine {
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.URL.Path == "/props" {
if propsHits != nil {
atomic.AddInt32(propsHits, 1)
}
w.Header().Set("Content-Type", "application/json")
_, _ = w.Write([]byte(`{"total_slots":1}`))
return
}
w.Header().Set("Content-Type", "application/json")
_, _ = w.Write([]byte(testLLMBody))
}))
t.Cleanup(srv.Close)
e := &Engine{
LLMEndpoint: srv.URL + "/v1/chat/completions",
LLMModel: "m",
APIKey: "k",
batchSize: 10,
batchTimeout: period,
dailyLimit: 5000,
flushTokenThreshold: 2000,
client: &http.Client{Timeout: 5 * time.Second},
}
e.RefreshConcurrency()
e.startFlushTicker()
return e
}
// waitDrained 轮询等待队列清空。
func waitDrained(e *Engine, within time.Duration) bool {
deadline := time.Now().Add(within)
for time.Now().Before(deadline) {
if e.QueueLen() == 0 {
return true
}
time.Sleep(10 * time.Millisecond)
}
return false
}
const tickerTestContent = "用户今天在鹤壁买了咖啡并读了关于马哲经济学的书,下午讨论了剪辑软件选型。"
// ① 忠实复现线上场景:flush 在跑期间入队 ⇒ 触发被守卫丢弃 ⇒ 生产者停止
//
// 期望:ticker 兜底把积压消化(修复前 = 永久冻结)。
func TestFlushTickerRescuesAfterDroppedTrigger(t *testing.T) {
e := tickerTestEngine(t, 150*time.Millisecond, nil)
// 1. 占住守卫 = 模拟「一个 flush 轮次正在跑」
e.flushing.Store(true)
// 2. 入队 10 条(≥batchSize ⇒ shouldFlush=true ⇒ go e.flush())
// 但守卫被占 ⇒ CompareAndSwap 失败 ⇒ 静默 return,触发被丢弃。
const n = 10
for i := 0; i < n; i++ {
e.Enqueue(DistillInput{EpisodeID: "ep_drop", Content: tickerTestContent})
}
time.Sleep(300 * time.Millisecond) // 让注定失败的那次 flush goroutine 跑完
if got := e.QueueLen(); got != n {
t.Fatalf("前置条件不成立:期望 %d 条积压在队列(触发已被丢弃),实得 %d", n, got)
}
// 3. 轮次结束,释放守卫。此后**不再有任何 Enqueue** —— 修复前就此死锁。
e.flushing.Store(false)
// 4. 只有 ticker(周期 150ms)能救它
if !waitDrained(e, 4*time.Second) {
t.Fatal("❌ 修复未生效:守卫释放后队列未被兜底 ticker 消化(= 修复前的永久冻结行为)")
}
t.Logf("✅ ① 忠实复现:触发被守卫丢弃后,兜底 ticker 在 4s 内救活 %d 条积压", n)
}
// ② 纯积压无触发源:直接塞队列(完全绕过 Enqueue)⇒ 只有 ticker 能消化。
func TestFlushTickerRescuesIdleQueue(t *testing.T) {
e := tickerTestEngine(t, 150*time.Millisecond, nil)
e.mu.Lock()
e.queue = append(e.queue, DistillInput{EpisodeID: "ep_idle", Content: tickerTestContent})
e.mu.Unlock()
e.lastDistill = time.Now() // 抑制 timeout 分支 —— 只有 ticker 能救
if got := e.QueueLen(); got != 1 {
t.Fatalf("前置条件不成立:队列应为 1,实得 %d", got)
}
if !waitDrained(e, 4*time.Second) {
t.Fatal("❌ 兜底 ticker 未消化静止队列")
}
t.Log("✅ ② 静止队列(无任何 Enqueue)被兜底 ticker 消化")
}
// ③ 反向保护:队列为空时 ticker 不得空转触发 flush(否则每周期白探一次端点)。
func TestFlushTickerIdleWhenQueueEmpty(t *testing.T) {
var propsHits int32
e := tickerTestEngine(t, 100*time.Millisecond, &propsHits)
e.RefreshConcurrency() // 定基线
base := atomic.LoadInt32(&propsHits)
time.Sleep(600 * time.Millisecond) // ≈6 个 ticker 周期
if got := atomic.LoadInt32(&propsHits); got != base {
t.Fatalf("❌ 空队列时 ticker 空转触发了 flush:/props 探测 %d 次(基线 %d)", got, base)
}
t.Logf("✅ ③ 空队列 600ms(≈6 周期)内 ticker 零空转(/props 探测仍 %d 次)", base)
}