From c7ceb11cda4e4a29ed093172cb21fe895ce1a255 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=B0=8F=E5=94=AF?= Date: Mon, 21 Sep 2026 21:58:52 +0800 Subject: [PATCH] =?UTF-8?q?fix(distill):=20LLM=20=E8=B0=83=E7=94=A8?= =?UTF-8?q?=E9=80=80=E9=81=BF/=E7=86=94=E6=96=AD=20+=20=E6=88=AA=E6=96=AD?= =?UTF-8?q?=20JSON=20=E5=AE=B9=E9=94=99=20(t=5F9b2c7943=20AC1+AC3)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit AC1: callLLM5D 遇 429/5xx 指数退避+抖动重试 (<=2 次额外重试, 单次退避 <=8s, +/-25% 抖动防惊群)。原实现首次 429/网络错即 return err, 上层立刻 fallbackSingle 启发式降级 (质量下降)。现在先退避重试, 真超限才走 fallback。 AC3: max_tokens 1200 提到 2400 (prompt "facts 要详尽" 与 1200 自相矛盾, 截断 JSON 导致 parse 失败丢整条)。新增 recoverTruncatedJSON: 被 max_tokens 截断的 JSON 用 [ { 栈补齐 + 闭合未闭字符串 + 截到最后一个 配平 } 救回"最后完整对象", 不再直接 parse 失败。救不回时返回 error, 上层 fallbackSingle (保留启发式 fact)。 新增测试 engine_backoff_recover_test.go (5 个): - 429->200: 调用次数>1 / 两次间隔>0(真退避) / 最终成功未走 fallback - 5xx->200 同样恢复 - 截断 JSON 救回 facts (含尾部垃圾、无骨架两条边界) 仅改码 + 提交, 未部署/未重启 zhiyid (等 09-23 窗口, 见卡 AC2)。 Co-Authored-By: prof-cloud --- go/internal/distill/engine.go | 215 ++++++++++++++++-- .../distill/engine_backoff_recover_test.go | 149 ++++++++++++ 2 files changed, 349 insertions(+), 15 deletions(-) create mode 100644 go/internal/distill/engine_backoff_recover_test.go diff --git a/go/internal/distill/engine.go b/go/internal/distill/engine.go index bcf4a68..beb131b 100644 --- a/go/internal/distill/engine.go +++ b/go/internal/distill/engine.go @@ -9,6 +9,7 @@ import ( "fmt" "io" "log" + "math/rand" "net/http" "strings" "sync" @@ -420,7 +421,10 @@ func (e *Engine) callLLM5D(content string) (LLMResponse, error) { {"role": "user", "content": prompt}, }, "temperature": 0.2, - "max_tokens": 1200, + // AC3 (t_9b2c7943): 1200→2400。prompt 里"facts 要详尽"与 max_tokens 自相矛盾—— + // 1200 会在 facts 数组中途截断 → 非法 JSON → 直接 parse 失败丢整条。提到 2400 给足 + // 详尽 facts 的空间;即使仍截断,下方 recoverTruncatedJSON 会兜底救回。 + "max_tokens": 2400, } jsonBody, err := json.Marshal(body) @@ -428,22 +432,67 @@ func (e *Engine) callLLM5D(content string) (LLMResponse, error) { return LLMResponse{}, err } - req, err := http.NewRequest("POST", e.LLMEndpoint, bytes.NewReader(jsonBody)) - if err != nil { - return LLMResponse{}, err - } - req.Header.Set("Content-Type", "application/json") - if e.APIKey != "" { - req.Header.Set("Authorization", "Bearer "+e.APIKey) + // AC1 (t_9b2c7943): 429/5xx 指数退避 + 抖动重试(上限 2 次额外重试,退避上限 ~8s)。 + // 原实现:client.Do 失败/限流 → 直接 return err → 上层 distillOne 立刻 fallbackSingle + // (启发式降级、质量下降)。现在:遇 429 或 5xx,先退避重试,真不行再走 fallback。 + // 抖动避免并发 3 条同时醒来再次撞 429(惊群)。 + const ( + maxRetries = 2 // 额外重试次数(首次不算) + initialDelay = 300 * time.Millisecond + maxDelay = 8 * time.Second // 单次退避上限 + ) + rng := newRand() + + var respBody []byte + var lastStatus int + for attempt := 0; ; attempt++ { + req, reqErr := http.NewRequest("POST", e.LLMEndpoint, bytes.NewReader(jsonBody)) + if reqErr != nil { + return LLMResponse{}, reqErr + } + req.Header.Set("Content-Type", "application/json") + if e.APIKey != "" { + req.Header.Set("Authorization", "Bearer "+e.APIKey) + } + + resp, doErr := e.client.Do(req) + if doErr != nil { + // 网络/超时错误:可重试;到上限即上抛,让上层走 fallback。 + if attempt < maxRetries { + d := backoffDelay(attempt, initialDelay, maxDelay, rng) + log.Printf("[distill] callLLM5D transient err (attempt %d/%d): %v → retry in %v", + attempt+1, maxRetries, doErr, d) + time.Sleep(d) + continue + } + return LLMResponse{}, doErr + } + + status := resp.StatusCode + respBody, _ = io.ReadAll(resp.Body) + resp.Body.Close() + lastStatus = status + + if status == http.StatusTooManyRequests || (status >= 500 && status <= 599) { + // 429 / 5xx:指数退避 + 抖动后重试;到上限即跳出(走 fallback,body 已读)。 + if attempt < maxRetries { + d := backoffDelay(attempt, initialDelay, maxDelay, rng) + log.Printf("[distill] callLLM5D HTTP %d (attempt %d/%d) → backoff %v | body=%q", + status, attempt+1, maxRetries, d, truncate(string(respBody), 120)) + time.Sleep(d) + continue + } + break // 超限:保留最后一次 body,下方按 429/5xx 上抛 + } + + break // 2xx 成功 } - resp, err := e.client.Do(req) - if err != nil { - return LLMResponse{}, err + // 退出循环:若最后仍是 429/5xx(重试上限耗尽)→ 上抛 error,让 distillOne 走 fallback。 + if lastStatus == http.StatusTooManyRequests || (lastStatus >= 500 && lastStatus <= 599) { + return LLMResponse{}, fmt.Errorf("callLLM5D: HTTP %d after retries | body=%q", + lastStatus, truncate(string(respBody), 200)) } - defer resp.Body.Close() - - respBody, _ := io.ReadAll(resp.Body) var result struct { Choices []struct { @@ -487,7 +536,23 @@ func (e *Engine) callLLM5D(content string) (LLMResponse, error) { } llmContent = strings.TrimSpace(llmContent) if err := json.Unmarshal([]byte(llmContent), &llmResp); err != nil { - log.Printf("[distill] LLM JSON parse error: %v | content=%q", err, truncate(llmContent, 200)) + // AC3 (t_9b2c7943): 截断 JSON 容错。max_tokens 截断会把 facts 数组切到一半 → + // 尾部 "}" 缺失 → 非法 JSON。不再直接丢整条,先救回"最后完整对象"再解析。 + recovered, ok := recoverTruncatedJSON(llmContent) + if ok { + log.Printf("[distill] LLM JSON truncated, recovered last complete object (%d→%d bytes)", + len(llmContent), len(recovered)) + llmContent = recovered + } else { + log.Printf("[distill] LLM JSON parse error: %v | content=%q", err, truncate(llmContent, 200)) + return LLMResponse{}, fmt.Errorf("parse score: %w", err) + } + } + if err := json.Unmarshal([]byte(llmContent), &llmResp); err != nil { + // 救回后仍解析失败(极端情况):记录但不静默——返回 error 让上层走 + // fallbackSingle(保留启发式 fact),而不是把整条 episode 当空结果丢掉。 + log.Printf("[distill] LLM JSON parse error after recovery: %v | content=%q", + err, truncate(llmContent, 200)) return LLMResponse{}, fmt.Errorf("parse score: %w", err) } @@ -502,6 +567,126 @@ func (e *Engine) callLLM5D(content string) (LLMResponse, error) { return llmResp, nil } +// AC1 辅助:指数退避 + 抖动。 +// 基础为指数(initialDelay << attempt),封顶 maxDelay;叠加 ±25% 抖动避免惊群。 +// 用 math/rand(Go 1.20+ 全局自动随机化,无需手动 seed)。 +func newRand() *rand.Rand { return rand.New(rand.NewSource(time.Now().UnixNano())) } + +// backoffDelay 返回第 attempt 次(0 基)重试前应等待的时长: +// attempt 0 → ~300ms,attempt 1 → ~600ms(指数翻倍),封顶 maxDelay,再叠 ±25% 抖动。 +func backoffDelay(attempt int, initial, max time.Duration, r *rand.Rand) time.Duration { + d := initial << attempt + if d > max { + d = max + } + // 抖动:在 [d*0.75, d*1.25] 内随机,避免并发请求同时醒来再次撞 429。 + jitterFactor := 0.75 + 0.5*r.Float64() + d = time.Duration(float64(d) * jitterFactor) + if d < initial { + d = initial + } + return d +} + +// recoverTruncatedJSON 把被 max_tokens 截断的 JSON 救回成「最后一个完整对象」。 +// +// 场景:LLM 输出 {"facts":["a","b","c 中途被 max_tokens 截断,尾部 } 缺失(甚至 [ 也缺失) +// → 直接 Unmarshal 报错。本函数从外向内逐步补齐,任一成功即返回。 +// +// 策略: +// ① 先找「最后一个配平的最外层 }」:若截断发生在外层对象之外(尾部多了一段被切的 +// 额外内容),截到那个 } 丢弃尾部即可,json.Valid 通过 → 直接返回。 +// ② 否则(截在外层对象内部):用栈记录所有未闭合的 [ 和 {,从尾部逐个补 ] 和 } +// (栈顶先补,保证嵌套顺序正确);若截在字符串字面量中间,先补闭合引号。 +// 补齐后 json.Valid 通过 → 返回。 +// ③ 救不出对象骨架(连最外层 { 都没了 / 纯文本)→ 返回 ("", false),上层走 fallback。 +// +// 注意:补齐后得到的可能是「截断前已完整的那些条目」,而非完整 facts——这正是容错目标 +// (保留能救的部分,而不是把整条 episode 当空结果丢弃)。 +func recoverTruncatedJSON(s string) (string, bool) { + s = strings.TrimSpace(s) + if s == "" { + return "", false + } + + // 扫描一遍:跟踪字符串状态、栈([ { 的开闭)。同时记录「深度归 0 的最后一个 }」位置。 + // 栈元素:'[' 或 '{'。 + var stack []byte + inString := false + escape := false + depthZeroAt := -1 // 最外层对象({ 深度归 0)的最后结束位置 + for i := 0; i < len(s); i++ { + c := s[i] + if escape { + escape = false + continue + } + switch c { + case '\\': + if inString { + escape = true + } + case '"': + inString = !inString + case '{': + if !inString { + stack = append(stack, '{') + } + case '[': + if !inString { + stack = append(stack, '[') + } + case '}': + if !inString { + if len(stack) > 0 && stack[len(stack)-1] == '{' { + stack = stack[:len(stack)-1] + } + if len(stack) == 0 { + depthZeroAt = i // 记最外层对象终点(多次则取最后一次) + } + } + case ']': + if !inString { + if len(stack) > 0 && stack[len(stack)-1] == '[' { + stack = stack[:len(stack)-1] + } + } + } + } + + // ① 有完整外层对象(深度曾归 0):截到最后一个配平 } 即可,丢弃尾部半截内容。 + if depthZeroAt >= 0 { + candidate := s[:depthZeroAt+1] + if json.Valid([]byte(candidate)) { + return candidate, true + } + } + + // ② 截在对象内部:补齐未闭合的 [ { 与未闭合的字符串。 + // 从栈尾(最内层)到栈底(最外层)逐个补对应的闭合符。 + var patch strings.Builder + // 若截在字符串字面量中间(最后一个 " 之后未闭合),先补一个引号闭合它。 + if inString { + patch.WriteByte('"') + } + // 栈尾 → 栈底(最内层先补) + for i := len(stack) - 1; i >= 0; i-- { + switch stack[i] { + case '{': + patch.WriteByte('}') + case '[': + patch.WriteByte(']') + } + } + candidate := s + patch.String() + if json.Valid([]byte(candidate)) { + return candidate, true + } + + // 兜底:连最外层 { 都没了(骨架残缺)或补齐后仍非法 → 救不出,返回失败。 + return "", false +} + // extractFacts 从内容中提取事实和实体(关键词 + 命名实体启发式) func (e *Engine) extractFacts(content string) ([]string, []Entity) { var facts []string diff --git a/go/internal/distill/engine_backoff_recover_test.go b/go/internal/distill/engine_backoff_recover_test.go new file mode 100644 index 0000000..a03cb35 --- /dev/null +++ b/go/internal/distill/engine_backoff_recover_test.go @@ -0,0 +1,149 @@ +package distill + +import ( + "encoding/json" + "net/http" + "net/http/httptest" + "sync" + "sync/atomic" + "testing" + "time" +) + +// AC1 (t_9b2c7943):429/5xx 指数退避 + 抖动。 +// httptest 桩「先 429 再 200」,断言: +// ① 调用次数 >1(真的重试了,不是首次 429 就 fallback) +// ② 两次调用间隔 >0(真的退避了,不是立即重发) +// ③ 最终成功、未走 fallback(返回合法 LLMResponse,而非 error→fallbackSingle) +func TestCallLLM5D_BackoffOn429ThenSucceeds(t *testing.T) { + var calls int32 + var ts []time.Time + var tsMu sync.Mutex + + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + n := atomic.AddInt32(&calls, 1) + tsMu.Lock() + ts = append(ts, time.Now()) + tsMu.Unlock() + + if n == 1 { + // 第一次返回 429(限流) + w.Header().Set("Content-Type", "application/json") + w.WriteHeader(http.StatusTooManyRequests) + _, _ = w.Write([]byte(`{"error":"rate limited"}`)) + return + } + // 之后返回 200 + 合法 body + w.Header().Set("Content-Type", "application/json") + _, _ = w.Write([]byte(testLLMBody)) + })) + defer srv.Close() + + e := NewEngine(srv.URL, "test-model", "test-key") + resp, err := e.callLLM5D("用户今天买了咖啡") + if err != nil { + t.Fatalf("判据③未满足:callLLM5D 报错(疑似走了 fallback / 重试耗尽): %v", err) + } + // ① 真的重试了:调用次数 >1 + if c := atomic.LoadInt32(&calls); c < 2 { + t.Fatalf("判据①未满足:429 后未重试,调用次数=%d(期望 ≥2)", c) + } + // ② 两次调用间隔 >0(真的退避了) + tsMu.Lock() + if len(ts) < 2 { + tsMu.Unlock() + t.Fatalf("判据②无法验证:仅记录到 %d 次调用(期望 ≥2)", len(ts)) + } + gap := ts[1].Sub(ts[0]) + tsMu.Unlock() + if gap <= 0 { + t.Fatalf("判据②未满足:两次调用间隔=%v(应为正数,即真的退避了)", gap) + } + // ③ 最终成功且内容正确(未走 fallback:facts 来自 LLM 而非启发式) + if len(resp.Facts) == 0 { + t.Fatalf("判据③未满足:LLMResponse.Facts 为空(疑似走了 fallback 启发式)") + } + t.Logf("✅ AC1: 429→200 成功,调用次数=%d, 间隔=%v, facts=%v", + atomic.LoadInt32(&calls), gap, resp.Facts) +} + +// AC1 补充:5xx(如 503)同样应触发退避重试,且「先 503 再 200」最终成功。 +func TestCallLLM5D_BackoffOn5xxThenSucceeds(t *testing.T) { + var calls int32 + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + n := atomic.AddInt32(&calls, 1) + if n == 1 { + w.Header().Set("Content-Type", "application/json") + w.WriteHeader(http.StatusServiceUnavailable) + _, _ = w.Write([]byte(`{"error":"server busy"}`)) + return + } + w.Header().Set("Content-Type", "application/json") + _, _ = w.Write([]byte(testLLMBody)) + })) + defer srv.Close() + + e := NewEngine(srv.URL, "test-model", "test-key") + resp, err := e.callLLM5D("用户今天买了咖啡") + if err != nil { + t.Fatalf("503 后未恢复: %v", err) + } + if c := atomic.LoadInt32(&calls); c < 2 { + t.Fatalf("5xx 后未重试,调用次数=%d(期望 ≥2)", c) + } + if len(resp.Facts) == 0 { + t.Fatalf("facts 为空(疑似走了 fallback)") + } + t.Logf("✅ AC1(5xx): 503→200 成功,调用次数=%d", atomic.LoadInt32(&calls)) +} + +// AC3 (t_9b2c7943):截断 JSON 容错。 +// 喂一个被 max_tokens 截断的 JSON(facts 数组中途被切、尾部 } 缺失), +// 断言 recoverTruncatedJSON 能救回「最后完整对象」并解析出 facts。 +func TestRecoverTruncatedJSON(t *testing.T) { + // 模拟:LLM 输出在 facts 数组第 3 条中途被截断(缺尾 }) + truncated := `{"facts":["用户今天买了咖啡","用户在读马哲经济学","用户讨论了剪辑软件` + recovered, ok := recoverTruncatedJSON(truncated) + if !ok { + t.Fatalf("判据未满足:截断 JSON 救不回任何对象 | input=%q", truncated) + } + + var resp LLMResponse + if err := json.Unmarshal([]byte(recovered), &resp); err != nil { + t.Fatalf("救回的字符串仍无法解析: %v | recovered=%q", err, recovered) + } + if len(resp.Facts) == 0 { + t.Fatalf("判据未满足:救回的 facts 为空(应至少保留截断前已完整的条目)") + } + t.Logf("✅ AC3: 截断 JSON 救回 facts=%d 条 → %v", len(resp.Facts), resp.Facts) +} + +// AC3 补强:截在最外层对象「之外」(尾部多了一段被切的数组/字段), +// recoverTruncatedJSON 应截到最后一个配平 } 并成功。 +func TestRecoverTruncatedJSON_TailGarbage(t *testing.T) { + // 外层对象完整,但尾部又跟了一段被截断的额外内容(模型把 JSON 写长了再被切) + input := `{"facts":["a","b"],"is":0.9,"su":0.8,"pa":0.7,"vd":0.9,"ru":0.8},{"extra":"被截断的尾部` + recovered, ok := recoverTruncatedJSON(input) + if !ok { + t.Fatalf("判据未满足:带尾部垃圾的 JSON 救不回 | input=%q", input) + } + var resp LLMResponse + if err := json.Unmarshal([]byte(recovered), &resp); err != nil { + t.Fatalf("救回字符串无法解析: %v | recovered=%q", err, recovered) + } + if len(resp.Facts) != 2 { + t.Fatalf("facts 数量不符: 期望 2, 实得 %d | recovered=%q", len(resp.Facts), recovered) + } + t.Logf("✅ AC3 补强: 截到最后一个配平 },facts=%v", resp.Facts) +} + +// AC3 兜底路径:连最外层 { 都没了(骨架残缺 / 纯文本)→ 救不回,必须返回 ok=false。 +// 保证「救不回时不再抛 parse error」由 callLLM5D 上层兜底(fallbackSingle)。 +func TestRecoverTruncatedJSON_UncountableReturnsFalse(t *testing.T) { + // 纯文本、无任何 JSON 骨架:救不回对象,应明确失败(上层走 fallback) + input := "用户今天说了一大段话但完全没有给出JSON结构" + if _, ok := recoverTruncatedJSON(input); ok { + t.Fatalf("无 JSON 骨架的字符串不应被「救回」,应返回 ok=false | input=%q", input) + } + t.Logf("✅ AC3 兜底: 无 JSON 骨架 → ok=false(上层走 fallback,不再抛 parse error)") +}