From 34ed6347f957ef023ee24feea8b20a8c9d312057 Mon Sep 17 00:00:00 2001 From: ihsieh31 <410110@email.wlsh.tyc.edu.tw> Date: Fri, 20 Nov 2026 10:44:43 +0800 Subject: [PATCH 1/2] =?UTF-8?q?fix(responses):=20=E4=BC=BA=E6=9C=8D?= =?UTF-8?q?=E7=AB=AF=E5=B0=8D=E8=A9=B1=E6=AD=B7=E5=8F=B2=E6=9A=AB=E5=AD=98?= =?UTF-8?q?=20+=20=E6=8C=89=E6=A8=A1=E5=9E=8B=E6=9C=89=E6=95=88=E4=B8=8A?= =?UTF-8?q?=E4=B8=8B=E6=96=87=E4=B8=8A=E9=99=90?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 問題: - /v1/responses 遇 previous_response_id 直接回 400 unsupported_parameter, 依賴服務端狀態的客戶端(Claude Code / Codex / magpie 插件)收到 400 後 靜默重開對話,造成「對話到一半失憶」。 - 上游無狀態,單一 120k 上限對多數模型過於保守;上游甚至會在約 128k 靜默丟棄舊歷史,造成另一種失憶。 修改: - 新增 response_history.go:進程內對話歷史暫存(TTL 24h / 最多 500 輪), 四條路徑(透傳/合成 x 串流/非串流)皆記錄;收到 previous_response_id 時沿鏈重組完整 input 送上游,不再回 400。 - truncation:auto 且重放鏈超過上限時,裁掉最舊中段並插入 user 角色標記; 未設 truncation 則明確 400,不靜默砍歷史。 - 有效上下文上限改按模型查表:9 個免費模型 320k、glyph-cluster 256k、 mimo-2.6-flash 140k(170k 起上游靜默截斷);其餘 min(標示值, 320k)。 可用 DEEPAI2API_EFFECTIVE_CONTEXT_WINDOW / DEEPAI2API_CONTEXT_WINDOWS 覆寫。 - token 估算校準(ASCII ~1.6 bytes/token),裁剪標記改用 user 角色 (system 出現在中段會被上游 400)。 - 回歸測試 10 條全過,go test ./... 全綠。 Co-Authored-By: Claude Code --- .env.example | 8 + README.md | 80 +++- internal/server/response_history.go | 414 ++++++++++++++++++ internal/server/response_history_test.go | 518 +++++++++++++++++++++++ internal/server/responses.go | 79 +++- internal/server/responses_stream.go | 6 +- internal/server/server.go | 5 + 7 files changed, 1079 insertions(+), 31 deletions(-) create mode 100644 internal/server/response_history.go create mode 100644 internal/server/response_history_test.go diff --git a/.env.example b/.env.example index a6dc1f8..d59c693 100644 --- a/.env.example +++ b/.env.example @@ -52,3 +52,11 @@ DEEPAI2API_ALLOW_INSECURE= # deepaicode2api -seal -yes # 把存量主文件、统计与历史日志行一并封存。 DEEPAI2API_MASTER_KEY= + +# ── /v1/responses 重放有效上下文上限(按模型實測值)────────────── +# 內建按模型查表:9 個免費模型 320k、glyph-cluster 256k、mimo-2.6-flash 140k; +# 其餘 min(標示值, 320k)。一般情況無須設定,以下僅供排查/臨時調整。 +# 全域覆寫(优先级最高;0/負數 = 不設上限): +# DEEPAI2API_EFFECTIVE_CONTEXT_WINDOW=64000 +# 按模型 JSON 覆寫(值 0/負數 = 該模型不設上限;格式錯誤忽略): +# DEEPAI2API_CONTEXT_WINDOWS={"mimo-2.6-flash":140000,"glm-5.3-flash":320000} diff --git a/README.md b/README.md index 315fbb7..54acda9 100644 --- a/README.md +++ b/README.md @@ -126,10 +126,10 @@ OpenRouter 风格的 `provider`、`reasoning`、`reasoning_details`、`cost` 等 | --- | --- | ---: | ---: | ---: | --- | | `deepai-cyber` | DeepAI Cyber | 320,000 | 131,072 | **0** | 免费,纯文本 | | `deepseek-v4.1-flash` | DeepSeek V4.1 Flash 1017 | 320,000 | 131,072 | **0** | 免费(上游下拉是 `DeepSeek V4.1 Flash 1017`,桌面端会把旧名改写成它) | -| `glm-5.3-flash` | GLM 5.3 Flash | 320,000 | 131,072 | **0** | 免费,默认模型 | -| `glyph-cluster` | Glyph Cluster | 256,000 | 131,072 | **0** | 免费,纯文本 | +| `glm-5.3-flash` | GLM 5.3 Flash | 320,000 | 131,072 | **0** | 免费,默认模型;實測 320k 完整(見下方「有效上下文上限」) | +| `glyph-cluster` | Glyph Cluster | 256,000 | 131,072 | **0** | 免费,纯文本;實測上限 **256k**(260k 完整、320k 硬拒絕) | | `gpt-6-luna` | GPT-6 Luna | 320,000 | 128,000 | **0** | 免费 | -| `mimo-2.6-flash` | MiMo 2.6 Flash | 320,000 | 131,072 | **0** | 免费 | +| `mimo-2.6-flash` | MiMo 2.6 Flash | 320,000 | 131,072 | **0** | 免费;實測上限 **140k**(170k 起上游靜默截斷,網關提前裁剪) | | `mimo-2.6-pro` | MiMo 2.6 Pro | 320,000 | 131,072 | **0** | 免费 | | `minimax-m3.1-flash` | MiniMax M3.1 Flash | 320,000 | 131,072 | **0** | 免费 | | `muse-ember` | Muse Ember | 320,000 | 131,072 | **0** | 免费(2026-11-14 新增) | @@ -204,22 +204,66 @@ OpenRouter 风格的 `provider`、`reasoning`、`reasoning_details`、`cost` 等 | POST | `/v1/messages` | 流式 / 非流式,支持 `tool_use`、`thinking`、图片 | | POST | `/v1/messages/count_tokens` | 本地估算(上游不提供) | -#### 上下文契约:网关是**无状态**的 - -三套协议都按「调用方每轮发完整历史」工作(和桌面端一致):网关不存对话, -也不会替你补上一轮。具体到 `/v1/responses`: - -- `openai-responses` 模型(如 `gpt-6-astra`):请求**原样透传**到上游 - `/responses`,`previous_response_id` / `conversation` 能否续接取决于上游 - (2026-11-19 该模型持续 429,尚未验证;桌面端自身从不使用链式续接); -- 其余模型:网关把 `input` 翻译成 chat messages。此时**凡是依赖上游保存状态 - 的请求会直接返回 400 `unsupported_parameter`**,而不是静默丢掉上下文: - `previous_response_id`、`conversation`、`input` 里的 `item_reference`。 - 修法:把完整历史放进 `input` 重发,或改用透传模型。 +#### 上下文契约:`/v1/responses` 伺服端歷史暫存(链式续接) + +三套协议中,`/v1/chat/completions` 与 `/v1/messages` 仍按「调用方每轮发完整历史」工作 +(和桌面端一致):网关不存对话,也不会替你补上一轮。但 `/v1/responses` 自 2026-11-20 +起支持**伺服端對話歷史暫存 + 重放**,解决反代 / magpie 插件客户端攜帶 +`previous_response_id` 續接时的「失忆」问题: + +- **其余模型(chat/completions 合成路径,如 `glm-5.3-flash`)**:每轮 `/v1/responses` + 回應完成後,网关把该轮的 input 与 output 存进进程内暫存(按 response id 索引)。 + 下一轮帶 `previous_response_id` 时,网关沿鏈重組完整 input 再送上游——客户端无需 + 自己维护历史,链式续接不再回 400,也不会失忆。新回應有自己的 id,可继续链接。 + - **暫存上限**:默认 TTL 24 小时、每个进程最多 500 轮,可用环境变量调整: + - `DEEPAI2API_HISTORY_TTL_HOURS`(默认 `24`) + - `DEEPAI2API_HISTORY_MAX_ENTRIES`(默认 `500`) + - **有效上下文上限(按模型實測值,避免上游靜默丟歷史)**:2026-11-20 把 11 個 + 免費模型全部實測(純透傳 + 唯一隨機 ASCII 階梯,附多輪對照),有效窗口按模型查表: + - **9 個免費模型**:`glm-5.3-flash`、`deepseek-v4.1-flash`、`qwen-3.8-flash`、 + `minimax-m3.1-flash`、`muse-ember`、`solar-mini-4`、`gpt-6-luna`、 + `mimo-2.6-pro`、`deepai-cyber` → **320,000**(等於標示值,不再人為砍到 120k)。 + - **`glyph-cluster` → 256,000**(260k 完整,320k 被上游硬拒絕 400,目錄標 256k 一致)。 + - **`mimo-2.6-flash` → 140,000**(140k 完整,170k 起上游「靜默截斷」: + `prompt_tokens` 掉到 5,296 ≈ 3%;上限落在 140k–170k,保守取 140k)。 + - 未知/付費模型 → `min(標示值, 320,000)`,不再一律硬壓 120k。 + - 網關重放時若超過各模型的有效窗口,先由網關裁剪並在 input 留下 + 「中間歷史已省略」標記,也不讓上游偷偷砍歷史。 + - **環境變數覆寫**(排查/臨時調整用): + - `DEEPAI2API_EFFECTIVE_CONTEXT_WINDOW`:全域覆寫(舊行為保留)。如 `64000`; + 設 `0`/負數關閉上限。優先權最高。 + - `DEEPAI2API_CONTEXT_WINDOWS`:按模型 JSON 覆寫,例如 + `{"mimo-2.6-flash":140000,"glm-5.3-flash":320000}`(值 `0`/負數 = 該模型不設上限, + JSON 格式錯誤則忽略)。優先權低於全域覆寫、高於內建實測表。 + - 單發探測(不鏈式)實測:唯一隨機 ASCII 160,000 bytes → 上游 + `input_tokens=100,761`(比值約 1.59 tokens/byte);重複填充會被前綴快取, + `input_tokens` 不可作為窗口判斷依據。 + - **自動上下文壓縮(`truncation`)**:重放整條鏈後若超過有效窗口(見上): + - `"truncation":"auto"`:網關自動裁掉最舊的**中段**輪次(保留開頭系統/首則訊息 + 與最近的可容納範圍,並插入一則「中間歷史已省略」說明),照常送上游。 + - 未設或 `"default"`:回明確 400 `invalid_request_error`,訊息寫明 token 估算與 + 有效窗口/標示值,並提示「請由客戶端壓縮歷史,或改用 `truncation:auto`」。 + **绝不靜默砍歷史**——那正是「失憶」的根源。 + - token 估算:ASCII 按 ~1.6 bytes/token、非 ASCII 按 ~1 token/字粗估 + (實測與上游 `input_tokens` 偏差在 ±30% 內);只在上限判斷時計算, + 正常情況零額外開銷。 + - **生命周期**:进程内存储,**重启后历史清空**。重启后客户端若仍帶旧的 + `previous_response_id`,网关找不到记录会回 400 `unsupported_parameter`—— + 此时客户端应重新发送完整 `input`(或在重启后先开新对话)。 + - 仍**不支持**:`conversation`(服务端会话)与 `input` 里的 `item_reference` + ——它们依赖上游保存的状态,网关无从重建,会回明确的 400 `unsupported_parameter`。 +- **`openai-responses` 模型(如 `gpt-6-astra`)**:请求**原样透传**到上游 `/responses`, + `previous_response_id` / `conversation` 能否续接取决于上游 + (2026-11-19 该模型持续 429,尚未验证;桌面端自身从不使用链式续接)。 + +**受益的客户端用法**:任何在「同一視窗」连续多轮、且依赖服务端状态的 Responses 客户端 +(典型是 Claude Code / Codex 经反代、magpie 插件反代)——现在可以放心用 +`previous_response_id` 续接,不必每轮重发整段历史。非链式用法(每轮 `input` 直接带 +完整历史)行为不变,不会回歸。 排障:请求日志(控制台日志页「消息」列 / `<数据文件>-logs.jsonl` 的 `messages`、 `system` 字段)记录每次请求回喂的消息条数与是否带系统提示,不含正文—— -条数 1 通常说明调用方只发了本轮。 +链式续接时该条数会随轮次增长,说明历史确实被重放。 Claude Code 只需: @@ -362,6 +406,10 @@ print(client.chat.completions.create( | `PROXY_POOL` | 推理代理池(逗号或换行分隔完整 URL;入池时按账号轮询分配) | | `PROXY_POOL_FILE` | 代理池文件(每行一个) | | `DEEPAI2API_ENV_FILE` | 指定 `.env` 路径 | +| `DEEPAI2API_HISTORY_TTL_HOURS` | `/v1/responses` 伺服端歷史暫存存活小時數(默认 `24`) | +| `DEEPAI2API_HISTORY_MAX_ENTRIES` | `/v1/responses` 伺服端歷史暫存最多輪次(默认 `500`) | +| `DEEPAI2API_EFFECTIVE_CONTEXT_WINDOW` | 重放有效上下文上限的全域覆寫(优先級最高;默认按模型查表,見上方上下文契約;`0`/負數關閉) | +| `DEEPAI2API_CONTEXT_WINDOWS` | 按模型覆寫有效上下文上限,JSON 物件如 `{"mimo-2.6-flash":140000}`(值 `0`/負數 = 該模型不設上限;格式錯誤忽略) | | `T3CODE_HOME` / `DEEPAI_CODE_HOME` | 桌面端数据目录 | ### 诊断工具 diff --git a/internal/server/response_history.go b/internal/server/response_history.go new file mode 100644 index 0000000..473eb7d --- /dev/null +++ b/internal/server/response_history.go @@ -0,0 +1,414 @@ +package server + +// Responses 伺服端對話歷史暫存 + 重放。 +// +// 背景:宗恩透過反代(含 magpie 插件)使用 /v1/responses 時,同一視窗 +// 對話到一半模型「失憶」。根因是用戶端攜帶 previous_response_id 續接, +// 但網關的 chat/completions 合成路徑是無狀態的,舊版直接回 400 +// unsupported_parameter;客戶端收到 400 後靜默重開對話,上下文被截斷。 +// +// 解法:網關自己記住每一輪的 input 與 output(按 response id 索引), +// 收到 previous_response_id 時沿鏈重組完整 input 再送上游,取代 400。 +// 進程內存储,TTL 與上限可調;重啟後歷史清空(客戶端應重新帶完整 input)。 + +import ( + "encoding/json" + "os" + "strconv" + "strings" + "sync" + "time" +) + +// historyEntry 是一輪已完成的 Responses 交互。 +// +// input 是「本輪送出前的完整對話 input」(含之前所有輪次的 input 與 output), +// 因此重放是 O(1):取上一輪的 input+output 接上本輪 input 即可, +// 不必每次都遍歷整條鏈。 +type historyEntry struct { + id string + input []any // 完整對話 input(Responses item 格式) + instructions string + output []any // 本輪助手輸出 item + createdAt time.Time +} + +// responseTurn 是單輪請求送出前的輸入快照,回應完成後連同輸出寫入暫存。 +type responseTurn struct { + input []any + instructions string +} + +// remember 把這輪的輸入快照與輸出寫入暫存。 +func (h *responseHistory) remember(turn *responseTurn, respID string, output []any) { + if h == nil || turn == nil || respID == "" { + return + } + h.put(respID, &historyEntry{ + input: cloneAnySlice(turn.input), + instructions: turn.instructions, + output: cloneAnySlice(output), + }) +} + +// responseHistory 是執行緒安全的對話歷史暫存。 +type responseHistory struct { + mu sync.RWMutex + entries map[string]*historyEntry + order []string // 插入順序,供容量淘汰 + ttl time.Duration + max int + now func() time.Time // 測試可注入 +} + +// newResponseHistoryFromEnv 從環境變數構造暫存。 +// +// DEEPAI2API_HISTORY_TTL_HOURS 歷史存活小時數(預設 24,0/負數用預設)。 +// DEEPAI2API_HISTORY_MAX_ENTRIES 最多保留輪次(預設 500,0/負數用預設)。 +func newResponseHistoryFromEnv() *responseHistory { + ttlH := envPositiveInt("DEEPAI2API_HISTORY_TTL_HOURS", 24) + max := envPositiveInt("DEEPAI2API_HISTORY_MAX_ENTRIES", 500) + return newResponseHistory(time.Duration(ttlH)*time.Hour, max) +} + +func newResponseHistory(ttl time.Duration, max int) *responseHistory { + if ttl <= 0 { + ttl = 24 * time.Hour + } + if max <= 0 { + max = 500 + } + return &responseHistory{ + entries: map[string]*historyEntry{}, + ttl: ttl, + max: max, + now: time.Now, + } +} + +func envPositiveInt(key string, def int) int { + v := strings.TrimSpace(os.Getenv(key)) + if v == "" { + return def + } + n, err := strconv.Atoi(v) + if err != nil || n <= 0 { + return def + } + return n +} + +// put 存入一輪交互;同 id 重複存入為覆蓋。 +func (h *responseHistory) put(id string, e *historyEntry) { + if h == nil || id == "" { + return + } + e.id = id + if e.createdAt.IsZero() { + e.createdAt = h.now() + } + h.mu.Lock() + defer h.mu.Unlock() + h.purgeExpiredLocked() + if _, exists := h.entries[id]; !exists { + h.order = append(h.order, id) + } + h.entries[id] = e + for len(h.order) > h.max { + oldest := h.order[0] + h.order = h.order[1:] + delete(h.entries, oldest) + } +} + +// get 取出一輪交互;過期視為不存在。 +func (h *responseHistory) get(id string) *historyEntry { + if h == nil || id == "" { + return nil + } + h.mu.Lock() + defer h.mu.Unlock() + h.purgeExpiredLocked() + e := h.entries[id] + if e == nil { + return nil + } + cp := *e + cp.input = cloneAnySlice(e.input) + cp.output = cloneAnySlice(e.output) + return &cp +} + +// replayOutcome 是重放結果的語意分類。 +type replayOutcome int + +const ( + replayOK replayOutcome = iota // 已重放(可能已自動裁減) + replayNotFound // id 找不到 / 過期 → 400 unsupported_parameter + replayTooLong // 超過 contextWindow 且未開 truncation:auto → 400 +) + +// replay 把 previous_response_id 指向的歷史重組進目前請求。 +// +// 成功時:payload.input 被換成完整歷史、previous_response_id 被移除、 +// 必要時補回最初的 instructions;回傳 replayOK。 +// 找不到 / 已過期 → replayNotFound(呼叫方回 400 unsupported_parameter)。 +// +// 若有效窗口 > 0 且重放後的鏈超過上限: +// - payload["truncation"] == "auto":裁掉最舊的中段輪次(保留開頭系統/首則訊息 +// 與最近可容納範圍),照常送上游,回 replayOK。 +// - 否則:不更動 payload,回 replayTooLong 與明確訊息(呼叫方回 400), +// 绝不靜默砍歷史——那正是「失憶」的根源。 +func (h *responseHistory) replay(payload map[string]any, prevID, modelID string, contextWindow int) (replayOutcome, string) { + e := h.get(prevID) + if e == nil { + return replayNotFound, "" + } + merged := make([]any, 0, len(e.input)+len(e.output)+4) + merged = append(merged, e.input...) + merged = append(merged, e.output...) + merged = append(merged, responsesInputArray(payload)...) + + // 有效窗口按模型實測值查表(見 effectiveContextWindow);少數模型上限低於 + // 目錄標示(mimo-flash 140k、glyph 256k),其餘 9 個免費模型可吃滿 320k。 + // 讓網關先裁剪並留下標記,也不要讓上游偷偷砍歷史。 + limit := effectiveContextWindow(modelID, contextWindow) + if limit > 0 { + total := 0 + for _, it := range merged { + total += itemApproxTokens(it) + } + if total > limit { + if strOf(payload["truncation"]) != "auto" { + return replayTooLong, "重放後的對話歷史約 " + itoaApprox(total) + + " tokens,超過模型有效上下文 contextWindow " + itoaApprox(limit) + + "(目錄標示 " + itoaApprox(contextWindow) + + ");請由客戶端壓縮歷史,或於請求設定 \"truncation\":\"auto\" 由網關自動裁減最舊中段。" + } + merged = truncateHistory(merged, limit) + } + } + + payload["input"] = merged + if strOf(payload["instructions"]) == "" && e.instructions != "" { + payload["instructions"] = e.instructions + } + delete(payload, "previous_response_id") + return replayOK, "" +} + +// truncateHistory 裁掉最舊的中段輪次:保留開頭(系統訊息 + 第一則使用者訊息, +// 通常是重要背景/暗號)與最近可容納的尾段;中間插入一則說明訊息。 +func truncateHistory(items []any, contextWindow int) []any { + if contextWindow <= 0 || len(items) <= 2 { + return items + } + // head = 開頭連續的 system 訊息,再加上第一則非 system 訊息(開頭訊息)。 + headEnd := 0 + for headEnd < len(items) { + m, ok := items[headEnd].(map[string]any) + if !ok || strOf(m["role"]) != "system" { + break + } + headEnd++ + } + if headEnd < len(items) { + headEnd++ + } + used := 0 + for _, it := range items[:headEnd] { + used += itemApproxTokens(it) + } + + // tail = 由最新往回,尽可能容納。 + tailStart := len(items) + for tailStart > headEnd { + t := itemApproxTokens(items[tailStart-1]) + if used+t > contextWindow { + break + } + used += t + tailStart-- + } + if tailStart >= len(items) { + tailStart = len(items) - 1 // 至少保留最新一則 + } + if tailStart < headEnd { + tailStart = headEnd + } + + // 標記必須用 user role:上游會拒絕「system 出現在非首則」的請求體 + // (實測 Chat Completions:system 在中間 → 400 This request cannot be accepted)。 + out := make([]any, 0, headEnd+(len(items)-tailStart)+1) + out = append(out, items[:headEnd]...) + out = append(out, map[string]any{ + "type": "message", "role": "user", + "content": "(中間的對話歷史因超過上下文長度已由網關自動省略)", + }) + out = append(out, items[tailStart:]...) + return out +} + +// perModelContextWindow 是實測得出的「例外」上限:少數模型的可靠窗口 +// 低於目錄標示值,不能跟其他模型一樣一律用 320k。 +// +// 2026-11-20 11 個免費模型實測(純透傳 + 唯一隨機 ASCII 階梯,附多輪對照): +// - mimo-2.6-flash:140k 完整,170k 起上游「靜默截斷」(prompt_tokens 掉到 +// 5,296 ≈ 3%)。真正上限落在 140k–170k,保守取 140000,避免上游偷砍歷史。 +// - glyph-cluster:260k 完整,320k 硬拒絕(400 provider rejected);目錄標 +// 256k 與實測一致,取 256000。 +// - 其餘 9 個免費模型:320k 完整(glm/deepseek/qwen/minimax/muse/solar/ +// gpt-6-luna/mimo-pro/deepai-cyber),等於目錄標示值,不再人為砍到 120k。 +// +// 未列在此表的模型(含付費模型)走 min(標示值, catalogContextCap)。 +var perModelContextWindow = map[string]int{ + "mimo-2.6-flash": 140000, + "glyph-cluster": 256000, +} + +// catalogContextCap 是目錄標示值的通用上限;目前所有模型標示值皆 ≤ 320k。 +const catalogContextCap = 320000 + +// effectiveContextWindow 回傳重放時真正可用的上下文上限(按模型)。 +// +// 優先順序(高 → 低): +// 1. DEEPAI2API_EFFECTIVE_CONTEXT_WINDOW:全域覆寫(0/負數 = 不設上限)。 +// 保留舊行為,作為排查/臨時降上限用。 +// 2. DEEPAI2API_CONTEXT_WINDOWS:JSON 物件,按 model id 覆寫,例如 +// {"mimo-2.6-flash":140000,"glm-5.3-flash":320000} +// (值 0/負數 = 該模型不設上限;格式錯誤則忽略整項)。 +// 3. perModelContextWindow:上面的實測例外表。 +// 4. min(標示值, catalogContextCap);標示值 ≤ 0 時用 catalogContextCap。 +func effectiveContextWindow(modelID string, catalog int) int { + if raw := strings.TrimSpace(os.Getenv("DEEPAI2API_EFFECTIVE_CONTEXT_WINDOW")); raw != "" { + if n, err := strconv.Atoi(raw); err == nil { + if n <= 0 { + return 0 + } + return n + } + } + if raw := strings.TrimSpace(os.Getenv("DEEPAI2API_CONTEXT_WINDOWS")); raw != "" { + var overrides map[string]int + if err := json.Unmarshal([]byte(raw), &overrides); err == nil { + if n, ok := overrides[modelID]; ok { + if n <= 0 { + return 0 + } + return n + } + } + } + if n, ok := perModelContextWindow[modelID]; ok { + return n + } + if catalog <= 0 || catalog > catalogContextCap { + return catalogContextCap + } + return catalog +} + +// itemApproxTokens 粗估 item 的 token 數。中文等全形字元約 1 token/字, +// ASCII 約 1.6 bytes/token(實測 160k 英文隨機字串 → 100,761 input_tokens, +// 比值 1.59;舊的 len/3 對程式碼場景低估約一倍,會讓自動壓縮太晚觸發)。 +// 只在上限判斷時呼叫,正常情況零額外開銷。 +func itemApproxTokens(item any) int { + raw, err := json.Marshal(item) + if err != nil { + return 0 + } + tokens := 0 + asciiRun := 0 + flush := func() { + if asciiRun > 0 { + tokens += (asciiRun*10 + 15) / 16 // ceil(run / 1.6) + asciiRun = 0 + } + } + for _, r := range string(raw) { + if r < 0x80 { + asciiRun++ + continue + } + flush() + tokens++ // 一個非 ASCII 字元約 1 token(中文、emoji 等同量級) + } + flush() + return tokens +} + +func itoaApprox(n int) string { + if n == 0 { + return "0" + } + neg := n < 0 + if neg { + n = -n + } + var buf [20]byte + i := len(buf) + for n > 0 { + i-- + buf[i] = byte('0' + n%10) + n /= 10 + } + if neg { + i-- + buf[i] = '-' + } + return string(buf[i:]) +} + +func (h *responseHistory) purgeExpiredLocked() { + now := h.now() + kept := h.order[:0] + for _, id := range h.order { + e := h.entries[id] + if e == nil || now.Sub(e.createdAt) > h.ttl { + delete(h.entries, id) + continue + } + kept = append(kept, id) + } + h.order = kept +} + +// len 供測試與監控使用。 +func (h *responseHistory) len() int { + if h == nil { + return 0 + } + h.mu.RLock() + defer h.mu.RUnlock() + return len(h.entries) +} + +// --- 工具函式 --- + +// responsesInputArray 把 payload.input 正規化成 Responses item 切片(深拷貝)。 +// 字串 input 轉成單一 user message item,與 gateway 的轉換保持一致。 +func responsesInputArray(payload map[string]any) []any { + switch v := payload["input"].(type) { + case []any: + return cloneAnySlice(v) + case string: + return []any{map[string]any{"type": "message", "role": "user", "content": v}} + } + return nil +} + +// cloneAnySlice 用 JSON 往返做深拷貝;input/output item 都是純 JSON 值。 +func cloneAnySlice(in []any) []any { + if in == nil { + return nil + } + raw, err := json.Marshal(in) + if err != nil { + return append([]any(nil), in...) + } + var out []any + if err := json.Unmarshal(raw, &out); err != nil { + return append([]any(nil), in...) + } + return out +} diff --git a/internal/server/response_history_test.go b/internal/server/response_history_test.go new file mode 100644 index 0000000..e9b4a4f --- /dev/null +++ b/internal/server/response_history_test.go @@ -0,0 +1,518 @@ +package server + +import ( + "encoding/json" + "io" + "net/http" + "net/http/httptest" + "strings" + "testing" + "time" + + "deepaicode2api/internal/deepai" +) + +// codewordUpstream 回一個假上游:它會把所有 chat messages 的字串化內容 +// 拿去比對暗號。只有當「問題」與「暗號」同時出現在訊息裡才回答暗號, +// 否則回答 UNKNOWN —— 用來斷言歷史是否真的被重放到上游。 +// +// 注意:自己讀 r.Body 並記錄(newUpstream 的包裝會先讀走 body), +// 因此这里直接建 httptest.Server,不走 newUpstream。 +func codewordUpstream(t *testing.T, codeword string) *upstream { + t.Helper() + u := &upstream{} + u.srv = httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + raw, _ := io.ReadAll(r.Body) + var payload map[string]any + _ = json.Unmarshal(raw, &payload) + u.mu.Lock() + u.requests = append(u.requests, recordedRequest{ + Path: r.URL.Path, Header: r.Header.Clone(), Payload: payload, Body: raw, + }) + u.mu.Unlock() + + w.Header().Set("Content-Type", "application/json") + blob, _ := json.Marshal(payload["messages"]) + text := string(blob) + answer := "UNKNOWN" + if strings.Contains(text, "What is the codeword") { + if strings.Contains(text, codeword) { + answer = "CODEWORD=" + codeword + } + } else { + answer = "STORED" + } + _ = json.NewEncoder(w).Encode(map[string]any{ + "choices": []any{map[string]any{ + "index": 0, "message": map[string]any{ + "role": "assistant", "content": answer, + }, + "finish_reason": "stop", + }}, + "usage": map[string]any{"prompt_tokens": 10, "completion_tokens": 3}, + }) + })) + t.Cleanup(u.srv.Close) + return u +} + +func respIDAndText(t *testing.T, rec *httptest.ResponseRecorder) (string, string) { + t.Helper() + var out map[string]any + if err := json.Unmarshal(rec.Body.Bytes(), &out); err != nil { + t.Fatalf("回應不是 JSON: %v\n%s", err, rec.Body.String()) + } + id, _ := out["id"].(string) + text, _ := out["output_text"].(string) + return id, text +} + +// TestResponsesChainMemory3Rounds 鎖住「鏈式記憶」:3 輪以上, +// 第一輪給暗號,第三輪用 previous_response_id 續接問暗號,必须答對。 +func TestResponsesChainMemory3Rounds(t *testing.T) { + const codeword = "ZEBRA42" + u := codewordUpstream(t, codeword) + s, key := newTestServer(t, u) + + // 第 1 輪:給暗號。 + r1 := do(t, s, http.MethodPost, "/v1/responses", key, + `{"model":"glm-5.3-flash","input":"Remember codeword ZEBRA42"}`) + if r1.Code != http.StatusOK { + t.Fatalf("第 1 輪狀態 = %d:%s", r1.Code, r1.Body.String()) + } + id1, _ := respIDAndText(t, r1) + if id1 == "" { + t.Fatal("第 1 輪沒有 id") + } + if got := s.history.len(); got != 1 { + t.Fatalf("歷史條目 = %d,期望 1", got) + } + + // 第 2 輪:帶上一輪 id,問不相關問題(延長鏈)。 + r2 := do(t, s, http.MethodPost, "/v1/responses", key, + `{"model":"glm-5.3-flash","previous_response_id":"`+id1+`","input":"Still there?"}`) + if r2.Code != http.StatusOK { + t.Fatalf("第 2 輪狀態 = %d:%s", r2.Code, r2.Body.String()) + } + id2, _ := respIDAndText(t, r2) + if id2 == "" || id2 == id1 { + t.Fatalf("第 2 輪 id 應為新的:id1=%s id2=%s", id1, id2) + } + + // 第 3 輪:帶第 2 輪 id 問暗號,必须答對。 + r3 := do(t, s, http.MethodPost, "/v1/responses", key, + `{"model":"glm-5.3-flash","previous_response_id":"`+id2+`","input":"What is the codeword?"}`) + if r3.Code != http.StatusOK { + t.Fatalf("第 3 輪狀態 = %d:%s", r3.Code, r3.Body.String()) + } + _, text := respIDAndText(t, r3) + if !strings.Contains(text, "CODEWORD="+codeword) { + t.Fatalf("第 3 輪失憶:output_text = %q,期望含 CODEWORD=%s", text, codeword) + } + + // 斷言上游確實收到了被重放的暗號。 + last := u.last(t) + blob, _ := json.Marshal(last.Payload["messages"]) + if !strings.Contains(string(blob), codeword) { + t.Fatalf("上游未收到重放的暗號:%s", blob) + } + if n := s.metrics.statefulReject.Load(); n != 0 { + t.Fatalf("續接成功不應記拒絕,實際 = %d", n) + } +} + +// TestResponsesNonChainInputUnchanged 驗證非鏈式路徑(input 直接帶完整歷史) +// 不被改寫、不回歸:沒有 previous_response_id 时不應動 input。 +func TestResponsesNonChainInputUnchanged(t *testing.T) { + u := codewordUpstream(t, "ZEBRA42") + s, key := newTestServer(t, u) + + body := `{"model":"glm-5.3-flash","input":[ + {"type":"message","role":"user","content":"Remember codeword ZEBRA42"}, + {"type":"message","role":"assistant","content":"STORED"}, + {"type":"message","role":"user","content":"What is the codeword?"} + ]}` + rec := do(t, s, http.MethodPost, "/v1/responses", key, body) + if rec.Code != http.StatusOK { + t.Fatalf("狀態 = %d:%s", rec.Code, rec.Body.String()) + } + last := u.last(t) + msgs, ok := last.Payload["messages"].([]any) + if !ok || len(msgs) != 3 { + t.Fatalf("上游 messages 數 = %d,期望 3(原樣 3 條):%#v", len(msgs), last.Payload["messages"]) + } + if n := s.metrics.statefulReject.Load(); n != 0 { + t.Fatalf("非鏈式請求不應記 stateful 拒絕,實際 = %d", n) + } +} + +// TestResponsesStreamChainMemoryAndEvents 驗證串流路徑也存歷史、 +// 能重放,且事件序列完整(created → deltas → completed)。 +func TestResponsesStreamChainMemoryAndEvents(t *testing.T) { + const codeword = "ZEBRA42" + // 自建 httptest.Server 以便讀到 request body(newUpstream 會先讀走)。 + u := &upstream{} + u.srv = httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + w.Header().Set("Content-Type", "text/event-stream") + raw, _ := io.ReadAll(r.Body) + var payload map[string]any + _ = json.Unmarshal(raw, &payload) + u.mu.Lock() + u.requests = append(u.requests, recordedRequest{ + Path: r.URL.Path, Header: r.Header.Clone(), Payload: payload, Body: raw, + }) + u.mu.Unlock() + blob, _ := json.Marshal(payload["messages"]) + answer := "STORED" + if strings.Contains(string(blob), "What is the codeword") { + answer = "UNKNOWN" + if strings.Contains(string(blob), codeword) { + answer = "CODEWORD=" + codeword + } + } + for _, c := range []string{ + `{"choices":[{"index":0,"delta":{"content":"` + answer + `"}}]}`, + `{"choices":[{"index":0,"delta":{},"finish_reason":"stop"}]}`, + `{"choices":[],"usage":{"prompt_tokens":10,"completion_tokens":3}}`, + `[DONE]`, + } { + _, _ = io.WriteString(w, "data: "+c+"\n\n") + w.(http.Flusher).Flush() + } + })) + t.Cleanup(u.srv.Close) + s, key := newTestServer(t, u) + + // 第 1 輪(串流):給暗號,取出 response id。 + r1 := do(t, s, http.MethodPost, "/v1/responses", key, + `{"model":"gpt-4o","stream":true,"input":"Remember codeword ZEBRA42"}`) + if r1.Code != http.StatusOK { + t.Fatalf("第 1 輪狀態 = %d:%s", r1.Code, r1.Body.String()) + } + events1 := sseEvents(t, r1.Body.String()) + var id1 string + for _, e := range events1 { + if e.Event == "response.completed" { + id1, _ = e.JSON(t)["response"].(map[string]any)["id"].(string) + } + } + if id1 == "" { + t.Fatal("串流第 1 輪 response.completed 缺少 id") + } + if got := s.history.len(); got != 1 { + t.Fatalf("串流後歷史條目 = %d,期望 1", got) + } + + // 第 2 輪(串流):帶 id 問暗號。 + r2 := do(t, s, http.MethodPost, "/v1/responses", key, + `{"model":"gpt-4o","stream":true,"previous_response_id":"`+id1+`","input":"What is the codeword?"}`) + if r2.Code != http.StatusOK { + t.Fatalf("第 2 輪狀態 = %d:%s", r2.Code, r2.Body.String()) + } + + // 事件序列完整。 + events2 := sseEvents(t, r2.Body.String()) + names := eventNames(events2) + if len(names) == 0 || names[0] != "response.created" { + t.Fatalf("首事件 = %v,期望 response.created 開頭", names) + } + if last := names[len(names)-1]; last != "response.completed" { + t.Fatalf("末事件 = %q,期望 response.completed(全部:%v)", last, names) + } + for _, want := range []string{ + "response.output_item.added", "response.output_text.delta", + "response.output_text.done", "response.completed", + } { + found := false + for _, n := range names { + if n == want { + found = true + } + } + if !found { + t.Fatalf("串流缺少事件 %q:%v", want, names) + } + } + + // 文字含暗號 → 證明串流路徑也重放了歷史。 + var text strings.Builder + for _, e := range events2 { + if e.Event == "response.output_text.delta" { + if d, ok := e.JSON(t)["delta"].(string); ok { + text.WriteString(d) + } + } + } + if !strings.Contains(text.String(), "CODEWORD="+codeword) { + t.Fatalf("串流失憶:文字 = %q", text.String()) + } +} + +// TestResponsesHistoryTTLAndMax 驗證 TTL 與容量上限。 +func TestResponsesHistoryTTLAndMax(t *testing.T) { + base := time.Date(2026, 1, 1, 0, 0, 0, 0, time.UTC) + h := newResponseHistory(time.Hour, 2) + h.now = func() time.Time { return base } + + h.put("a", &historyEntry{input: []any{"a"}}) + h.now = func() time.Time { return base.Add(30 * time.Minute) } + h.put("b", &historyEntry{input: []any{"b"}}) + h.now = func() time.Time { return base.Add(90 * time.Minute) } // a 已過期 + h.put("c", &historyEntry{input: []any{"c"}}) + if h.get("a") != nil { + t.Fatal("過期條目 a 應被清除") + } + if h.get("b") == nil || h.get("c") == nil { + t.Fatal("未過期條目應保留") + } + + // 容量上限:再加兩筆後只留最新 2 筆。 + h.now = func() time.Time { return base.Add(95 * time.Minute) } + h.put("d", &historyEntry{input: []any{"d"}}) + h.put("e", &historyEntry{input: []any{"e"}}) + if h.len() != 2 { + t.Fatalf("容量上限後條目 = %d,期望 2", h.len()) + } + if h.get("b") != nil || h.get("c") != nil { + t.Fatal("最舊的 b/c 應被淘汰") + } + if h.get("d") == nil || h.get("e") == nil { + t.Fatal("最新的 d/e 應保留") + } +} + +// TestResponsesConversationStillRejected conversation / item_reference +// 需要上游服務端狀態,網關無從重建,保留明確 400。 +func TestResponsesConversationStillRejected(t *testing.T) { + u := newUpstream(t, func(w http.ResponseWriter, r *http.Request) { + t.Errorf("conversation 不應打到上游") + }) + s, key := newTestServer(t, u) + + for _, body := range []string{ + `{"model":"glm-5.3-flash","conversation":"conv_abc","input":"hi"}`, + `{"model":"glm-5.3-flash","input":[{"type":"item_reference","id":"item_1"}]}`, + } { + rec := do(t, s, http.MethodPost, "/v1/responses", key, body) + if rec.Code != http.StatusBadRequest || + !strings.Contains(rec.Body.String(), "unsupported_parameter") { + t.Fatalf("應回 400 unsupported_parameter:%s(%s)", rec.Body.String(), body) + } + } +} + +// TestResponsesTruncationAuto 驗證 truncation:auto 在超限时裁剪最舊中段, +// 保留開頭暗號與最近訊息,照常送上游(200,暗號仍可見)。 +func TestResponsesTruncationAuto(t *testing.T) { + const codeword = "ZEBRA42" + u := codewordUpstream(t, codeword) + s, key := newTestServer(t, u) + // 用全域環境覆寫把有效窗口壓到很小(約 200 tokens → 600 bytes), + // 讓「開頭暗號 + 數輪填充 + 最新提問」必然超限;不影響按模型查表。 + t.Setenv("DEEPAI2API_EFFECTIVE_CONTEXT_WINDOW", "200") + + // 第 1 輪:暗號。 + r1 := do(t, s, http.MethodPost, "/v1/responses", key, + `{"model":"glm-5.3-flash","input":"Remember codeword ZEBRA42"}`) + if r1.Code != http.StatusOK { + t.Fatalf("第 1 輪 = %d:%s", r1.Code, r1.Body.String()) + } + id, _ := respIDAndText(t, r1) + + // 第 2 輪:帶長填充讓鏈變很長,truncation:auto。 + longFill := strings.Repeat("filler word ", 120) // ~1440 bytes → 远超 600 + body2 := `{"model":"glm-5.3-flash","previous_response_id":"` + id + + `","truncation":"auto","input":"What is the codeword? ` + longFill + `"}` + r2 := do(t, s, http.MethodPost, "/v1/responses", key, body2) + if r2.Code != http.StatusOK { + t.Fatalf("truncation:auto 應回 200,實際 %d:%s", r2.Code, r2.Body.String()) + } + + // 上游收到的 messages 應含裁減標記、開頭暗號、以及最新提問。 + last := u.last(t) + blob, _ := json.Marshal(last.Payload["messages"]) + text := string(blob) + if !strings.Contains(text, "自動省略") { + t.Fatalf("truncation:auto 應插入裁減說明:%s", text) + } + // 裁減標記必須是 user role:上游會拒絕 system 出現在非首則的請求體。 + msgs, _ := last.Payload["messages"].([]any) + if len(msgs) > 1 { + for i, m := range msgs { + mm, _ := m.(map[string]any) + if i > 0 && strOf(mm["role"]) == "system" { + t.Fatalf("裁減後 system 出現在非首則(上游會 400):%s", text) + } + } + } + if !strings.Contains(text, codeword) { + t.Fatalf("裁減後應保留開頭暗號:%s", text) + } + if !strings.Contains(text, "What is the codeword") { + t.Fatalf("裁減後應保留最新提問:%s", text) + } +} + +// TestResponsesTruncationRequired 驗證未設 truncation 時超限回明確 400, +// 不靜默砍歷史(那是失憶根源)。 +func TestResponsesTruncationRequired(t *testing.T) { + u := codewordUpstream(t, "ZEBRA42") + s, key := newTestServer(t, u) + t.Setenv("DEEPAI2API_EFFECTIVE_CONTEXT_WINDOW", "200") + + r1 := do(t, s, http.MethodPost, "/v1/responses", key, + `{"model":"glm-5.3-flash","input":"Remember codeword ZEBRA42"}`) + if r1.Code != http.StatusOK { + t.Fatalf("第 1 輪 = %d:%s", r1.Code, r1.Body.String()) + } + id, _ := respIDAndText(t, r1) + + longFill := strings.Repeat("filler word ", 120) + body2 := `{"model":"glm-5.3-flash","previous_response_id":"` + id + + `","input":"What is the codeword? ` + longFill + `"}` + r2 := do(t, s, http.MethodPost, "/v1/responses", key, body2) + if r2.Code != http.StatusBadRequest { + t.Fatalf("未設 truncation 超限應回 400,實際 %d:%s", r2.Code, r2.Body.String()) + } + if !strings.Contains(r2.Body.String(), "contextWindow") || + !strings.Contains(r2.Body.String(), "truncation") { + t.Fatalf("400 訊息應指明 contextWindow 與 truncation:%s", r2.Body.String()) + } +} + +// TestItemApproxTokensCalibration 驗證估算與上游 input_tokens 偏差在 ±30% 內。 +// 壓力測試實測:160k ASCII bytes → 上游 input_tokens=100,761(比值 1.59)。 +func TestItemApproxTokensCalibration(t *testing.T) { + ascii := strings.Repeat("a", 160000) + got := itemApproxTokens(ascii) + want := 100761 // 上游實測值 + if diff := float64(got-want) / float64(want); diff > 0.30 || diff < -0.30 { + t.Fatalf("ASCII token 估算 = %d,上游實測 %d,偏差 %.1f%% 超出 ±30%%", got, want, diff*100) + } + // 中文:一個字元約 1 token。 + zh := itemApproxTokens(strings.Repeat("中", 1000)) + if zh < 800 || zh > 1200 { + t.Fatalf("中文 token 估算 = %d,期望約 1000", zh) + } +} + +// TestEffectiveContextWindow 驗證有效窗口按模型實測值查表、其餘模型用目錄標示、 +// 以及兩種環境覆寫(全域 + 按模型)都生效。 +func TestEffectiveContextWindow(t *testing.T) { + // 11 個免費模型的實測上限。 + want := map[string]int{ + "mimo-2.6-flash": 140000, // 140k 完整,170k 起靜默截斷 → 保守取 140k + "glyph-cluster": 256000, // 260k 完整,320k 硬拒絕 → 目錄標 256k + "glm-5.3-flash": 320000, + "deepseek-v4.1-flash": 320000, + "qwen-3.8-flash": 320000, + "minimax-m3.1-flash": 320000, + "muse-ember": 320000, + "solar-mini-4": 320000, + "gpt-6-luna": 320000, + "mimo-2.6-pro": 320000, + "deepai-cyber": 320000, + } + for id, exp := range want { + if got := effectiveContextWindow(id, 320000); got != exp { + t.Fatalf("%s 有效窗口 = %d,期望 %d", id, got, exp) + } + } + // 未知/付費模型:min(標示, 320k),不再硬壓 120k。 + if got := effectiveContextWindow("some-paid-model", 320000); got != 320000 { + t.Fatalf("未知模型 320k 標示應為 320000,實際 %d", got) + } + if got := effectiveContextWindow("some-paid-model", 200); got != 200 { + t.Fatalf("小於上限的標示應原樣保留,實際 %d", got) + } + + // 全域環境覆寫(舊行為保留)。 + t.Setenv("DEEPAI2API_EFFECTIVE_CONTEXT_WINDOW", "64000") + if got := effectiveContextWindow("glm-5.3-flash", 320000); got != 64000 { + t.Fatalf("全域環境覆寫應為 64000,實際 %d", got) + } + t.Setenv("DEEPAI2API_EFFECTIVE_CONTEXT_WINDOW", "0") + if got := effectiveContextWindow("glm-5.3-flash", 320000); got != 0 { + t.Fatalf("全域設 0 應關閉上限,實際 %d", got) + } +} + +// TestEffectiveContextWindowPerModelOverride 驗證 DEEPAI2API_CONTEXT_WINDOWS +// 按模型 JSON 覆寫:只改指定模型,不影響其他模型;全域覆寫優先於按模型。 +func TestEffectiveContextWindowPerModelOverride(t *testing.T) { + t.Setenv("DEEPAI2API_EFFECTIVE_CONTEXT_WINDOW", "") + t.Setenv("DEEPAI2API_CONTEXT_WINDOWS", `{"glm-5.3-flash":64000,"mimo-2.6-flash":0}`) + if got := effectiveContextWindow("glm-5.3-flash", 320000); got != 64000 { + t.Fatalf("按模型覆寫 glm 應為 64000,實際 %d", got) + } + if got := effectiveContextWindow("mimo-2.6-flash", 320000); got != 0 { + t.Fatalf("按模型覆寫 mimo 設 0 應關閉上限,實際 %d", got) + } + // 未列入 JSON 的模型仍走表格/標示值。 + if got := effectiveContextWindow("glyph-cluster", 320000); got != 256000 { + t.Fatalf("未覆寫的 glyph 應為 256000,實際 %d", got) + } + // 全域覆寫優先於按模型。 + t.Setenv("DEEPAI2API_EFFECTIVE_CONTEXT_WINDOW", "100000") + if got := effectiveContextWindow("glm-5.3-flash", 320000); got != 100000 { + t.Fatalf("全域覆寫應優先,實際 %d", got) + } + // 格式錯誤的 JSON 應忽略。 + t.Setenv("DEEPAI2API_EFFECTIVE_CONTEXT_WINDOW", "") + t.Setenv("DEEPAI2API_CONTEXT_WINDOWS", `not-json`) + if got := effectiveContextWindow("glm-5.3-flash", 320000); got != 320000 { + t.Fatalf("錯誤 JSON 應忽略,實際 %d", got) + } +} + +// TestTruncationPointFollowsModelWindow 驗證 truncation:auto 的裁剪點跟著 +// 各模型上限走:同一段約 20 萬 token 的歷史,mimo-flash(140k)會被裁, +// glm(320k)不會被裁——證明不再一律在 12 萬就提前裁剪。 +func TestTruncationPointFollowsModelWindow(t *testing.T) { + // 用 itemApproxTokens 反推:產生約 200000 tokens 的 ASCII(每 token ~1.6 bytes)。 + bigFill := strings.Repeat("a", 200000*8/5) // 320000 bytes → 約 200000 tokens + items := []any{ + map[string]any{"type": "message", "role": "user", "content": "開頭暗號 ZEBRA42"}, + map[string]any{"type": "message", "role": "user", "content": bigFill}, + map[string]any{"type": "message", "role": "user", "content": "最新提問"}, + } + total := 0 + for _, it := range items { + total += itemApproxTokens(it) + } + if total < 150000 || total > 250000 { + t.Fatalf("測試資料 token 估算 = %d,期望約 20 萬", total) + } + + // 模擬 replay 的判斷:只有 total > limit 才裁剪。 + maybeTruncate := func(modelID string) ([]any, int) { + limit := effectiveContextWindow(modelID, 320000) + if total > limit { + return truncateHistory(cloneAnySlice(items), limit), limit + } + return cloneAnySlice(items), limit + } + + // mimo-2.6-flash:上限 140k,20 萬歷史超限 → 應裁剪並留標記。 + mimoOut, mimoLimit := maybeTruncate("mimo-2.6-flash") + if mimoLimit != 140000 { + t.Fatalf("mimo 上限 = %d,期望 140000", mimoLimit) + } + mimoBlob, _ := json.Marshal(mimoOut) + if !strings.Contains(string(mimoBlob), "自動省略") { + t.Fatalf("mimo 在 140k 上限應裁剪並留標記,實際未裁") + } + + // glm:上限 320k,同一段 20 萬歷史不超限 → 不應裁剪。 + glmOut, glmLimit := maybeTruncate("glm-5.3-flash") + if glmLimit != 320000 { + t.Fatalf("glm 上限 = %d,期望 320000", glmLimit) + } + glmBlob, _ := json.Marshal(glmOut) + if strings.Contains(string(glmBlob), "自動省略") { + t.Fatalf("glm 在 320k 上限不應裁剪 20 萬歷史,卻被裁了") + } +} + +// 確保 deepai import 被使用(模型的 IsResponses 路徑在別的測試覆蓋)。 +var _ = deepai.PathChat diff --git a/internal/server/responses.go b/internal/server/responses.go index dce297e..2017bc2 100644 --- a/internal/server/responses.go +++ b/internal/server/responses.go @@ -45,20 +45,44 @@ func (s *Server) handleResponses(w http.ResponseWriter, r *http.Request) { rls := s.newReqLog(key, nil, model.ID, "responses", stream, start, promptLen).withHistory(payload) if p := statefulParam(payload); p != "" { - // 依赖上游保存的响应状态:合成路径无法重建,必须明说;透传路径 - // 原样交给上游(能不能续接由上游决定),但留一条日志。 - if !model.IsResponses() { + // previous_response_id:合成路徑現在透過伺服端歷史暫存重放上下文, + // 不再直接回 400(那是「失憶」的根因)。重放失敗才退回明確 400。 + // conversation / item_reference 需要上游保存的服務端會話/條目, + // 網關無從重建,保留明確 400 並在文件寫清楚。 + if !model.IsResponses() && p == "previous_response_id" { + prevID := strOf(payload["previous_response_id"]) + outcome, msg := s.history.replay(payload, prevID, model.ID, model.ContextWindow) + switch outcome { + case replayNotFound: + s.metrics.addStateful(p, true) + httpx.WriteErr(w, http.StatusBadRequest, + (&statefulParamError{Param: p}).Error(), "unsupported_parameter") + return + case replayTooLong: + s.metrics.addStateful(p, true) + httpx.WriteErr(w, http.StatusBadRequest, msg, "invalid_request_error") + return + } + s.metrics.addStateful(p, false) // 已重放,視為成功續接 + logx.Info("Responses 歷史重放成功", "model", model.ID, "prev", prevID) + } else if !model.IsResponses() { s.metrics.addStateful(p, true) httpx.WriteErr(w, http.StatusBadRequest, (&statefulParamError{Param: p}).Error(), "unsupported_parameter") return + } else { + s.metrics.addStateful(p, false) + logx.Warn("上游 /responses 透傳帶狀態字段:續接能力取決於上游", + "param", p, "model", model.ID) } - s.metrics.addStateful(p, false) - logx.Warn("上游 /responses 透传带状态字段:续接能力取决于上游", - "param", p, "model", model.ID) + } + // 記錄本輪「送出前的輸入快照」,回應完成後連同輸出寫入暫存。 + turn := &responseTurn{ + input: responsesInputArray(payload), + instructions: strOf(payload["instructions"]), } if model.IsResponses() { - s.passthroughResponses(w, r, payload, affinity, rls) + s.passthroughResponses(w, r, payload, affinity, rls, turn) return } @@ -68,14 +92,14 @@ func (s *Server) handleResponses(w http.ResponseWriter, r *http.Request) { return } if stream { - s.streamResponsesAsChat(w, r, chatPayload, affinity, rls) + s.streamResponsesAsChat(w, r, chatPayload, affinity, rls, turn) return } - s.blockingResponsesAsChat(w, r, chatPayload, affinity, rls) + s.blockingResponsesAsChat(w, r, chatPayload, affinity, rls, turn) } // passthroughResponses 透传上游 /responses。 -func (s *Server) passthroughResponses(w http.ResponseWriter, r *http.Request, payload map[string]any, affinity string, rl reqLog) { +func (s *Server) passthroughResponses(w http.ResponseWriter, r *http.Request, payload map[string]any, affinity string, rl reqLog, turn *responseTurn) { ctx, cancel := httpx.ContextWithTimeout(r, s.requestTimeout()) defer cancel() @@ -116,6 +140,7 @@ func (s *Server) passthroughResponses(w http.ResponseWriter, r *http.Request, pa rewriteResponsesModel(out, rl.model) usage := parseUsage(out["usage"]) outLen := responsesTextLen(out) + s.rememberResponse(turn, out) encoded, _ := json.Marshal(out) rl.done(outLen, usage, nil) httpx.WriteRawJSON(w, http.StatusOK, encoded) @@ -124,8 +149,9 @@ func (s *Server) passthroughResponses(w http.ResponseWriter, r *http.Request, pa sw := newSSEWriter(w) var ( - usage Usage - outLen int + usage Usage + outLen int + finalResp map[string]any ) streamErr := forEachSSEFrame(resp.Body, func(f sseFrame) bool { if f.Event != "" { @@ -146,6 +172,12 @@ func (s *Server) passthroughResponses(w http.ResponseWriter, r *http.Request, pa return true } rewriteResponsesModel(obj, rl.model) + // 記住最終 response 物件(含 id / output):串流重放的依據。 + if strOf(obj["type"]) == "response.completed" { + if respObj, ok := obj["response"].(map[string]any); ok { + finalResp = respObj + } + } if respObj, ok := obj["response"].(map[string]any); ok { if u := parseUsage(respObj["usage"]); u.TotalTokens > 0 || u.Cost > 0 { usage = u @@ -169,11 +201,14 @@ func (s *Server) passthroughResponses(w http.ResponseWriter, r *http.Request, pa sw.event("error", payload) } } + if streamErr == nil { + s.rememberResponse(turn, finalResp) + } rl.done(outLen, usage, streamErr) } // blockingResponsesAsChat 用 Chat Completions 合成 Responses 响应。 -func (s *Server) blockingResponsesAsChat(w http.ResponseWriter, r *http.Request, chatPayload map[string]any, affinity string, rl reqLog) { +func (s *Server) blockingResponsesAsChat(w http.ResponseWriter, r *http.Request, chatPayload map[string]any, affinity string, rl reqLog, turn *responseTurn) { ctx, cancel := httpx.ContextWithTimeout(r, s.requestTimeout()) defer cancel() @@ -188,12 +223,13 @@ func (s *Server) blockingResponsesAsChat(w http.ResponseWriter, r *http.Request, usage := parseUsage(out["usage"]) outLen := responsesTextLen(respObj) + s.rememberResponse(turn, respObj) rl.done(outLen, usage, nil) httpx.WriteJSON(w, http.StatusOK, respObj) } // streamResponsesAsChat 用 Chat Completions 流合成 Responses 事件流。 -func (s *Server) streamResponsesAsChat(w http.ResponseWriter, r *http.Request, chatPayload map[string]any, affinity string, rl reqLog) { +func (s *Server) streamResponsesAsChat(w http.ResponseWriter, r *http.Request, chatPayload map[string]any, affinity string, rl reqLog, turn *responseTurn) { ctx, cancel := httpx.ContextWithTimeout(r, s.requestTimeout()) defer cancel() @@ -246,11 +282,26 @@ func (s *Server) streamResponsesAsChat(w http.ResponseWriter, r *http.Request, c gen.fail(streamErr) } gen.complete(usage) + s.rememberResponse(turn, gen.finalResponse) rl.done(outLen, usage, streamErr) } // --- 工具函数 --- +// rememberResponse 從最終 Responses 物件取出 id / output 寫入歷史暫存。 +// 只有成功完成(有 id 與 output)的回應才會被記住。 +func (s *Server) rememberResponse(turn *responseTurn, resp map[string]any) { + if resp == nil || s.history == nil { + return + } + id := strOf(resp["id"]) + output, _ := resp["output"].([]any) + if id == "" || len(output) == 0 { + return + } + s.history.remember(turn, id, output) +} + // rewriteResponsesModel 把 Responses 对象 / 事件里的 model 改为对外模型名。 func rewriteResponsesModel(obj map[string]any, publicModel string) { if publicModel == "" { diff --git a/internal/server/responses_stream.go b/internal/server/responses_stream.go index 2269a87..119bebc 100644 --- a/internal/server/responses_stream.go +++ b/internal/server/responses_stream.go @@ -31,6 +31,8 @@ type responsesStreamGen struct { // output_index 不一定同序(上游可能先发工具再发文本),发出前必须按 // index 排序,否则 response.output 的顺序与流里报的 output_index 矛盾。 output []responsesOutputItem + // finalResponse 是 complete() 時的最終 response 物件;供伺服端歷史暫存使用。 + finalResponse map[string]any } // responsesOutputItem 是最终 response.output 的一项(带排序键)。 @@ -268,7 +270,9 @@ func (g *responsesStreamGen) complete(usage Usage) { g.closeText() g.closeReasoning() g.closeTools() + resp := g.response("completed", usage) + g.finalResponse = resp g.emit("response.completed", map[string]any{ - "response": g.response("completed", usage), + "response": resp, }) } diff --git a/internal/server/server.go b/internal/server/server.go index 2cba788..94a9b55 100644 --- a/internal/server/server.go +++ b/internal/server/server.go @@ -116,6 +116,10 @@ type Server struct { // shapeNeed 记忆「哪些调用方需要桌面端形状」(见 shape.go)。 shapeMu sync.Mutex shapeNeed map[string]time.Time + + // history 是 /v1/responses 的伺服端對話歷史暫存(見 response_history.go)。 + // 讓 previous_response_id 在無狀態合成路徑上也能續接,而非回 400 造成失憶。 + history *responseHistory } // New 构造服务。 @@ -133,6 +137,7 @@ func New(st *store.Store) *Server { adminGuard: newAdminGuard(), metrics: newMetrics(), sticky: map[string]store.StickyBinding{}, + history: newResponseHistoryFromEnv(), } // 上次探测到的车道优先(跨重启保留);CurrentLane 会区分「本次构建验证过 // 的探测值」与「旧版本残留」,后者才用较新的编译期默认值兜底。 From 594b6914763d324947a5ee19360f701fe64061aa Mon Sep 17 00:00:00 2001 From: lizi <2951461586@qq.com> Date: Fri, 20 Nov 2026 13:22:08 +0800 Subject: [PATCH 2/2] fix(responses): bound history cache and reject incomplete replay --- README.md | 7 +-- internal/server/protocol_fixes_test.go | 4 +- internal/server/response_history.go | 69 +++++++++++++++++++----- internal/server/response_history_test.go | 62 ++++++++++++++++++--- internal/server/responses.go | 11 ++-- 5 files changed, 123 insertions(+), 30 deletions(-) diff --git a/README.md b/README.md index 54acda9..91835be 100644 --- a/README.md +++ b/README.md @@ -754,9 +754,10 @@ go build -ldflags "-X main.version=v0.1.2" -o bin/deepaicode2api . ## 十、限制与说明 -- 网关是**无状态代理**:不存对话,也不补历史。`/v1/responses` 的续接字段 - (`previous_response_id` / `conversation` / `item_reference`)在合成路径直接回 400 - `unsupported_parameter`,在透传路径交给上游(详见「上下文契约」一节); +- `/v1/chat/completions` 与 `/v1/messages` 不存对话,也不补历史。`/v1/responses` + 合成路径会在进程内暂存已完成响应,支持 `previous_response_id` 重放;缓存有 TTL、条目数 + 与 64 MiB 总量上限,进程重启后清空。找不到历史、`conversation` / `item_reference` + 仍回明确 400;上下文超限时按「上下文契约」处理; - `X-DeepAI-Code-Theos` 发 `7`(0.3.41 起)。上游门槛可能放宽:2026-11-19 实测 ≤7 全通过、 8 及以上 426,此时旧车道「能用」并不代表车道是对的 —— 与上游当前车道的差异由 `/theos` 的 `lane_version` 观测(`Server.UpstreamLane` / `LaneDrift`,控制台概览可见); diff --git a/internal/server/protocol_fixes_test.go b/internal/server/protocol_fixes_test.go index 3bdd579..7062c7a 100644 --- a/internal/server/protocol_fixes_test.go +++ b/internal/server/protocol_fixes_test.go @@ -370,9 +370,9 @@ func TestSessionAffinitySkipsBareRequests(t *testing.T) { // // 非 openai-responses 模型走 chat 合成路径,只有 input 里的内容; // previous_response_id 若被忽略,客户端以为续接成功,实际模型只看得到本轮。 -func TestResponsesStatefulRejectedOnTranslatedModel(t *testing.T) { +func TestResponsesStatefulRejectedWhenHistoryMissing(t *testing.T) { u := newUpstream(t, func(w http.ResponseWriter, r *http.Request) { - t.Errorf("不应打到上游,路径 %s", r.URL.Path) + t.Errorf("找不到历史时不应打到上游,路径 %s", r.URL.Path) w.WriteHeader(http.StatusOK) }) s, key := newTestServer(t, u) diff --git a/internal/server/response_history.go b/internal/server/response_history.go index 473eb7d..8a60c25 100644 --- a/internal/server/response_history.go +++ b/internal/server/response_history.go @@ -53,12 +53,14 @@ func (h *responseHistory) remember(turn *responseTurn, respID string, output []a // responseHistory 是執行緒安全的對話歷史暫存。 type responseHistory struct { - mu sync.RWMutex - entries map[string]*historyEntry - order []string // 插入順序,供容量淘汰 - ttl time.Duration - max int - now func() time.Time // 測試可注入 + mu sync.RWMutex + entries map[string]*historyEntry + order []string // 插入順序,供容量淘汰 + ttl time.Duration + max int + maxBytes int64 + usedBytes int64 + now func() time.Time // 測試可注入 } // newResponseHistoryFromEnv 從環境變數構造暫存。 @@ -79,10 +81,11 @@ func newResponseHistory(ttl time.Duration, max int) *responseHistory { max = 500 } return &responseHistory{ - entries: map[string]*historyEntry{}, - ttl: ttl, - max: max, - now: time.Now, + entries: map[string]*historyEntry{}, + ttl: ttl, + max: max, + maxBytes: 64 << 20, + now: time.Now, } } @@ -107,17 +110,27 @@ func (h *responseHistory) put(id string, e *historyEntry) { if e.createdAt.IsZero() { e.createdAt = h.now() } + size := historyEntryBytes(e) + if size > h.maxBytes { + return + } h.mu.Lock() defer h.mu.Unlock() h.purgeExpiredLocked() - if _, exists := h.entries[id]; !exists { + if old := h.entries[id]; old != nil { + h.usedBytes -= historyEntryBytes(old) + } else { h.order = append(h.order, id) } h.entries[id] = e - for len(h.order) > h.max { + h.usedBytes += size + for len(h.order) > h.max || h.usedBytes > h.maxBytes { oldest := h.order[0] h.order = h.order[1:] - delete(h.entries, oldest) + if old := h.entries[oldest]; old != nil { + h.usedBytes -= historyEntryBytes(old) + delete(h.entries, oldest) + } } } @@ -173,8 +186,13 @@ func (h *responseHistory) replay(payload map[string]any, prevID, modelID string, // 目錄標示(mimo-flash 140k、glyph 256k),其餘 9 個免費模型可吃滿 320k。 // 讓網關先裁剪並留下標記,也不要讓上游偷偷砍歷史。 limit := effectiveContextWindow(modelID, contextWindow) + instructions := strOf(payload["instructions"]) + if instructions == "" { + instructions = e.instructions + } + instructionTokens := itemApproxTokens(instructions) if limit > 0 { - total := 0 + total := instructionTokens for _, it := range merged { total += itemApproxTokens(it) } @@ -186,6 +204,13 @@ func (h *responseHistory) replay(payload map[string]any, prevID, modelID string, ");請由客戶端壓縮歷史,或於請求設定 \"truncation\":\"auto\" 由網關自動裁減最舊中段。" } merged = truncateHistory(merged, limit) + remaining := instructionTokens + for _, it := range merged { + remaining += itemApproxTokens(it) + } + if remaining > limit { + return replayTooLong, "truncation:auto 無法將對話壓至模型有效上下文 contextWindow " + itoaApprox(limit) + " tokens;請先縮短單則訊息或工具輸出。" + } } } @@ -365,6 +390,9 @@ func (h *responseHistory) purgeExpiredLocked() { for _, id := range h.order { e := h.entries[id] if e == nil || now.Sub(e.createdAt) > h.ttl { + if e != nil { + h.usedBytes -= historyEntryBytes(e) + } delete(h.entries, id) continue } @@ -373,6 +401,19 @@ func (h *responseHistory) purgeExpiredLocked() { h.order = kept } +func historyEntryBytes(e *historyEntry) int64 { + if e == nil { + return 0 + } + raw, _ := json.Marshal(struct { + ID string `json:"id"` + Input []any `json:"input"` + Instructions string `json:"instructions"` + Output []any `json:"output"` + }{e.id, e.input, e.instructions, e.output}) + return int64(len(raw)) +} + // len 供測試與監控使用。 func (h *responseHistory) len() int { if h == nil { diff --git a/internal/server/response_history_test.go b/internal/server/response_history_test.go index e9b4a4f..3b7a56b 100644 --- a/internal/server/response_history_test.go +++ b/internal/server/response_history_test.go @@ -248,6 +248,32 @@ func TestResponsesStreamChainMemoryAndEvents(t *testing.T) { } } +func TestRememberResponseSkipsIncomplete(t *testing.T) { + s := &Server{history: newResponseHistory(time.Hour, 10)} + turn := &responseTurn{input: []any{"hello"}} + s.rememberResponse(turn, map[string]any{ + "id": "resp_incomplete", "status": "incomplete", + "output": []any{map[string]any{"type": "message"}}, + }) + if s.history.get("resp_incomplete") != nil { + t.Fatal("incomplete response 不應進入歷史快取") + } +} + +// TestResponsesHistoryByteLimit 验证单条过大时不写入,且不会挤掉已有历史。 +func TestResponsesHistoryByteLimit(t *testing.T) { + h := newResponseHistory(time.Hour, 10) + h.maxBytes = 128 + h.put("small", &historyEntry{input: []any{"ok"}}) + h.put("large", &historyEntry{input: []any{strings.Repeat("x", 256)}}) + if h.get("large") != nil || h.get("small") == nil { + t.Fatal("应拒绝过大的单条历史,并保留已有小条目") + } + if h.usedBytes > h.maxBytes { + t.Fatalf("缓存占用 %d 超过上限 %d", h.usedBytes, h.maxBytes) + } +} + // TestResponsesHistoryTTLAndMax 驗證 TTL 與容量上限。 func TestResponsesHistoryTTLAndMax(t *testing.T) { base := time.Date(2026, 1, 1, 0, 0, 0, 0, time.UTC) @@ -307,9 +333,8 @@ func TestResponsesTruncationAuto(t *testing.T) { const codeword = "ZEBRA42" u := codewordUpstream(t, codeword) s, key := newTestServer(t, u) - // 用全域環境覆寫把有效窗口壓到很小(約 200 tokens → 600 bytes), - // 讓「開頭暗號 + 數輪填充 + 最新提問」必然超限;不影響按模型查表。 - t.Setenv("DEEPAI2API_EFFECTIVE_CONTEXT_WINDOW", "200") + // 用全域環境覆寫把有效窗口壓到 400 tokens,便於測試多輪舊歷史裁剪。 + t.Setenv("DEEPAI2API_EFFECTIVE_CONTEXT_WINDOW", "400") // 第 1 輪:暗號。 r1 := do(t, s, http.MethodPost, "/v1/responses", key, @@ -319,13 +344,20 @@ func TestResponsesTruncationAuto(t *testing.T) { } id, _ := respIDAndText(t, r1) - // 第 2 輪:帶長填充讓鏈變很長,truncation:auto。 - longFill := strings.Repeat("filler word ", 120) // ~1440 bytes → 远超 600 + // 累積多輪中段歷史,再以短問題觸發舊歷史裁剪。 + fill := strings.Repeat("filler ", 50) body2 := `{"model":"glm-5.3-flash","previous_response_id":"` + id + - `","truncation":"auto","input":"What is the codeword? ` + longFill + `"}` + `","truncation":"auto","input":"` + fill + `"}` r2 := do(t, s, http.MethodPost, "/v1/responses", key, body2) if r2.Code != http.StatusOK { - t.Fatalf("truncation:auto 應回 200,實際 %d:%s", r2.Code, r2.Body.String()) + t.Fatalf("第 2 輪 = %d:%s", r2.Code, r2.Body.String()) + } + id, _ = respIDAndText(t, r2) + body3 := `{"model":"glm-5.3-flash","previous_response_id":"` + id + + `","truncation":"auto","input":"What is the codeword?"}` + r3 := do(t, s, http.MethodPost, "/v1/responses", key, body3) + if r3.Code != http.StatusOK { + t.Fatalf("truncation:auto 應回 200,實際 %d:%s", r3.Code, r3.Body.String()) } // 上游收到的 messages 應含裁減標記、開頭暗號、以及最新提問。 @@ -353,6 +385,22 @@ func TestResponsesTruncationAuto(t *testing.T) { } } +func TestTruncateHistoryRejectsOversizedItems(t *testing.T) { + items := []any{ + map[string]any{"type": "message", "role": "user", "content": strings.Repeat("x", 500)}, + map[string]any{"type": "message", "role": "assistant", "content": "ok"}, + map[string]any{"type": "message", "role": "user", "content": "latest"}, + } + got := truncateHistory(items, 100) + total := 0 + for _, item := range got { + total += itemApproxTokens(item) + } + if total <= 100 { + t.Fatalf("期望单条消息仍超限以便 replay 返回错误,估算=%d", total) + } +} + // TestResponsesTruncationRequired 驗證未設 truncation 時超限回明確 400, // 不靜默砍歷史(那是失憶根源)。 func TestResponsesTruncationRequired(t *testing.T) { diff --git a/internal/server/responses.go b/internal/server/responses.go index 2017bc2..4fca386 100644 --- a/internal/server/responses.go +++ b/internal/server/responses.go @@ -140,7 +140,9 @@ func (s *Server) passthroughResponses(w http.ResponseWriter, r *http.Request, pa rewriteResponsesModel(out, rl.model) usage := parseUsage(out["usage"]) outLen := responsesTextLen(out) - s.rememberResponse(turn, out) + if strOf(out["status"]) == "completed" { + s.rememberResponse(turn, out) + } encoded, _ := json.Marshal(out) rl.done(outLen, usage, nil) httpx.WriteRawJSON(w, http.StatusOK, encoded) @@ -280,9 +282,10 @@ func (s *Server) streamResponsesAsChat(w http.ResponseWriter, r *http.Request, c if streamErr != nil { gen.fail(streamErr) + } else { + gen.complete(usage) + s.rememberResponse(turn, gen.finalResponse) } - gen.complete(usage) - s.rememberResponse(turn, gen.finalResponse) rl.done(outLen, usage, streamErr) } @@ -291,7 +294,7 @@ func (s *Server) streamResponsesAsChat(w http.ResponseWriter, r *http.Request, c // rememberResponse 從最終 Responses 物件取出 id / output 寫入歷史暫存。 // 只有成功完成(有 id 與 output)的回應才會被記住。 func (s *Server) rememberResponse(turn *responseTurn, resp map[string]any) { - if resp == nil || s.history == nil { + if resp == nil || s.history == nil || strOf(resp["status"]) != "completed" { return } id := strOf(resp["id"])