From 4d4a0be1ad2a994bcf8ca175444a9eb2facb28b4 Mon Sep 17 00:00:00 2001 From: Pengap Date: Mon, 10 Aug 2026 11:29:49 +0800 Subject: [PATCH 001/204] =?UTF-8?q?fix(apicompat):=20chat/completions=20fi?= =?UTF-8?q?le=20part=20=E4=B8=8D=E5=86=8D=E8=A2=AB=E9=9D=99=E9=BB=98?= =?UTF-8?q?=E4=B8=A2=E5=BC=83=EF=BC=8C=E8=BD=AC=E6=8D=A2=E4=B8=BA=20Respon?= =?UTF-8?q?ses=20input=5Ffile?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit /v1/chat/completions → Responses 转换层此前只处理 text 和 image_url 两种 content part,type:"file"(PDF 附件)被静默丢弃:请求返回 200、模型正常 回答,但 prompt 里没有文件(prompt_tokens 只剩纯文字)。 现将 file part 映射为 Responses API 的 input_file(filename/file_data/ file_id 透传),与同网关 /v1/responses + input_file 实测可用的格式一致。 无 file_data 且无 file_id 的空 file part 跳过,与空 image URL 行为一致。 参考上游 PR #2497(因混入无关改动未合并)。 --- .../chatcompletions_responses_test.go | 73 +++++++++++++++++++ .../apicompat/chatcompletions_to_responses.go | 9 +++ backend/internal/pkg/apicompat/types.go | 17 ++++- 3 files changed, 97 insertions(+), 2 deletions(-) diff --git a/backend/internal/pkg/apicompat/chatcompletions_responses_test.go b/backend/internal/pkg/apicompat/chatcompletions_responses_test.go index 4e319f9751..7a1584b529 100644 --- a/backend/internal/pkg/apicompat/chatcompletions_responses_test.go +++ b/backend/internal/pkg/apicompat/chatcompletions_responses_test.go @@ -407,6 +407,79 @@ func TestChatCompletionsToResponses_WhitespaceOnlyBase64ImageURLSkipped(t *testi assert.Equal(t, "Describe this", parts[0].Text) } +func TestChatCompletionsToResponses_FilePartFileData(t *testing.T) { + content := `[{"type":"text","text":"Summarize the attached document"},{"type":"file","file":{"filename":"document.pdf","file_data":"data:application/pdf;base64,JVBERi0xLjQ="}}]` + req := &ChatCompletionsRequest{ + Model: "gpt-4o", + Messages: []ChatMessage{ + {Role: "user", Content: json.RawMessage(content)}, + }, + } + resp, err := ChatCompletionsToResponses(req) + require.NoError(t, err) + + var items []ResponsesInputItem + require.NoError(t, json.Unmarshal(resp.Input, &items)) + require.Len(t, items, 1) + + var parts []ResponsesContentPart + require.NoError(t, json.Unmarshal(items[0].Content, &parts)) + require.Len(t, parts, 2) + assert.Equal(t, "input_text", parts[0].Type) + assert.Equal(t, "Summarize the attached document", parts[0].Text) + assert.Equal(t, "input_file", parts[1].Type) + assert.Equal(t, "document.pdf", parts[1].Filename) + assert.Equal(t, "data:application/pdf;base64,JVBERi0xLjQ=", parts[1].FileData) + assert.Empty(t, parts[1].FileID) +} + +func TestChatCompletionsToResponses_FilePartFileID(t *testing.T) { + content := `[{"type":"file","file":{"file_id":"file-abc123"}}]` + req := &ChatCompletionsRequest{ + Model: "gpt-4o", + Messages: []ChatMessage{ + {Role: "user", Content: json.RawMessage(content)}, + }, + } + resp, err := ChatCompletionsToResponses(req) + require.NoError(t, err) + + var items []ResponsesInputItem + require.NoError(t, json.Unmarshal(resp.Input, &items)) + require.Len(t, items, 1) + + var parts []ResponsesContentPart + require.NoError(t, json.Unmarshal(items[0].Content, &parts)) + require.Len(t, parts, 1) + assert.Equal(t, "input_file", parts[0].Type) + assert.Equal(t, "file-abc123", parts[0].FileID) + assert.Empty(t, parts[0].FileData) +} + +func TestChatCompletionsToResponses_EmptyFilePartSkipped(t *testing.T) { + // A file part with neither file_data nor file_id carries nothing the + // Responses API can use; dropping it (like empty image URLs) avoids an + // upstream 400 on an empty input_file part. + content := `[{"type":"text","text":"Describe this"},{"type":"file","file":{"filename":"empty.pdf"}}]` + req := &ChatCompletionsRequest{ + Model: "gpt-4o", + Messages: []ChatMessage{ + {Role: "user", Content: json.RawMessage(content)}, + }, + } + resp, err := ChatCompletionsToResponses(req) + require.NoError(t, err) + + var items []ResponsesInputItem + require.NoError(t, json.Unmarshal(resp.Input, &items)) + require.Len(t, items, 1) + + var parts []ResponsesContentPart + require.NoError(t, json.Unmarshal(items[0].Content, &parts)) + require.Len(t, parts, 1) + assert.Equal(t, "input_text", parts[0].Type) +} + func TestChatCompletionsToResponses_EmptyContentNeverNull(t *testing.T) { // Regression for #2515: the upstream Responses API rejects an input item // whose content field is JSON null. Any chat-completions message that diff --git a/backend/internal/pkg/apicompat/chatcompletions_to_responses.go b/backend/internal/pkg/apicompat/chatcompletions_to_responses.go index 0f65d217e8..de908c86a1 100644 --- a/backend/internal/pkg/apicompat/chatcompletions_to_responses.go +++ b/backend/internal/pkg/apicompat/chatcompletions_to_responses.go @@ -378,6 +378,15 @@ func convertChatContentPartsToResponses(parts []ChatContentPart) []ResponsesCont ImageURL: p.ImageURL.URL, }) } + case "file": + if p.File != nil && (p.File.FileData != "" || p.File.FileID != "") { + responseParts = append(responseParts, ResponsesContentPart{ + Type: "input_file", + Filename: p.File.Filename, + FileData: p.File.FileData, + FileID: p.File.FileID, + }) + } } } return responseParts diff --git a/backend/internal/pkg/apicompat/types.go b/backend/internal/pkg/apicompat/types.go index c4cde405e1..52d03876cb 100644 --- a/backend/internal/pkg/apicompat/types.go +++ b/backend/internal/pkg/apicompat/types.go @@ -295,9 +295,14 @@ func (i *ResponsesInputItem) UnmarshalJSON(data []byte) error { // ResponsesContentPart is a typed content part in a Responses message. type ResponsesContentPart struct { - Type string `json:"type"` // "input_text" | "output_text" | "input_image" + Type string `json:"type"` // "input_text" | "output_text" | "input_image" | "input_file" Text string `json:"text,omitempty"` ImageURL string `json:"image_url,omitempty"` // data URI for input_image + + // input_file fields. + Filename string `json:"filename,omitempty"` + FileData string `json:"file_data,omitempty"` // data URI + FileID string `json:"file_id,omitempty"` } // ResponsesTool describes a tool in the Responses API. @@ -661,9 +666,10 @@ type ChatMessage struct { // ChatContentPart is a typed content part in a multi-modal message. type ChatContentPart struct { - Type string `json:"type"` // "text" | "image_url" + Type string `json:"type"` // "text" | "image_url" | "file" Text string `json:"text,omitempty"` ImageURL *ChatImageURL `json:"image_url,omitempty"` + File *ChatFile `json:"file,omitempty"` } // ChatImageURL contains the URL for an image content part. @@ -672,6 +678,13 @@ type ChatImageURL struct { Detail string `json:"detail,omitempty"` // "auto" | "low" | "high" } +// ChatFile contains the payload of a "file" content part (e.g. PDF input). +type ChatFile struct { + Filename string `json:"filename,omitempty"` + FileData string `json:"file_data,omitempty"` // data URI + FileID string `json:"file_id,omitempty"` +} + // ChatTool describes a tool available to the model. type ChatTool struct { Type string `json:"type"` // "function" From e7a3c1202eafca989857dd18f9cfaf0c4de9be67 Mon Sep 17 00:00:00 2001 From: wucm667 Date: Fri, 14 Aug 2026 02:40:18 +0800 Subject: [PATCH 002/204] fix(antigravity): route paid accounts to daily endpoint --- .../service/antigravity_gateway_retry.go | 30 +++++++++--- .../service/antigravity_rate_limit_test.go | 46 ++++++++++++++++--- 2 files changed, 63 insertions(+), 13 deletions(-) diff --git a/backend/internal/service/antigravity_gateway_retry.go b/backend/internal/service/antigravity_gateway_retry.go index f2f5d44f84..5e16ba8692 100644 --- a/backend/internal/service/antigravity_gateway_retry.go +++ b/backend/internal/service/antigravity_gateway_retry.go @@ -48,17 +48,14 @@ type antigravityRetryLoopResult struct { // resolveAntigravityForwardBaseURL 解析转发用 base URL。 // -// 默认使用生产端点 cloudcode-pa.googleapis.com(antigravity.BaseURLs 的首个地址, -// 与账号 OAuth 登录/测试连接所用的 antigravity.BaseURL 一致)。 +// 显式环境变量优先。未配置时,LoadCodeAssist 返回 paidTier 的付费账号使用 +// daily 端点,其他账号继续使用生产端点,避免免费账号的 OAuth token 出现 401。 // // 历史上这里改用 ForwardBaseURLs()(把 daily/sandbox 排到首位)并默认取首个地址, // 导致网关把带生产 OAuth token 的请求发到 daily-cloudcode-pa.sandbox.googleapis.com, // 上游拒绝 → 账号被 401「Invalid bearer token」/502 打入临时不可调度且无法恢复 // (见 #3611 / #2962)。后台「测试连接」用的是生产端点,所以「测试成功但网关 401」。 -// -// daily/sandbox 端点仅供内部联调,需显式设置 -// GATEWAY_ANTIGRAVITY_FORWARD_BASE_URL=daily(或 sandbox)才启用。 -func resolveAntigravityForwardBaseURL() string { +func resolveAntigravityForwardBaseURL(account *Account) string { baseURLs := antigravity.BaseURLs if len(baseURLs) == 0 { return "" @@ -67,9 +64,28 @@ func resolveAntigravityForwardBaseURL() string { if (mode == "daily" || mode == "sandbox") && len(baseURLs) > 1 { return baseURLs[1] } + if mode == "" && accountHasAntigravityPaidTier(account) && len(baseURLs) > 1 { + return baseURLs[1] + } return baseURLs[0] } +func accountHasAntigravityPaidTier(account *Account) bool { + if account == nil || account.Credentials == nil { + return false + } + planType, ok := account.Credentials["plan_type"].(string) + if !ok { + return false + } + switch strings.ToLower(strings.TrimSpace(planType)) { + case "pro", "ultra": + return true + default: + return false + } +} + // smartRetryAction 智能重试的处理结果 type smartRetryAction int @@ -488,7 +504,7 @@ func (s *AntigravityGatewayService) antigravityRetryLoop(p antigravityRetryLoopP } } - baseURL := resolveAntigravityForwardBaseURL() + baseURL := resolveAntigravityForwardBaseURL(p.account) if baseURL == "" { return nil, errors.New("no antigravity forward base url configured") } diff --git a/backend/internal/service/antigravity_rate_limit_test.go b/backend/internal/service/antigravity_rate_limit_test.go index 374b29f610..c9b4298291 100644 --- a/backend/internal/service/antigravity_rate_limit_test.go +++ b/backend/internal/service/antigravity_rate_limit_test.go @@ -1009,9 +1009,7 @@ func TestIsAntigravityAccountSwitchError(t *testing.T) { } } -func TestResolveAntigravityForwardBaseURL_DefaultDaily(t *testing.T) { - t.Setenv(antigravityForwardBaseURLEnv, "") - +func TestResolveAntigravityForwardBaseURL(t *testing.T) { oldBaseURLs := append([]string(nil), antigravity.BaseURLs...) defer func() { antigravity.BaseURLs = oldBaseURLs @@ -1019,10 +1017,46 @@ func TestResolveAntigravityForwardBaseURL_DefaultDaily(t *testing.T) { prodURL := "https://prod.test" dailyURL := "https://daily.test" - antigravity.BaseURLs = []string{dailyURL, prodURL} + antigravity.BaseURLs = []string{prodURL, dailyURL} - resolved := resolveAntigravityForwardBaseURL() - require.Equal(t, dailyURL, resolved) + tests := []struct { + name string + env string + account *Account + want string + }{ + { + name: "pro defaults to daily", account: &Account{Credentials: map[string]any{"plan_type": " Pro "}}, + want: dailyURL, + }, + { + name: "ultra defaults to daily", account: &Account{Credentials: map[string]any{"plan_type": "ULTRA"}}, + want: dailyURL, + }, + {name: "free defaults to prod", account: &Account{Credentials: map[string]any{"plan_type": "free"}}, want: prodURL}, + {name: "abnormal defaults to prod", account: &Account{Credentials: map[string]any{"plan_type": "Abnormal"}}, want: prodURL}, + {name: "unknown defaults to prod", account: &Account{Credentials: map[string]any{"plan_type": "enterprise"}}, want: prodURL}, + {name: "malformed defaults to prod", account: &Account{Credentials: map[string]any{"plan_type": map[string]any{"name": "pro"}}}, want: prodURL}, + {name: "missing defaults to prod", account: &Account{Credentials: map[string]any{}}, want: prodURL}, + {name: "nil account defaults to prod", account: nil, want: prodURL}, + { + name: "daily override wins for free tier", env: " daily ", + account: &Account{Credentials: map[string]any{"plan_type": "free"}}, + want: dailyURL, + }, + { + name: "prod override wins for paid tier", env: " PROD ", + account: &Account{Credentials: map[string]any{"plan_type": "pro"}}, + want: prodURL, + }, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + t.Setenv(antigravityForwardBaseURLEnv, tt.env) + require.Equal(t, tt.want, resolveAntigravityForwardBaseURL(tt.account)) + }) + } } func TestAntigravityAccountSwitchError_Error(t *testing.T) { From 901a77cfb1097cc9808ee2f6a041b044d3c278dd Mon Sep 17 00:00:00 2001 From: li Date: Fri, 14 Aug 2026 10:33:47 +0800 Subject: [PATCH 003/204] =?UTF-8?q?fix(apicompat):=20Anthropic=E2=86=92Cha?= =?UTF-8?q?t=20=E6=A1=A5=E5=9B=9E=E4=BC=A0=E5=B7=A5=E5=85=B7=E8=B0=83?= =?UTF-8?q?=E7=94=A8=E7=9A=84=20thinking=EF=BC=8C=E4=BF=AE=E5=A4=8D=20Deep?= =?UTF-8?q?Seek=20=E5=A4=9A=E8=BD=AE=20400?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit /v1/messages 打到只支持 Chat Completions 的 OpenAI 兼容上游时, anthropicAssistantToChatMessages 把历史 assistant 消息里的 thinking 块整块丢弃。 DeepSeek 的 thinking mode 要求产生工具调用的 reasoning_content 随该 assistant 消息回传,缺失即 400 —— 表现为「单轮正常,一进多轮工具对话必现失败」。 这些 thinking 块本来就是同一个文件的出站方向 (chatMessageToAnthropicBlocks) 用上游 reasoning_content 生成的,客户端只是 原样回传:桥自己造出来的东西,回来时被自己丢掉。 兄弟路径 Responses→Chat (buildChatMessagesFromItems 的 pendingReasoning) 早已 处理同一约束。本次把同一策略补到漏掉的这条桥上,作用域严格对齐:reasoning 只挂 到带 tool_calls 的 assistant 消息,纯文本轮次维持现状。 Fixes #5528 --- .../chatcompletions_anthropic_bridge.go | 35 ++- .../chatcompletions_anthropic_bridge_test.go | 5 +- ...tions_anthropic_reasoning_passback_test.go | 229 ++++++++++++++++++ 3 files changed, 266 insertions(+), 3 deletions(-) create mode 100644 backend/internal/pkg/apicompat/chatcompletions_anthropic_reasoning_passback_test.go diff --git a/backend/internal/pkg/apicompat/chatcompletions_anthropic_bridge.go b/backend/internal/pkg/apicompat/chatcompletions_anthropic_bridge.go index 1a62f5620f..47d4601c24 100644 --- a/backend/internal/pkg/apicompat/chatcompletions_anthropic_bridge.go +++ b/backend/internal/pkg/apicompat/chatcompletions_anthropic_bridge.go @@ -249,8 +249,8 @@ func anthropicUserToChatMessages(raw json.RawMessage) ([]ChatMessage, error) { // anthropicAssistantToChatMessages handles an Anthropic assistant message. // Text content → assistant message content; tool_use blocks → tool_calls on the -// same assistant message; thinking blocks are dropped (Chat Completions has no -// inbound thinking field, matching anthropicAssistantToResponses). +// same assistant message; thinking blocks → reasoning_content, but only on a +// message that carries tool calls (see anthropicThinkingToReasoningContent). func anthropicAssistantToChatMessages(raw json.RawMessage) ([]ChatMessage, error) { // Plain string → single assistant message. var s string @@ -289,9 +289,40 @@ func anthropicAssistantToChatMessages(raw json.RawMessage) ([]ChatMessage, error }) } + msg.ReasoningContent = anthropicThinkingToReasoningContent(blocks, len(msg.ToolCalls) > 0) + return []ChatMessage{msg}, nil } +// anthropicThinkingToReasoningContent folds thinking blocks back into the +// Chat Completions reasoning_content field. +// +// chatMessageToAnthropicBlocks emits the upstream's reasoning_content as a +// thinking block on the way out, so a multi-turn client echoes it back on the +// next request; dropping it here made the bridge lose exactly what it had just +// produced. DeepSeek's thinking mode requires the reasoning_content that +// produced a tool call to be replayed on that assistant message and answers +// 400 otherwise, which is why buildChatMessagesFromItems already carries +// pendingReasoning onto assistant tool-call messages in the Responses→Chat +// bridge. hasToolCalls keeps the scope identical to that sibling: reasoning +// rides along with tool calls only, never on a plain assistant text turn. +// +// redacted_thinking blocks and signature-only placeholders carry no plaintext +// and contribute nothing. Multiple blocks join with "\n", matching +// extractResponsesReasoningText. +func anthropicThinkingToReasoningContent(blocks []AnthropicContentBlock, hasToolCalls bool) string { + if !hasToolCalls { + return "" + } + var parts []string + for _, b := range blocks { + if b.Type == "thinking" && b.Thinking != "" { + parts = append(parts, b.Thinking) + } + } + return strings.Join(parts, "\n") +} + // anthropicToolsToChatTools maps Anthropic tool definitions to Chat Completions // function tools. Server-side tools (web_search_*) are dropped — they have no // Chat Completions equivalent. diff --git a/backend/internal/pkg/apicompat/chatcompletions_anthropic_bridge_test.go b/backend/internal/pkg/apicompat/chatcompletions_anthropic_bridge_test.go index 00726f5ef7..eb979f70e0 100644 --- a/backend/internal/pkg/apicompat/chatcompletions_anthropic_bridge_test.go +++ b/backend/internal/pkg/apicompat/chatcompletions_anthropic_bridge_test.go @@ -143,8 +143,11 @@ func TestAnthropicToChatCompletionsRequest_ThinkingDropped(t *testing.T) { out, err := AnthropicToChatCompletionsRequest(req) require.NoError(t, err) require.Len(t, out.Messages, 1) - // Only text survives; thinking is dropped + // Only text survives. Thinking is dropped because this turn carries no tool + // calls — reasoning rides along with tool calls only, matching the + // Responses→Chat bridge (see anthropicThinkingToReasoningContent). require.Equal(t, `"answer"`, string(out.Messages[0].Content)) + require.Empty(t, out.Messages[0].ReasoningContent) } func TestAnthropicToChatCompletionsRequest_ToolChoiceAuto(t *testing.T) { diff --git a/backend/internal/pkg/apicompat/chatcompletions_anthropic_reasoning_passback_test.go b/backend/internal/pkg/apicompat/chatcompletions_anthropic_reasoning_passback_test.go new file mode 100644 index 0000000000..007a5face6 --- /dev/null +++ b/backend/internal/pkg/apicompat/chatcompletions_anthropic_reasoning_passback_test.go @@ -0,0 +1,229 @@ +package apicompat + +import ( + "encoding/json" + "testing" + + "github.com/stretchr/testify/require" +) + +// issue #5528:/v1/messages 客户端(Claude Code 等)打到只会 Chat Completions 的 +// OpenAI 兼容上游时,历史 assistant 消息里的 thinking 块被整块丢弃。DeepSeek 的 +// thinking mode 要求产生工具调用的 reasoning_content 随该 assistant 消息回传, +// 于是「单轮正常、一进多轮工具对话必现 400」。 + +func anthropicAssistantMsg(t *testing.T, blocks string) *AnthropicRequest { + t.Helper() + return &AnthropicRequest{ + Model: "deepseek-v4-flash", + MaxTokens: 256, + Messages: []AnthropicMessage{ + {Role: "user", Content: json.RawMessage(`"what's the weather?"`)}, + {Role: "assistant", Content: json.RawMessage(blocks)}, + {Role: "user", Content: json.RawMessage(`[{"type":"tool_result","tool_use_id":"toolu_1","content":"sunny"}]`)}, + }, + } +} + +const anthropicThinkingToolTurn = `[ + {"type":"thinking","thinking":"user wants weather, call the tool"}, + {"type":"text","text":"checking"}, + {"type":"tool_use","id":"toolu_1","name":"get_weather","input":{"city":"SF"}} +]` + +func TestAnthropicToChatCompletionsRequest_ThinkingBecomesReasoningContentOnToolTurn(t *testing.T) { + out, err := AnthropicToChatCompletionsRequest(anthropicAssistantMsg(t, anthropicThinkingToolTurn)) + require.NoError(t, err) + + var assistant *ChatMessage + for i := range out.Messages { + if out.Messages[i].Role == "assistant" { + assistant = &out.Messages[i] + break + } + } + require.NotNil(t, assistant, "assistant message must survive the bridge") + require.Equal(t, "user wants weather, call the tool", assistant.ReasoningContent, + "产生工具调用的 thinking 必须作为 reasoning_content 回传,否则 DeepSeek 400") + require.Len(t, assistant.ToolCalls, 1) + require.Equal(t, `"checking"`, string(assistant.Content), "text/tool_use 处理保持不变") +} + +// 上游线格式才是上游看到的东西:字段没序列化出去,等于没修。 +func TestAnthropicToChatCompletionsRequest_ReasoningContentSerializesOnWire(t *testing.T) { + out, err := AnthropicToChatCompletionsRequest(anthropicAssistantMsg(t, anthropicThinkingToolTurn)) + require.NoError(t, err) + + payload, err := json.Marshal(out) + require.NoError(t, err) + require.Contains(t, string(payload), `"reasoning_content":"user wants weather, call the tool"`) +} + +// 闭环不变式:thinking 块本来就是本桥出站时用上游 reasoning_content 生成的 +// (chatMessageToAnthropicBlocks),客户端只是原样回传。出站造、入站丢 = 自己丢自己的东西。 +func TestAnthropicChatBridge_ReasoningSurvivesOutboundInboundRoundTrip(t *testing.T) { + upstream := ChatMessage{ + Role: "assistant", + ReasoningContent: "step 1: need the weather tool", + Content: json.RawMessage(`"checking"`), + ToolCalls: []ChatToolCall{{ + ID: "call_1", + Type: "function", + Function: ChatFunctionCall{Name: "get_weather", Arguments: `{"city":"SF"}`}, + }}, + } + + // 出站:Chat 响应 → Anthropic content blocks + blocks := chatMessageToAnthropicBlocks(upstream) + require.Equal(t, "thinking", blocks[0].Type) + require.Equal(t, upstream.ReasoningContent, blocks[0].Thinking) + + // 客户端下一轮把同一组 blocks 原样回传 + raw, err := json.Marshal(blocks) + require.NoError(t, err) + + // 入站:Anthropic content blocks → Chat 请求 + back, err := anthropicAssistantToChatMessages(raw) + require.NoError(t, err) + require.Len(t, back, 1) + require.Equal(t, upstream.ReasoningContent, back[0].ReasoningContent, + "出站生成的 thinking 必须能原样还原回 reasoning_content") + require.Len(t, back[0].ToolCalls, 1) +} + +// 兄弟不变式:Responses→Chat 桥(buildChatMessagesFromItems 的 pendingReasoning) +// 早就把 reasoning 挂到带 tool_calls 的 assistant 消息上了。等价历史下两条桥必须一致。 +func TestAnthropicChatBridge_MatchesResponsesChatBridgeReasoningPlacement(t *testing.T) { + responsesReq := &ResponsesRequest{ + Model: "deepseek-v4-flash", + Input: json.RawMessage(`[ + {"type":"message","role":"user","content":[{"type":"input_text","text":"what's the weather?"}]}, + {"type":"reasoning","summary":[{"type":"summary_text","text":"call the tool"}]}, + {"type":"function_call","call_id":"call_1","name":"get_weather","arguments":"{\"city\":\"SF\"}"}, + {"type":"function_call_output","call_id":"call_1","output":"sunny"} + ]`), + } + viaResponses, err := ResponsesToChatCompletionsRequest(responsesReq) + require.NoError(t, err) + + viaAnthropic, err := AnthropicToChatCompletionsRequest(anthropicAssistantMsg(t, `[ + {"type":"thinking","thinking":"call the tool"}, + {"type":"tool_use","id":"toolu_1","name":"get_weather","input":{"city":"SF"}} + ]`)) + require.NoError(t, err) + + reasoningOnToolCallMessage := func(msgs []ChatMessage) string { + for _, m := range msgs { + if m.Role == "assistant" && len(m.ToolCalls) > 0 { + return m.ReasoningContent + } + } + return "" + } + require.Equal(t, "call the tool", reasoningOnToolCallMessage(viaResponses.Messages), + "前置条件:兄弟桥本来就带 reasoning_content") + require.Equal(t, reasoningOnToolCallMessage(viaResponses.Messages), + reasoningOnToolCallMessage(viaAnthropic.Messages), + "两条桥对等价历史必须产出同样的 reasoning_content 位置") +} + +// 作用域守卫:不带工具调用的纯文本轮次维持现状(与兄弟桥一致 —— reasoning 只随 +// 工具调用回传),避免把 reasoning_content 撒到不需要它的上游请求上。 +func TestAnthropicToChatCompletionsRequest_ThinkingWithoutToolCallsStaysDropped(t *testing.T) { + req := &AnthropicRequest{ + Model: "deepseek-v4-flash", + MaxTokens: 100, + Messages: []AnthropicMessage{ + {Role: "assistant", Content: json.RawMessage( + `[{"type":"thinking","thinking":"secret thoughts"},{"type":"text","text":"answer"}]`)}, + }, + } + + out, err := AnthropicToChatCompletionsRequest(req) + require.NoError(t, err) + require.Len(t, out.Messages, 1) + require.Empty(t, out.Messages[0].ReasoningContent) + require.Equal(t, `"answer"`, string(out.Messages[0].Content)) + + payload, err := json.Marshal(out) + require.NoError(t, err) + require.NotContains(t, string(payload), "reasoning_content") +} + +func TestAnthropicThinkingToReasoningContent(t *testing.T) { + blocksOf := func(t *testing.T, raw string) []AnthropicContentBlock { + t.Helper() + var blocks []AnthropicContentBlock + require.NoError(t, json.Unmarshal([]byte(raw), &blocks)) + return blocks + } + + cases := []struct { + name string + raw string + hasToolCalls bool + want string + }{ + { + name: "single_thinking_block", + raw: `[{"type":"thinking","thinking":"a"}]`, + hasToolCalls: true, + want: "a", + }, + { + // 多个 thinking 块用 "\n" 连接,与 extractResponsesReasoningText 一致。 + name: "multiple_blocks_join_with_newline", + raw: `[{"type":"thinking","thinking":"a"},{"type":"text","text":"x"},{"type":"thinking","thinking":"b"}]`, + hasToolCalls: true, + want: "a\nb", + }, + { + // redacted_thinking 没有明文可回传。 + name: "redacted_thinking_has_no_plaintext", + raw: `[{"type":"redacted_thinking","signature":"abc"}]`, + hasToolCalls: true, + want: "", + }, + { + // 只带 signature 的 thinking 占位块(xAI/Codex 密文回放形态)同样无明文。 + name: "signature_only_thinking", + raw: `[{"type":"thinking","thinking":"","signature":"gAAAAxxx"}]`, + hasToolCalls: true, + want: "", + }, + { + name: "no_tool_calls_returns_empty", + raw: `[{"type":"thinking","thinking":"a"}]`, + hasToolCalls: false, + want: "", + }, + { + name: "no_thinking_blocks", + raw: `[{"type":"text","text":"x"}]`, + hasToolCalls: true, + want: "", + }, + { + name: "empty_blocks", + raw: `[]`, + hasToolCalls: true, + want: "", + }, + } + + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + require.Equal(t, tc.want, + anthropicThinkingToReasoningContent(blocksOf(t, tc.raw), tc.hasToolCalls)) + }) + } +} + +// 纯字符串形态的 assistant content 没有 blocks 可读,走早返回分支,不得 panic。 +func TestAnthropicAssistantToChatMessages_PlainStringContentUnaffected(t *testing.T) { + msgs, err := anthropicAssistantToChatMessages(json.RawMessage(`"just text"`)) + require.NoError(t, err) + require.Len(t, msgs, 1) + require.Empty(t, msgs[0].ReasoningContent) + require.Equal(t, `"just text"`, string(msgs[0].Content)) +} From 3c5553e253acfd01a147e0cca48cbf0cf36de38a Mon Sep 17 00:00:00 2001 From: li Date: Fri, 14 Aug 2026 11:05:29 +0800 Subject: [PATCH 004/204] =?UTF-8?q?fix(responses):=20=E7=BD=91=E5=85=B3?= =?UTF-8?q?=E5=90=88=E6=88=90=E7=9A=84=20Responses=20=E5=AF=B9=E8=B1=A1?= =?UTF-8?q?=E8=A1=A5=E9=BD=90=20created=5Fat=EF=BC=8C=E4=BF=AE=E5=A4=8D?= =?UTF-8?q?=E4=B8=A5=E6=A0=BC=E5=AE=A2=E6=88=B7=E7=AB=AF=E5=8F=8D=E5=BA=8F?= =?UTF-8?q?=E5=88=97=E5=8C=96=E5=A4=B1=E8=B4=A5?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 严格的 Responses 客户端(Rust serde 系,如 Codex / Grok CLI)把 created_at 声明为 必填字段,缺失即 `missing field 'created_at'` 直接读不出响应。 apicompat.ResponsesResponse 此前根本没有这个字段,六个构造点全部不写: Chat→Responses 与 Anthropic→Responses 两座桥的非流式结果、response.created、 终止事件,以及两处手写的 response.failed 帧。 两个流式 state 早就在 New*State() 里采集了 Created 时间戳,只是没有出口—— 反方向(Responses→Chat)每个 chunk 都老老实实发 created,正方向直接丢在地上。 原生 Responses 透传走 gjson/sjson 字节级改写,保留上游原样,不受影响; 本次只补合成路径。 Fixes #5601 --- .../internal/handler/stream_error_event.go | 27 +-- .../handler/stream_error_event_test.go | 16 ++ .../anthropic_to_responses_response.go | 21 ++- .../chatcompletions_responses_bridge.go | 31 +++- .../responses_created_at_wire_test.go | 166 ++++++++++++++++++ backend/internal/pkg/apicompat/types.go | 17 +- .../service/openai_compact_stream_bridge.go | 8 +- ..._compact_stream_failure_created_at_test.go | 49 ++++++ 8 files changed, 299 insertions(+), 36 deletions(-) create mode 100644 backend/internal/pkg/apicompat/responses_created_at_wire_test.go create mode 100644 backend/internal/service/openai_compact_stream_failure_created_at_test.go diff --git a/backend/internal/handler/stream_error_event.go b/backend/internal/handler/stream_error_event.go index 2af098dbed..8ba6095cfb 100644 --- a/backend/internal/handler/stream_error_event.go +++ b/backend/internal/handler/stream_error_event.go @@ -5,6 +5,7 @@ import ( "fmt" "net/http" "strings" + "time" "github.com/Wei-Shaw/sub2api/internal/pkg/ctxkey" "github.com/gin-gonic/gin" @@ -19,13 +20,16 @@ type responsesFailedError struct { // responsesFailedBody 对齐 apicompat.makeResponsesCompletedEvent 输出的 response 子对象字段集。 // Output 用空 slice(不是 nil)确保 marshal 为 `[]` 而非 `null`。 +// CreatedAt 不带 omitempty:严格客户端把它当必填字段,缺失会以 +// `missing field 'created_at'` 反序列化失败——那正是本文件要避免的"客户端读不懂终止事件"。 type responsesFailedBody struct { - ID string `json:"id"` - Object string `json:"object"` - Model string `json:"model,omitempty"` - Status string `json:"status"` - Output []any `json:"output"` - Error responsesFailedError `json:"error"` + ID string `json:"id"` + Object string `json:"object"` + CreatedAt int64 `json:"created_at"` + Model string `json:"model,omitempty"` + Status string `json:"status"` + Output []any `json:"output"` + Error responsesFailedError `json:"error"` } // responsesFailedEvent 是写入 SSE data 行的顶层结构。 @@ -61,11 +65,12 @@ func writeResponsesFailedSSE(c *gin.Context, errType, message string) bool { payload, err := json.Marshal(responsesFailedEvent{ Type: "response.failed", Response: responsesFailedBody{ - ID: synthesizeResponseID(c), - Object: "response", - Model: requestModel(c), - Status: "failed", - Output: []any{}, + ID: synthesizeResponseID(c), + Object: "response", + CreatedAt: time.Now().Unix(), + Model: requestModel(c), + Status: "failed", + Output: []any{}, Error: responsesFailedError{ Code: mapResponsesErrorCode(errType), Message: message, diff --git a/backend/internal/handler/stream_error_event_test.go b/backend/internal/handler/stream_error_event_test.go index f24cf97fff..187deda19d 100644 --- a/backend/internal/handler/stream_error_event_test.go +++ b/backend/internal/handler/stream_error_event_test.go @@ -227,6 +227,22 @@ func TestOpenAIHandleStreamingAwareError_BareResponsesRouteEmitsResponseFailed(t } // Synthesized response.failed id falls back to uuid when no request_id is present. +// issue #5601:严格的 Responses 客户端把 created_at 当必填字段,缺失即 +// `missing field 'created_at'`。合成的终止事件若解析不了,本文件存在的意义 +// (给客户端一个可识别的终止事件而不是盲重连)就落空了。 +func TestOpenAIHandleStreamingAwareError_ResponsesStreamingCarriesCreatedAt(t *testing.T) { + c, w := newGinContextForEndpoint(t, EndpointResponses) + h := &OpenAIGatewayHandler{} + h.handleStreamingAwareError(c, http.StatusBadGateway, "upstream_error", "boom", true) + + resp, _ := parseResponsesFailedSSE(t, w.Body.String()) + raw, ok := resp["created_at"] + assert.True(t, ok, "response.failed 必须带 created_at") + createdAt, ok := raw.(float64) + assert.True(t, ok, "created_at 必须是数字,得到 %T", raw) + assert.Greater(t, int64(createdAt), int64(0), "created_at 必须是有效的 unix 时间戳") +} + func TestSynthesizeResponseID_FallbackUUID(t *testing.T) { c, _ := newGinContextForEndpoint(t, EndpointResponses) id := synthesizeResponseID(c) diff --git a/backend/internal/pkg/apicompat/anthropic_to_responses_response.go b/backend/internal/pkg/apicompat/anthropic_to_responses_response.go index db0343cd73..d5a7057036 100644 --- a/backend/internal/pkg/apicompat/anthropic_to_responses_response.go +++ b/backend/internal/pkg/apicompat/anthropic_to_responses_response.go @@ -21,10 +21,13 @@ func AnthropicToResponsesResponse(resp *AnthropicResponse) *ResponsesResponse { id = generateResponsesID() } + // Anthropic responses carry no creation timestamp, so stamp now — the same + // synthesize-what-the-client-requires rule the generated id above follows. out := &ResponsesResponse{ - ID: id, - Object: "response", - Model: resp.Model, + ID: id, + Object: "response", + CreatedAt: time.Now().Unix(), + Model: resp.Model, } var outputs []ResponsesOutput @@ -551,11 +554,12 @@ func makeResponsesCreatedEvent(state *AnthropicEventToResponsesState) ResponsesS Type: "response.created", SequenceNumber: seq, Response: &ResponsesResponse{ - ID: state.ResponseID, - Object: "response", - Model: state.Model, - Status: "in_progress", - Output: []ResponsesOutput{}, + ID: state.ResponseID, + Object: "response", + CreatedAt: state.Created, + Model: state.Model, + Status: "in_progress", + Output: []ResponsesOutput{}, }, } } @@ -602,6 +606,7 @@ func makeResponsesCompletedEvent( Response: &ResponsesResponse{ ID: state.ResponseID, Object: "response", + CreatedAt: state.Created, Model: state.Model, Status: status, Output: outputs, diff --git a/backend/internal/pkg/apicompat/chatcompletions_responses_bridge.go b/backend/internal/pkg/apicompat/chatcompletions_responses_bridge.go index 70dee035d8..c58caa1a56 100644 --- a/backend/internal/pkg/apicompat/chatcompletions_responses_bridge.go +++ b/backend/internal/pkg/apicompat/chatcompletions_responses_bridge.go @@ -1042,11 +1042,22 @@ func ChatCompletionsResponseToResponses(resp *ChatCompletionsResponse, model str id = generateResponsesID() } + // Carry the upstream's own creation timestamp when it sent one; otherwise + // stamp now, same fallback shape as the generated id above. + createdAt := int64(0) + if resp != nil { + createdAt = resp.Created + } + if createdAt <= 0 { + createdAt = time.Now().Unix() + } + out := &ResponsesResponse{ - ID: id, - Object: "response", - Model: model, - Status: "completed", + ID: id, + Object: "response", + CreatedAt: createdAt, + Model: model, + Status: "completed", } if resp == nil { out.Output = []ResponsesOutput{emptyResponsesMessageOutput()} @@ -1493,6 +1504,7 @@ func FinalizeChatCompletionsResponsesStream(state *ChatCompletionsToResponsesStr Response: &ResponsesResponse{ ID: state.ResponseID, Object: "response", + CreatedAt: state.Created, Model: state.Model, Status: status, Output: state.chatOutput(), @@ -1510,11 +1522,12 @@ func ensureChatToResponsesCreated(state *ChatCompletionsToResponsesStreamState) state.CreatedSent = true return []ResponsesStreamEvent{chatToResponsesEvent(state, "response.created", &ResponsesStreamEvent{ Response: &ResponsesResponse{ - ID: state.ResponseID, - Object: "response", - Model: state.Model, - Status: "in_progress", - Output: []ResponsesOutput{}, + ID: state.ResponseID, + Object: "response", + CreatedAt: state.Created, + Model: state.Model, + Status: "in_progress", + Output: []ResponsesOutput{}, }, })} } diff --git a/backend/internal/pkg/apicompat/responses_created_at_wire_test.go b/backend/internal/pkg/apicompat/responses_created_at_wire_test.go new file mode 100644 index 0000000000..48468409d6 --- /dev/null +++ b/backend/internal/pkg/apicompat/responses_created_at_wire_test.go @@ -0,0 +1,166 @@ +package apicompat + +import ( + "encoding/json" + "testing" + + "github.com/stretchr/testify/require" +) + +// issue #5601:严格的 Responses 客户端(Rust serde 系,如 Codex / Grok CLI)把 +// created_at 声明为必填字段,缺失即 `missing field 'created_at'` 反序列化失败。 +// 网关合成的 Responses 对象(Chat→Responses、Anthropic→Responses 两座桥)此前从不 +// 写这个字段——尽管两个流式 state 早就采集好了 Created 时间戳,只是没有出口。 +// 原生 Responses 透传走 gjson/sjson 字节级改写,不受影响。 + +// responseObjectOf 取出事件里的 response 子对象(按线格式,而不是按 Go 结构体)。 +func responseObjectOf(t *testing.T, evt ResponsesStreamEvent) map[string]any { + t.Helper() + m := marshalEvent(t, evt) + resp, ok := m["response"].(map[string]any) + require.True(t, ok, "event must carry a response object: %v", m) + return resp +} + +func requireCreatedAt(t *testing.T, resp map[string]any) int64 { + t.Helper() + raw, ok := resp["created_at"] + require.True(t, ok, "response 对象必须带 created_at,否则严格客户端直接反序列化失败") + value, ok := raw.(float64) + require.True(t, ok, "created_at 必须是数字,得到 %T", raw) + require.Greater(t, int64(value), int64(0), "created_at 必须是有效的 unix 时间戳") + return int64(value) +} + +// omitempty 陷阱守卫:created_at 为 0 时也必须出现在线格式里, +// 否则「字段存在」这件事就依赖于运行时恰好非零。 +func TestWire_CreatedAtPresentEvenAtZero(t *testing.T) { + resp := responseObjectOf(t, ResponsesStreamEvent{ + Type: "response.created", + Response: &ResponsesResponse{ID: "resp_1", Object: "response", Status: "in_progress"}, + }) + require.Contains(t, resp, "created_at", "created_at 不得带 omitempty") + require.EqualValues(t, 0, resp["created_at"]) +} + +// --------------------------------------------------------------------------- +// Chat Completions → Responses +// --------------------------------------------------------------------------- + +func TestChatCompletionsResponseToResponses_CarriesCreatedAt(t *testing.T) { + t.Run("uses_upstream_created_when_present", func(t *testing.T) { + out := ChatCompletionsResponseToResponses(&ChatCompletionsResponse{ + ID: "chatcmpl_1", + Created: 1700000000, + Model: "deepseek-v4-flash", + Choices: []ChatChoice{{Message: ChatMessage{Role: "assistant", Content: json.RawMessage(`"hi"`)}}}, + }, "deepseek-v4-flash", nil, false, nil) + require.EqualValues(t, 1700000000, out.CreatedAt, "上游给了 created 就照搬,不要另起时间") + }) + + t.Run("stamps_now_when_upstream_omits_created", func(t *testing.T) { + out := ChatCompletionsResponseToResponses(&ChatCompletionsResponse{ + ID: "chatcmpl_2", + Model: "deepseek-v4-flash", + Choices: []ChatChoice{{Message: ChatMessage{Role: "assistant", Content: json.RawMessage(`"hi"`)}}}, + }, "deepseek-v4-flash", nil, false, nil) + require.Greater(t, out.CreatedAt, int64(0)) + }) + + t.Run("nil_upstream_response_still_stamps", func(t *testing.T) { + out := ChatCompletionsResponseToResponses(nil, "deepseek-v4-flash", nil, false, nil) + require.Greater(t, out.CreatedAt, int64(0), "空上游响应也必须产出可解析的对象") + }) +} + +// 同一条流里 response.created 与终止事件必须报同一个 created_at +// (官方语义:created_at 是这次 response 的创建时刻,不随事件变化)。 +func TestChatCompletionsToResponsesStream_CreatedAtStableAcrossEvents(t *testing.T) { + state := NewChatCompletionsToResponsesStreamState("deepseek-v4-flash") + require.Greater(t, state.Created, int64(0), "前提:state 早就采集了时间戳") + + var chunk ChatCompletionsChunk + require.NoError(t, json.Unmarshal( + []byte(`{"choices":[{"index":0,"delta":{"content":"hi"}}]}`), &chunk)) + + events := ChatCompletionsChunkToResponsesEvents(&chunk, state) + events = append(events, FinalizeChatCompletionsResponsesStream(state)...) + + seen := map[string]int64{} + for _, evt := range events { + if evt.Response == nil { + continue + } + seen[evt.Type] = requireCreatedAt(t, responseObjectOf(t, evt)) + } + + require.Contains(t, seen, "response.created") + require.Contains(t, seen, "response.completed") + require.Equal(t, state.Created, seen["response.created"]) + require.Equal(t, seen["response.created"], seen["response.completed"], + "同一条流的 created_at 必须恒定") +} + +// --------------------------------------------------------------------------- +// Anthropic → Responses +// --------------------------------------------------------------------------- + +func TestAnthropicToResponsesResponse_StampsCreatedAt(t *testing.T) { + out := AnthropicToResponsesResponse(&AnthropicResponse{ + ID: "msg_1", + Type: "message", + Role: "assistant", + Model: "claude-sonnet-4-20250514", + Content: []AnthropicContentBlock{{Type: "text", Text: "hi"}}, + }) + require.Greater(t, out.CreatedAt, int64(0), + "Anthropic 响应不带时间戳,网关必须自己盖一个") +} + +func TestAnthropicEventToResponsesStream_CreatedAtStableAcrossEvents(t *testing.T) { + state := NewAnthropicEventToResponsesState() + state.Model = "claude-sonnet-4-20250514" + require.Greater(t, state.Created, int64(0), "前提:state 早就采集了时间戳") + + var events []ResponsesStreamEvent + for _, raw := range []string{ + `{"type":"message_start","message":{"id":"msg_1","type":"message","role":"assistant","model":"claude-sonnet-4-20250514","content":[],"usage":{"input_tokens":3,"output_tokens":0}}}`, + `{"type":"content_block_start","index":0,"content_block":{"type":"text","text":""}}`, + `{"type":"content_block_delta","index":0,"delta":{"type":"text_delta","text":"hi"}}`, + `{"type":"content_block_stop","index":0}`, + `{"type":"message_delta","delta":{"stop_reason":"end_turn"},"usage":{"output_tokens":2}}`, + `{"type":"message_stop"}`, + } { + var evt AnthropicStreamEvent + require.NoError(t, json.Unmarshal([]byte(raw), &evt)) + events = append(events, AnthropicEventToResponsesEvents(&evt, state)...) + } + events = append(events, FinalizeAnthropicResponsesStream(state)...) + + seen := map[string]int64{} + for _, evt := range events { + if evt.Response == nil { + continue + } + seen[evt.Type] = requireCreatedAt(t, responseObjectOf(t, evt)) + } + + require.Contains(t, seen, "response.created") + require.Contains(t, seen, "response.completed") + require.Equal(t, state.Created, seen["response.created"]) + require.Equal(t, seen["response.created"], seen["response.completed"], + "同一条流的 created_at 必须恒定") +} + +// ResponsesClientToolStreamRestorer 对部分事件走 unmarshal→re-marshal。 +// 结构体没有该字段时,上游带来的 created_at 会在这一步被静默抹掉。 +func TestResponsesStreamEvent_CreatedAtSurvivesUnmarshalRemarshal(t *testing.T) { + upstream := []byte(`{"type":"response.completed","response":{"id":"resp_9","object":"response",` + + `"created_at":1700000123,"model":"gpt-5.5","status":"completed","output":[]}}`) + + var evt ResponsesStreamEvent + require.NoError(t, json.Unmarshal(upstream, &evt)) + require.EqualValues(t, 1700000123, evt.Response.CreatedAt) + + require.EqualValues(t, 1700000123, requireCreatedAt(t, responseObjectOf(t, evt))) +} diff --git a/backend/internal/pkg/apicompat/types.go b/backend/internal/pkg/apicompat/types.go index bcc8cd481e..84175f2a89 100644 --- a/backend/internal/pkg/apicompat/types.go +++ b/backend/internal/pkg/apicompat/types.go @@ -339,12 +339,17 @@ func (t *ResponsesTool) UnmarshalJSON(data []byte) error { // ResponsesResponse is the non-streaming response from POST /v1/responses. type ResponsesResponse struct { - ID string `json:"id"` - Object string `json:"object"` // "response" - Model string `json:"model"` - Status string `json:"status"` // "completed" | "incomplete" | "failed" - Output []ResponsesOutput `json:"output"` - Usage *ResponsesUsage `json:"usage,omitempty"` + ID string `json:"id"` + Object string `json:"object"` // "response" + // CreatedAt is the unix creation timestamp. Strict Responses clients declare + // it non-optional and abort with `missing field 'created_at'` when it is + // absent, so it is always emitted — no omitempty. Same rule as ID (see the + // "clients treat it as required" fallback in ChatCompletionsResponseToAnthropic). + CreatedAt int64 `json:"created_at"` + Model string `json:"model"` + Status string `json:"status"` // "completed" | "incomplete" | "failed" + Output []ResponsesOutput `json:"output"` + Usage *ResponsesUsage `json:"usage,omitempty"` // incomplete_details is present when status="incomplete" IncompleteDetails *ResponsesIncompleteDetails `json:"incomplete_details,omitempty"` diff --git a/backend/internal/service/openai_compact_stream_bridge.go b/backend/internal/service/openai_compact_stream_bridge.go index bcac8304c2..1c36f9f27c 100644 --- a/backend/internal/service/openai_compact_stream_bridge.go +++ b/backend/internal/service/openai_compact_stream_bridge.go @@ -6,6 +6,7 @@ import ( "net/http" "strconv" "strings" + "time" "github.com/gin-gonic/gin" "github.com/google/uuid" @@ -117,8 +118,11 @@ func writeOpenAICompactSSEFailureMessage(c *gin.Context, statusCode int, errType "response": map[string]any{ "id": "resp_" + strings.ReplaceAll(uuid.NewString(), "-", ""), "object": "response", - "status": "failed", - "output": []any{}, + // 严格客户端把 created_at 当必填字段,缺失会反序列化失败, + // 终止事件就白发了(退化成盲重连)。与 writeResponsesFailedSSE 对齐。 + "created_at": time.Now().Unix(), + "status": "failed", + "output": []any{}, "error": map[string]any{ "code": errType, "message": message, diff --git a/backend/internal/service/openai_compact_stream_failure_created_at_test.go b/backend/internal/service/openai_compact_stream_failure_created_at_test.go new file mode 100644 index 0000000000..a3b6f9bd78 --- /dev/null +++ b/backend/internal/service/openai_compact_stream_failure_created_at_test.go @@ -0,0 +1,49 @@ +//go:build unit + +package service + +import ( + "encoding/json" + "net/http" + "net/http/httptest" + "strings" + "testing" + + "github.com/gin-gonic/gin" + "github.com/stretchr/testify/require" +) + +// issue #5601:严格的 Responses 客户端把 created_at 当必填字段,缺失即 +// `missing field 'created_at'`。writeOpenAICompactSSEFailureMessage 存在的理由就是 +// 让 Codex 能把这帧识别成合法终止事件;解析不了就退化回它想避免的盲重连。 +func TestWriteOpenAICompactSSEFailureMessage_CarriesCreatedAt(t *testing.T) { + gin.SetMode(gin.TestMode) + rec := httptest.NewRecorder() + c, _ := gin.CreateTestContext(rec) + c.Request = httptest.NewRequest(http.MethodPost, "/v1/responses", nil) + + writeOpenAICompactSSEFailureMessage(c, http.StatusBadGateway, "upstream_error", "boom") + + body := rec.Body.String() + require.Contains(t, body, "event: response.failed") + + _, payload, found := strings.Cut(body, "data: ") + require.True(t, found, "SSE 帧必须带 data 行: %q", body) + + var event struct { + Type string `json:"type"` + Response struct { + ID string `json:"id"` + Object string `json:"object"` + CreatedAt int64 `json:"created_at"` + Status string `json:"status"` + } `json:"response"` + } + require.NoError(t, json.Unmarshal([]byte(strings.TrimSpace(payload)), &event)) + + require.Equal(t, "response.failed", event.Type) + require.Equal(t, "response", event.Response.Object) + require.Equal(t, "failed", event.Response.Status) + require.Greater(t, event.Response.CreatedAt, int64(0), + "response.failed 必须带有效的 created_at,否则严格客户端读不出这帧") +} From 21c07e83517a49bbfa5498afd604aa6b3a8cb43c Mon Sep 17 00:00:00 2001 From: Cornna <96944678+ymylive@users.noreply.github.com> Date: Thu, 13 Aug 2026 21:31:42 -0700 Subject: [PATCH 005/204] fix(antigravity): use official daily endpoint Align the daily Cloud Code host with the current Antigravity client so requests do not use the legacy sandbox hostname. --- backend/internal/pkg/antigravity/oauth.go | 2 +- backend/internal/pkg/antigravity/oauth_test.go | 3 +++ 2 files changed, 4 insertions(+), 1 deletion(-) diff --git a/backend/internal/pkg/antigravity/oauth.go b/backend/internal/pkg/antigravity/oauth.go index 4ffb0cbad9..26b307bbf7 100644 --- a/backend/internal/pkg/antigravity/oauth.go +++ b/backend/internal/pkg/antigravity/oauth.go @@ -54,7 +54,7 @@ const ( // Antigravity API 端点 antigravityProdBaseURL = "https://cloudcode-pa.googleapis.com" - antigravityDailyBaseURL = "https://daily-cloudcode-pa.sandbox.googleapis.com" + antigravityDailyBaseURL = "https://daily-cloudcode-pa.googleapis.com" ) var userAgentVersionPattern = regexp.MustCompile(`^\d+\.\d+\.\d+$`) diff --git a/backend/internal/pkg/antigravity/oauth_test.go b/backend/internal/pkg/antigravity/oauth_test.go index 69d9ddc4f8..7849492c7c 100644 --- a/backend/internal/pkg/antigravity/oauth_test.go +++ b/backend/internal/pkg/antigravity/oauth_test.go @@ -94,6 +94,9 @@ func TestForwardBaseURLs_Daily优先(t *testing.T) { if len(urls) == 0 { t.Fatal("ForwardBaseURLs 返回空列表") } + if antigravityDailyBaseURL != "https://daily-cloudcode-pa.googleapis.com" { + t.Fatalf("daily URL 未与官方客户端对齐: got %s", antigravityDailyBaseURL) + } // daily URL 应排在第一位 if urls[0] != antigravityDailyBaseURL { From bafd2e293f797676e4d974093e6f6670e4d44764 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E9=A3=8E=E8=B5=B7?= <3219378872@qq.com> Date: Fri, 14 Aug 2026 06:32:38 +0000 Subject: [PATCH 006/204] fix(apicompat): omit empty tool name on streamed arguments deltas The responses->chat streaming converter re-emits the tool name as an empty string on every function_call_arguments.delta because ChatFunctionCall.Name has no omitempty. OpenAI-compatible clients accumulate the name from the first tool-call delta, so the trailing "name":"" overwrites it and the call fails dispatch (unknown tool ""). Empty names also break the next round-trip upstream (missing field 'name'). Fixes #5631 --- ...onses_to_chatcompletions_tool_name_test.go | 44 +++++++++++++++++++ backend/internal/pkg/apicompat/types.go | 4 +- 2 files changed, 47 insertions(+), 1 deletion(-) create mode 100644 backend/internal/pkg/apicompat/responses_to_chatcompletions_tool_name_test.go diff --git a/backend/internal/pkg/apicompat/responses_to_chatcompletions_tool_name_test.go b/backend/internal/pkg/apicompat/responses_to_chatcompletions_tool_name_test.go new file mode 100644 index 0000000000..c30ca97389 --- /dev/null +++ b/backend/internal/pkg/apicompat/responses_to_chatcompletions_tool_name_test.go @@ -0,0 +1,44 @@ +package apicompat + +import ( + "encoding/json" + "testing" + + "github.com/stretchr/testify/require" +) + +// TestResponsesEventToChatChunks_ArgumentsDeltaOmitsEmptyName pins that +// streamed arguments-only deltas never re-emit the tool name as an empty +// string. OpenAI-compatible clients accumulate the name from the first +// tool-call delta; a trailing "name":"" would overwrite the accumulated name +// and break tool dispatch ("unknown tool"). +func TestResponsesEventToChatChunks_ArgumentsDeltaOmitsEmptyName(t *testing.T) { + state := NewResponsesEventToChatState() + + added := ResponsesEventToChatChunks(&ResponsesStreamEvent{ + Type: "response.output_item.added", + OutputIndex: 0, + Item: &ResponsesOutput{ + Type: "function_call", + CallID: "call_a", + Name: "exec", + }, + }, state) + require.Len(t, added, 1) + first, err := json.Marshal(added[0]) + require.NoError(t, err) + require.Contains(t, string(first), `"name":"exec"`) + + for _, fragment := range []string{`{"cmd":"ls"}`, `{"cmd":"ls","flags":"-la"}`} { + deltas := ResponsesEventToChatChunks(&ResponsesStreamEvent{ + Type: "response.function_call_arguments.delta", + OutputIndex: 0, + Delta: fragment, + }, state) + require.Len(t, deltas, 1) + raw, err := json.Marshal(deltas[0]) + require.NoError(t, err) + require.NotContains(t, string(raw), `"name"`, "arguments delta must not carry a name field") + require.Contains(t, string(raw), `"arguments"`) + } +} diff --git a/backend/internal/pkg/apicompat/types.go b/backend/internal/pkg/apicompat/types.go index bcc8cd481e..9f2e8388e7 100644 --- a/backend/internal/pkg/apicompat/types.go +++ b/backend/internal/pkg/apicompat/types.go @@ -714,7 +714,9 @@ type ChatToolCall struct { // ChatFunctionCall contains the function name and arguments. type ChatFunctionCall struct { - Name string `json:"name"` + // Empty name is omitted so streamed arguments-only deltas never overwrite + // the tool name a client accumulated from the first delta. + Name string `json:"name,omitempty"` Arguments string `json:"arguments"` } From 1e1798d90d4dffd37b53fc0d5642afa9960c0ecc Mon Sep 17 00:00:00 2001 From: zninggo Date: Sat, 15 Aug 2026 01:12:22 +0800 Subject: [PATCH 007/204] =?UTF-8?q?fix(gateway):=20Composite=20=E5=88=86?= =?UTF-8?q?=E7=BB=84=E6=94=BE=E8=A1=8C=E8=A7=86=E9=A2=91=E7=94=9F=E6=88=90?= =?UTF-8?q?=E7=AB=AF=E7=82=B9?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 视频状态(/videos/:id)与内容下载(/videos/:id/content)都已放行 PlatformComposite, 唯独创建端点仅放行 PlatformGrok. Composite 分组 用户配好模型路由后可查询可下载, 唯独创建 404. 补齐放行判断, 与另外两个视频端点保持一致; 其他平台行为不变. --- backend/internal/server/routes/gateway.go | 5 ++++- backend/internal/server/routes/gateway_test.go | 12 ++++++++++++ 2 files changed, 16 insertions(+), 1 deletion(-) diff --git a/backend/internal/server/routes/gateway.go b/backend/internal/server/routes/gateway.go index 6d99d2c7ea..0d35a7a48f 100644 --- a/backend/internal/server/routes/gateway.go +++ b/backend/internal/server/routes/gateway.go @@ -93,7 +93,10 @@ func RegisterGatewayRoutes( } } videoGenerationHandler := func(c *gin.Context) { - if getGroupPlatform(c) == service.PlatformGrok { + // Video status/content lookups below already allow Composite groups; keep + // task creation aligned so composite keys that route to Grok accounts can + // submit video generation jobs. + if platform := getGroupPlatform(c); platform == service.PlatformGrok || platform == service.PlatformComposite { h.OpenAIGateway.GrokVideoGeneration(c) return } diff --git a/backend/internal/server/routes/gateway_test.go b/backend/internal/server/routes/gateway_test.go index ded7bd2989..7fb127ccc2 100644 --- a/backend/internal/server/routes/gateway_test.go +++ b/backend/internal/server/routes/gateway_test.go @@ -345,6 +345,18 @@ func TestGatewayRoutesNonGrokVideosAreRejectedAtPlatformGate(t *testing.T) { } } +func TestGatewayRoutesCompositeVideoGenerationAllowed(t *testing.T) { + router := newGatewayRoutesTestRouter(service.PlatformComposite) + + req := httptest.NewRequest(http.MethodPost, "/v1/videos/generations", strings.NewReader(`{"model":"grok-imagine-video-1.5","prompt":"waves"}`)) + req.Header.Set("Content-Type", "application/json") + w := httptest.NewRecorder() + + router.ServeHTTP(w, req) + require.NotEqual(t, http.StatusNotFound, w.Code) + require.NotContains(t, w.Body.String(), "not supported") +} + func TestGatewayRoutesCompositeOpenAIOnlyEndpointsRequireOpenAITarget(t *testing.T) { router := newGatewayRoutesTestRouter(service.PlatformComposite) From 98c7b0e88e86515bc586522f14aab0b787e9d00c Mon Sep 17 00:00:00 2001 From: yzxcj797 <1784931579@qq.com> Date: Sat, 15 Aug 2026 11:42:47 +0800 Subject: [PATCH 008/204] docs: fix self-referential URLs after file moved into docs/ --- docs/ADMIN_PAYMENT_INTEGRATION_API.md | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/docs/ADMIN_PAYMENT_INTEGRATION_API.md b/docs/ADMIN_PAYMENT_INTEGRATION_API.md index f674f86c93..6d3cd0122e 100644 --- a/docs/ADMIN_PAYMENT_INTEGRATION_API.md +++ b/docs/ADMIN_PAYMENT_INTEGRATION_API.md @@ -119,8 +119,8 @@ https://pay.example.com/pay?user_id=123&token=&theme=light&lang=zh&ui_mode= - 重试保持相同 `code`,并使用新的 `Idempotency-Key` ### 6) `doc_url` 配置建议 -- 查看链接:`https://github.com/Wei-Shaw/sub2api/blob/main/ADMIN_PAYMENT_INTEGRATION_API.md` -- 下载链接:`https://raw.githubusercontent.com/Wei-Shaw/sub2api/main/ADMIN_PAYMENT_INTEGRATION_API.md` +- 查看链接:`https://github.com/Wei-Shaw/sub2api/blob/main/docs/ADMIN_PAYMENT_INTEGRATION_API.md` +- 下载链接:`https://raw.githubusercontent.com/Wei-Shaw/sub2api/main/docs/ADMIN_PAYMENT_INTEGRATION_API.md` --- @@ -239,5 +239,5 @@ https://pay.example.com/pay?user_id=123&token=&theme=light&lang=zh&ui_mode= - Keep the same `code` for retry, and use a new `Idempotency-Key` ### 6) Recommended `doc_url` -- View URL: `https://github.com/Wei-Shaw/sub2api/blob/main/ADMIN_PAYMENT_INTEGRATION_API.md` -- Download URL: `https://raw.githubusercontent.com/Wei-Shaw/sub2api/main/ADMIN_PAYMENT_INTEGRATION_API.md` +- View URL: `https://github.com/Wei-Shaw/sub2api/blob/main/docs/ADMIN_PAYMENT_INTEGRATION_API.md` +- Download URL: `https://raw.githubusercontent.com/Wei-Shaw/sub2api/main/docs/ADMIN_PAYMENT_INTEGRATION_API.md` From b1e60ba4535ea1fc2cc57a181a92bab03a2e0782 Mon Sep 17 00:00:00 2001 From: myy_321 <1948281933@qq.com> Date: Sun, 16 Aug 2026 08:29:12 +0800 Subject: [PATCH 009/204] =?UTF-8?q?fix(gateway):=20=E4=BF=AE=E5=A4=8D?= =?UTF-8?q?=E6=B1=A0=E6=A8=A1=E5=BC=8F=E5=90=8C=E8=B4=A6=E5=8F=B7=E9=94=99?= =?UTF-8?q?=E8=AF=AF=E9=87=8D=E8=AF=95?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - 透传上游错误处理结果,保留池模式重试判定\n- 对可重试状态码设置同账号重试标记\n- 补充 Chat Completions 与 Responses 的 429 回归测试 --- .../gateway_forward_as_chat_completions.go | 8 +- .../service/gateway_forward_as_responses.go | 8 +- .../service/gateway_pool_mode_retry_test.go | 78 +++++++++++++++++++ 3 files changed, 88 insertions(+), 6 deletions(-) create mode 100644 backend/internal/service/gateway_pool_mode_retry_test.go diff --git a/backend/internal/service/gateway_forward_as_chat_completions.go b/backend/internal/service/gateway_forward_as_chat_completions.go index 93da85a7b2..24c4b39b56 100644 --- a/backend/internal/service/gateway_forward_as_chat_completions.go +++ b/backend/internal/service/gateway_forward_as_chat_completions.go @@ -165,12 +165,14 @@ func (s *GatewayService) ForwardAsChatCompletions( Kind: "failover", Message: upstreamMsg, }) + shouldDisable := false if s.rateLimitService != nil { - s.rateLimitService.HandleUpstreamError(ctx, account, resp.StatusCode, resp.Header, respBody, mappedModel) + shouldDisable = s.rateLimitService.HandleUpstreamError(ctx, account, resp.StatusCode, resp.Header, respBody, mappedModel) } return nil, &UpstreamFailoverError{ - StatusCode: resp.StatusCode, - ResponseBody: respBody, + StatusCode: resp.StatusCode, + ResponseBody: respBody, + RetryableOnSameAccount: !shouldDisable && account.IsPoolMode() && account.IsPoolModeRetryableStatus(resp.StatusCode), } } diff --git a/backend/internal/service/gateway_forward_as_responses.go b/backend/internal/service/gateway_forward_as_responses.go index 2aa5255c29..a4c4f0670b 100644 --- a/backend/internal/service/gateway_forward_as_responses.go +++ b/backend/internal/service/gateway_forward_as_responses.go @@ -170,12 +170,14 @@ func (s *GatewayService) ForwardAsResponses( Kind: "failover", Message: upstreamMsg, }) + shouldDisable := false if s.rateLimitService != nil { - s.rateLimitService.HandleUpstreamError(ctx, account, resp.StatusCode, resp.Header, respBody, mappedModel) + shouldDisable = s.rateLimitService.HandleUpstreamError(ctx, account, resp.StatusCode, resp.Header, respBody, mappedModel) } return nil, &UpstreamFailoverError{ - StatusCode: resp.StatusCode, - ResponseBody: respBody, + StatusCode: resp.StatusCode, + ResponseBody: respBody, + RetryableOnSameAccount: !shouldDisable && account.IsPoolMode() && account.IsPoolModeRetryableStatus(resp.StatusCode), } } diff --git a/backend/internal/service/gateway_pool_mode_retry_test.go b/backend/internal/service/gateway_pool_mode_retry_test.go new file mode 100644 index 0000000000..83455e5b95 --- /dev/null +++ b/backend/internal/service/gateway_pool_mode_retry_test.go @@ -0,0 +1,78 @@ +package service + +import ( + "context" + "io" + "net/http" + "net/http/httptest" + "testing" + + "github.com/Wei-Shaw/sub2api/internal/config" + "github.com/gin-gonic/gin" + "github.com/stretchr/testify/require" +) + +func TestGatewayCompatPoolMode429AllowsSameAccountRetry(t *testing.T) { + gin.SetMode(gin.TestMode) + + tests := []struct { + name string + path string + body []byte + call func(*GatewayService, context.Context, *gin.Context, *Account, []byte) (*ForwardResult, error) + }{ + { + name: "chat completions", + path: "/v1/chat/completions", + body: []byte(`{"model":"claude-sonnet-4-5","messages":[{"role":"user","content":"hello"}]}`), + call: func(svc *GatewayService, ctx context.Context, c *gin.Context, account *Account, body []byte) (*ForwardResult, error) { + return svc.ForwardAsChatCompletions(ctx, c, account, body, nil) + }, + }, + { + name: "responses", + path: "/v1/responses", + body: []byte(`{"model":"claude-sonnet-4-5","input":"hello"}`), + call: func(svc *GatewayService, ctx context.Context, c *gin.Context, account *Account, body []byte) (*ForwardResult, error) { + return svc.ForwardAsResponses(ctx, c, account, body, nil) + }, + }, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + upstream := &queuedHTTPUpstreamStub{responses: []*http.Response{{ + StatusCode: http.StatusTooManyRequests, + Header: http.Header{"X-Request-Id": []string{"pool-429"}}, + Body: io.NopCloser(http.NoBody), + }}} + svc := &GatewayService{ + cfg: &config.Config{}, + httpUpstream: upstream, + tlsFPProfileService: &TLSFingerprintProfileService{}, + } + recorder := httptest.NewRecorder() + c, _ := gin.CreateTestContext(recorder) + c.Request = httptest.NewRequest(http.MethodPost, tt.path, nil) + account := &Account{ + ID: 1, + Name: "pool-account", + Platform: PlatformAnthropic, + Type: AccountTypeAPIKey, + Credentials: map[string]any{ + "api_key": "test-key", + "pool_mode": true, + }, + } + + result, err := tt.call(svc, context.Background(), c, account, tt.body) + require.Nil(t, result) + var failoverErr *UpstreamFailoverError + require.ErrorAs(t, err, &failoverErr) + require.Equal(t, http.StatusTooManyRequests, failoverErr.StatusCode) + require.True(t, failoverErr.RetryableOnSameAccount) + require.Equal(t, 1, upstream.callCount) + require.Empty(t, recorder.Body.String()) + }) + } +} From b410c39133a117a05745a2eb2ba5fecd5f598c69 Mon Sep 17 00:00:00 2001 From: wucm667 Date: Wed, 19 Aug 2026 10:17:52 +0800 Subject: [PATCH 010/204] fix(security): add nanoid audit exception for GHSA-2v37-7h3g-55p8 --- .github/audit-exceptions.yml | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/.github/audit-exceptions.yml b/.github/audit-exceptions.yml index 2a89dd0761..6243f0fa7f 100644 --- a/.github/audit-exceptions.yml +++ b/.github/audit-exceptions.yml @@ -35,3 +35,10 @@ exceptions: mitigation: "Proxy configuration not user-controlled; upgrade when axios releases fix" expires_on: "2026-07-10" owner: "security@your-domain" + - package: nanoid + advisory: "GHSA-2v37-7h3g-55p8" + severity: high + reason: "Custom generator with size=0 not used; all nanoid calls use default size or positive values" + mitigation: "No zero-size custom generators in codebase; upgrade when nanoid releases fix" + expires_on: "2026-10-13" + owner: "security@your-domain" From b0464a986303d4e4e300d5fcb5b66b0d78a51b2b Mon Sep 17 00:00:00 2001 From: hank Date: Wed, 19 Aug 2026 16:28:53 +0800 Subject: [PATCH 011/204] feat(proxy): allow configurable probe targets --- backend/internal/config/config.go | 10 +++ .../repository/proxy_probe_service.go | 69 +++++++++++++++++-- .../repository/proxy_probe_service_test.go | 16 +++++ deploy/config.example.yaml | 10 +++ 4 files changed, 100 insertions(+), 5 deletions(-) diff --git a/backend/internal/config/config.go b/backend/internal/config/config.go index e437b11150..798c08017c 100644 --- a/backend/internal/config/config.go +++ b/backend/internal/config/config.go @@ -830,6 +830,16 @@ type ProxyFallbackConfig struct { type ProxyProbeConfig struct { InsecureSkipVerify bool `mapstructure:"insecure_skip_verify"` // 已禁用:禁止跳过 TLS 证书验证 + // URLs 按优先级排列的自定义探测 URL 列表。 + // 留空时使用内置默认列表(ip-api → ipify)。 + // 某些 AI API 专用代理只允许访问特定域名,配置多个备选可提高探测成功率。 + URLs []ProbeURLConfig `mapstructure:"urls"` +} + +// ProbeURLConfig 描述一个探测端点及其响应解析方式。 +type ProbeURLConfig struct { + URL string `mapstructure:"url"` + Parser string `mapstructure:"parser"` // "ip-api" / "ipify" / "chatgpt-trace" } type BillingConfig struct { diff --git a/backend/internal/repository/proxy_probe_service.go b/backend/internal/repository/proxy_probe_service.go index 245eaade81..7ecb26cfdd 100644 --- a/backend/internal/repository/proxy_probe_service.go +++ b/backend/internal/repository/proxy_probe_service.go @@ -31,11 +31,27 @@ func NewProxyExitInfoProber(cfg *config.Config) service.ProxyExitInfoProber { if insecure { log.Printf("[ProxyProbe] Warning: insecure_skip_verify is not allowed and will cause probe failure.") } + // 构建探测 URL 列表:优先用配置的自定义列表,否则用内置默认列表 + probeTargets := defaultProbeURLs + if cfg != nil && len(cfg.Security.ProxyProbe.URLs) > 0 { + probeTargets = make([]probeTarget, 0, len(cfg.Security.ProxyProbe.URLs)) + for _, u := range cfg.Security.ProxyProbe.URLs { + if strings.TrimSpace(u.URL) == "" || strings.TrimSpace(u.Parser) == "" { + continue + } + probeTargets = append(probeTargets, probeTarget{url: u.URL, parser: u.Parser}) + } + if len(probeTargets) == 0 { + probeTargets = defaultProbeURLs + } + } + return &proxyProbeService{ insecureSkipVerify: insecure, allowPrivateHosts: allowPrivate, validateResolvedIP: validateResolvedIP, maxResponseBytes: maxResponseBytes, + probeURLs: probeTargets, } } @@ -44,12 +60,16 @@ const ( defaultProxyProbeResponseMaxBytes = int64(1024 * 1024) ) -// probeURLs 按优先级排列的探测 URL 列表 -// 某些 AI API 专用代理只允许访问特定域名,因此需要多个备选 -var probeURLs = []struct { +// probeTarget 描述一个探测端点及其响应解析方式。 +type probeTarget struct { url string - parser string // "ip-api" or "ipify" -}{ + parser string // "ip-api" / "ipify" / "chatgpt-trace" +} + +// defaultProbeURLs 按优先级排列的默认探测 URL 列表。 +// 某些 AI API 专用代理只允许访问特定域名,因此需要多个备选。 +// 可通过配置 security.proxy_probe.urls 覆盖。 +var defaultProbeURLs = []probeTarget{ {"http://ip-api.com/json/?lang=zh-CN", "ip-api"}, {"http://api64.ipify.org?format=json", "ipify"}, } @@ -59,6 +79,7 @@ type proxyProbeService struct { allowPrivateHosts bool validateResolvedIP bool maxResponseBytes int64 + probeURLs []probeTarget } func (s *proxyProbeService) ProbeProxy(ctx context.Context, proxyURL string) (*service.ProxyExitInfo, int64, error) { @@ -74,6 +95,10 @@ func (s *proxyProbeService) ProbeProxy(ctx context.Context, proxyURL string) (*s } var lastErr error + probeURLs := s.probeURLs + if len(probeURLs) == 0 { + probeURLs = defaultProbeURLs + } for _, probe := range probeURLs { exitInfo, latencyMs, err := s.probeWithURL(ctx, client, probe.url, probe.parser) if err == nil { @@ -121,6 +146,8 @@ func (s *proxyProbeService) probeWithURL(ctx context.Context, client *http.Clien return s.parseIPAPI(body, latencyMs) case "ipify": return s.parseIPify(body, latencyMs) + case "chatgpt-trace": + return s.parseChatGPTTrace(body, latencyMs) default: return nil, latencyMs, fmt.Errorf("unknown parser: %s", parser) } @@ -179,3 +206,35 @@ func (s *proxyProbeService) parseIPify(body []byte, latencyMs int64) (*service.P IP: result.IP, }, latencyMs, nil } + +// parseChatGPTTrace 解析 Cloudflare trace 端点(如 chatgpt.com/cdn-cgi/trace)的纯文本响应。 +// 响应按行给出键值对,其中 ip= 为出口 IP,loc= 为国家代码。 +func (s *proxyProbeService) parseChatGPTTrace(body []byte, latencyMs int64) (*service.ProxyExitInfo, int64, error) { + var ip, loc string + for _, line := range strings.Split(string(body), "\n") { + key, value, found := strings.Cut(strings.TrimSpace(line), "=") + if !found { + continue + } + switch key { + case "ip": + ip = strings.TrimSpace(value) + case "loc": + loc = strings.TrimSpace(value) + } + } + if ip == "" { + preview := string(body) + if len(preview) > 200 { + preview = preview[:200] + "..." + } + return nil, latencyMs, fmt.Errorf("chatgpt-trace: no ip= found in response (body: %s)", preview) + } + info := &service.ProxyExitInfo{ + IP: ip, + } + if loc != "" { + info.CountryCode = loc + } + return info, latencyMs, nil +} diff --git a/backend/internal/repository/proxy_probe_service_test.go b/backend/internal/repository/proxy_probe_service_test.go index c778f6c1eb..45c342cb4b 100644 --- a/backend/internal/repository/proxy_probe_service_test.go +++ b/backend/internal/repository/proxy_probe_service_test.go @@ -166,6 +166,22 @@ func (s *ProxyProbeServiceSuite) TestParseIPify_NoIP() { require.ErrorContains(s.T(), err, "no IP found") } +func (s *ProxyProbeServiceSuite) TestParseChatGPTTrace_Success() { + body := []byte("fl=abc\nh=chatgpt.com\nip=203.0.113.5\nts=1700000000\nloc=US\ntz=UTC\n") + info, latencyMs, err := s.prober.parseChatGPTTrace(body, 320) + require.NoError(s.T(), err) + require.Equal(s.T(), int64(320), latencyMs) + require.Equal(s.T(), "203.0.113.5", info.IP) + require.Equal(s.T(), "US", info.CountryCode) +} + +func (s *ProxyProbeServiceSuite) TestParseChatGPTTrace_NoIP() { + body := []byte("fl=abc\nh=chatgpt.com\nloc=US\n") + _, _, err := s.prober.parseChatGPTTrace(body, 100) + require.Error(s.T(), err) + require.ErrorContains(s.T(), err, "chatgpt-trace: no ip= found") +} + func TestProxyProbeServiceSuite(t *testing.T) { suite.Run(t, new(ProxyProbeServiceSuite)) } diff --git a/deploy/config.example.yaml b/deploy/config.example.yaml index e8c1c84b78..8f134dd609 100644 --- a/deploy/config.example.yaml +++ b/deploy/config.example.yaml @@ -186,6 +186,16 @@ security: # Allow skipping TLS verification for proxy probe (debug only) # 允许代理探测时跳过 TLS 证书验证(仅用于调试) insecure_skip_verify: false + # Optional ordered probe targets. Leave empty to use the built-in ip-api/ipify fallback. + # parser supports: ip-api, ipify, chatgpt-trace + # 可选的有序探测目标。留空时使用内置 ip-api/ipify 回退。 + # parser 支持:ip-api、ipify、chatgpt-trace + urls: [] + # urls: + # - url: "https://chatgpt.com/cdn-cgi/trace" + # parser: "chatgpt-trace" + # - url: "https://api64.ipify.org?format=json" + # parser: "ipify" proxy_fallback: # Allow auxiliary services (update check, pricing data) to fallback to direct # connection when proxy initialization fails. Does NOT affect AI gateway connections. From 63839f193ac7e5c73f2974182e2b5b9d08495a78 Mon Sep 17 00:00:00 2001 From: hank Date: Wed, 19 Aug 2026 16:36:18 +0800 Subject: [PATCH 012/204] fix(frontend): align admin role selector styling --- .../components/admin/user/UserEditModal.vue | 27 ++++++++++++++----- 1 file changed, 21 insertions(+), 6 deletions(-) diff --git a/frontend/src/components/admin/user/UserEditModal.vue b/frontend/src/components/admin/user/UserEditModal.vue index ea9bf21e69..4d02c4d6e0 100644 --- a/frontend/src/components/admin/user/UserEditModal.vue +++ b/frontend/src/components/admin/user/UserEditModal.vue @@ -31,10 +31,11 @@
- + + + + +
+
@@ -371,6 +379,12 @@
+
+ + + +
+
@@ -8937,6 +8951,10 @@ const rateLimit429CooldownSaving = ref(false); const rateLimit429CooldownForm = reactive({ enabled: true, cooldown_seconds: 5, + strategy: "cooldown" as "cooldown" | "same_account_retry", + retry_interval_ms: 500, + retry_max_duration_seconds: 120, + max_account_switches: 2, }); // Panel API Rate Limit 状态 @@ -11837,6 +11855,10 @@ async function saveRateLimit429CooldownSettings() { const updated = await adminAPI.settings.updateRateLimit429CooldownSettings({ enabled: rateLimit429CooldownForm.enabled, cooldown_seconds: rateLimit429CooldownForm.cooldown_seconds, + strategy: rateLimit429CooldownForm.strategy, + retry_interval_ms: rateLimit429CooldownForm.retry_interval_ms, + retry_max_duration_seconds: rateLimit429CooldownForm.retry_max_duration_seconds, + max_account_switches: rateLimit429CooldownForm.max_account_switches, }); Object.assign(rateLimit429CooldownForm, updated); appStore.showSuccess(t("admin.settings.rateLimit429Cooldown.saved")); From e62ec2c42fa8abf3a9d03d6454f4cdadace95069 Mon Sep 17 00:00:00 2001 From: IanShaw <131567472+IanShaw027@users.noreply.github.com> Date: Thu, 20 Aug 2026 05:44:21 -0700 Subject: [PATCH 060/204] Revert "feat(429): add configurable cooldown and retry strategies" This reverts commit 6c3edc095640fe651d1b4524c39ed1e550ca298b. --- .../handler/admin/setting_handler_runtime.go | 32 +- backend/internal/handler/dto/settings.go | 172 ++++----- backend/internal/handler/failover_loop.go | 91 +---- .../openai_account_runtime_block_fastpath.go | 190 +-------- .../service/openai_gateway_cc_pipeline.go | 18 +- .../service/openai_gateway_forward.go | 134 ++++--- .../service/openai_gateway_passthrough.go | 362 ++++++++++++++++-- .../service/openai_gateway_service.go | 106 +---- backend/internal/service/setting_features.go | 37 -- backend/internal/service/settings_view.go | 78 +--- frontend/src/api/admin/settings.ts | 4 - frontend/src/views/admin/SettingsView.vue | 24 +- 12 files changed, 555 insertions(+), 693 deletions(-) diff --git a/backend/internal/handler/admin/setting_handler_runtime.go b/backend/internal/handler/admin/setting_handler_runtime.go index ef16e8979f..eb89b5472c 100644 --- a/backend/internal/handler/admin/setting_handler_runtime.go +++ b/backend/internal/handler/admin/setting_handler_runtime.go @@ -112,23 +112,15 @@ func (h *SettingHandler) GetRateLimit429CooldownSettings(c *gin.Context) { } response.Success(c, dto.RateLimit429CooldownSettings{ - Enabled: settings.Enabled, - CooldownSeconds: settings.CooldownSeconds, - Strategy: settings.Strategy, - RetryIntervalMs: settings.RetryIntervalMs, - RetryMaxDurationSeconds: settings.RetryMaxDurationSeconds, - MaxAccountSwitches: settings.MaxAccountSwitches, + Enabled: settings.Enabled, + CooldownSeconds: settings.CooldownSeconds, }) } // UpdateRateLimit429CooldownSettingsRequest 更新429默认回避配置请求 type UpdateRateLimit429CooldownSettingsRequest struct { - Strategy string `json:"strategy"` - RetryIntervalMs int `json:"retry_interval_ms"` - RetryMaxDurationSeconds int `json:"retry_max_duration_seconds"` - MaxAccountSwitches int `json:"max_account_switches"` - Enabled bool `json:"enabled"` - CooldownSeconds int `json:"cooldown_seconds"` + Enabled bool `json:"enabled"` + CooldownSeconds int `json:"cooldown_seconds"` } // UpdateRateLimit429CooldownSettings 更新429默认回避配置 @@ -141,12 +133,8 @@ func (h *SettingHandler) UpdateRateLimit429CooldownSettings(c *gin.Context) { } settings := &service.RateLimit429CooldownSettings{ - Strategy: req.Strategy, - RetryIntervalMs: req.RetryIntervalMs, - RetryMaxDurationSeconds: req.RetryMaxDurationSeconds, - MaxAccountSwitches: req.MaxAccountSwitches, - Enabled: req.Enabled, - CooldownSeconds: req.CooldownSeconds, + Enabled: req.Enabled, + CooldownSeconds: req.CooldownSeconds, } if err := h.settingService.SetRateLimit429CooldownSettings(c.Request.Context(), settings); err != nil { @@ -161,12 +149,8 @@ func (h *SettingHandler) UpdateRateLimit429CooldownSettings(c *gin.Context) { } response.Success(c, dto.RateLimit429CooldownSettings{ - Enabled: updatedSettings.Enabled, - CooldownSeconds: updatedSettings.CooldownSeconds, - Strategy: updatedSettings.Strategy, - RetryIntervalMs: updatedSettings.RetryIntervalMs, - RetryMaxDurationSeconds: updatedSettings.RetryMaxDurationSeconds, - MaxAccountSwitches: updatedSettings.MaxAccountSwitches, + Enabled: updatedSettings.Enabled, + CooldownSeconds: updatedSettings.CooldownSeconds, }) } diff --git a/backend/internal/handler/dto/settings.go b/backend/internal/handler/dto/settings.go index c0ef93e8cd..798de2fed9 100644 --- a/backend/internal/handler/dto/settings.go +++ b/backend/internal/handler/dto/settings.go @@ -148,23 +148,21 @@ type SystemSettings struct { GoogleOAuthRedirectURL string `json:"google_oauth_redirect_url"` GoogleOAuthFrontendRedirectURL string `json:"google_oauth_frontend_redirect_url"` - SiteName string `json:"site_name"` - SiteLogo string `json:"site_logo"` - SiteSubtitle string `json:"site_subtitle"` - APIBaseURL string `json:"api_base_url"` - ContactInfo string `json:"contact_info"` - SupportQRCodes []service.SupportQRCodeEntry `json:"support_qr_codes"` - DownloadToolsURL string `json:"download_tools_url"` - DocURL string `json:"doc_url"` - HomeContent string `json:"home_content"` - CompactHomeEnabled bool `json:"compact_home_enabled"` - HideCcsImportButton bool `json:"hide_ccs_import_button"` - PurchaseSubscriptionEnabled bool `json:"purchase_subscription_enabled"` - PurchaseSubscriptionURL string `json:"purchase_subscription_url"` - TableDefaultPageSize int `json:"table_default_page_size"` - TablePageSizeOptions []int `json:"table_page_size_options"` - CustomMenuItems []CustomMenuItem `json:"custom_menu_items"` - CustomEndpoints []CustomEndpoint `json:"custom_endpoints"` + SiteName string `json:"site_name"` + SiteLogo string `json:"site_logo"` + SiteSubtitle string `json:"site_subtitle"` + APIBaseURL string `json:"api_base_url"` + ContactInfo string `json:"contact_info"` + DocURL string `json:"doc_url"` + HomeContent string `json:"home_content"` + CompactHomeEnabled bool `json:"compact_home_enabled"` + HideCcsImportButton bool `json:"hide_ccs_import_button"` + PurchaseSubscriptionEnabled bool `json:"purchase_subscription_enabled"` + PurchaseSubscriptionURL string `json:"purchase_subscription_url"` + TableDefaultPageSize int `json:"table_default_page_size"` + TablePageSizeOptions []int `json:"table_page_size_options"` + CustomMenuItems []CustomMenuItem `json:"custom_menu_items"` + CustomEndpoints []CustomEndpoint `json:"custom_endpoints"` DefaultConcurrency int `json:"default_concurrency"` DefaultBalance float64 `json:"default_balance"` @@ -172,9 +170,6 @@ type SystemSettings struct { AffiliateRebateFreezeHours int `json:"affiliate_rebate_freeze_hours"` AffiliateRebateDurationDays int `json:"affiliate_rebate_duration_days"` AffiliateRebatePerInviteeCap float64 `json:"affiliate_rebate_per_invitee_cap"` - AffiliateRebateCap float64 `json:"affiliate_rebate_cap"` - AffiliateRebateInviteeLimit int `json:"affiliate_rebate_invitee_limit"` - AffiliateSignupBonus float64 `json:"affiliate_signup_bonus"` AdminRechargeRebateEnabled bool `json:"affiliate_admin_recharge_enabled"` DefaultUserRPMLimit int `json:"default_user_rpm_limit"` DefaultSubscriptions []DefaultSubscriptionSetting `json:"default_subscriptions"` @@ -310,23 +305,13 @@ type SystemSettings struct { ChannelMonitorMode string `json:"channel_monitor_mode"` ChannelMonitorDefaultIntervalSeconds int `json:"channel_monitor_default_interval_seconds"` ChannelMonitorHideThroughput bool `json:"channel_monitor_hide_throughput"` + ChannelMonitorShowQuota bool `json:"channel_monitor_show_quota"` // Grok model mapping policy (admin settings; empty account mapping falls back to these). GrokDefaultTextModel string `json:"grok_default_text_model"` GrokCrossClientModelMapEnabled bool `json:"grok_cross_client_model_map_enabled"` GrokDefaultBaseURLMode string `json:"grok_default_base_url_mode"` - // Kiro runtime defaults (admin-only; not exposed on PublicSettings). - KiroDefaultVersion string `json:"kiro_version"` - KiroDefaultCommit string `json:"kiro_commit"` - KiroDefaultSystemVersion string `json:"system_version"` - KiroDefaultNodeVersion string `json:"node_version"` - KiroCacheHitRateScale int `json:"cache_hit_rate_scale"` - KiroCacheMinBlockTokens int `json:"cache_min_block_tokens"` - KiroCacheIndependentTTLSeconds int `json:"cache_independent_ttl_seconds"` - KiroCachePrefixTTLSeconds int `json:"cache_prefix_ttl_seconds"` - KiroCodeExecutionSandboxCommand string `json:"kiro_code_execution_sandbox_command"` - // Available Channels feature switch (user-facing aggregate view) AvailableChannelsEnabled bool `json:"available_channels_enabled"` @@ -345,14 +330,6 @@ type SystemSettings struct { // Affiliate (邀请返利) feature switch AffiliateEnabled bool `json:"affiliate_enabled"` - // Ticket feature switch (default enabled) - TicketEnabled bool `json:"ticket_enabled"` - - IPMultiAccountBanEnabled bool `json:"ip_multi_account_ban_enabled"` - IPMultiAccountBanWindowMinutes int `json:"ip_multi_account_ban_window_minutes"` - IPMultiAccountBanThreshold int `json:"ip_multi_account_ban_threshold"` - IPMultiAccountBanLearningUntil string `json:"ip_multi_account_ban_learning_until"` - // OpenAI fast/flex policy OpenAIFastPolicySettings *OpenAIFastPolicySettings `json:"openai_fast_policy_settings,omitempty"` @@ -372,61 +349,58 @@ type DefaultSubscriptionSetting struct { } type PublicSettings struct { - RegistrationEnabled bool `json:"registration_enabled"` - EmailVerifyEnabled bool `json:"email_verify_enabled"` - ForceEmailOnThirdPartySignup bool `json:"force_email_on_third_party_signup"` - RegistrationEmailSuffixWhitelist []string `json:"registration_email_suffix_whitelist"` - RegistrationEmailDomainQuotaEnabled bool `json:"registration_email_domain_quota_enabled"` - PromoCodeEnabled bool `json:"promo_code_enabled"` - PasswordResetEnabled bool `json:"password_reset_enabled"` - InvitationCodeEnabled bool `json:"invitation_code_enabled"` - TotpEnabled bool `json:"totp_enabled"` // TOTP 双因素认证 - PasskeyEnabled bool `json:"passkey_enabled"` - LoginAgreementEnabled bool `json:"login_agreement_enabled"` - LoginAgreementMode string `json:"login_agreement_mode"` - LoginAgreementUpdatedAt string `json:"login_agreement_updated_at"` - LoginAgreementRevision string `json:"login_agreement_revision"` - LoginAgreementDocuments []LoginAgreementDocument `json:"login_agreement_documents"` - TurnstileEnabled bool `json:"turnstile_enabled"` - TurnstileSiteKey string `json:"turnstile_site_key"` - TencentCaptchaEnabled bool `json:"tencent_captcha_enabled"` - TencentCaptchaAppID string `json:"tencent_captcha_app_id"` - TencentCaptchaRegion string `json:"tencent_captcha_region"` - AliyunCaptchaEnabled bool `json:"aliyun_captcha_enabled"` - AliyunCaptchaSceneID string `json:"aliyun_captcha_scene_id"` - AliyunCaptchaPrefix string `json:"aliyun_captcha_prefix"` - AliyunCaptchaRegion string `json:"aliyun_captcha_region"` - SiteName string `json:"site_name"` - SiteLogo string `json:"site_logo"` - SiteSubtitle string `json:"site_subtitle"` - APIBaseURL string `json:"api_base_url"` - ContactInfo string `json:"contact_info"` - SupportQRCodes []service.SupportQRCodeEntry `json:"support_qr_codes"` - DownloadToolsURL string `json:"download_tools_url"` - DocURL string `json:"doc_url"` - HomeContent string `json:"home_content"` - CompactHomeEnabled bool `json:"compact_home_enabled"` - HideCcsImportButton bool `json:"hide_ccs_import_button"` - PurchaseSubscriptionEnabled bool `json:"purchase_subscription_enabled"` - PurchaseSubscriptionURL string `json:"purchase_subscription_url"` - TableDefaultPageSize int `json:"table_default_page_size"` - TablePageSizeOptions []int `json:"table_page_size_options"` - CustomMenuItems []CustomMenuItem `json:"custom_menu_items"` - CustomEndpoints []CustomEndpoint `json:"custom_endpoints"` - DingTalkOAuthEnabled bool `json:"dingtalk_oauth_enabled"` - LinuxDoOAuthEnabled bool `json:"linuxdo_oauth_enabled"` - WeChatOAuthEnabled bool `json:"wechat_oauth_enabled"` - WeChatOAuthOpenEnabled bool `json:"wechat_oauth_open_enabled"` - WeChatOAuthMPEnabled bool `json:"wechat_oauth_mp_enabled"` - WeChatOAuthMobileEnabled bool `json:"wechat_oauth_mobile_enabled"` - OIDCOAuthEnabled bool `json:"oidc_oauth_enabled"` - OIDCOAuthProviderName string `json:"oidc_oauth_provider_name"` - GitHubOAuthEnabled bool `json:"github_oauth_enabled"` - GoogleOAuthEnabled bool `json:"google_oauth_enabled"` - SoraClientEnabled bool `json:"sora_client_enabled"` - BackendModeEnabled bool `json:"backend_mode_enabled"` - PaymentEnabled bool `json:"payment_enabled"` - Version string `json:"version"` + RegistrationEnabled bool `json:"registration_enabled"` + EmailVerifyEnabled bool `json:"email_verify_enabled"` + ForceEmailOnThirdPartySignup bool `json:"force_email_on_third_party_signup"` + RegistrationEmailSuffixWhitelist []string `json:"registration_email_suffix_whitelist"` + RegistrationEmailDomainQuotaEnabled bool `json:"registration_email_domain_quota_enabled"` + PromoCodeEnabled bool `json:"promo_code_enabled"` + PasswordResetEnabled bool `json:"password_reset_enabled"` + InvitationCodeEnabled bool `json:"invitation_code_enabled"` + TotpEnabled bool `json:"totp_enabled"` // TOTP 双因素认证 + PasskeyEnabled bool `json:"passkey_enabled"` + LoginAgreementEnabled bool `json:"login_agreement_enabled"` + LoginAgreementMode string `json:"login_agreement_mode"` + LoginAgreementUpdatedAt string `json:"login_agreement_updated_at"` + LoginAgreementRevision string `json:"login_agreement_revision"` + LoginAgreementDocuments []LoginAgreementDocument `json:"login_agreement_documents"` + TurnstileEnabled bool `json:"turnstile_enabled"` + TurnstileSiteKey string `json:"turnstile_site_key"` + TencentCaptchaEnabled bool `json:"tencent_captcha_enabled"` + TencentCaptchaAppID string `json:"tencent_captcha_app_id"` + TencentCaptchaRegion string `json:"tencent_captcha_region"` + AliyunCaptchaEnabled bool `json:"aliyun_captcha_enabled"` + AliyunCaptchaSceneID string `json:"aliyun_captcha_scene_id"` + AliyunCaptchaPrefix string `json:"aliyun_captcha_prefix"` + AliyunCaptchaRegion string `json:"aliyun_captcha_region"` + SiteName string `json:"site_name"` + SiteLogo string `json:"site_logo"` + SiteSubtitle string `json:"site_subtitle"` + APIBaseURL string `json:"api_base_url"` + ContactInfo string `json:"contact_info"` + DocURL string `json:"doc_url"` + HomeContent string `json:"home_content"` + CompactHomeEnabled bool `json:"compact_home_enabled"` + HideCcsImportButton bool `json:"hide_ccs_import_button"` + PurchaseSubscriptionEnabled bool `json:"purchase_subscription_enabled"` + PurchaseSubscriptionURL string `json:"purchase_subscription_url"` + TableDefaultPageSize int `json:"table_default_page_size"` + TablePageSizeOptions []int `json:"table_page_size_options"` + CustomMenuItems []CustomMenuItem `json:"custom_menu_items"` + CustomEndpoints []CustomEndpoint `json:"custom_endpoints"` + DingTalkOAuthEnabled bool `json:"dingtalk_oauth_enabled"` + LinuxDoOAuthEnabled bool `json:"linuxdo_oauth_enabled"` + WeChatOAuthEnabled bool `json:"wechat_oauth_enabled"` + WeChatOAuthOpenEnabled bool `json:"wechat_oauth_open_enabled"` + WeChatOAuthMPEnabled bool `json:"wechat_oauth_mp_enabled"` + WeChatOAuthMobileEnabled bool `json:"wechat_oauth_mobile_enabled"` + OIDCOAuthEnabled bool `json:"oidc_oauth_enabled"` + OIDCOAuthProviderName string `json:"oidc_oauth_provider_name"` + GitHubOAuthEnabled bool `json:"github_oauth_enabled"` + GoogleOAuthEnabled bool `json:"google_oauth_enabled"` + BackendModeEnabled bool `json:"backend_mode_enabled"` + PaymentEnabled bool `json:"payment_enabled"` + Version string `json:"version"` // 服务器全局时区(IANA 名称与当前 UTC 偏移,如 "Asia/Shanghai" / "+08:00")。 // 高峰时段等按服务器本地时间判定的窗口,前端展示时据此标注,避免用户按浏览器本地时间误读。 ServerTimezone string `json:"server_timezone"` @@ -440,6 +414,7 @@ type PublicSettings struct { ChannelMonitorMode string `json:"channel_monitor_mode"` ChannelMonitorDefaultIntervalSeconds int `json:"channel_monitor_default_interval_seconds"` ChannelMonitorHideThroughput bool `json:"channel_monitor_hide_throughput"` + ChannelMonitorShowQuota bool `json:"channel_monitor_show_quota"` AvailableChannelsEnabled bool `json:"available_channels_enabled"` @@ -447,7 +422,6 @@ type PublicSettings struct { ModelPlazaRequireAuth bool `json:"model_plaza_require_auth"` AffiliateEnabled bool `json:"affiliate_enabled"` - TicketEnabled bool `json:"ticket_enabled"` RiskControlEnabled bool `json:"risk_control_enabled"` @@ -468,12 +442,8 @@ type OverloadCooldownSettings struct { // RateLimit429CooldownSettings 429默认回避配置 DTO type RateLimit429CooldownSettings struct { - Strategy string `json:"strategy"` - RetryIntervalMs int `json:"retry_interval_ms"` - RetryMaxDurationSeconds int `json:"retry_max_duration_seconds"` - MaxAccountSwitches int `json:"max_account_switches"` - Enabled bool `json:"enabled"` - CooldownSeconds int `json:"cooldown_seconds"` + Enabled bool `json:"enabled"` + CooldownSeconds int `json:"cooldown_seconds"` } // PanelRateLimitSettings 面板 API 限流配置 DTO diff --git a/backend/internal/handler/failover_loop.go b/backend/internal/handler/failover_loop.go index 71a0f0615d..d349980fc6 100644 --- a/backend/internal/handler/failover_loop.go +++ b/backend/internal/handler/failover_loop.go @@ -56,16 +56,13 @@ const ( const profitVetoExhaustedMessage = "No available accounts: all candidates rejected by group profit control" func sameAccountRetryDelayFor(failoverErr *service.UpstreamFailoverError, retryCount int) time.Duration { - // An OAuth 429 with a request-scoped deadline intentionally retries - // immediately; zero is meaningful here and must not fall back to 500ms. - if failoverErr != nil && failoverErr.StatusCode == http.StatusTooManyRequests && - !failoverErr.SameAccountRetryDeadline.IsZero() && failoverErr.SameAccountRetryDelay <= 0 { - return 0 + if failoverErr == nil { + return sameAccountRetryDelay } - if failoverErr != nil && failoverErr.SameAccountRetryDelay > 0 { + if failoverErr.SameAccountRetryDelay > 0 { return failoverErr.SameAccountRetryDelay } - if failoverErr == nil || !failoverErr.RequestScopedTransient || retryCount <= 1 { + if !failoverErr.RequestScopedTransient || retryCount <= 1 { return sameAccountRetryDelay } @@ -79,43 +76,10 @@ func sameAccountRetryDelayFor(failoverErr *service.UpstreamFailoverError, retryC return delay } -func sameAccountRetryAllowed(failoverErr *service.UpstreamFailoverError, retryCount, retryLimit int) bool { - if failoverErr == nil || !failoverErr.RetryableOnSameAccount { - return false - } - if retryLimit > 0 && retryCount >= retryLimit { - return false - } - if !failoverErr.SameAccountRetryDeadline.IsZero() { - return time.Now().Before(failoverErr.SameAccountRetryDeadline) - } - return retryCount < retryLimit -} - -func pinSameAccountRetryContext( - ctx context.Context, - fs *FailoverState, - accountID int64, - groupID *int64, - failoverErr *service.UpstreamFailoverError, - prevRetryCount int, - prevSwitchCount int, - bridgeOldKeys bool, -) context.Context { - if ctx == nil || fs == nil || failoverErr == nil || !failoverErr.RetryableOnSameAccount { - return ctx - } - if fs.SwitchCount != prevSwitchCount { - return ctx - } - if fs.SameAccountRetryCount[accountID] != prevRetryCount+1 { - return ctx - } - prefetchedGroupID := int64(0) - if groupID != nil { - prefetchedGroupID = *groupID - } - return service.WithPrefetchedStickySession(ctx, accountID, prefetchedGroupID, bridgeOldKeys) +// sameAccountRetryDeadlineAllows prevents a retry from starting after the +// service-provided same-account retry window has elapsed. +func sameAccountRetryDeadlineAllows(failoverErr *service.UpstreamFailoverError) bool { + return failoverErr == nil || failoverErr.SameAccountRetryDeadline.IsZero() || time.Now().Before(failoverErr.SameAccountRetryDeadline) } // FailoverState 跨循环迭代共享的 failover 状态 @@ -168,24 +132,6 @@ func (s *FailoverState) RecordProfitVeto(accountID int64) FailoverAction { return FailoverContinue } -// RecordConcurrencyTimeout excludes a busy account after the slot ladder -// (deadline two-shot or wait-queue full) and continues onto another account -// while the original sticky binding is preserved by the caller. -func (s *FailoverState) RecordConcurrencyTimeout(accountID int64) FailoverAction { - if s == nil { - return FailoverExhausted - } - if s.FailedAccountIDs == nil { - s.FailedAccountIDs = make(map[int64]struct{}) - } - s.FailedAccountIDs[accountID] = struct{}{} - if s.SwitchCount >= s.MaxSwitches { - return FailoverExhausted - } - s.SwitchCount++ - return FailoverContinue -} - // ProfitVetoCount 返回本次请求累计的利润否决次数(供日志使用)。 func (s *FailoverState) ProfitVetoCount() int { return s.profitVetoCount } @@ -223,27 +169,27 @@ func (s *FailoverState) HandleFailoverError( return FailoverExhausted } - retryMax := retryLimit - if failoverErr.SameAccountRetryMax > 0 { - retryMax = failoverErr.SameAccountRetryMax - } - // 同账号重试不算切换账号,粘性会话仅在实际切换时强制缓存计费。 - sameAccountRetry := sameAccountRetryAllowed(failoverErr, s.SameAccountRetryCount[accountID], retryMax) + retryCount := s.SameAccountRetryCount[accountID] + sameAccountRetryAllowed := failoverErr.RetryableOnSameAccount && retryLimit > 0 && retryCount < retryLimit + if sameAccountRetryAllowed && !failoverErr.SameAccountRetryDeadline.IsZero() { + sameAccountRetryAllowed = time.Now().Before(failoverErr.SameAccountRetryDeadline) + } + sameAccountRetry := sameAccountRetryAllowed if needForceCacheBilling(s.hasBoundSession, failoverErr, sameAccountRetry) { s.ForceCacheBilling = true } // 同账号重试:对 RetryableOnSameAccount 的临时性错误,先在同一账号上重试。 // 重试次数上限 retryLimit 由调用方传入(账号级 pool_mode_retry_count 配置)。 - if sameAccountRetryAllowed(failoverErr, s.SameAccountRetryCount[accountID], retryMax) { + if sameAccountRetryAllowed { s.SameAccountRetryCount[accountID]++ retryDelay := sameAccountRetryDelayFor(failoverErr, s.SameAccountRetryCount[accountID]) logger.FromContext(ctx).Warn("gateway.failover_same_account_retry", zap.Int64("account_id", accountID), zap.Int("upstream_status", failoverErr.StatusCode), zap.Int("same_account_retry_count", s.SameAccountRetryCount[accountID]), - zap.Int("same_account_retry_max", retryMax), + zap.Int("same_account_retry_max", retryLimit), zap.Duration("retry_delay", retryDelay), ) if !sleepWithContext(ctx, retryDelay) { @@ -259,11 +205,6 @@ func (s *FailoverState) HandleFailoverError( // 加入失败列表 s.FailedAccountIDs[accountID] = struct{}{} - for _, excludedAccountID := range failoverErr.ExcludedAccountIDs { - if excludedAccountID > 0 { - s.FailedAccountIDs[excludedAccountID] = struct{}{} - } - } // 检查是否耗尽 if s.SwitchCount >= s.MaxSwitches { diff --git a/backend/internal/service/openai_account_runtime_block_fastpath.go b/backend/internal/service/openai_account_runtime_block_fastpath.go index dd683262f4..6853cc8487 100644 --- a/backend/internal/service/openai_account_runtime_block_fastpath.go +++ b/backend/internal/service/openai_account_runtime_block_fastpath.go @@ -11,34 +11,13 @@ import ( const ( openAIAccountStateUpdateTimeout = 5 * time.Second - openAIOAuth429RetryWindow = 2 * time.Minute - openAIOAuth429RetryDelay = 0 + openAIOAuth429FallbackCooldown = 5 * time.Second openAIStopSchedulingBridgeCooldown = 2 * time.Minute - openAIOAuth429MaxAccountAttempts = 3 openAIOAuth429StormWindow = 10 * time.Second openAIOAuth429StormThreshold = 20 openAIOAuth429StormMaxAccountSwitches = 1 ) -func (s *OpenAIGatewayService) rateLimit429StrategySettings() RateLimit429CooldownSettings { - defaults := DefaultRateLimit429CooldownSettings() - if s == nil || s.settingService == nil { - return *defaults - } - s.openai429StrategyMu.Lock() - defer s.openai429StrategyMu.Unlock() - if time.Since(s.openai429StrategyCachedAt) < 5*time.Second { - return s.openai429StrategyCached - } - settings := *defaults - if loaded, err := s.settingService.GetRateLimit429CooldownSettings(context.Background()); err == nil && loaded != nil { - settings = *loaded - } - s.openai429StrategyCached = settings - s.openai429StrategyCachedAt = time.Now() - return settings -} - // OpenAIOAuth429FailoverState tracks the request-local follow-up budget after // the first Grok OAuth 429. Once that 429 occurs, exactly one different account // may be attempted; any failure from that follow-up account ends failover. @@ -76,6 +55,11 @@ func (s *OpenAIGatewayService) handleOpenAIAccountUpstreamError(ctx context.Cont if s != nil { scheduleOllamaCloudUsageActivity(s.deferredService, account) } + // Capacity shedding describes this request, not account health. Keep the + // account schedulable while the request-local retry budget handles recovery. + if account != nil && account.Platform == PlatformOpenAI && isOpenAIRequestScopedCapacityShed("", responseBody) { + return false + } stateCtx, cancel := openAIAccountStateContext(ctx) defer cancel() @@ -93,6 +77,10 @@ func (s *OpenAIGatewayService) handleOpenAIAccountUpstreamError(ctx context.Cont if s == nil || account == nil { return false } + // Team 联动熔断必须先于 model-not-found 与账户级临时不可调度规则的早退。 + if s.rateLimitService != nil { + s.rateLimitService.maybeHandleOpenAITeamLinkedError(stateCtx, account, statusCode, responseBody) + } stateCtx = withTempUnschedulableModel(stateCtx, canonicalModel) if s.rateLimitService != nil && len(canonicalModel) > 0 && s.rateLimitService.HandleUpstreamModelNotFound(stateCtx, account, canonicalModel[0], statusCode, responseBody) { return true @@ -161,164 +149,20 @@ func (s *OpenAIGatewayService) markOpenAIOAuth429RateLimited(ctx context.Context return } s.recordOpenAIOAuth429() - if s.ShouldRetryOpenAIOAuth429(account, headers, responseBody) { - return - } - cooldownUntil := time.Time{} - hasCooldown := false + cooldownUntil := time.Now().Add(openAIOAuth429FallbackCooldown) if s.rateLimitService != nil { if resetAt := s.rateLimitService.calculateOpenAI429ResetTime(headers); resetAt != nil && resetAt.After(time.Now()) { cooldownUntil = *resetAt - hasCooldown = true } else if resetUnix := parseOpenAIRateLimitResetTime(responseBody); resetUnix != nil { if resetAt := time.Unix(*resetUnix, 0); resetAt.After(time.Now()) { cooldownUntil = resetAt - hasCooldown = true } } else if cooldown, ok := s.rateLimitService.get429FallbackCooldown(ctx, account); ok && cooldown > 0 { cooldownUntil = time.Now().Add(cooldown) - hasCooldown = true } } - if !hasCooldown { - // The request-local retry window has expired without an upstream reset - // signal. Keep the account out of new selections while this request - // switches to another candidate, rather than immediately selecting it - // again on a concurrent request. - cooldownUntil = time.Now().Add(openAIStopSchedulingBridgeCooldown) - } s.BlockAccountScheduling(account, cooldownUntil, "429") - s.openaiOAuth429RetryStartedAt.Delete(account.ID) -} - -// shouldRetryOpenAIOAuth429OnSameAccount keeps an OAuth account pinned while -// a transient 429 is still inside its retry window. API-key accounts keep the -// existing pool-mode behavior. -func (s *OpenAIGatewayService) shouldRetryOpenAIOAuth429OnSameAccount(account *Account, statusCode int, shouldDisable bool) bool { - if shouldDisable || account == nil { - return false - } - if statusCode == http.StatusTooManyRequests && isOpenAIOAuthAccount(account) && !account.IsShadow() { - if s.settingService != nil && s.rateLimit429StrategySettings().Strategy != "same_account_retry" { - return false - } - // A prior retry window may already have expired and parked this account. - // Do not create a fresh window while that runtime block is active. - if s.isOpenAIAccountRuntimeBlocked(account) { - return false - } - return s.openAIOAuth429RetryWindowActive(account) - } - return account.IsPoolMode() && account.IsPoolModeRetryableStatus(statusCode) -} - -// ShouldRetryOpenAIOAuth429 is used before persisting a scheduler block. An -// upstream-provided reset takes precedence; only temporary 429s without one -// stay on the same OAuth account during the retry window. -func (s *OpenAIGatewayService) ShouldRetryOpenAIOAuth429(account *Account, headers http.Header, responseBody []byte) bool { - if s == nil || !isOpenAIOAuthAccount(account) || account.IsShadow() { - return false - } - if s.isOpenAIAccountRuntimeBlocked(account) { - return false - } - if s.settingService != nil && s.rateLimit429StrategySettings().Strategy != "same_account_retry" { - return false - } - if s.rateLimitService != nil && s.rateLimitService.calculateOpenAI429ResetTime(headers) != nil { - return false - } - if parseOpenAIRateLimitResetTime(responseBody) != nil { - return false - } - return s.openAIOAuth429RetryWindowActive(account) -} - -func (s *OpenAIGatewayService) openAIOAuth429RetryWindowActive(account *Account) bool { - if s == nil || !isOpenAIOAuthAccount(account) || account.IsShadow() { - return false - } - now := time.Now() - value, _ := s.openaiOAuth429RetryStartedAt.LoadOrStore(account.ID, now) - startedAt, ok := value.(time.Time) - if !ok { - s.openaiOAuth429RetryStartedAt.Store(account.ID, now) - startedAt = now - } - window := openAIOAuth429RetryWindow - if s.settingService != nil { - window = time.Duration(s.rateLimit429StrategySettings().RetryMaxDurationSeconds) * time.Second - } - return now.Sub(startedAt) < window -} - -func openAIOAuth429SameAccountRetryDelay(statusCode int, account *Account) time.Duration { - if statusCode == http.StatusTooManyRequests && isOpenAIOAuthAccount(account) && !account.IsShadow() { - return openAIOAuth429RetryDelay - } - return 0 -} - -func (s *OpenAIGatewayService) openAIOAuth429SameAccountRetryDelay(statusCode int, account *Account) time.Duration { - if statusCode == http.StatusTooManyRequests && isOpenAIOAuthAccount(account) && !account.IsShadow() && s != nil && s.settingService != nil { - return time.Duration(s.rateLimit429StrategySettings().RetryIntervalMs) * time.Millisecond - } - return openAIOAuth429SameAccountRetryDelay(statusCode, account) -} - -// openAIOAuth429RetryDeadline returns the request-local retry window end that -// was established when the account first saw a temporary OAuth 429. -func (s *OpenAIGatewayService) openAIOAuth429RetryDeadline(account *Account) time.Time { - if s == nil || !isOpenAIOAuthAccount(account) || account.IsShadow() { - return time.Time{} - } - value, ok := s.openaiOAuth429RetryStartedAt.Load(account.ID) - if !ok { - return time.Time{} - } - startedAt, ok := value.(time.Time) - if !ok { - return time.Time{} - } - window := openAIOAuth429RetryWindow - if s.settingService != nil { - window = time.Duration(s.rateLimit429StrategySettings().RetryMaxDurationSeconds) * time.Second - } - return startedAt.Add(window) -} - -// SameAccountRetryLimit returns the request-local retry budget. OAuth 429s -// deliberately use a time-derived budget rather than an account pool setting. -func SameAccountRetryLimit(account *Account, failoverErr *UpstreamFailoverError) int { - if failoverErr != nil && failoverErr.StatusCode == http.StatusTooManyRequests && - isOpenAIOAuthAccount(account) && !account.IsShadow() { - if failoverErr.SameAccountRetryMax > 0 { - return failoverErr.SameAccountRetryMax - } - return 24 - } - if account == nil { - return 0 - } - return account.GetPoolModeRetryCount() -} - -func (s *OpenAIGatewayService) openAIOAuth429SameAccountRetryMax() int { - if s == nil || s.settingService == nil { - return 24 - } - settings := s.rateLimit429StrategySettings() - interval := time.Duration(settings.RetryIntervalMs) * time.Millisecond - window := time.Duration(settings.RetryMaxDurationSeconds) * time.Second - max := int(window / interval) - if max < 1 { - max = 1 - } - if max > 240 { - max = 240 - } - return max } func (s *OpenAIGatewayService) BlockAccountScheduling(account *Account, until time.Time, reason string) { @@ -501,11 +345,7 @@ func (s *OpenAIGatewayService) isOpenAIOAuth429Storm() bool { } func (s *OpenAIGatewayService) ShouldStopOpenAIOAuth429Failover(account *Account, statusCode int, failedSwitches int, state *OpenAIOAuth429FailoverState) bool { - maxSwitches := openAIOAuth429StormMaxAccountSwitches - if s != nil && s.settingService != nil { - maxSwitches = s.rateLimit429StrategySettings().MaxAccountSwitches - } - if failedSwitches < maxSwitches { + if failedSwitches < openAIOAuth429StormMaxAccountSwitches { return false } if state != nil && state.grokOAuth429FollowupPending { @@ -528,9 +368,5 @@ func (s *OpenAIGatewayService) ShouldStopOpenAIOAuth429Failover(account *Account if statusCode != http.StatusTooManyRequests || !isOpenAIOAuthAccount(account) { return false } - // failedSwitches is incremented after each exhausted candidate. Therefore, - // a value of three means this request has already given three distinct OAuth - // accounts their full same-account retry window. A 429 storm is diagnostic - // only; it must not skip those candidates and return a client 429 early. - return failedSwitches >= maxSwitches+1 + return s.isOpenAIOAuth429Storm() } diff --git a/backend/internal/service/openai_gateway_cc_pipeline.go b/backend/internal/service/openai_gateway_cc_pipeline.go index 66eb53575d..ce9dd54d37 100644 --- a/backend/internal/service/openai_gateway_cc_pipeline.go +++ b/backend/internal/service/openai_gateway_cc_pipeline.go @@ -125,19 +125,13 @@ func (s *OpenAIGatewayService) failoverOpenAIUpstreamHTTPError( if account.Platform != PlatformGrok && !tempUnscheduled { shouldDisable = s.handleOpenAIAccountUpstreamError(ctx, account, resp.StatusCode, resp.Header, respBody, upstreamModel) } - failoverErr := newOpenAIUpstreamFailoverError( + return newOpenAIUpstreamFailoverError( resp.StatusCode, resp.Header, respBody, upstreamMsg, - s.shouldRetryOpenAIOAuth429OnSameAccount(account, resp.StatusCode, shouldDisable) || (!shouldDisable && account.IsPoolMode() && isOpenAITransientProcessingError(resp.StatusCode, upstreamMsg, respBody)), + !shouldDisable && account.IsPoolMode() && (account.IsPoolModeRetryableStatus(resp.StatusCode) || isOpenAITransientProcessingError(resp.StatusCode, upstreamMsg, respBody)), ) - if failoverErr.RetryableOnSameAccount { - failoverErr.SameAccountRetryDelay = s.openAIOAuth429SameAccountRetryDelay(resp.StatusCode, account) - failoverErr.SameAccountRetryDeadline = s.openAIOAuth429RetryDeadline(account) - failoverErr.SameAccountRetryMax = s.openAIOAuth429SameAccountRetryMax() - } - return failoverErr } // openAIChatCompletionsTargetURL 解析账号的(非 Grok)Chat Completions 上游端点。 @@ -156,7 +150,7 @@ func (s *OpenAIGatewayService) openAIChatCompletionsTargetURL(account *Account) // resolveCCFallbackTarget 解析两条 CC 回退路径共用的账号凭证与上游端点 // (回退路径仅面向 APIKey 账号,凭证恒为 openai api_key)。 func (s *OpenAIGatewayService) resolveCCFallbackTarget(account *Account) (apiKey string, targetURL string, err error) { - apiKey = account.GetOpenAIApiKey() + apiKey = strings.TrimSpace(account.GetOpenAIProtocolAPIKey()) if apiKey == "" { return "", "", fmt.Errorf("account %d missing api_key", account.ID) } @@ -214,9 +208,7 @@ func (s *OpenAIGatewayService) sendCCUpstreamRequest( if account.Platform == PlatformGrok { if account.IsGrokOAuth() { - if err := applyGrokInteractiveUpstreamHeadersFromAccount(ctx, upstreamReq, account); err != nil { - return nil, err - } + applyGrokCLIHeaders(upstreamReq.Header) } applyGrokCacheHeaders(upstreamReq.Header, grokCacheIdentity) } @@ -228,7 +220,7 @@ func (s *OpenAIGatewayService) sendCCUpstreamRequest( if account.Proxy != nil { proxyURL = account.Proxy.URL() } - resp, err := s.httpUpstream.Do(upstreamReq, proxyURL, account.ID, account.EffectiveConcurrency()) + resp, err := s.httpUpstream.Do(upstreamReq, proxyURL, account.ID, account.Concurrency) if err != nil { return nil, s.handleOpenAIUpstreamTransportError(ctx, c, account, err, false) } diff --git a/backend/internal/service/openai_gateway_forward.go b/backend/internal/service/openai_gateway_forward.go index 95f742b6e4..ec5fafdb72 100644 --- a/backend/internal/service/openai_gateway_forward.go +++ b/backend/internal/service/openai_gateway_forward.go @@ -21,6 +21,7 @@ import ( func (s *OpenAIGatewayService) Forward(ctx context.Context, c *gin.Context, account *Account, body []byte) (*OpenAIForwardResult, error) { beginUpstreamResponseModelObservation(c) clearGrokResponsesClientToolMapping(c) + clearOpenAIResponsesClientToolMapping(c) clearOpenAIResponsesNamespaceNames(c) startTime := time.Now() // 固定渠道映射后的请求级 canonical body;账号 normalize/strip 不得改写跨 failover hint。 @@ -39,9 +40,6 @@ func (s *OpenAIGatewayService) Forward(ctx context.Context, c *gin.Context, acco }) return nil, errors.New("codex_cli_only restriction: only codex official clients are allowed") } - if c != nil && c.Request != nil { - maybeLearnOfficialDeviceProfile(ctx, account, c.Request.Header) - } normalizedBody, normalized, err := normalizeOpenAICodexCompactReasoningEffortForAccount(c, account, body) if err != nil { @@ -106,12 +104,21 @@ func (s *OpenAIGatewayService) Forward(ctx context.Context, c *gin.Context, acco requestView := newOpenAIRequestView(body) reqModel, reqStream, promptCacheKey := requestView.Model, requestView.Stream, requestView.PromptCacheKey originalModel := reqModel + nativeDeepSeekResponses := account.Platform == PlatformDeepseek && + (account.GetAPIProtocol() == APIProtocolResponses || account.IsAdaptiveAPIProtocol()) if account.Platform == PlatformGrok { return s.forwardGrokResponses(ctx, c, account, body, originalModel, reqStream, startTime) } - if account.Type == AccountTypeAPIKey && !openai_compat.ShouldUseResponsesAPI(account.Extra) { + // CN 供应商 anthropic 协议账号:/v1/responses 入站是交叉协议组合 + // (Responses 客户端 × Anthropic 上游),转成 Anthropic 请求走原生端点。 + // 不能落到下面的 raw-CC 分支——其 URL 构造会把 anthropic base 当 CC base 用。 + if account.IsAnthropicProtocol() { + return s.forwardResponsesViaNativeAnthropic(ctx, c, account, body, reqModel) + } + + if shouldForwardOpenAIResponsesViaRawChatCompletions(account) { return s.forwardResponsesViaRawChatCompletions(ctx, c, account, body) } if account.Platform == PlatformOpenAI && account.Type == AccountTypeAPIKey { @@ -281,7 +288,7 @@ func (s *OpenAIGatewayService) Forward(ctx context.Context, c *gin.Context, acco instructions := gjson.GetBytes(body, "instructions") instructionsEmpty := !instructions.Exists() || instructions.Type != gjson.String || strings.TrimSpace(instructions.String()) == "" - if instructionsEmpty && !compatMessagesBridge { + if instructionsEmpty && !compatMessagesBridge && !nativeDeepSeekResponses { markPatchSet("instructions", defaultCodexSynthInstructions(reqModel)) } @@ -413,22 +420,35 @@ func (s *OpenAIGatewayService) Forward(ctx context.Context, c *gin.Context, acco if codexResult.Modified { markDecodedModified() } - // 一次加载档案:请求体 client_metadata 与出站头共享同一份 fingerprint IDs。 - // compact 形态不同,跳过。fpIDs == nil 时不单独盖 installation id。 + // 带真实 device_id 时补齐 client_metadata 安装标识,与真实 Codex 对齐(compact 形态不同,跳过)。 + if !isCompactRequest && applyCodexClientMetadata(decoded, account) { + markDecodedModified() + } + stageCodexFingerprintIDs(c, nil) + // 指纹收敛:一次性解析收敛 ID,请求体和出站头共享同一份 IDs(保证 turn_id 等随机字段一致)。 + // fingerprintIDs 在此处解析,后续 buildUpstreamRequest 中使用同一份。 if !isCompactRequest { var clientHeaders http.Header if c != nil && c.Request != nil { clientHeaders = c.Request.Header } - fpIDs := applyCodexForwardRequestIdentity(ctx, c, decoded, account, clientHeaders) + fpIDs := resolveCodexFingerprintIDsFromRequest(account, clientHeaders) if fpIDs != nil { - markDecodedModified() + if applyCodexFingerprintClientMetadata(decoded, fpIDs) { + markDecodedModified() + } } + // 将 fpIDs 存入 gin context,供 buildUpstreamRequest 中头改写使用。 + // 无条件覆写(含 nil):failover 从收敛账号切到 off 账号时,上一 + // 账号的 IDs 不得残留(stageCodexFingerprintIDs 注释)。 + stageCodexFingerprintIDs(c, fpIDs) } if codexResult.NormalizedModel != "" { upstreamModel = codexResult.NormalizedModel } - if codexResult.PromptCacheKey != "" { + if currentPromptCacheKey, ok := decoded["prompt_cache_key"].(string); ok && currentPromptCacheKey != "" { + promptCacheKey = currentPromptCacheKey + } else if codexResult.PromptCacheKey != "" { promptCacheKey = codexResult.PromptCacheKey } } @@ -441,7 +461,7 @@ func (s *OpenAIGatewayService) Forward(ctx context.Context, c *gin.Context, acco maxOutputTokens := gjson.GetBytes(body, "max_output_tokens") if maxOutputTokens.Exists() { switch account.Platform { - case PlatformOpenAI: + case PlatformOpenAI, PlatformDeepseek: // Preserve Responses-native output limits unless the selected upstream // explicitly rejects the field in the bounded HTTP retry loop below. case PlatformAnthropic: @@ -835,7 +855,7 @@ func (s *OpenAIGatewayService) Forward(ctx context.Context, c *gin.Context, acco // Send request upstreamStart := time.Now() - resp, err := s.doAccountHTTP(ctx, c, account, upstreamReq, proxyURL, "responses") + resp, err := s.httpUpstream.Do(upstreamReq, proxyURL, account.ID, account.Concurrency) SetOpsLatencyMs(c, OpsUpstreamLatencyMsKey, time.Since(upstreamStart).Milliseconds()) if headerGuard != nil && headerGuard.stopHeaderWait() { if resp != nil && resp.Body != nil { @@ -929,19 +949,13 @@ func (s *OpenAIGatewayService) Forward(ctx context.Context, c *gin.Context, acco }) shouldDisable := s.handleFailoverSideEffects(ctx, resp, account, respBody, upstreamModel) - failoverErr := newOpenAIUpstreamFailoverError( + return nil, newOpenAIUpstreamFailoverError( resp.StatusCode, resp.Header, respBody, upstreamMsg, - s.shouldRetryOpenAIOAuth429OnSameAccount(account, resp.StatusCode, shouldDisable) || (!shouldDisable && account.IsPoolMode() && isOpenAITransientProcessingError(resp.StatusCode, upstreamMsg, respBody)), + !shouldDisable && account.IsPoolMode() && (account.IsPoolModeRetryableStatus(resp.StatusCode) || isOpenAITransientProcessingError(resp.StatusCode, upstreamMsg, respBody)), ) - if failoverErr.RetryableOnSameAccount { - failoverErr.SameAccountRetryDelay = s.openAIOAuth429SameAccountRetryDelay(resp.StatusCode, account) - failoverErr.SameAccountRetryDeadline = s.openAIOAuth429RetryDeadline(account) - failoverErr.SameAccountRetryMax = s.openAIOAuth429SameAccountRetryMax() - } - return nil, failoverErr } return s.handleErrorResponse(ctx, resp, c, account, body, billingModel) } @@ -1027,6 +1041,25 @@ func (s *OpenAIGatewayService) Forward(ctx context.Context, c *gin.Context, acco } } +func shouldForwardOpenAIResponsesViaRawChatCompletions(account *Account) bool { + if account == nil || account.Type != AccountTypeAPIKey { + return false + } + if account.IsCNProvider() { + // CN 的显式协议配置优先于异步探针 Extra;adaptive 仅 DeepSeek 有原生 + // Responses,Kimi/GLM 回退 Chat Completions。 + switch account.GetAPIProtocol() { + case APIProtocolChatCompletions: + return true + case APIProtocolAdaptive: + return account.Platform != PlatformDeepseek + default: + return false + } + } + return !openai_compat.ShouldUseResponsesAPI(account.Extra) +} + func (s *OpenAIGatewayService) buildUpstreamRequest(ctx context.Context, c *gin.Context, account *Account, body []byte, token string, isStream bool, promptCacheKey string, isCodexCLI bool) (*http.Request, error) { // Determine target URL based on account type var targetURL string @@ -1037,6 +1070,9 @@ func (s *OpenAIGatewayService) buildUpstreamRequest(ctx context.Context, c *gin. case AccountTypeAPIKey: // API Key accounts use Platform API or custom base URL baseURL := account.GetOpenAIBaseURL() + if account.Platform == PlatformDeepseek && account.IsAdaptiveAPIProtocol() { + baseURL = account.GetCNProtocolBaseURL(APIProtocolResponses) + } if baseURL == "" { targetURL = openaiPlatformAPIURL } else { @@ -1044,13 +1080,17 @@ func (s *OpenAIGatewayService) buildUpstreamRequest(ctx context.Context, c *gin. if err != nil { return nil, err } - targetURL = buildOpenAIResponsesURL(validatedURL) + targetURL = buildOpenAIResponsesURLForPlatform(account.Platform, validatedURL) } default: targetURL = openaiPlatformAPIURL } targetURL = appendOpenAIResponsesRequestPathSuffix(targetURL, openAIResponsesRequestPathSuffix(c)) + // DeepSeek 原生 Responses 端点为无状态实现:强制 store=false、清除 + // previous_response_id,避免携带状态字段被上游拒绝。 + body = normalizeDeepSeekResponsesRequestBody(account, body) + req, err := http.NewRequestWithContext(ctx, "POST", targetURL, bytes.NewReader(body)) if err != nil { return nil, err @@ -1087,6 +1127,9 @@ func (s *OpenAIGatewayService) buildUpstreamRequest(ctx context.Context, c *gin. } } } + // 客户端回带的 x-codex-turn-state 若已知由其他账号铸造(failover 换号), + // 剥离后再出站——异账号 blob 与本账号的(指纹收敛后)出站身份自相矛盾。 + s.guardOpenAICodexTurnStateEcho(c, account, req.Header) if account.Type == AccountTypeOAuth { compatMessagesBridge := isOpenAICompatMessagesBridgeContext(c) || isOpenAICompatMessagesBridgeBody(body) // 清除客户端透传的 session 头,后续用隔离后的值重新设置,防止跨用户会话碰撞。 @@ -1101,19 +1144,18 @@ func (s *OpenAIGatewayService) buildUpstreamRequest(ctx context.Context, c *gin. req.Header.Set("originator", resolveOpenAIUpstreamOriginator(c, isCodexCLI)) } apiKeyID := getAPIKeyIDFromContext(c) - profile := resolveOpenAIOutboundDeviceProfile(ctx, c, account) if isOpenAIResponsesCompactPath(c) { req.Header.Set("accept", "application/json") if req.Header.Get("version") == "" { - req.Header.Set("version", codexCLIVersion) + req.Header.Set("version", CodexCanonicalClientVersion()) } compactSession := resolveOpenAICompactSessionID(c) - req.Header.Set("session_id", openaiOutboundSessionIDFromProfile(profile, apiKeyID, compactSession)) + req.Header.Set("session_id", isolateOpenAISessionID(apiKeyID, compactSession)) } else { req.Header.Set("accept", "text/event-stream") } if promptCacheKey != "" { - isolated := openaiOutboundSessionIDFromProfile(profile, apiKeyID, promptCacheKey) + isolated := isolateOpenAISessionID(apiKeyID, promptCacheKey) req.Header.Set("session_id", isolated) if !compatMessagesBridge || clientConversationID != "" { req.Header.Set("conversation_id", isolated) @@ -1131,28 +1173,19 @@ func (s *OpenAIGatewayService) buildUpstreamRequest(ctx context.Context, c *gin. req.Header.Set("user-agent", customUA) } - // 若开启 ForceCodexCLI,则强制将上游 User-Agent 伪装为 Codex CLI。 + // 若开启 ForceCodexCLI,则强制将上游 User-Agent 伪装为规范 Codex 身份。 // 用于网关未透传/改写 User-Agent 时,仍能命中 Codex 侧识别逻辑。 if s.cfg != nil && s.cfg.Gateway.ForceCodexCLI { - req.Header.Set("user-agent", codexCLIUserAgent) + req.Header.Set("user-agent", CodexCanonicalUserAgent()) } // 指纹收敛:使用 Forward() 中预计算的收敛 ID 改写出站头,与请求体使用同一份 IDs。 - // leftover 5 session/full 模式会用账号级恒定 session_id 覆盖上面的 - // isolate+namespace 值;那是「一号一安装」收敛,不是 leftover 11 的缺口。 - // leftover 11 在 off/device、以及不走指纹的 passthrough/WS/compat 路径生效。 - if account.Type == AccountTypeOAuth && c != nil { - if fpIDs, ok := c.Get("codex_fingerprint_ids"); ok { - if ids, ok := fpIDs.(*codexFingerprintIDs); ok && fingerprintIDsBelongToAccount(ids, account) { - applyCodexFingerprintHeaders(req.Header, ids) - } - } - } + applyStagedCodexFingerprintHeaders(c, account, req.Header) // 终态收口:强制统一 OAuth 出站身份(User-Agent / originator / version 同源自洽)。 // 客户端自报身份不参与构造,浏览器型 UA 也因此不会再到达上游(原浏览器 UA 兜底已被吸收)。 if account.Type == AccountTypeOAuth { - s.enforceCodexIdentityFromLoadedProfile(req.Header, account, outboundDeviceProfileFromGin(c, account)) + enforceCodexIdentityHeadersWithUA(req.Header, s.codexIdentityOverrideUA(account)) } // Ensure required headers exist @@ -1162,6 +1195,9 @@ func (s *OpenAIGatewayService) buildUpstreamRequest(ctx context.Context, c *gin. // 账号级请求头覆写(仅 openai api_key 账号启用时生效;OAuth 路径 no-op) account.ApplyHeaderOverrides(req.Header) + // x-codex-beta-features:按真实 Codex 的会话级行为补注(在账号级覆写之后, + // 保证不被覆盖丢失)。 + applyOpenAICodexBetaFeatures(c, account, req.Header) setOpenAICodexRoutingHintFromBody(req.Header, account, body) logOpenAIRoutingDiagnosticsFromBody(ctx, account, "http", req.Header, body, "not_applicable") @@ -1177,25 +1213,3 @@ func (s *OpenAIGatewayService) codexIdentityOverrideUA(account *Account) string } return account.GetOpenAIUserAgent() } - -func (s *OpenAIGatewayService) enforceCodexIdentityFromAccount(ctx context.Context, h http.Header, account *Account) { - if account == nil { - s.enforceCodexIdentityFromLoadedProfile(h, account, nil) - return - } - profile, err := LoadOutboundDeviceProfile(ctx, account) - if err != nil { - profile = nil - } - s.enforceCodexIdentityFromLoadedProfile(h, account, profile) -} - -func (s *OpenAIGatewayService) enforceCodexIdentityFromLoadedProfile(h http.Header, account *Account, profile *AccountDeviceProfile) { - fallback := s.codexIdentityOverrideUA(account) - if profile == nil { - enforceCodexIdentityHeadersWithUA(h, fallback) - return - } - identity := resolveCodexOutboundIdentityFromProfile(profile, fallback) - enforceCodexIdentityHeadersWithUA(h, identity.userAgent) -} diff --git a/backend/internal/service/openai_gateway_passthrough.go b/backend/internal/service/openai_gateway_passthrough.go index b54fb4d594..c15a78ef48 100644 --- a/backend/internal/service/openai_gateway_passthrough.go +++ b/backend/internal/service/openai_gateway_passthrough.go @@ -16,8 +16,8 @@ import ( "strings" "time" + "github.com/Wei-Shaw/sub2api/internal/pkg/apicompat" "github.com/Wei-Shaw/sub2api/internal/pkg/logger" - "github.com/Wei-Shaw/sub2api/internal/pkg/openai" "github.com/Wei-Shaw/sub2api/internal/util/responseheaders" "github.com/gin-gonic/gin" "github.com/tidwall/gjson" @@ -25,6 +25,84 @@ import ( "go.uber.org/zap" ) +const openAIResponsesClientToolMappingContextKey = "openai_responses_client_tool_mapping" + +func hasOpenAIResponsesClientToolMapping(mapping apicompat.ResponsesClientToolMapping) bool { + return len(mapping.CustomTools) > 0 || mapping.ToolSearch || len(mapping.NamespaceTools) > 0 +} + +func adaptOpenAIResponsesClientTools(body []byte) ([]byte, apicompat.ResponsesClientToolMapping, error) { + if !needsOpenAIResponsesClientToolAdaptation(body) { + return body, apicompat.ResponsesClientToolMapping{}, nil + } + + decoder := json.NewDecoder(bytes.NewReader(body)) + decoder.UseNumber() + var requestBody map[string]any + if err := decoder.Decode(&requestBody); err != nil { + return body, apicompat.ResponsesClientToolMapping{}, fmt.Errorf("decode OpenAI Responses client tools: %w", err) + } + var trailingValue any + if err := decoder.Decode(&trailingValue); !errors.Is(err, io.EOF) { + if err == nil { + err = errors.New("multiple JSON values") + } + return body, apicompat.ResponsesClientToolMapping{}, fmt.Errorf("decode OpenAI Responses client tools trailing data: %w", err) + } + mapping, changed, err := apicompat.AdaptResponsesClientTools(requestBody) + if err != nil || !changed { + return body, mapping, err + } + rebuilt, err := marshalOpenAIUpstreamJSON(requestBody) + if err != nil { + return body, apicompat.ResponsesClientToolMapping{}, fmt.Errorf("encode OpenAI Responses client tools: %w", err) + } + return rebuilt, mapping, nil +} + +func needsOpenAIResponsesClientToolAdaptation(body []byte) bool { + needsAdaptation := false + var visit func(gjson.Result) bool + visit = func(value gjson.Result) bool { + if value.IsObject() { + switch strings.TrimSpace(value.Get("type").String()) { + case "custom", "custom_tool_call", "custom_tool_call_output", + "tool_search", "tool_search_call", "tool_search_output": + needsAdaptation = true + return false + } + } + if value.IsObject() || value.IsArray() { + value.ForEach(func(_, child gjson.Result) bool { + return visit(child) + }) + } + return !needsAdaptation + } + visit(gjson.ParseBytes(body)) + return needsAdaptation +} + +func openAIResponsesClientToolMapping(c *gin.Context) (apicompat.ResponsesClientToolMapping, bool) { + if c == nil { + return apicompat.ResponsesClientToolMapping{}, false + } + value, ok := c.Get(openAIResponsesClientToolMappingContextKey) + mapping, typed := value.(apicompat.ResponsesClientToolMapping) + return mapping, ok && typed && hasOpenAIResponsesClientToolMapping(mapping) +} + +// clearOpenAIResponsesClientToolMapping removes mapping state from the prior +// forwarding attempt. Forward retries accounts on the same Gin context. +func clearOpenAIResponsesClientToolMapping(c *gin.Context) { + if c == nil { + return + } + if _, exists := c.Get(openAIResponsesClientToolMappingContextKey); exists { + c.Set(openAIResponsesClientToolMappingContextKey, apicompat.ResponsesClientToolMapping{}) + } +} + func (s *OpenAIGatewayService) forwardOpenAIPassthrough( ctx context.Context, c *gin.Context, @@ -80,6 +158,39 @@ func (s *OpenAIGatewayService) forwardOpenAIPassthrough( body = normalizedBody } reqStream = gjson.GetBytes(body, "stream").Bool() + + stageCodexFingerprintIDs(c, nil) + // 指纹收敛:与非透传路径同门控(仅 OAuth、legacy compact 形态跳过)。 + // 一次性解析收敛 ID:请求体 client_metadata 在此改写(raw 字节外科 + // 手术,透传热路径禁全量 Unmarshal),出站头改写由请求构造器读取 + // context 中的同一份 IDs 完成(turn_id 等随机字段两侧必须一致)。 + if !isOpenAIResponsesCompactPath(c) { + var clientHeaders http.Header + if c != nil && c.Request != nil { + clientHeaders = c.Request.Header + } + fpIDs := resolveCodexFingerprintIDsFromRequest(account, clientHeaders) + if fpIDs != nil { + fpBody, fpChanged, fpErr := applyCodexFingerprintClientMetadataRaw(body, fpIDs) + if fpErr != nil { + return nil, fpErr + } + if fpChanged { + body = fpBody + } + } + stageCodexFingerprintIDs(c, fpIDs) + } + } + + if account != nil && account.Platform == PlatformOpenAI && account.Type == AccountTypeAPIKey && + !isOpenAIResponsesCompactPath(c) && needsOpenAIResponsesClientToolAdaptation(body) { + adaptedBody, mapping, adaptErr := adaptOpenAIResponsesClientTools(body) + if adaptErr != nil { + return nil, adaptErr + } + body = adaptedBody + c.Set(openAIResponsesClientToolMappingContextKey, mapping) } sanitizedBody, sanitized, err := sanitizeEmptyBase64InputImagesInOpenAIBody(body) @@ -202,7 +313,7 @@ func (s *OpenAIGatewayService) forwardOpenAIPassthrough( } upstreamStart := time.Now() - resp, err = s.doAccountHTTP(ctx, c, account, upstreamReq, proxyURL, "responses") + resp, err = s.httpUpstream.Do(upstreamReq, proxyURL, account.ID, account.Concurrency) SetOpsLatencyMs(c, OpsUpstreamLatencyMsKey, time.Since(upstreamStart).Milliseconds()) if err != nil { // Transport-level failure (proxy/DNS/TCP/TLS — no HTTP response). Convert to @@ -236,9 +347,23 @@ func (s *OpenAIGatewayService) forwardOpenAIPassthrough( return nil, s.handleErrorResponsePassthrough(ctx, resp, c, account, body, probeBody) } defer func() { _ = resp.Body.Close() }() + if mapping, ok := openAIResponsesClientToolMapping(c); ok && isEventStreamResponse(resp.Header) { + maxLineSize := defaultMaxLineSize + if s.cfg != nil && s.cfg.Gateway.MaxLineSize > 0 { + maxLineSize = s.cfg.Gateway.MaxLineSize + } + resp.Body = newGrokResponsesClientToolStreamBody(resp.Body, mapping, maxLineSize) + } serviceTier := extractOpenAIServiceTierFromBody(body) + // x-codex-turn-state 溯源:下游回传由 writeOpenAIPassthroughResponseHeaders + // 在各 handler 的写头点强制放行,铸造账号在此统一记录,供出站守卫剥离 + // failover 换号后的跨账号回带(openai_codex_turn_state.go)。 + if extractOpenAICodexTurnState(resp.Header) != "" { + s.noteOpenAICodexTurnStateProvenance(c, account) + } + var usage *OpenAIUsage var firstTokenMs *int responseID := "" @@ -351,11 +476,14 @@ func (s *OpenAIGatewayService) buildUpstreamRequestOpenAIPassthrough( if err != nil { return nil, err } - targetURL = buildOpenAIResponsesURL(validatedURL) + targetURL = buildOpenAIResponsesURLForPlatform(account.Platform, validatedURL) } } targetURL = appendOpenAIResponsesRequestPathSuffix(targetURL, openAIResponsesRequestPathSuffix(c)) + // DeepSeek 原生 Responses 端点为无状态实现(见 normalizeDeepSeekResponsesRequestBody)。 + body = normalizeDeepSeekResponsesRequestBody(account, body) + req, err := http.NewRequestWithContext(ctx, http.MethodPost, targetURL, bytes.NewReader(body)) if err != nil { return nil, err @@ -376,6 +504,10 @@ func (s *OpenAIGatewayService) buildUpstreamRequestOpenAIPassthrough( } } + // 客户端回带的 x-codex-turn-state 若已知由其他账号铸造(failover 换号), + // 剥离后再出站(openai_codex_turn_state.go)。 + s.guardOpenAICodexTurnStateEcho(c, account, req.Header) + // 覆盖入站鉴权残留,并注入上游认证 req.Header.Del("authorization") req.Header.Del("x-api-key") @@ -408,7 +540,7 @@ func (s *OpenAIGatewayService) buildUpstreamRequestOpenAIPassthrough( if isOpenAIResponsesCompactPath(c) { req.Header.Set("accept", "application/json") if req.Header.Get("version") == "" { - req.Header.Set("version", codexCLIVersion) + req.Header.Set("version", CodexCanonicalClientVersion()) } if clientSessionID == "" { clientSessionID = resolveOpenAICompactSessionID(c) @@ -417,7 +549,7 @@ func (s *OpenAIGatewayService) buildUpstreamRequestOpenAIPassthrough( req.Header.Set("accept", "text/event-stream") } if req.Header.Get("originator") == "" { - req.Header.Set("originator", openai.CodexDefaultOriginator) + req.Header.Set("originator", resolveCodexOutboundIdentity("").originator) } // 用隔离后的 session 标识符覆盖客户端透传值,防止跨用户会话碰撞。 if clientSessionID == "" { @@ -426,14 +558,11 @@ func (s *OpenAIGatewayService) buildUpstreamRequestOpenAIPassthrough( if clientConversationID == "" { clientConversationID = promptCacheKey } - if clientSessionID != "" || clientConversationID != "" { - sessionID, conversationID := openaiOutboundSessionPair(ctx, account, apiKeyID, clientSessionID, clientConversationID) - if clientSessionID != "" { - req.Header.Set("session_id", sessionID) - } - if clientConversationID != "" { - req.Header.Set("conversation_id", conversationID) - } + if clientSessionID != "" { + req.Header.Set("session_id", isolateOpenAISessionID(apiKeyID, clientSessionID)) + } + if clientConversationID != "" { + req.Header.Set("conversation_id", isolateOpenAISessionID(apiKeyID, clientConversationID)) } } else if isOpenAIResponsesCompactPath(c) { // 透传白名单会放行客户端的 Accept: text/event-stream;compact 上游是 @@ -448,12 +577,16 @@ func (s *OpenAIGatewayService) buildUpstreamRequestOpenAIPassthrough( req.Header.Set("user-agent", customUA) } if s.cfg != nil && s.cfg.Gateway.ForceCodexCLI { - req.Header.Set("user-agent", codexCLIUserAgent) + req.Header.Set("user-agent", CodexCanonicalUserAgent()) } + // 指纹收敛:使用 forwardOpenAIPassthrough 中预计算的收敛 ID 改写出站头, + // 与请求体 client_metadata 共享同一份 IDs(与非透传路径相同的相对位置: + // 会话隔离之后、终态身份收口之前)。 + applyStagedCodexFingerprintHeaders(c, account, req.Header) // 终态收口:透传路径的 OAuth 与非透传完全一致,同样强制统一出站身份 // (User-Agent / originator / version 同源自洽),客户端自报身份不会到达上游。 if account.Type == AccountTypeOAuth { - s.enforceCodexIdentityFromAccount(ctx, req.Header, account) + enforceCodexIdentityHeadersWithUA(req.Header, s.codexIdentityOverrideUA(account)) } if req.Header.Get("content-type") == "" { @@ -462,6 +595,9 @@ func (s *OpenAIGatewayService) buildUpstreamRequestOpenAIPassthrough( // 账号级请求头覆写(仅 openai api_key 账号启用时生效;OAuth 路径 no-op) account.ApplyHeaderOverrides(req.Header) + // x-codex-beta-features:按真实 Codex 的会话级行为补注(在账号级覆写之后, + // 保证不被覆盖丢失)。 + applyOpenAICodexBetaFeatures(c, account, req.Header) setOpenAICodexRoutingHintFromBody(req.Header, account, body) logOpenAIRoutingDiagnosticsFromBody(ctx, account, "http_passthrough", req.Header, body, "not_applicable") @@ -638,19 +774,13 @@ func (s *OpenAIGatewayService) handleFailoverErrorResponsePassthrough( Detail: upstreamDetail, UpstreamResponseBody: upstreamDetail, }) - failoverErr := newOpenAIUpstreamFailoverError( + return newOpenAIUpstreamFailoverError( resp.StatusCode, resp.Header, body, upstreamMsg, - s.shouldRetryOpenAIOAuth429OnSameAccount(account, resp.StatusCode, shouldDisable), + !shouldDisable && account.IsPoolMode() && account.IsPoolModeRetryableStatus(resp.StatusCode), ) - if failoverErr.RetryableOnSameAccount { - failoverErr.SameAccountRetryDelay = s.openAIOAuth429SameAccountRetryDelay(resp.StatusCode, account) - failoverErr.SameAccountRetryDeadline = s.openAIOAuth429RetryDeadline(account) - failoverErr.SameAccountRetryMax = s.openAIOAuth429SameAccountRetryMax() - } - return failoverErr } func (s *OpenAIGatewayService) handleErrorResponsePassthrough( @@ -778,6 +908,19 @@ type openaiNonStreamingResultPassthrough struct { imageOutputSizes []string } +const openAIStreamKeepaliveBytesKey = "openai_stream_keepalive_bytes" + +func recordOpenAIStreamKeepaliveBytes(c *gin.Context, written int) { + if c == nil || written <= 0 { + return + } + current := 0 + if value, ok := c.Get(openAIStreamKeepaliveBytesKey); ok { + current, _ = value.(int) + } + c.Set(openAIStreamKeepaliveBytesKey, current+written) +} + func openAIStreamClientOutputStarted(c *gin.Context, localStarted bool) bool { if localStarted { return true @@ -800,6 +943,85 @@ func openAIStreamEventIsPreamble(eventType string) bool { } } +func openAIStreamAddedEventStartsClientOutput(payload []byte, eventType string) bool { + if len(payload) == 0 || !gjson.ValidBytes(payload) { + return true + } + + switch strings.TrimSpace(eventType) { + case "response.output_item.added": + item := gjson.GetBytes(payload, "item") + if !item.Exists() || !item.IsObject() { + return true + } + switch strings.TrimSpace(item.Get("type").String()) { + case "reasoning": + if item.Get("encrypted_content").String() != "" { + return true + } + summary := item.Get("summary") + if !summary.IsArray() { + return false + } + for _, part := range summary.Array() { + if strings.TrimSpace(part.Get("type").String()) != "summary_text" || part.Get("text").String() != "" { + return true + } + } + return false + case "message": + content := item.Get("content") + if !content.IsArray() { + return false + } + for _, part := range content.Array() { + switch strings.TrimSpace(part.Get("type").String()) { + case "output_text": + if part.Get("text").String() != "" { + return true + } + case "refusal": + if part.Get("refusal").String() != "" { + return true + } + default: + return true + } + } + return false + case "function_call": + return item.Get("arguments").String() != "" + case "custom_tool_call": + return item.Get("input").String() != "" + case "compaction": + return item.Get("encrypted_content").String() != "" + default: + return true + } + case "response.content_part.added": + part := gjson.GetBytes(payload, "part") + if !part.Exists() || !part.IsObject() { + return true + } + switch strings.TrimSpace(part.Get("type").String()) { + case "output_text": + return part.Get("text").String() != "" + case "refusal": + return part.Get("refusal").String() != "" + default: + return true + } + case "response.reasoning_summary_part.added": + part := gjson.GetBytes(payload, "part") + if !part.Exists() || !part.IsObject() || strings.TrimSpace(part.Get("type").String()) != "summary_text" { + return true + } + return part.Get("text").String() != "" + default: + return true + } +} + func openAIStreamDataStartsClientOutput(data, eventType string) bool { trimmed := strings.TrimSpace(data) if trimmed == "" { @@ -816,6 +1038,8 @@ func openAIStreamDataStartsClientOutput(data, eventType string) bool { // (content_policy / invalid_request 等)维持原样转发,保留上游错误细节。 payload := []byte(trimmed) return !openAIStreamFailedEventShouldFailover(payload, extractOpenAISSEErrorMessage(payload)) + case "response.output_item.added", "response.content_part.added", "response.reasoning_summary_part.added": + return openAIStreamAddedEventStartsClientOutput([]byte(trimmed), eventType) } return !openAIStreamEventIsPreamble(eventType) } @@ -894,9 +1118,34 @@ func isOpenAIUpstreamCapacityShedEvent(payload []byte) bool { switch openAIStreamFailedEventErrorCode(payload) { case "server_is_overloaded", "slow_down": return true - default: - return false } + for _, path := range []string{"response.error.message", "error.message", "message"} { + if isOpenAICapacityShedMessage(gjson.GetBytes(payload, path).String()) { + return true + } + } + return false +} + +func logOpenAICapacityFailoverSuppressed( + ctx context.Context, + account *Account, + path string, + upstreamRequestID string, + eventType string, +) { + fields := []zap.Field{ + zap.String("path", path), + zap.String("event_type", strings.TrimSpace(eventType)), + zap.String("upstream_request_id", strings.TrimSpace(upstreamRequestID)), + } + if account != nil { + fields = append(fields, + zap.Int64("account_id", account.ID), + zap.String("platform", account.Platform), + ) + } + logger.FromContext(ctx).Warn("gateway.failover_suppressed_after_semantic_output", fields...) } // openAICapacityShedRetryableClientCode 是把上游容量降载错误转发给客户端时改写 @@ -919,9 +1168,12 @@ func sanitizeOpenAICapacityShedErrorCodeForClient(payload []byte) ([]byte, bool) updated := payload changed := false for _, path := range []string{"response.error.code", "error.code"} { - switch strings.ToLower(strings.TrimSpace(gjson.GetBytes(updated, path).String())) { - case "server_is_overloaded", "slow_down": - default: + parent := strings.TrimSuffix(path, ".code") + if !gjson.GetBytes(updated, parent).Exists() { + continue + } + code := strings.ToLower(strings.TrimSpace(gjson.GetBytes(updated, path).String())) + if code != "" && code != "server_is_overloaded" && code != "slow_down" { continue } next, err := sjson.SetBytes(updated, path, openAICapacityShedRetryableClientCode) @@ -954,7 +1206,7 @@ func openAIStreamFailedEventSemanticStatus(payload []byte, message string) int { return http.StatusUnauthorized case strings.Contains(combined, "permission") || strings.Contains(combined, "forbidden") || strings.Contains(combined, "access denied"): return http.StatusForbidden - case code == "server_is_overloaded" || code == "slow_down": + case isOpenAIUpstreamCapacityShedEvent(payload): return http.StatusServiceUnavailable default: return http.StatusBadGateway @@ -1088,6 +1340,16 @@ func openAIStreamFailedEventShouldFailover(payload []byte, message string) bool return true } +func openAIStreamErrorEventShouldFailover(payload []byte, message string) bool { + if strings.TrimSpace(gjson.GetBytes(payload, "type").String()) != "error" { + return false + } + if isOpenAIContextWindowError(message, payload) { + return false + } + return isOpenAITransientProcessingError(http.StatusBadRequest, message, payload) +} + func openAIStreamFailedEventRetryableOnSameAccount(account *Account, payload []byte, message string) bool { if account == nil { return false @@ -1230,6 +1492,7 @@ func (s *OpenAIGatewayService) handleStreamingResponsePassthrough( sawTerminalEvent := false sawFailedEvent := false semanticOutputSeen := false + capacityFailoverSuppressedLogged := false failedMessage := "" clientOutputStarted := false upstreamRequestID := strings.TrimSpace(resp.Header.Get("x-request-id")) @@ -1316,6 +1579,32 @@ func (s *OpenAIGatewayService) handleStreamingResponsePassthrough( } } eventType := strings.TrimSpace(gjson.Get(trimmedData, "type").String()) + if !capacityFailoverSuppressedLogged && account != nil && account.Platform == PlatformOpenAI && + (eventType == "error" || eventType == "response.failed") && + openAIStreamClientOutputStarted(c, clientOutputStarted) && + isOpenAIUpstreamCapacityShedEvent(dataBytes) { + logOpenAICapacityFailoverSuppressed(ctx, account, "passthrough_sse", upstreamRequestID, eventType) + capacityFailoverSuppressedLogged = true + } + if eventType == "error" && !openAIStreamClientOutputStarted(c, clientOutputStarted) { + errorMessage := extractOpenAISSEErrorMessage(dataBytes) + if status, errType, errMsg, matched := applyOpenAIStreamFailedErrorPassthroughRule(c, account.Platform, dataBytes, errorMessage); matched { + s.recordOpenAIStreamUpstreamError(c, account, true, upstreamRequestID, "http_error", dataBytes, errorMessage) + MarkResponseCommitted(c) + c.Writer.Header().Set("Content-Type", "application/json; charset=utf-8") + c.JSON(status, gin.H{ + "error": gin.H{ + "type": errType, + "message": errMsg, + }, + }) + return resultWithUsage(), fmt.Errorf("upstream error event: passthrough rule matched message=%s", errMsg) + } + if openAIStreamErrorEventShouldFailover(dataBytes, errorMessage) { + return resultWithUsage(), + s.newOpenAIStreamFailoverError(c, account, true, upstreamRequestID, dataBytes, errorMessage, resp.Header) + } + } if eventType == "response.failed" { failedMessage = extractOpenAISSEErrorMessage(dataBytes) // response.failed 自带上游已消耗的 usage(input token 通常已扣);必须先解析 @@ -1529,6 +1818,12 @@ func (s *OpenAIGatewayService) handleNonStreamingResponsePassthrough( if err != nil { return nil, fmt.Errorf("restore OpenAI passthrough namespace response: %w", err) } + if mapping, ok := openAIResponsesClientToolMapping(c); ok && json.Valid(body) { + body, _, err = apicompat.RestoreResponsesClientToolPayload(body, mapping) + if err != nil { + return nil, fmt.Errorf("restore OpenAI Responses client tools: %w", err) + } + } if !writeOpenAICompactSSEBridge(c, resp.StatusCode, body) { c.Data(resp.StatusCode, contentType, body) } @@ -1659,4 +1954,13 @@ func writeOpenAIPassthroughResponseHeaders(dst http.Header, src http.Header, fil dst.Add(key, v) } } + + // x-codex-turn-state:Codex 回合状态头,客户端会在同回合后续请求回带。 + // 与上面的用量头不同,这里在上游缺失时也主动清除——failover 换号后残留 + // 上一账号的 blob 会构成跨账号矛盾(openai_codex_turn_state.go)。 + turnStateKey := http.CanonicalHeaderKey(openAICodexTurnStateHeader) + dst.Del(turnStateKey) + for _, v := range getCaseInsensitiveValues(src, openAICodexTurnStateHeader) { + dst.Add(turnStateKey, v) + } } diff --git a/backend/internal/service/openai_gateway_service.go b/backend/internal/service/openai_gateway_service.go index dee8a6dbf2..16082a16a4 100644 --- a/backend/internal/service/openai_gateway_service.go +++ b/backend/internal/service/openai_gateway_service.go @@ -61,7 +61,7 @@ const ( // 陈旧版本会被优先丢弃(HTTP 200 + 流内 server_is_overloaded);非官方客户端配不出 // 官方身份时整体回退到本常量,因此它必须跟随官方 CLI 的当前发布版本, // 落后多个版本会让这些请求稳定落在被优先丢弃的一侧。 - codexCLIVersion = "0.147.0" + codexCLIVersion = "0.146.0" // Codex 限额快照仅用于后台展示/诊断,不需要每个成功请求都立即落库。 openAICodexSnapshotPersistMinInterval = 30 * time.Second // 配额自动暂停时,超过该时长仍未刷新的 used% 快照视为陈旧,不再据此暂停账号。 @@ -284,8 +284,9 @@ type OpenAIForwardResult struct { // AudioUsage carries Voice billing units when present. AudioUsage *AudioUsage - wsReplayInput []json.RawMessage - wsReplayInputExists bool + wsReplayInput []json.RawMessage + wsReplayInputExists bool + wsAccountFailoverReplayInput []json.RawMessage } // SucceededForScheduling reports whether this result is an upstream success @@ -398,8 +399,8 @@ func (t *accountWriteThrottle) Allow(id int64, now time.Time) bool { var defaultOpenAICodexSnapshotPersistThrottle = newAccountWriteThrottle(openAICodexSnapshotPersistMinInterval) -// ErrNoAvailableCompactAccounts indicates the request needs /responses/compact -// support but no compatible account is available. +// ErrNoAvailableCompactAccounts indicates a legacy /responses/compact request +// needs compact support but no compatible account is available. var ErrNoAvailableCompactAccounts = errors.New("no available accounts support /responses/compact") // OpenAIGatewayService handles OpenAI API gateway operations @@ -428,8 +429,6 @@ type OpenAIGatewayService struct { channelService *ChannelService balanceNotifyService *BalanceNotifyService settingService *SettingService - tlsFPProfileService *TLSFingerprintProfileService - tlsFPRouterService *TLSFingerprintRouterService userPlatformQuotaRepo UserPlatformQuotaRepository liveAttestation liveattestation.Provider liveAttestationCipher SecretEncryptor @@ -455,10 +454,6 @@ type OpenAIGatewayService struct { openaiAccountRuntimeBlockLocks sync.Map // key: int64(accountID), value: *sync.Mutex openaiAccountRuntimeBlockGeneration sync.Map // key: int64(accountID), value: uint64 openaiAccountRuntimeBlockSequence atomic.Uint64 - openaiOAuth429RetryStartedAt sync.Map // key: int64(accountID), value: time.Time - openai429StrategyMu sync.Mutex - openai429StrategyCachedAt time.Time - openai429StrategyCached RateLimit429CooldownSettings grokCredentialMutationLocks sync.Map // key: int64(accountID), value: *sync.Mutex openaiOAuth429WindowStartUnixNano atomic.Int64 openaiOAuth429WindowCount atomic.Int64 @@ -468,6 +463,11 @@ type OpenAIGatewayService struct { codexModelsManifestCache codexModelsManifestCache openaiCompatSessionResponses sync.Map openaiCompatAnthropicDigestSessions sync.Map + // openaiCodexTurnStateOrigins: 下游会话 seed → openAICodexTurnStateOrigin, + // 记录最近一次向该会话下发 x-codex-turn-state 的铸造账号,供出站守卫 + // 剥离跨账号回带(openai_codex_turn_state.go)。 + openaiCodexTurnStateOrigins sync.Map + openaiCodexTurnStateWrites atomic.Uint64 } // NewOpenAIGatewayService creates a new OpenAIGatewayService @@ -548,27 +548,6 @@ func NewOpenAIGatewayService( return svc } -func (s *OpenAIGatewayService) SetTLSFingerprintServices(profile *TLSFingerprintProfileService, router *TLSFingerprintRouterService) { - if s == nil { - return - } - s.tlsFPProfileService = profile - s.tlsFPRouterService = router -} - -func (s *OpenAIGatewayService) doAccountHTTP(ctx context.Context, c *gin.Context, account *Account, req *http.Request, proxyURL, protocol string) (*http.Response, error) { - if account != nil && account.Platform == PlatformGrok { - return doLeftoverAccountHTTP(ctx, s.httpUpstream, req, proxyURL, account, s.tlsFPProfileService, s.tlsFPRouterService, inboundUserAgentFromGin(c), "http", protocol) - } - // Last mutation before send: callers may Header.Set/Get after buildUpstreamRequest - // (images Content-Type, messages identity + turn-state). leftover 5 session_id - // values are unchanged; originator stays lowercase. - if account != nil && account.Type == AccountTypeOAuth && req != nil { - applyCodexHeaderWireCasing(req.Header) - } - return doAccountHTTPUpstreamFromGin(ctx, c, s.httpUpstream, req, proxyURL, account, s.tlsFPProfileService, s.tlsFPRouterService, "http", protocol) -} - // ResolveChannelMapping 解析渠道级模型映射(代理到 ChannelService) func (s *OpenAIGatewayService) ResolveChannelMapping(ctx context.Context, groupID int64, model string) ChannelMappingResult { if s.channelService == nil { @@ -625,6 +604,10 @@ func (s *OpenAIGatewayService) isUpstreamModelRestrictedByChannel(ctx context.Co if s.channelService == nil { return false } + if compactForwardModel, ok := openAIForwardModelFromContext(ctx); ok { + requestedModel = compactForwardModel.model + requireCompact = compactForwardModel.useCompactModelMapping + } upstreamModel := resolveOpenAIAccountUpstreamModelForRequest(account, requestedModel, requireCompact) if upstreamModel == "" { return false @@ -1073,9 +1056,6 @@ func getAPIKeyIDFromContext(c *gin.Context) int64 { // isolateOpenAISessionID 将 apiKeyID 混入 session 标识符, // 确保不同 API Key 的用户即使使用相同的原始 session_id/conversation_id, // 到达上游的标识符也不同,防止跨用户会话碰撞。 -// -// Outbound session/conversation headers should use openaiOutboundSessionID -// or openaiOutboundSessionUUID so a valid device-profile namespace is folded in. func isolateOpenAISessionID(apiKeyID int64, raw string) string { raw = strings.TrimSpace(raw) if raw == "" { @@ -1087,60 +1067,6 @@ func isolateOpenAISessionID(apiKeyID int64, raw string) string { return fmt.Sprintf("%016x", h.Sum64()) } -func loadOpenAIOutboundSessionProfile(ctx context.Context, account *Account) *AccountDeviceProfile { - if account == nil || !account.IsOpenAIOAuth() { - return nil - } - return loadOutboundCodexProfile(ctx, account) -} - -func deriveOpenAIOutboundSessionIDFromProfile(profile *AccountDeviceProfile, isolated string) string { - if profile == nil || isolated == "" { - return "" - } - sessionID, _, _, err := DeriveSessionIDs(profile.SessionNamespace, isolated) - if err != nil || sessionID == "" { - return "" - } - return sessionID -} - -func deriveOpenAIOutboundSessionID(ctx context.Context, account *Account, apiKeyID int64, raw string) string { - isolated := isolateOpenAISessionID(apiKeyID, raw) - if isolated == "" { - return "" - } - return deriveOpenAIOutboundSessionIDFromProfile(loadOpenAIOutboundSessionProfile(ctx, account), isolated) -} - -func openaiOutboundSessionIDFromProfile(profile *AccountDeviceProfile, apiKeyID int64, raw string) string { - isolated := isolateOpenAISessionID(apiKeyID, raw) - if derived := deriveOpenAIOutboundSessionIDFromProfile(profile, isolated); derived != "" { - return derived - } - return isolated -} - -func openaiOutboundSessionID(ctx context.Context, account *Account, apiKeyID int64, raw string) string { - if derived := deriveOpenAIOutboundSessionID(ctx, account, apiKeyID, raw); derived != "" { - return derived - } - return isolateOpenAISessionID(apiKeyID, raw) -} - -func openaiOutboundSessionUUID(ctx context.Context, account *Account, apiKeyID int64, raw string) string { - if derived := deriveOpenAIOutboundSessionID(ctx, account, apiKeyID, raw); derived != "" { - return derived - } - return generateSessionUUID(isolateOpenAISessionID(apiKeyID, raw)) -} - -func openaiOutboundSessionPair(ctx context.Context, account *Account, apiKeyID int64, sessionRaw, conversationRaw string) (sessionID, conversationID string) { - profile := loadOpenAIOutboundSessionProfile(ctx, account) - return openaiOutboundSessionIDFromProfile(profile, apiKeyID, sessionRaw), - openaiOutboundSessionIDFromProfile(profile, apiKeyID, conversationRaw) -} - func logCodexCLIOnlyDetection(ctx context.Context, c *gin.Context, account *Account, apiKeyID int64, result CodexClientRestrictionDetectionResult, body []byte) { if !result.Enabled { return @@ -1280,7 +1206,7 @@ func (s *OpenAIGatewayService) GetAccessToken(ctx context.Context, account *Acco } return apiKey, "apikey", nil } - apiKey := account.GetOpenAIApiKey() + apiKey := strings.TrimSpace(account.GetOpenAIProtocolAPIKey()) if apiKey == "" { return "", "", errors.New("api_key not found in credentials") } diff --git a/backend/internal/service/setting_features.go b/backend/internal/service/setting_features.go index 69b23a8fe1..648fa1dc21 100644 --- a/backend/internal/service/setting_features.go +++ b/backend/internal/service/setting_features.go @@ -739,27 +739,6 @@ func (s *SettingService) GetRateLimit429CooldownSettings(ctx context.Context) (* if settings.CooldownSeconds > 7200 { settings.CooldownSeconds = 7200 } - if settings.Strategy != "same_account_retry" { - settings.Strategy = "cooldown" - } - if settings.RetryIntervalMs < 100 { - settings.RetryIntervalMs = 500 - } - if settings.RetryIntervalMs > 60000 { - settings.RetryIntervalMs = 60000 - } - if settings.RetryMaxDurationSeconds < 1 { - settings.RetryMaxDurationSeconds = 120 - } - if settings.RetryMaxDurationSeconds > 600 { - settings.RetryMaxDurationSeconds = 600 - } - if settings.MaxAccountSwitches < 0 { - settings.MaxAccountSwitches = 0 - } - if settings.MaxAccountSwitches > 10 { - settings.MaxAccountSwitches = 10 - } return &settings, nil } @@ -769,10 +748,6 @@ func (s *SettingService) SetRateLimit429CooldownSettings(ctx context.Context, se if settings == nil { return fmt.Errorf("settings cannot be nil") } - if settings.Strategy == "" { settings.Strategy = "cooldown" } - if settings.RetryIntervalMs == 0 { settings.RetryIntervalMs = 500 } - if settings.RetryMaxDurationSeconds == 0 { settings.RetryMaxDurationSeconds = 120 } - if settings.MaxAccountSwitches < 0 { settings.MaxAccountSwitches = 0 } if settings.CooldownSeconds < 1 || settings.CooldownSeconds > 7200 { if settings.Enabled { @@ -780,18 +755,6 @@ func (s *SettingService) SetRateLimit429CooldownSettings(ctx context.Context, se } settings.CooldownSeconds = 5 } - if settings.Strategy != "cooldown" && settings.Strategy != "same_account_retry" { - return fmt.Errorf("strategy must be cooldown or same_account_retry") - } - if settings.RetryIntervalMs < 100 || settings.RetryIntervalMs > 60000 { - return fmt.Errorf("retry_interval_ms must be between 100-60000") - } - if settings.RetryMaxDurationSeconds < 1 || settings.RetryMaxDurationSeconds > 600 { - return fmt.Errorf("retry_max_duration_seconds must be between 1-600") - } - if settings.MaxAccountSwitches < 0 || settings.MaxAccountSwitches > 10 { - return fmt.Errorf("max_account_switches must be between 0-10") - } data, err := json.Marshal(settings) if err != nil { diff --git a/backend/internal/service/settings_view.go b/backend/internal/service/settings_view.go index 7f7cbbc67f..a939000947 100644 --- a/backend/internal/service/settings_view.go +++ b/backend/internal/service/settings_view.go @@ -154,8 +154,6 @@ type SystemSettings struct { SiteSubtitle string APIBaseURL string ContactInfo string - SupportQRCodes string - DownloadToolsURL string DocURL string HomeContent string CompactHomeEnabled bool @@ -167,36 +165,19 @@ type SystemSettings struct { CustomMenuItems string // JSON array of custom menu items CustomEndpoints string // JSON array of custom endpoints - DefaultConcurrency int - DefaultBalance float64 - RiskControlEnabled bool - CyberSessionBlockEnabled bool - CyberSessionBlockTTLSeconds int - AffiliateEnabled bool - AffiliateRebateRate float64 - AffiliateRebateFreezeHours int - AffiliateRebateDurationDays int - AffiliateRebatePerInviteeCap float64 - AffiliateRebateCap float64 - AffiliateRebateInviteeLimit int - AffiliateSignupBonus float64 - AdminRechargeRebateEnabled bool - TicketEnabled bool - KiroDefaultVersion string - KiroDefaultCommit string - KiroDefaultSystemVersion string - KiroDefaultNodeVersion string - KiroCacheHitRateScale int - KiroCacheMinBlockTokens int - KiroCacheIndependentTTLSeconds int - KiroCachePrefixTTLSeconds int - KiroCodeExecutionSandboxCommand string - IPMultiAccountBanEnabled bool - IPMultiAccountBanWindowMinutes int - IPMultiAccountBanThreshold int - IPMultiAccountBanLearningUntil string - DefaultUserRPMLimit int - DefaultSubscriptions []DefaultSubscriptionSetting + DefaultConcurrency int + DefaultBalance float64 + RiskControlEnabled bool + CyberSessionBlockEnabled bool + CyberSessionBlockTTLSeconds int + AffiliateEnabled bool + AffiliateRebateRate float64 + AffiliateRebateFreezeHours int + AffiliateRebateDurationDays int + AffiliateRebatePerInviteeCap float64 + AdminRechargeRebateEnabled bool + DefaultUserRPMLimit int + DefaultSubscriptions []DefaultSubscriptionSetting // Model fallback configuration EnableModelFallback bool `json:"enable_model_fallback"` @@ -220,6 +201,7 @@ type SystemSettings struct { ChannelMonitorMode string `json:"channel_monitor_mode"` ChannelMonitorDefaultIntervalSeconds int `json:"channel_monitor_default_interval_seconds"` ChannelMonitorHideThroughput bool `json:"channel_monitor_hide_throughput"` + ChannelMonitorShowQuota bool `json:"channel_monitor_show_quota"` // Grok model mapping policy (admin settings; empty mapping falls back to these). GrokDefaultTextModel string `json:"grok_default_text_model"` @@ -331,18 +313,6 @@ type DefaultSubscriptionSetting struct { ValidityDays int `json:"validity_days"` } -type DefaultAccountModelConfig struct { - ModelWhitelist []string `json:"model_whitelist,omitempty"` - ModelMapping map[string]string `json:"model_mapping,omitempty"` - CompactModelMapping map[string]string `json:"compact_model_mapping,omitempty"` - KiroSubscriptionTypeModelMap map[string]DefaultAccountModelConfig `json:"kiro_subscription_type_model_config,omitempty"` - - TempUnschedulableEnabled bool `json:"temp_unschedulable_enabled,omitempty"` - TempUnschedulableRules []TempUnschedulableRule `json:"temp_unschedulable_rules,omitempty"` - CustomErrorCodesEnabled bool `json:"custom_error_codes_enabled,omitempty"` - CustomErrorCodes []int `json:"custom_error_codes,omitempty"` -} - type PublicSettings struct { RegistrationEnabled bool EmailVerifyEnabled bool @@ -373,8 +343,6 @@ type PublicSettings struct { SiteSubtitle string APIBaseURL string ContactInfo string - SupportQRCodes string - DownloadToolsURL string DocURL string HomeContent string CompactHomeEnabled bool @@ -411,6 +379,7 @@ type PublicSettings struct { ChannelMonitorMode string `json:"channel_monitor_mode"` ChannelMonitorDefaultIntervalSeconds int `json:"channel_monitor_default_interval_seconds"` ChannelMonitorHideThroughput bool `json:"channel_monitor_hide_throughput"` + ChannelMonitorShowQuota bool `json:"channel_monitor_show_quota"` // Grok model mapping policy (admin settings). GrokDefaultTextModel string `json:"grok_default_text_model"` @@ -427,9 +396,6 @@ type PublicSettings struct { // Affiliate (邀请返利) feature toggle AffiliateEnabled bool `json:"affiliate_enabled"` - // Ticket feature toggle (default enabled) - TicketEnabled bool `json:"ticket_enabled"` - // 风控中心功能开关 RiskControlEnabled bool `json:"risk_control_enabled"` @@ -594,11 +560,7 @@ type RateLimit429CooldownSettings struct { // Enabled 是否在无法解析上游重置时间时应用默认429回避 Enabled bool `json:"enabled"` // CooldownSeconds 默认回避时长(秒) - CooldownSeconds int `json:"cooldown_seconds"` - Strategy string `json:"strategy"` - RetryIntervalMs int `json:"retry_interval_ms"` - RetryMaxDurationSeconds int `json:"retry_max_duration_seconds"` - MaxAccountSwitches int `json:"max_account_switches"` + CooldownSeconds int `json:"cooldown_seconds"` } // DefaultOverloadCooldownSettings 返回默认的过载冷却配置(启用,10分钟) @@ -612,12 +574,8 @@ func DefaultOverloadCooldownSettings() *OverloadCooldownSettings { // DefaultRateLimit429CooldownSettings 返回默认的429回避配置(启用,5秒) func DefaultRateLimit429CooldownSettings() *RateLimit429CooldownSettings { return &RateLimit429CooldownSettings{ - Enabled: true, - CooldownSeconds: 5, - Strategy: "cooldown", - RetryIntervalMs: 500, - RetryMaxDurationSeconds: 120, - MaxAccountSwitches: 2, + Enabled: true, + CooldownSeconds: 5, } } diff --git a/frontend/src/api/admin/settings.ts b/frontend/src/api/admin/settings.ts index a956a150a5..f5f19918a8 100644 --- a/frontend/src/api/admin/settings.ts +++ b/frontend/src/api/admin/settings.ts @@ -1289,10 +1289,6 @@ export async function updateOverloadCooldownSettings( export interface RateLimit429CooldownSettings { enabled: boolean; cooldown_seconds: number; - strategy: "cooldown" | "same_account_retry"; - retry_interval_ms: number; - retry_max_duration_seconds: number; - max_account_switches: number; } export async function getRateLimit429CooldownSettings(): Promise { diff --git a/frontend/src/views/admin/SettingsView.vue b/frontend/src/views/admin/SettingsView.vue index cc63ae24de..80af0b1940 100644 --- a/frontend/src/views/admin/SettingsView.vue +++ b/frontend/src/views/admin/SettingsView.vue @@ -340,16 +340,8 @@
-
- - -
-
@@ -379,12 +371,6 @@
-
- - - -
-
@@ -8951,10 +8937,6 @@ const rateLimit429CooldownSaving = ref(false); const rateLimit429CooldownForm = reactive({ enabled: true, cooldown_seconds: 5, - strategy: "cooldown" as "cooldown" | "same_account_retry", - retry_interval_ms: 500, - retry_max_duration_seconds: 120, - max_account_switches: 2, }); // Panel API Rate Limit 状态 @@ -11855,10 +11837,6 @@ async function saveRateLimit429CooldownSettings() { const updated = await adminAPI.settings.updateRateLimit429CooldownSettings({ enabled: rateLimit429CooldownForm.enabled, cooldown_seconds: rateLimit429CooldownForm.cooldown_seconds, - strategy: rateLimit429CooldownForm.strategy, - retry_interval_ms: rateLimit429CooldownForm.retry_interval_ms, - retry_max_duration_seconds: rateLimit429CooldownForm.retry_max_duration_seconds, - max_account_switches: rateLimit429CooldownForm.max_account_switches, }); Object.assign(rateLimit429CooldownForm, updated); appStore.showSuccess(t("admin.settings.rateLimit429Cooldown.saved")); From 8db8791a73aebc2afa60e6c61534894028d8b219 Mon Sep 17 00:00:00 2001 From: IanShaw <131567472+IanShaw027@users.noreply.github.com> Date: Thu, 20 Aug 2026 05:53:55 -0700 Subject: [PATCH 061/204] =?UTF-8?q?=E4=B8=BA=20Grok=20=E6=99=AE=E9=80=9A?= =?UTF-8?q?=20429=20=E5=A2=9E=E5=8A=A0=E6=9C=89=E9=99=90=E5=90=8C=E5=8F=B7?= =?UTF-8?q?=E9=87=8D=E8=AF=95?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- backend/internal/service/grok_upstream_failure.go | 9 ++++++++- backend/internal/service/grok_upstream_failure_test.go | 8 ++++---- 2 files changed, 12 insertions(+), 5 deletions(-) diff --git a/backend/internal/service/grok_upstream_failure.go b/backend/internal/service/grok_upstream_failure.go index 3d6aa05c6e..51edbc3332 100644 --- a/backend/internal/service/grok_upstream_failure.go +++ b/backend/internal/service/grok_upstream_failure.go @@ -402,6 +402,13 @@ func grokRetryableOnSameAccount(account *Account, statusCode int, responseBody [ if statusCode == http.StatusTooManyRequests { return true } + case GrokFailureRateLimit: + // A transient 429 does not identify a bad credential. Give every Grok + // account a bounded same-account retry window before failover; the + // failover loop still caps attempts and the client receives 429 after it. + if statusCode == http.StatusTooManyRequests { + return true + } } return account.IsPoolMode() && account.IsPoolModeRetryableStatus(statusCode) } @@ -411,7 +418,7 @@ func grokSameAccountRetryMetadata(account *Account, statusCode int, responseBody return false, 0, time.Time{} } decision := classifyGrokUpstreamFailure(statusCode, responseBody, "") - if decision.Class != GrokFailureModelCapacity { + if decision.Class != GrokFailureModelCapacity && decision.Class != GrokFailureRateLimit { return true, 0, time.Time{} } return true, 500 * time.Millisecond, time.Now().Add(30 * time.Second) diff --git a/backend/internal/service/grok_upstream_failure_test.go b/backend/internal/service/grok_upstream_failure_test.go index d6e6ec7ace..0cc8cd1efa 100644 --- a/backend/internal/service/grok_upstream_failure_test.go +++ b/backend/internal/service/grok_upstream_failure_test.go @@ -81,7 +81,7 @@ func TestGrokRetryableOnSameAccount_CapacityAndRateLimit(t *testing.T) { account := &Account{ID: 9105, Platform: PlatformGrok, Type: AccountTypeOAuth} require.True(t, grokRetryableOnSameAccount(account, http.StatusTooManyRequests, []byte(`{"error":{"message":"The model is currently at capacity due to high demand"}}`))) - require.False(t, grokRetryableOnSameAccount(account, http.StatusTooManyRequests, + require.True(t, grokRetryableOnSameAccount(account, http.StatusTooManyRequests, []byte(`{"error":{"message":"rate limit exceeded"}}`))) require.False(t, grokRetryableOnSameAccount(account, http.StatusPaymentRequired, []byte(`{"error":{"message":"You have run out of credits or need a Grok subscription"}}`))) @@ -118,9 +118,9 @@ func TestGrokSameAccountRetryMetadata_CapacityDeadline(t *testing.T) { retryable, delay, deadline = grokSameAccountRetryMetadata(account, http.StatusTooManyRequests, []byte(`{"error":{"message":"rate limit exceeded"}}`)) - require.False(t, retryable) - require.Zero(t, delay) - require.True(t, deadline.IsZero()) + require.True(t, retryable) + require.Equal(t, 500*time.Millisecond, delay) + require.WithinDuration(t, time.Now().Add(30*time.Second), deadline, 2*time.Second) } func TestClassifyGrokUpstreamFailure_ValidationNoCool(t *testing.T) { From ad87ddee125cf7d5aebac417acd5119a21e6c644 Mon Sep 17 00:00:00 2001 From: IanShaw <131567472+IanShaw027@users.noreply.github.com> Date: Thu, 20 Aug 2026 06:08:09 -0700 Subject: [PATCH 062/204] =?UTF-8?q?=E8=A1=A5=E9=BD=90=20Grok=20CC=20?= =?UTF-8?q?=E9=87=8D=E8=AF=95=E4=B8=8E=20compaction=20=E6=81=A2=E5=A4=8D?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../service/openai_gateway_chat_completions_raw.go | 12 ++++++++---- backend/internal/service/openai_gateway_grok.go | 14 ++++++++------ .../internal/service/openai_gateway_grok_test.go | 10 ++++++++++ 3 files changed, 26 insertions(+), 10 deletions(-) diff --git a/backend/internal/service/openai_gateway_chat_completions_raw.go b/backend/internal/service/openai_gateway_chat_completions_raw.go index 3c46194188..00a7ece52c 100644 --- a/backend/internal/service/openai_gateway_chat_completions_raw.go +++ b/backend/internal/service/openai_gateway_chat_completions_raw.go @@ -200,11 +200,15 @@ func (s *OpenAIGatewayService) forwardAsRawChatCompletions( }) s.handleGrokAccountUpstreamError(withGrokTeamRateLimitModel(ctx, upstreamModel), account, resp.StatusCode, resp.Header, respBody) if s.shouldFailoverGrokUpstreamError(resp.StatusCode, respBody) { + retryable, retryDelay, retryDeadline := grokSameAccountRetryMetadata(account, resp.StatusCode, respBody) return nil, &UpstreamFailoverError{ - StatusCode: resp.StatusCode, - ResponseBody: respBody, - ResponseHeaders: resp.Header.Clone(), - RetryableOnSameAccount: account.IsPoolMode() && account.IsPoolModeRetryableStatus(resp.StatusCode), + StatusCode: resp.StatusCode, + ResponseBody: respBody, + ResponseHeaders: resp.Header.Clone(), + RetryableOnSameAccount: retryable, + RequestScopedTransient: retryable && resp.StatusCode == http.StatusTooManyRequests, + SameAccountRetryDelay: retryDelay, + SameAccountRetryDeadline: retryDeadline, } } return s.handleChatCompletionsErrorResponse(resp, c, account, billingModel) diff --git a/backend/internal/service/openai_gateway_grok.go b/backend/internal/service/openai_gateway_grok.go index 1933cd2550..132f7b3159 100644 --- a/backend/internal/service/openai_gateway_grok.go +++ b/backend/internal/service/openai_gateway_grok.go @@ -258,7 +258,7 @@ func (s *OpenAIGatewayService) forwardGrokResponses( } func isGrokInvalidEncryptedContentResponse(statusCode int, body []byte) bool { - if statusCode != http.StatusBadRequest { + if statusCode != http.StatusBadRequest && statusCode != http.StatusUnprocessableEntity { return false } @@ -284,7 +284,7 @@ func isGrokInvalidEncryptedContentResponse(statusCode int, body []byte) bool { return false } - if strings.EqualFold(code, "invalid_encrypted_content") { + if strings.EqualFold(code, "invalid_encrypted_content") || strings.EqualFold(code, "invalid_compaction") || strings.EqualFold(code, "compaction_decode_error") { return true } // Keep the official xAI flat-code gate so unrelated 400s are not retried. @@ -292,12 +292,13 @@ func isGrokInvalidEncryptedContentResponse(statusCode int, body []byte) bool { return false } // Nested OpenAI-style envelopes may omit top-level code; require decrypt text. - if code == "" && !strings.Contains(normalizedMessage, "decrypt") { + if code == "" && !strings.Contains(normalizedMessage, "decrypt") && !strings.Contains(normalizedMessage, "decode the compaction blob") { return false } - return strings.Contains(normalizedMessage, "encrypted_content") && + return (strings.Contains(normalizedMessage, "encrypted_content") && (strings.Contains(normalizedMessage, "decrypt") || - strings.Contains(normalizedMessage, "unmodified")) + strings.Contains(normalizedMessage, "unmodified"))) || + strings.Contains(normalizedMessage, "decode the compaction blob") } // requestHasGrokEncryptedReasoning reports whether the outbound Responses body @@ -392,7 +393,8 @@ func trimGrokInvalidEncryptedContentRetryBody(body []byte) ([]byte, bool, error) hasEncryptedReasoning := false for _, item := range items { - if strings.TrimSpace(item.Get("type").String()) == "reasoning" && item.Get("encrypted_content").Exists() { + if (strings.TrimSpace(item.Get("type").String()) == "reasoning" && item.Get("encrypted_content").Exists()) || + (isOpenAICompactionType(strings.TrimSpace(item.Get("type").String())) && item.Get("encrypted_content").Exists()) { hasEncryptedReasoning = true break } diff --git a/backend/internal/service/openai_gateway_grok_test.go b/backend/internal/service/openai_gateway_grok_test.go index 541e3a3216..b89c9eef83 100644 --- a/backend/internal/service/openai_gateway_grok_test.go +++ b/backend/internal/service/openai_gateway_grok_test.go @@ -2053,6 +2053,16 @@ func TestForwardGrokResponsesInvalidEncryptedContentRecoveryDoesNotOvermatch(t * } } +func TestGrokCompactionBlobRecoveryStripsCompactionItem(t *testing.T) { + body := []byte(`{"model":"grok","input":[{"type":"compaction","id":"cmp_1","encrypted_content":"blob"},{"type":"message","role":"user","content":"hi"}]}`) + require.True(t, isGrokInvalidEncryptedContentResponse(http.StatusUnprocessableEntity, []byte(`{"code":"invalid_compaction","error":"could not decode the compaction blob"}`))) + retry, changed, err := trimGrokInvalidEncryptedContentRetryBody(body) + require.NoError(t, err) + require.True(t, changed) + require.Equal(t, "message", gjson.GetBytes(retry, "input.0.type").String()) + require.False(t, gjson.GetBytes(retry, "input.#(type==\"compaction\")").Exists()) +} + func TestForwardGrokResponsesInvalidEncryptedContentRecoveryNestedErrorShape(t *testing.T) { gin.SetMode(gin.TestMode) From 17c0ee385985073fb4a35a10ad1fb39eadb08959 Mon Sep 17 00:00:00 2001 From: IanShaw <131567472+IanShaw027@users.noreply.github.com> Date: Thu, 20 Aug 2026 06:08:34 -0700 Subject: [PATCH 063/204] =?UTF-8?q?=E6=94=AF=E6=8C=81=20Grok=20compaction?= =?UTF-8?q?=20422=20=E9=87=8D=E8=AF=95?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- backend/internal/service/openai_gateway_grok.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/backend/internal/service/openai_gateway_grok.go b/backend/internal/service/openai_gateway_grok.go index 132f7b3159..6ad03cc253 100644 --- a/backend/internal/service/openai_gateway_grok.go +++ b/backend/internal/service/openai_gateway_grok.go @@ -119,7 +119,7 @@ func (s *OpenAIGatewayService) forwardGrokResponses( // xAI can reject encrypted reasoning copied from a response produced under // another account or cache identity. Retry once with the same routing and // credential after removing only the rejected encrypted reasoning payload. - if attempt > 0 || resp.StatusCode != http.StatusBadRequest { + if attempt > 0 || (resp.StatusCode != http.StatusBadRequest && resp.StatusCode != http.StatusUnprocessableEntity) { break } respBody := s.readUpstreamErrorBody(resp) From 5ae254f771588d2aef990cb1205024d30aab6d81 Mon Sep 17 00:00:00 2001 From: IanShaw <131567472+IanShaw027@users.noreply.github.com> Date: Thu, 20 Aug 2026 06:25:57 -0700 Subject: [PATCH 064/204] =?UTF-8?q?=E8=A1=A5=E9=BD=90=20Grok=20CC=20bridge?= =?UTF-8?q?=20=E5=90=8C=E5=8F=B7=E9=87=8D=E8=AF=95?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- backend/internal/service/openai_gateway_grok_chat_bridge.go | 6 +++++- .../service/openai_gateway_grok_chat_bridge_test.go | 3 +++ 2 files changed, 8 insertions(+), 1 deletion(-) diff --git a/backend/internal/service/openai_gateway_grok_chat_bridge.go b/backend/internal/service/openai_gateway_grok_chat_bridge.go index e2b8f9a477..1c9f6c4b7d 100644 --- a/backend/internal/service/openai_gateway_grok_chat_bridge.go +++ b/backend/internal/service/openai_gateway_grok_chat_bridge.go @@ -633,11 +633,15 @@ func (s *OpenAIGatewayService) forwardGrokChatCompletionsViaResponses( }) s.handleGrokAccountUpstreamError(withGrokTeamRateLimitModel(ctx, upstreamModel), account, resp.StatusCode, resp.Header, respBody) if s.shouldFailoverGrokUpstreamError(resp.StatusCode, respBody) { + retryable, retryDelay, retryDeadline := grokSameAccountRetryMetadata(account, resp.StatusCode, respBody) return nil, &UpstreamFailoverError{ StatusCode: resp.StatusCode, ResponseBody: respBody, ResponseHeaders: resp.Header.Clone(), - RetryableOnSameAccount: account.IsPoolMode() && account.IsPoolModeRetryableStatus(resp.StatusCode), + RetryableOnSameAccount: retryable, + RequestScopedTransient: retryable && resp.StatusCode == http.StatusTooManyRequests, + SameAccountRetryDelay: retryDelay, + SameAccountRetryDeadline: retryDeadline, } } return s.handleChatCompletionsErrorResponse(resp, c, account, billingModel) diff --git a/backend/internal/service/openai_gateway_grok_chat_bridge_test.go b/backend/internal/service/openai_gateway_grok_chat_bridge_test.go index 5904c8ce3c..c854b462b7 100644 --- a/backend/internal/service/openai_gateway_grok_chat_bridge_test.go +++ b/backend/internal/service/openai_gateway_grok_chat_bridge_test.go @@ -614,6 +614,9 @@ func TestForwardGrokChatViaResponses429UsesGrokRateLimitPolicy(t *testing.T) { var failoverErr *UpstreamFailoverError require.True(t, errors.As(err, &failoverErr)) require.Equal(t, http.StatusTooManyRequests, failoverErr.StatusCode) + require.True(t, failoverErr.RetryableOnSameAccount) + require.Equal(t, 500*time.Millisecond, failoverErr.SameAccountRetryDelay) + require.False(t, failoverErr.SameAccountRetryDeadline.IsZero()) require.Equal(t, "45", failoverErr.ResponseHeaders.Get("Retry-After")) require.Equal(t, xai.DefaultCLIBaseURL+"/responses", upstream.lastReq.URL.String()) require.Equal(t, grokChatResponsesEndpoint, GetActualOpenAIUpstreamEndpoint(c)) From ab9cb69e7e5c8bf623ea6025bc6cc432c2401a3c Mon Sep 17 00:00:00 2001 From: IanShaw <131567472+IanShaw027@users.noreply.github.com> Date: Thu, 20 Aug 2026 06:36:42 -0700 Subject: [PATCH 065/204] =?UTF-8?q?Revert=20"=E4=BF=AE=E5=A4=8D=20Grok=20W?= =?UTF-8?q?ebSearch=20SSE=20action=20=E5=85=BC=E5=AE=B9"?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit This reverts commit 726de30101a75145e6b5a4bfc605e5a9d79007b7. --- .../openai_gateway_response_handling.go | 60 +------------------ .../service/openai_gateway_service_test.go | 11 ---- 2 files changed, 1 insertion(+), 70 deletions(-) diff --git a/backend/internal/service/openai_gateway_response_handling.go b/backend/internal/service/openai_gateway_response_handling.go index 5bc2d895e7..45a8e06de6 100644 --- a/backend/internal/service/openai_gateway_response_handling.go +++ b/backend/internal/service/openai_gateway_response_handling.go @@ -439,9 +439,7 @@ func (s *OpenAIGatewayService) handleStreamingResponseWithReasoning(ctx context. sendErrorEvent("stream_read_error") return resultWithUsage(), fmt.Errorf("stream read error: %w", scanErr), true } - var pendingGrokWebSearchCompleted string - var processSSELine func(line string, queueDrained bool) - processSSELine = func(line string, queueDrained bool) { + processSSELine := func(line string, queueDrained bool) { if streamEarlyErr != nil { return } @@ -450,26 +448,6 @@ func (s *OpenAIGatewayService) handleStreamingResponseWithReasoning(ctx context. dataBytes := []byte(data) eventTypeRaw := gjson.GetBytes(dataBytes, "type").String() eventType := strings.TrimSpace(eventTypeRaw) - // Grok Build's xAI decoder requires action on the completed search - // event, while OpenAI-compatible upstreams often provide it only on - // the following output_item.done event. Hold that one event until the - // matching item arrives, then replay it with action injected. - if account != nil && account.Platform == PlatformGrok && account.Type == AccountTypeAPIKey && - eventType == "response.web_search_call.completed" && - !gjson.GetBytes(dataBytes, "action").Exists() { - pendingGrokWebSearchCompleted = line - return - } - if pendingGrokWebSearchCompleted != "" && eventType == "response.output_item.done" { - if adapted, adaptedOK := adaptGrokWebSearchCompletedAction( - []byte(strings.TrimSpace(strings.TrimPrefix(pendingGrokWebSearchCompleted, "data:"))), dataBytes, - ); adaptedOK { - pendingGrokWebSearchCompleted = "data: " + string(adapted) - } - pending := pendingGrokWebSearchCompleted - pendingGrokWebSearchCompleted = "" - processSSELine(pending, queueDrained) - } observer.ObserveOpenAI(dataBytes, eventTypeRaw) // 初始上游 data 的 type 只解析一次:原始值保持终止事件的精确匹配,规范化值供后续分支复用。 if openAIStreamEventIsTerminalWithType(data, eventTypeRaw) { @@ -662,11 +640,6 @@ func (s *OpenAIGatewayService) handleStreamingResponseWithReasoning(ctx context. // A blank line dispatches a guarded event from the attempt-local stage. if stageFirstOutput && line == "" { - if pendingGrokWebSearchCompleted != "" { - pending := pendingGrokWebSearchCompleted - pendingGrokWebSearchCompleted = "" - processSSELine(pending, queueDrained) - } if !clientDisconnected { if _, err := writePendingString("\n"); err != nil { handlePendingWriteError(err) @@ -681,11 +654,6 @@ func (s *OpenAIGatewayService) handleStreamingResponseWithReasoning(ctx context. // or queue-drain flush must never split an open SSE event. shouldFlush := false if line == "" { - if pendingGrokWebSearchCompleted != "" { - pending := pendingGrokWebSearchCompleted - pendingGrokWebSearchCompleted = "" - processSSELine(pending, queueDrained) - } shouldFlush = eventShouldFlush || (queueDrained && clientOutputStarted) eventShouldFlush = false } @@ -1205,32 +1173,6 @@ func (s *OpenAIGatewayService) bindHTTPResponseAccount(ctx context.Context, c *g logOpenAIWSBindResponseAccountWarn(groupID, account.ID, responseID, store.BindResponseAccount(ctx, groupID, responseID, account.ID, ttl)) } -// adaptGrokWebSearchCompletedAction fills the xAI-specific action field that -// Grok Build expects on response.web_search_call.completed. OpenAI-compatible -// upstreams commonly emit the action only on the later output_item.done event. -func adaptGrokWebSearchCompletedAction(completed, outputItem []byte) ([]byte, bool) { - if strings.TrimSpace(gjson.GetBytes(completed, "type").String()) != "response.web_search_call.completed" { - return completed, false - } - itemID := strings.TrimSpace(gjson.GetBytes(completed, "item_id").String()) - item := gjson.GetBytes(outputItem, "item") - if itemID == "" || !item.Exists() || strings.TrimSpace(item.Get("type").String()) != "web_search_call" { - return completed, false - } - if itemID != strings.TrimSpace(item.Get("id").String()) { - return completed, false - } - action := item.Get("action") - if !action.Exists() || strings.TrimSpace(action.Raw) == "" || action.Raw == "null" { - return completed, false - } - updated, err := sjson.SetRawBytes(completed, "action", []byte(action.Raw)) - if err != nil { - return completed, false - } - return updated, true -} - func openAIUsageFromGJSON(value gjson.Result) (OpenAIUsage, bool) { if !value.Exists() || !value.IsObject() { return OpenAIUsage{}, false diff --git a/backend/internal/service/openai_gateway_service_test.go b/backend/internal/service/openai_gateway_service_test.go index 2b0344c309..998ab6a154 100644 --- a/backend/internal/service/openai_gateway_service_test.go +++ b/backend/internal/service/openai_gateway_service_test.go @@ -3463,17 +3463,6 @@ func TestExtractOpenAIUsageFromJSONBytes_AcceptsResponseAndChatUsageShapes(t *te require.Equal(t, 500, usage.OutputTokens) } -func TestAdaptGrokWebSearchCompletedAction(t *testing.T) { - completed := []byte(`{"type":"response.web_search_call.completed","item_id":"call_1"}`) - done := []byte(`{"type":"response.output_item.done","item":{"type":"web_search_call","id":"call_1","action":{"type":"search","query":"latest news"}}}`) - got, ok := adaptGrokWebSearchCompletedAction(completed, done) - require.True(t, ok) - require.Equal(t, "search", gjson.GetBytes(got, "action.type").String()) - require.Equal(t, "latest news", gjson.GetBytes(got, "action.query").String()) - _, ok = adaptGrokWebSearchCompletedAction(completed, []byte(`{"type":"response.output_item.done","item":{"type":"web_search_call","id":"other"}}`)) - require.False(t, ok) -} - func TestExtractOpenAIUsageFromJSONBytes_IncludesGrokReasoningTokens(t *testing.T) { usage, ok := extractOpenAIUsageFromJSONBytes([]byte(`{"usage":{"prompt_tokens":32,"completion_tokens":9,"total_tokens":135,"completion_tokens_details":{"reasoning_tokens":94}}}`)) require.True(t, ok) From 2ab24a1e77189138297605342586157bc66517b8 Mon Sep 17 00:00:00 2001 From: IanShaw <131567472+IanShaw027@users.noreply.github.com> Date: Thu, 20 Aug 2026 06:43:31 -0700 Subject: [PATCH 066/204] =?UTF-8?q?=E4=BF=AE=E6=AD=A3=20Grok=20429=20?= =?UTF-8?q?=E8=BE=B9=E7=95=8C=E4=B8=8E=20stream=20idle=20=E9=87=8D?= =?UTF-8?q?=E8=AF=95=E4=B8=8A=E9=99=90?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- backend/internal/handler/failover_loop.go | 3 +++ backend/internal/service/gateway_service.go | 1 + backend/internal/service/grok_stream_idle.go | 1 + backend/internal/service/grok_stream_idle_test.go | 1 + backend/internal/service/grok_upstream_failure.go | 9 +-------- backend/internal/service/grok_upstream_failure_test.go | 8 ++++---- backend/internal/service/openai_gateway_grok_test.go | 8 ++++---- 7 files changed, 15 insertions(+), 16 deletions(-) diff --git a/backend/internal/handler/failover_loop.go b/backend/internal/handler/failover_loop.go index d349980fc6..c51779c047 100644 --- a/backend/internal/handler/failover_loop.go +++ b/backend/internal/handler/failover_loop.go @@ -171,6 +171,9 @@ func (s *FailoverState) HandleFailoverError( // 同账号重试不算切换账号,粘性会话仅在实际切换时强制缓存计费。 retryCount := s.SameAccountRetryCount[accountID] + if failoverErr.SameAccountRetryMax > 0 && (retryLimit <= 0 || failoverErr.SameAccountRetryMax < retryLimit) { + retryLimit = failoverErr.SameAccountRetryMax + } sameAccountRetryAllowed := failoverErr.RetryableOnSameAccount && retryLimit > 0 && retryCount < retryLimit if sameAccountRetryAllowed && !failoverErr.SameAccountRetryDeadline.IsZero() { sameAccountRetryAllowed = time.Now().Before(failoverErr.SameAccountRetryDeadline) diff --git a/backend/internal/service/gateway_service.go b/backend/internal/service/gateway_service.go index 6e1ebecbbb..0269dc55c6 100644 --- a/backend/internal/service/gateway_service.go +++ b/backend/internal/service/gateway_service.go @@ -677,6 +677,7 @@ type UpstreamFailoverError struct { RetryableOnSameAccount bool // 临时性错误(如 Google 间歇性 400、空响应),应在同一账号上重试 N 次再切换 SameAccountRetryDelay time.Duration // 同账号重试的最小间隔;零值使用 handler 默认值 SameAccountRetryDeadline time.Time // 同账号重试截止时间;零值表示仅受 retryLimit 限制 + SameAccountRetryMax int // 可选的错误级同账号重试上限,低于 handler 默认预算时优先采用 RequestScopedTransient bool // 故障因素与账号无关(如上游按客户端身份/模型容量降载):可同账号重试,但不得据此对账号做临时封禁 SafeToFailoverAfterWrite bool // 仅写出 SSE 注释等非语义字节时,仍可在同一客户端流中切换账号 Stage GatewayFailureStage diff --git a/backend/internal/service/grok_stream_idle.go b/backend/internal/service/grok_stream_idle.go index cbe1fdc767..ddfa9f80bd 100644 --- a/backend/internal/service/grok_stream_idle.go +++ b/backend/internal/service/grok_stream_idle.go @@ -38,6 +38,7 @@ func grokStreamIdleFailoverError(account *Account, idle time.Duration) *Upstream // the request's retry limit. RetryableOnSameAccount: account != nil && account.Platform == PlatformGrok, RequestScopedTransient: true, + SameAccountRetryMax: 1, // Permit at most one same-account replay after the idle failure. The // deadline is anchored at failure time, so a hung stream cannot consume // the normal three-attempt budget before failover. diff --git a/backend/internal/service/grok_stream_idle_test.go b/backend/internal/service/grok_stream_idle_test.go index 69fdcc1da9..7110dac9f2 100644 --- a/backend/internal/service/grok_stream_idle_test.go +++ b/backend/internal/service/grok_stream_idle_test.go @@ -23,6 +23,7 @@ func TestGrokStreamIdleFailoverError(t *testing.T) { require.True(t, err.SafeToFailoverAfterWrite) require.True(t, err.RetryableOnSameAccount) require.True(t, err.RequestScopedTransient) + require.Equal(t, 1, err.SameAccountRetryMax) require.Contains(t, string(err.ResponseBody), "empty_upstream") require.WithinDuration(t, time.Now().Add(180*time.Second), err.SameAccountRetryDeadline, 2*time.Second) } diff --git a/backend/internal/service/grok_upstream_failure.go b/backend/internal/service/grok_upstream_failure.go index 51edbc3332..3d6aa05c6e 100644 --- a/backend/internal/service/grok_upstream_failure.go +++ b/backend/internal/service/grok_upstream_failure.go @@ -402,13 +402,6 @@ func grokRetryableOnSameAccount(account *Account, statusCode int, responseBody [ if statusCode == http.StatusTooManyRequests { return true } - case GrokFailureRateLimit: - // A transient 429 does not identify a bad credential. Give every Grok - // account a bounded same-account retry window before failover; the - // failover loop still caps attempts and the client receives 429 after it. - if statusCode == http.StatusTooManyRequests { - return true - } } return account.IsPoolMode() && account.IsPoolModeRetryableStatus(statusCode) } @@ -418,7 +411,7 @@ func grokSameAccountRetryMetadata(account *Account, statusCode int, responseBody return false, 0, time.Time{} } decision := classifyGrokUpstreamFailure(statusCode, responseBody, "") - if decision.Class != GrokFailureModelCapacity && decision.Class != GrokFailureRateLimit { + if decision.Class != GrokFailureModelCapacity { return true, 0, time.Time{} } return true, 500 * time.Millisecond, time.Now().Add(30 * time.Second) diff --git a/backend/internal/service/grok_upstream_failure_test.go b/backend/internal/service/grok_upstream_failure_test.go index 0cc8cd1efa..d6e6ec7ace 100644 --- a/backend/internal/service/grok_upstream_failure_test.go +++ b/backend/internal/service/grok_upstream_failure_test.go @@ -81,7 +81,7 @@ func TestGrokRetryableOnSameAccount_CapacityAndRateLimit(t *testing.T) { account := &Account{ID: 9105, Platform: PlatformGrok, Type: AccountTypeOAuth} require.True(t, grokRetryableOnSameAccount(account, http.StatusTooManyRequests, []byte(`{"error":{"message":"The model is currently at capacity due to high demand"}}`))) - require.True(t, grokRetryableOnSameAccount(account, http.StatusTooManyRequests, + require.False(t, grokRetryableOnSameAccount(account, http.StatusTooManyRequests, []byte(`{"error":{"message":"rate limit exceeded"}}`))) require.False(t, grokRetryableOnSameAccount(account, http.StatusPaymentRequired, []byte(`{"error":{"message":"You have run out of credits or need a Grok subscription"}}`))) @@ -118,9 +118,9 @@ func TestGrokSameAccountRetryMetadata_CapacityDeadline(t *testing.T) { retryable, delay, deadline = grokSameAccountRetryMetadata(account, http.StatusTooManyRequests, []byte(`{"error":{"message":"rate limit exceeded"}}`)) - require.True(t, retryable) - require.Equal(t, 500*time.Millisecond, delay) - require.WithinDuration(t, time.Now().Add(30*time.Second), deadline, 2*time.Second) + require.False(t, retryable) + require.Zero(t, delay) + require.True(t, deadline.IsZero()) } func TestClassifyGrokUpstreamFailure_ValidationNoCool(t *testing.T) { diff --git a/backend/internal/service/openai_gateway_grok_test.go b/backend/internal/service/openai_gateway_grok_test.go index b89c9eef83..27419e82c3 100644 --- a/backend/internal/service/openai_gateway_grok_test.go +++ b/backend/internal/service/openai_gateway_grok_test.go @@ -1794,7 +1794,7 @@ func TestForwardAsChatCompletionsForGrokStopFallsBackToXAIChatCompletions(t *tes require.Equal(t, "grok-4.6", gjson.GetBytes(upstream.lastBody, "model").String()) require.False(t, gjson.GetBytes(upstream.lastBody, "prompt_cache_key").Exists()) require.Equal(t, "grok", result.Model) - require.Equal(t, "grok-4.5", result.UpstreamModel) + require.Equal(t, "grok-4.6", result.UpstreamModel) require.Equal(t, 1, result.Usage.InputTokens) require.Equal(t, 2, result.Usage.OutputTokens) require.Equal(t, 1, result.Usage.CacheReadInputTokens) @@ -1848,7 +1848,7 @@ func TestForwardGrokResponsesStreamingDefaultsEmptyModelTo45AndSnapshots(t *test require.Equal(t, xai.DefaultCLIBaseURL+"/responses", upstream.lastReq.URL.String()) require.Equal(t, "Bearer access-token", upstream.lastReq.Header.Get("Authorization")) require.Equal(t, "responses=experimental", upstream.lastReq.Header.Get("OpenAI-Beta")) - require.Equal(t, "grok-4.6", gjson.GetBytes(upstream.lastBody, "model").String()) + require.Equal(t, "grok-4.5", gjson.GetBytes(upstream.lastBody, "model").String()) require.NotEmpty(t, gjson.GetBytes(upstream.lastBody, "prompt_cache_key").String()) require.Equal(t, gjson.GetBytes(upstream.lastBody, "prompt_cache_key").String(), upstream.lastReq.Header.Get(grokConversationIDHeader)) require.Equal(t, "web_search", gjson.GetBytes(upstream.lastBody, "tools.0.type").String()) @@ -2367,7 +2367,7 @@ func TestForwardAsChatCompletionsForGrokStreamingUsesRawXAIChatCompletions(t *te require.Equal(t, "Bearer access-token", upstream.lastReq.Header.Get("Authorization")) require.Equal(t, "text/event-stream", upstream.lastReq.Header.Get("Accept")) require.Equal(t, xai.CLIUserAgent(xai.CLIClientVersion), upstream.lastReq.Header.Get("User-Agent")) - require.Equal(t, "grok-4.5", gjson.GetBytes(upstream.lastBody, "model").String()) + require.Equal(t, "grok-4.6", gjson.GetBytes(upstream.lastBody, "model").String()) require.True(t, gjson.GetBytes(upstream.lastBody, "stream_options.include_usage").Bool()) require.True(t, result.Stream) require.Equal(t, 6, result.Usage.InputTokens) @@ -2648,7 +2648,7 @@ func TestForwardAsAnthropicForGrokUsesXAIResponses(t *testing.T) { require.Equal(t, "grok-experimental", upstream.lastReq.Header.Get("OpenAI-Beta")) require.Empty(t, upstream.lastReq.Header.Get("originator")) require.Empty(t, upstream.lastReq.Header.Get("version")) - require.Equal(t, "grok-4.5", gjson.GetBytes(upstream.lastBody, "model").String()) + require.Equal(t, "grok-4.6", gjson.GetBytes(upstream.lastBody, "model").String()) require.NotEmpty(t, gjson.GetBytes(upstream.lastBody, "prompt_cache_key").String()) require.Equal(t, gjson.GetBytes(upstream.lastBody, "prompt_cache_key").String(), upstream.lastReq.Header.Get(grokConversationIDHeader)) require.Equal(t, "web_search", gjson.GetBytes(upstream.lastBody, "tools.0.type").String()) From 0b1f79c83ce6ec088e266fba910db93f70fe9cbb Mon Sep 17 00:00:00 2001 From: IanShaw <131567472+IanShaw027@users.noreply.github.com> Date: Thu, 20 Aug 2026 06:43:54 -0700 Subject: [PATCH 067/204] =?UTF-8?q?=E5=90=8C=E6=AD=A5=20Grok=20429=20bridg?= =?UTF-8?q?e=20=E5=9B=9E=E5=BD=92=E6=96=AD=E8=A8=80?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../internal/service/openai_gateway_grok_chat_bridge_test.go | 3 --- 1 file changed, 3 deletions(-) diff --git a/backend/internal/service/openai_gateway_grok_chat_bridge_test.go b/backend/internal/service/openai_gateway_grok_chat_bridge_test.go index c854b462b7..5904c8ce3c 100644 --- a/backend/internal/service/openai_gateway_grok_chat_bridge_test.go +++ b/backend/internal/service/openai_gateway_grok_chat_bridge_test.go @@ -614,9 +614,6 @@ func TestForwardGrokChatViaResponses429UsesGrokRateLimitPolicy(t *testing.T) { var failoverErr *UpstreamFailoverError require.True(t, errors.As(err, &failoverErr)) require.Equal(t, http.StatusTooManyRequests, failoverErr.StatusCode) - require.True(t, failoverErr.RetryableOnSameAccount) - require.Equal(t, 500*time.Millisecond, failoverErr.SameAccountRetryDelay) - require.False(t, failoverErr.SameAccountRetryDeadline.IsZero()) require.Equal(t, "45", failoverErr.ResponseHeaders.Get("Retry-After")) require.Equal(t, xai.DefaultCLIBaseURL+"/responses", upstream.lastReq.URL.String()) require.Equal(t, grokChatResponsesEndpoint, GetActualOpenAIUpstreamEndpoint(c)) From f7bc1970efbda1a847b2465d233811ce6cd89ea9 Mon Sep 17 00:00:00 2001 From: IanShaw <131567472+IanShaw027@users.noreply.github.com> Date: Thu, 20 Aug 2026 07:00:42 -0700 Subject: [PATCH 068/204] =?UTF-8?q?=E5=90=8C=E6=AD=A5=20Grok=20=E9=BB=98?= =?UTF-8?q?=E8=AE=A4=E6=A8=A1=E5=9E=8B=E5=9B=9E=E5=BD=92=E6=96=AD=E8=A8=80?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- backend/internal/service/openai_gateway_grok_test.go | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/backend/internal/service/openai_gateway_grok_test.go b/backend/internal/service/openai_gateway_grok_test.go index 27419e82c3..3d2fd953fa 100644 --- a/backend/internal/service/openai_gateway_grok_test.go +++ b/backend/internal/service/openai_gateway_grok_test.go @@ -1848,7 +1848,7 @@ func TestForwardGrokResponsesStreamingDefaultsEmptyModelTo45AndSnapshots(t *test require.Equal(t, xai.DefaultCLIBaseURL+"/responses", upstream.lastReq.URL.String()) require.Equal(t, "Bearer access-token", upstream.lastReq.Header.Get("Authorization")) require.Equal(t, "responses=experimental", upstream.lastReq.Header.Get("OpenAI-Beta")) - require.Equal(t, "grok-4.5", gjson.GetBytes(upstream.lastBody, "model").String()) + require.Equal(t, "grok-4.6", gjson.GetBytes(upstream.lastBody, "model").String()) require.NotEmpty(t, gjson.GetBytes(upstream.lastBody, "prompt_cache_key").String()) require.Equal(t, gjson.GetBytes(upstream.lastBody, "prompt_cache_key").String(), upstream.lastReq.Header.Get(grokConversationIDHeader)) require.Equal(t, "web_search", gjson.GetBytes(upstream.lastBody, "tools.0.type").String()) @@ -2543,7 +2543,7 @@ func TestForwardAsChatCompletionsForGrokStreamingStopFallsBackToRawXAIChatComple require.Equal(t, grokCLIVersion, upstream.lastReq.Header.Get("X-Grok-Client-Version")) require.NotEmpty(t, upstream.lastReq.Header.Get(grokConversationIDHeader)) require.NotEqual(t, "native-client-conversation", upstream.lastReq.Header.Get(grokConversationIDHeader)) - require.Equal(t, "grok-4.5", gjson.GetBytes(upstream.lastBody, "model").String()) + require.Equal(t, "grok-4.6", gjson.GetBytes(upstream.lastBody, "model").String()) require.True(t, gjson.GetBytes(upstream.lastBody, "stream_options.include_usage").Bool()) require.True(t, result.Stream) require.Equal(t, 6, result.Usage.InputTokens) @@ -2658,7 +2658,7 @@ func TestForwardAsAnthropicForGrokUsesXAIResponses(t *testing.T) { require.True(t, gjson.GetBytes(upstream.lastBody, "stream").Bool()) require.NotContains(t, string(upstream.lastBody), "chatgpt.com") require.Equal(t, "grok", result.Model) - require.Equal(t, "grok-4.5", result.UpstreamModel) + require.Equal(t, "grok-4.6", result.UpstreamModel) require.Equal(t, 5, result.Usage.InputTokens) require.Equal(t, 2, result.Usage.OutputTokens) require.Equal(t, 3, result.Usage.CacheReadInputTokens) From c628b3eea70d3a8813074fdacc252d8c3af16bba Mon Sep 17 00:00:00 2001 From: IanShaw <131567472+IanShaw027@users.noreply.github.com> Date: Thu, 20 Aug 2026 07:07:55 -0700 Subject: [PATCH 069/204] =?UTF-8?q?=E8=AE=A9=20Grok=20stream=20idle=20?= =?UTF-8?q?=E9=87=8D=E8=AF=95=E4=B8=8A=E9=99=90=E4=BD=9C=E7=94=A8=E4=BA=8E?= =?UTF-8?q?=E4=B8=BB=E8=B7=AF=E5=BE=84?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- backend/internal/handler/failover_loop.go | 15 ++++++++++++++- backend/internal/handler/failover_loop_test.go | 7 +++++++ backend/internal/handler/grok_media.go | 2 +- .../internal/handler/openai_chat_completions.go | 2 +- .../internal/handler/openai_gateway_handler.go | 4 ++-- backend/internal/handler/openai_images.go | 2 +- .../service/openai_gateway_grok_chat_bridge.go | 8 ++++---- 7 files changed, 30 insertions(+), 10 deletions(-) diff --git a/backend/internal/handler/failover_loop.go b/backend/internal/handler/failover_loop.go index c51779c047..e626d66e05 100644 --- a/backend/internal/handler/failover_loop.go +++ b/backend/internal/handler/failover_loop.go @@ -82,6 +82,19 @@ func sameAccountRetryDeadlineAllows(failoverErr *service.UpstreamFailoverError) return failoverErr == nil || failoverErr.SameAccountRetryDeadline.IsZero() || time.Now().Before(failoverErr.SameAccountRetryDeadline) } +// effectiveSameAccountRetryLimit applies an error-specific cap without +// overriding an explicit account setting of zero (which disables retries). +func effectiveSameAccountRetryLimit(failoverErr *service.UpstreamFailoverError, account *service.Account) int { + if account == nil { + return 0 + } + limit := account.GetPoolModeRetryCount() + if limit > 0 && failoverErr != nil && failoverErr.SameAccountRetryMax > 0 && failoverErr.SameAccountRetryMax < limit { + return failoverErr.SameAccountRetryMax + } + return limit +} + // FailoverState 跨循环迭代共享的 failover 状态 type FailoverState struct { SwitchCount int @@ -171,7 +184,7 @@ func (s *FailoverState) HandleFailoverError( // 同账号重试不算切换账号,粘性会话仅在实际切换时强制缓存计费。 retryCount := s.SameAccountRetryCount[accountID] - if failoverErr.SameAccountRetryMax > 0 && (retryLimit <= 0 || failoverErr.SameAccountRetryMax < retryLimit) { + if failoverErr.SameAccountRetryMax > 0 && failoverErr.SameAccountRetryMax < retryLimit { retryLimit = failoverErr.SameAccountRetryMax } sameAccountRetryAllowed := failoverErr.RetryableOnSameAccount && retryLimit > 0 && retryCount < retryLimit diff --git a/backend/internal/handler/failover_loop_test.go b/backend/internal/handler/failover_loop_test.go index 40602f9df9..bcf8110850 100644 --- a/backend/internal/handler/failover_loop_test.go +++ b/backend/internal/handler/failover_loop_test.go @@ -70,6 +70,13 @@ func TestSameAccountRetryDeadlineAllows(t *testing.T) { })) } +func TestEffectiveSameAccountRetryLimitHonorsErrorCapAndDisabledAccount(t *testing.T) { + account := &service.Account{Type: service.AccountTypeAPIKey, Credentials: map[string]any{"pool_mode": true, "pool_mode_retry_count": float64(3)}} + require.Equal(t, 1, effectiveSameAccountRetryLimit(&service.UpstreamFailoverError{SameAccountRetryMax: 1}, account)) + account.Credentials["pool_mode_retry_count"] = float64(0) + require.Equal(t, 0, effectiveSameAccountRetryLimit(&service.UpstreamFailoverError{SameAccountRetryMax: 1}, account)) +} + // --------------------------------------------------------------------------- // Helper // --------------------------------------------------------------------------- diff --git a/backend/internal/handler/grok_media.go b/backend/internal/handler/grok_media.go index 6e5619b6e5..94f267a970 100644 --- a/backend/internal/handler/grok_media.go +++ b/backend/internal/handler/grok_media.go @@ -361,7 +361,7 @@ func (h *OpenAIGatewayHandler) handleGrokMedia(c *gin.Context, endpoint service. return } if failoverErr.RetryableOnSameAccount { - retryLimit := account.GetPoolModeRetryCount() + retryLimit := effectiveSameAccountRetryLimit(failoverErr, account) if sameAccountRetryCount[account.ID] < retryLimit && sameAccountRetryDeadlineAllows(failoverErr) { sameAccountRetryCount[account.ID]++ retryDelay := sameAccountRetryDelayFor(failoverErr, sameAccountRetryCount[account.ID]) diff --git a/backend/internal/handler/openai_chat_completions.go b/backend/internal/handler/openai_chat_completions.go index 1dd8f63ceb..78dd7eb098 100644 --- a/backend/internal/handler/openai_chat_completions.go +++ b/backend/internal/handler/openai_chat_completions.go @@ -327,7 +327,7 @@ func (h *OpenAIGatewayHandler) ChatCompletions(c *gin.Context) { } // Pool mode: retry on the same account if failoverErr.RetryableOnSameAccount { - retryLimit := account.GetPoolModeRetryCount() + retryLimit := effectiveSameAccountRetryLimit(failoverErr, account) if sameAccountRetryCount[account.ID] < retryLimit && sameAccountRetryDeadlineAllows(failoverErr) { sameAccountRetryCount[account.ID]++ retryDelay := sameAccountRetryDelayFor(failoverErr, sameAccountRetryCount[account.ID]) diff --git a/backend/internal/handler/openai_gateway_handler.go b/backend/internal/handler/openai_gateway_handler.go index 1f7c849a6a..bbece97730 100644 --- a/backend/internal/handler/openai_gateway_handler.go +++ b/backend/internal/handler/openai_gateway_handler.go @@ -717,7 +717,7 @@ func (h *OpenAIGatewayHandler) Responses(c *gin.Context) { } // 池模式:同账号重试 if failoverErr.RetryableOnSameAccount { - retryLimit := account.GetPoolModeRetryCount() + retryLimit := effectiveSameAccountRetryLimit(failoverErr, account) if sameAccountRetryCount[account.ID] < retryLimit && sameAccountRetryDeadlineAllows(failoverErr) { sameAccountRetryCount[account.ID]++ retryDelay := sameAccountRetryDelayFor(failoverErr, sameAccountRetryCount[account.ID]) @@ -1266,7 +1266,7 @@ func (h *OpenAIGatewayHandler) Messages(c *gin.Context) { } // 池模式:同账号重试 if failoverErr.RetryableOnSameAccount { - retryLimit := account.GetPoolModeRetryCount() + retryLimit := effectiveSameAccountRetryLimit(failoverErr, account) if sameAccountRetryCount[account.ID] < retryLimit && sameAccountRetryDeadlineAllows(failoverErr) { sameAccountRetryCount[account.ID]++ retryDelay := sameAccountRetryDelayFor(failoverErr, sameAccountRetryCount[account.ID]) diff --git a/backend/internal/handler/openai_images.go b/backend/internal/handler/openai_images.go index a82c7b7193..6ff30eccfe 100644 --- a/backend/internal/handler/openai_images.go +++ b/backend/internal/handler/openai_images.go @@ -304,7 +304,7 @@ func (h *OpenAIGatewayHandler) Images(c *gin.Context) { return } if failoverErr.RetryableOnSameAccount { - retryLimit := account.GetPoolModeRetryCount() + retryLimit := effectiveSameAccountRetryLimit(failoverErr, account) if sameAccountRetryCount[account.ID] < retryLimit && sameAccountRetryDeadlineAllows(failoverErr) { sameAccountRetryCount[account.ID]++ retryDelay := sameAccountRetryDelayFor(failoverErr, sameAccountRetryCount[account.ID]) diff --git a/backend/internal/service/openai_gateway_grok_chat_bridge.go b/backend/internal/service/openai_gateway_grok_chat_bridge.go index 1c9f6c4b7d..84e2c95e72 100644 --- a/backend/internal/service/openai_gateway_grok_chat_bridge.go +++ b/backend/internal/service/openai_gateway_grok_chat_bridge.go @@ -635,10 +635,10 @@ func (s *OpenAIGatewayService) forwardGrokChatCompletionsViaResponses( if s.shouldFailoverGrokUpstreamError(resp.StatusCode, respBody) { retryable, retryDelay, retryDeadline := grokSameAccountRetryMetadata(account, resp.StatusCode, respBody) return nil, &UpstreamFailoverError{ - StatusCode: resp.StatusCode, - ResponseBody: respBody, - ResponseHeaders: resp.Header.Clone(), - RetryableOnSameAccount: retryable, + StatusCode: resp.StatusCode, + ResponseBody: respBody, + ResponseHeaders: resp.Header.Clone(), + RetryableOnSameAccount: retryable, RequestScopedTransient: retryable && resp.StatusCode == http.StatusTooManyRequests, SameAccountRetryDelay: retryDelay, SameAccountRetryDeadline: retryDeadline, From cca235365b35c1a54fcdb1b1800807e9ee510bcd Mon Sep 17 00:00:00 2001 From: IanShaw <131567472+IanShaw027@users.noreply.github.com> Date: Thu, 20 Aug 2026 07:19:51 -0700 Subject: [PATCH 070/204] =?UTF-8?q?=E4=BF=AE=E6=AD=A3=20Grok=20=E9=BB=98?= =?UTF-8?q?=E8=AE=A4=E6=A8=A1=E5=9E=8B=E6=B5=8B=E8=AF=95=E6=96=AD=E8=A8=80?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- backend/internal/service/openai_gateway_grok_test.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/backend/internal/service/openai_gateway_grok_test.go b/backend/internal/service/openai_gateway_grok_test.go index 3d2fd953fa..92f9901142 100644 --- a/backend/internal/service/openai_gateway_grok_test.go +++ b/backend/internal/service/openai_gateway_grok_test.go @@ -1848,7 +1848,7 @@ func TestForwardGrokResponsesStreamingDefaultsEmptyModelTo45AndSnapshots(t *test require.Equal(t, xai.DefaultCLIBaseURL+"/responses", upstream.lastReq.URL.String()) require.Equal(t, "Bearer access-token", upstream.lastReq.Header.Get("Authorization")) require.Equal(t, "responses=experimental", upstream.lastReq.Header.Get("OpenAI-Beta")) - require.Equal(t, "grok-4.6", gjson.GetBytes(upstream.lastBody, "model").String()) + require.Equal(t, "grok-4.5", gjson.GetBytes(upstream.lastBody, "model").String()) require.NotEmpty(t, gjson.GetBytes(upstream.lastBody, "prompt_cache_key").String()) require.Equal(t, gjson.GetBytes(upstream.lastBody, "prompt_cache_key").String(), upstream.lastReq.Header.Get(grokConversationIDHeader)) require.Equal(t, "web_search", gjson.GetBytes(upstream.lastBody, "tools.0.type").String()) From d78e366db552a6dd361701981af2dc3065d2734a Mon Sep 17 00:00:00 2001 From: IanShaw <131567472+IanShaw027@users.noreply.github.com> Date: Thu, 20 Aug 2026 07:31:19 -0700 Subject: [PATCH 071/204] =?UTF-8?q?=E8=A1=A5=E9=BD=90=20Grok=20Realtime=20?= =?UTF-8?q?=E6=8F=A1=E6=89=8B=E5=A4=B1=E8=B4=A5=E8=B4=A6=E5=8F=B7=E5=86=B7?= =?UTF-8?q?=E5=8D=B4?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- backend/internal/handler/grok_audio.go | 6 ++++++ backend/internal/service/grok_audio.go | 23 +++++++++++++++++++++-- 2 files changed, 27 insertions(+), 2 deletions(-) diff --git a/backend/internal/handler/grok_audio.go b/backend/internal/handler/grok_audio.go index 08a8ff3c6c..c95b5ce559 100644 --- a/backend/internal/handler/grok_audio.go +++ b/backend/internal/handler/grok_audio.go @@ -98,6 +98,12 @@ func (h *OpenAIGatewayHandler) GrokRealtime(c *gin.Context) { cancelProbe() if openErr != nil { reqLog.Warn("grok_realtime.pre_accept_failed", zap.Int64("account_id", account.ID), zap.Error(openErr)) + statusCode := http.StatusBadGateway + var dialErr *service.GrokRealtimeDialError + if errors.As(openErr, &dialErr) && dialErr.StatusCode > 0 { + statusCode = dialErr.StatusCode + } + h.gatewayService.HandleGrokRealtimeUpstreamError(c.Request.Context(), account, statusCode, []byte(openErr.Error())) release() release = nil failed[account.ID] = struct{}{} diff --git a/backend/internal/service/grok_audio.go b/backend/internal/service/grok_audio.go index a2fb33f12d..771cae09f4 100644 --- a/backend/internal/service/grok_audio.go +++ b/backend/internal/service/grok_audio.go @@ -139,6 +139,16 @@ func (s *OpenAIGatewayService) ProxyGrokRealtime(ctx context.Context, c *gin.Con type GrokRealtimeUpstream struct{ conn openAIWSClientConn } +// GrokRealtimeDialError preserves an HTTP status returned before WebSocket +// upgrade so handlers can apply the normal Grok account policy. +type GrokRealtimeDialError struct { + StatusCode int + Err error +} + +func (e *GrokRealtimeDialError) Error() string { return e.Err.Error() } +func (e *GrokRealtimeDialError) Unwrap() error { return e.Err } + func (u *GrokRealtimeUpstream) Close() error { if u == nil || u.conn == nil { return nil @@ -171,13 +181,22 @@ func (s *OpenAIGatewayService) OpenGrokRealtime(ctx context.Context, account *Ac if account.ProxyID != nil && account.Proxy != nil { proxyURL = account.Proxy.URL() } - conn, _, _, err := s.getOpenAIWSPassthroughDialer().Dial(ctx, u.String(), headers, proxyURL) + conn, status, _, err := s.getOpenAIWSPassthroughDialer().Dial(ctx, u.String(), headers, proxyURL) if err != nil { - return nil, err + return nil, &GrokRealtimeDialError{StatusCode: status, Err: err} } return &GrokRealtimeUpstream{conn: conn}, nil } +// HandleGrokRealtimeUpstreamError applies the shared Grok account policy to a +// failed pre-accept WebSocket handshake. +func (s *OpenAIGatewayService) HandleGrokRealtimeUpstreamError(ctx context.Context, account *Account, statusCode int, body []byte) { + if statusCode <= 0 { + statusCode = http.StatusBadGateway + } + s.handleGrokAccountUpstreamError(ctx, account, statusCode, nil, body) +} + func (s *OpenAIGatewayService) ProxyGrokRealtimeConn(ctx context.Context, c *gin.Context, client *coderws.Conn, upstream *GrokRealtimeUpstream) (bool, error) { if s == nil || client == nil || upstream == nil || upstream.conn == nil { return false, fmt.Errorf("realtime connection is required") From 39aaf2fea32fc73097aa60197e963383672e0267 Mon Sep 17 00:00:00 2001 From: IanShaw <131567472+IanShaw027@users.noreply.github.com> Date: Thu, 20 Aug 2026 08:07:04 -0700 Subject: [PATCH 072/204] =?UTF-8?q?=E6=94=B6=E7=B4=A7=20Grok=20=E5=AE=B9?= =?UTF-8?q?=E9=87=8F=E9=87=8D=E8=AF=95=E4=B8=8E=E5=85=BC=E5=AE=B9=E6=80=A7?= =?UTF-8?q?=E5=88=86=E7=B1=BB?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- backend/internal/service/grok_media.go | 3 ++- .../internal/service/grok_upstream_failure.go | 19 +++++++++++++------ .../service/grok_upstream_failure_test.go | 15 +++++++++++++-- .../openai_gateway_chat_completions_raw.go | 3 ++- .../internal/service/openai_gateway_grok.go | 6 ++++-- .../openai_gateway_grok_chat_bridge.go | 3 ++- 6 files changed, 36 insertions(+), 13 deletions(-) diff --git a/backend/internal/service/grok_media.go b/backend/internal/service/grok_media.go index 7c4a12cd0b..3d7ad1fe31 100644 --- a/backend/internal/service/grok_media.go +++ b/backend/internal/service/grok_media.go @@ -1288,7 +1288,7 @@ func (s *OpenAIGatewayService) handleGrokMediaErrorResponse( Detail: upstreamDetail, }) if kind == "failover" { - retryable, retryDelay, retryDeadline := grokSameAccountRetryMetadata(account, resp.StatusCode, body) + retryable, retryDelay, retryDeadline, retryMax := grokSameAccountRetryMetadata(account, resp.StatusCode, body) return nil, &UpstreamFailoverError{ StatusCode: resp.StatusCode, ResponseBody: body, @@ -1297,6 +1297,7 @@ func (s *OpenAIGatewayService) handleGrokMediaErrorResponse( RequestScopedTransient: retryable && resp.StatusCode == http.StatusTooManyRequests, SameAccountRetryDelay: retryDelay, SameAccountRetryDeadline: retryDeadline, + SameAccountRetryMax: retryMax, } } diff --git a/backend/internal/service/grok_upstream_failure.go b/backend/internal/service/grok_upstream_failure.go index 3d6aa05c6e..53d9d5500a 100644 --- a/backend/internal/service/grok_upstream_failure.go +++ b/backend/internal/service/grok_upstream_failure.go @@ -119,7 +119,7 @@ func classifyGrokUpstreamFailure(statusCode int, responseBody []byte, requestedM // deployment while the same request is valid on another account. Treat // these precise decoder/content-shape failures as account compatibility // errors, rather than durable account health failures. - if isGrokCompatibilityError(low, code) { + if isGrokCompatibilityError(statusCode, low, code) { return GrokUpstreamFailureDecision{ Class: GrokFailureCompatibility, Model: model, @@ -406,15 +406,19 @@ func grokRetryableOnSameAccount(account *Account, statusCode int, responseBody [ return account.IsPoolMode() && account.IsPoolModeRetryableStatus(statusCode) } -func grokSameAccountRetryMetadata(account *Account, statusCode int, responseBody []byte) (bool, time.Duration, time.Time) { +func grokSameAccountRetryMetadata(account *Account, statusCode int, responseBody []byte) (bool, time.Duration, time.Time, int) { if !grokRetryableOnSameAccount(account, statusCode, responseBody) { - return false, 0, time.Time{} + return false, 0, time.Time{}, 0 } decision := classifyGrokUpstreamFailure(statusCode, responseBody, "") if decision.Class != GrokFailureModelCapacity { - return true, 0, time.Time{} + return true, 0, time.Time{}, 0 } - return true, 500 * time.Millisecond, time.Now().Add(30 * time.Second) + // The error is reconstructed after every upstream attempt, so a deadline + // stored on the error cannot provide a request-wide window. Cap capacity + // retries explicitly to one replay; this remains effective even when the + // first attempt itself takes longer than the nominal 30-second window. + return true, 500 * time.Millisecond, time.Now().Add(30 * time.Second), 1 } // shouldMarkGrokTeamModelRateLimit controls the process-local sibling-account @@ -430,7 +434,10 @@ func shouldMarkGrokTeamModelRateLimit(statusCode int, responseBody []byte) bool return statusCode == http.StatusTooManyRequests || decision.Class == GrokFailureFreeUsage } -func isGrokCompatibilityError(low, code string) bool { +func isGrokCompatibilityError(statusCode int, low, code string) bool { + if statusCode != http.StatusBadRequest && statusCode != http.StatusUnprocessableEntity { + return false + } combined := strings.ToLower(strings.TrimSpace(low + " " + code)) // Compaction blobs are account/session-bound and frequently fail with 400 // or 422 after a reconnect. Also cover xAI's JSON decoder shape errors. diff --git a/backend/internal/service/grok_upstream_failure_test.go b/backend/internal/service/grok_upstream_failure_test.go index d6e6ec7ace..4f6514cde1 100644 --- a/backend/internal/service/grok_upstream_failure_test.go +++ b/backend/internal/service/grok_upstream_failure_test.go @@ -110,17 +110,19 @@ func TestShouldMarkGrokTeamModelRateLimit_ExcludesCapacity(t *testing.T) { func TestGrokSameAccountRetryMetadata_CapacityDeadline(t *testing.T) { account := &Account{ID: 9107, Platform: PlatformGrok, Type: AccountTypeOAuth} - retryable, delay, deadline := grokSameAccountRetryMetadata(account, http.StatusTooManyRequests, + retryable, delay, deadline, retryMax := grokSameAccountRetryMetadata(account, http.StatusTooManyRequests, []byte(`{"error":{"message":"model capacity exceeded"}}`)) require.True(t, retryable) require.Equal(t, 500*time.Millisecond, delay) require.WithinDuration(t, time.Now().Add(30*time.Second), deadline, 2*time.Second) + require.Equal(t, 1, retryMax) - retryable, delay, deadline = grokSameAccountRetryMetadata(account, http.StatusTooManyRequests, + retryable, delay, deadline, retryMax = grokSameAccountRetryMetadata(account, http.StatusTooManyRequests, []byte(`{"error":{"message":"rate limit exceeded"}}`)) require.False(t, retryable) require.Zero(t, delay) require.True(t, deadline.IsZero()) + require.Zero(t, retryMax) } func TestClassifyGrokUpstreamFailure_ValidationNoCool(t *testing.T) { @@ -151,6 +153,15 @@ func TestClassifyGrokUpstreamFailure_CompatibilityDoesNotCooldown(t *testing.T) } } +func TestClassifyGrokUpstreamFailure_CompatibilityRequiresClientError(t *testing.T) { + body := []byte(`{"error":{"message":"upstream failed while handling the compaction blob"}}`) + for _, status := range []int{http.StatusBadGateway, http.StatusInternalServerError} { + d := classifyGrokUpstreamFailure(status, body, "grok-4.6") + require.NotEqual(t, GrokFailureCompatibility, d.Class) + require.True(t, d.ShouldCooldown) + } +} + func TestClassifyGrokUpstreamFailure_GenericShapeErrorDoesNotFailover(t *testing.T) { d := classifyGrokUpstreamFailure(http.StatusBadRequest, []byte(`{"error":{"message":"data did not match any variant of the untagged enum content"}}`), "grok-4.6") diff --git a/backend/internal/service/openai_gateway_chat_completions_raw.go b/backend/internal/service/openai_gateway_chat_completions_raw.go index 00a7ece52c..1ef181b21b 100644 --- a/backend/internal/service/openai_gateway_chat_completions_raw.go +++ b/backend/internal/service/openai_gateway_chat_completions_raw.go @@ -200,7 +200,7 @@ func (s *OpenAIGatewayService) forwardAsRawChatCompletions( }) s.handleGrokAccountUpstreamError(withGrokTeamRateLimitModel(ctx, upstreamModel), account, resp.StatusCode, resp.Header, respBody) if s.shouldFailoverGrokUpstreamError(resp.StatusCode, respBody) { - retryable, retryDelay, retryDeadline := grokSameAccountRetryMetadata(account, resp.StatusCode, respBody) + retryable, retryDelay, retryDeadline, retryMax := grokSameAccountRetryMetadata(account, resp.StatusCode, respBody) return nil, &UpstreamFailoverError{ StatusCode: resp.StatusCode, ResponseBody: respBody, @@ -209,6 +209,7 @@ func (s *OpenAIGatewayService) forwardAsRawChatCompletions( RequestScopedTransient: retryable && resp.StatusCode == http.StatusTooManyRequests, SameAccountRetryDelay: retryDelay, SameAccountRetryDeadline: retryDeadline, + SameAccountRetryMax: retryMax, } } return s.handleChatCompletionsErrorResponse(resp, c, account, billingModel) diff --git a/backend/internal/service/openai_gateway_grok.go b/backend/internal/service/openai_gateway_grok.go index 6ad03cc253..9a16c6c7a7 100644 --- a/backend/internal/service/openai_gateway_grok.go +++ b/backend/internal/service/openai_gateway_grok.go @@ -173,7 +173,7 @@ func (s *OpenAIGatewayService) forwardGrokResponses( markGrokTeamModelRateLimit(account, upstreamModel, resolveGrokTeamRateLimitUntil(time.Now().Add(grokTeamRateLimitDefaultTTL), time.Now())) } if s.shouldFailoverGrokUpstreamError(resp.StatusCode, respBody) { - retryable, retryDelay, retryDeadline := grokSameAccountRetryMetadata(account, resp.StatusCode, respBody) + retryable, retryDelay, retryDeadline, retryMax := grokSameAccountRetryMetadata(account, resp.StatusCode, respBody) return nil, &UpstreamFailoverError{ StatusCode: resp.StatusCode, ResponseBody: respBody, @@ -182,6 +182,7 @@ func (s *OpenAIGatewayService) forwardGrokResponses( RequestScopedTransient: retryable && resp.StatusCode == http.StatusTooManyRequests, SameAccountRetryDelay: retryDelay, SameAccountRetryDeadline: retryDeadline, + SameAccountRetryMax: retryMax, } } return s.handleErrorResponse(ctx, resp, c, account, patchedBody, upstreamModel) @@ -1186,7 +1187,7 @@ func (s *OpenAIGatewayService) describeGrokComposerImage( }) s.handleGrokAccountUpstreamError(withGrokTeamRateLimitModel(ctx, grokComposerImageBridgeVisionModel), account, resp.StatusCode, resp.Header, respBody) if s.shouldFailoverGrokUpstreamError(resp.StatusCode, respBody) { - retryable, retryDelay, retryDeadline := grokSameAccountRetryMetadata(account, resp.StatusCode, respBody) + retryable, retryDelay, retryDeadline, retryMax := grokSameAccountRetryMetadata(account, resp.StatusCode, respBody) return "", OpenAIUsage{}, &UpstreamFailoverError{ StatusCode: resp.StatusCode, ResponseBody: respBody, @@ -1195,6 +1196,7 @@ func (s *OpenAIGatewayService) describeGrokComposerImage( RequestScopedTransient: retryable && resp.StatusCode == http.StatusTooManyRequests, SameAccountRetryDelay: retryDelay, SameAccountRetryDeadline: retryDeadline, + SameAccountRetryMax: retryMax, } } return "", OpenAIUsage{}, fmt.Errorf("grok composer image bridge upstream error: %s", upstreamMsg) diff --git a/backend/internal/service/openai_gateway_grok_chat_bridge.go b/backend/internal/service/openai_gateway_grok_chat_bridge.go index 84e2c95e72..f04ab5ae43 100644 --- a/backend/internal/service/openai_gateway_grok_chat_bridge.go +++ b/backend/internal/service/openai_gateway_grok_chat_bridge.go @@ -633,7 +633,7 @@ func (s *OpenAIGatewayService) forwardGrokChatCompletionsViaResponses( }) s.handleGrokAccountUpstreamError(withGrokTeamRateLimitModel(ctx, upstreamModel), account, resp.StatusCode, resp.Header, respBody) if s.shouldFailoverGrokUpstreamError(resp.StatusCode, respBody) { - retryable, retryDelay, retryDeadline := grokSameAccountRetryMetadata(account, resp.StatusCode, respBody) + retryable, retryDelay, retryDeadline, retryMax := grokSameAccountRetryMetadata(account, resp.StatusCode, respBody) return nil, &UpstreamFailoverError{ StatusCode: resp.StatusCode, ResponseBody: respBody, @@ -642,6 +642,7 @@ func (s *OpenAIGatewayService) forwardGrokChatCompletionsViaResponses( RequestScopedTransient: retryable && resp.StatusCode == http.StatusTooManyRequests, SameAccountRetryDelay: retryDelay, SameAccountRetryDeadline: retryDeadline, + SameAccountRetryMax: retryMax, } } return s.handleChatCompletionsErrorResponse(resp, c, account, billingModel) From 2e68b10aadf13b94453bcca8c57605d754d4789a Mon Sep 17 00:00:00 2001 From: IanShaw <131567472+IanShaw027@users.noreply.github.com> Date: Thu, 20 Aug 2026 09:12:52 -0700 Subject: [PATCH 073/204] =?UTF-8?q?=E5=AE=8C=E5=96=84=20Grok=20=E5=86=85?= =?UTF-8?q?=E5=AE=B9=E6=8B=92=E7=BB=9D=E8=AE=A1=E8=B4=B9=E4=B8=8E=E5=AA=92?= =?UTF-8?q?=E4=BD=93=E5=85=BC=E5=AE=B9?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- backend/internal/pkg/xai/usage.go | 25 +++ backend/internal/pkg/xai/usage_test.go | 30 ++++ backend/internal/service/grok_media.go | 22 ++- .../service/grok_media_image_geometry.go | 149 ++++++++++++++++++ .../service/grok_media_image_geometry_test.go | 60 +++++++ .../internal/service/grok_upstream_errors.go | 6 +- .../service/grok_upstream_errors_test.go | 33 ++++ .../internal/service/openai_gateway_grok.go | 97 ++++++++++-- .../service/openai_gateway_grok_test.go | 94 ++++++++++- .../openai_gateway_response_handling.go | 13 +- .../service/openai_ws_v2/passthrough_relay.go | 11 ++ .../passthrough_relay_internal_test.go | 23 +++ 12 files changed, 530 insertions(+), 33 deletions(-) create mode 100644 backend/internal/pkg/xai/usage.go create mode 100644 backend/internal/pkg/xai/usage_test.go create mode 100644 backend/internal/service/grok_media_image_geometry.go create mode 100644 backend/internal/service/grok_media_image_geometry_test.go diff --git a/backend/internal/pkg/xai/usage.go b/backend/internal/pkg/xai/usage.go new file mode 100644 index 0000000000..77aa382900 --- /dev/null +++ b/backend/internal/pkg/xai/usage.go @@ -0,0 +1,25 @@ +package xai + +// IncludeIndependentReasoningTokens adds reasoning tokens to billed output +// only when total_tokens proves they are not already folded into output. +// +// Official xAI Chat Completions example: prompt=32, completion=9, +// reasoning=94, total=135. Responses example: input=32, output=9, +// reasoning=110, total=151. OpenAI's canonical completion_tokens already +// includes reasoning and total equals input+output. +func IncludeIndependentReasoningTokens(input, output, total, reasoning int64) int64 { + if input < 0 || output < 0 || reasoning <= 0 || total <= 0 { + return output + } + if total == input+output { + return output + } + gap := total - input - output + if gap <= 0 { + return output + } + if reasoning < gap { + gap = reasoning + } + return output + gap +} diff --git a/backend/internal/pkg/xai/usage_test.go b/backend/internal/pkg/xai/usage_test.go new file mode 100644 index 0000000000..79b8f8639c --- /dev/null +++ b/backend/internal/pkg/xai/usage_test.go @@ -0,0 +1,30 @@ +package xai + +import "testing" + +func TestIncludeIndependentReasoningTokens(t *testing.T) { + t.Parallel() + tests := []struct { + name string + input, output, total, reason int64 + want int64 + }{ + {name: "xAI chat example", input: 32, output: 9, total: 135, reason: 94, want: 103}, + {name: "xAI responses example", input: 32, output: 9, total: 151, reason: 110, want: 119}, + {name: "OpenAI inclusive output", input: 32, output: 103, total: 135, reason: 94, want: 103}, + {name: "gap smaller than reasoning", input: 10, output: 20, total: 33, reason: 5, want: 23}, + {name: "absent total", input: 10, output: 20, total: 0, reason: 5, want: 20}, + {name: "total already complete", input: 10, output: 20, total: 30, reason: 5, want: 20}, + {name: "inconsistent undershoot", input: 10, output: 20, total: 25, reason: 5, want: 20}, + {name: "zero reasoning", input: 10, output: 20, total: 35, reason: 0, want: 20}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + t.Parallel() + got := IncludeIndependentReasoningTokens(tt.input, tt.output, tt.total, tt.reason) + if got != tt.want { + t.Fatalf("got %d, want %d", got, tt.want) + } + }) + } +} diff --git a/backend/internal/service/grok_media.go b/backend/internal/service/grok_media.go index 3d7ad1fe31..85dd1b14ec 100644 --- a/backend/internal/service/grok_media.go +++ b/backend/internal/service/grok_media.go @@ -59,6 +59,8 @@ type GrokMediaRequestInfo struct { N int Size string SizeTier string + AspectRatio string + ImageResolution string Resolution string DurationSeconds int InputImageURLs []string @@ -127,6 +129,8 @@ func ParseGrokMediaRequest(contentType string, body []byte) GrokMediaRequestInfo info.Prompt = strings.TrimSpace(info.Prompt) info.Size = strings.TrimSpace(info.Size) info.SizeTier = NormalizeImageBillingTierOrDefault(info.Size) + info.AspectRatio = strings.TrimSpace(info.AspectRatio) + info.ImageResolution = grokImagineImageResolution(info.ImageResolution) info.Resolution = NormalizeVideoBillingResolutionOrDefault(info.Resolution) info.DurationSeconds = NormalizeVideoBillingDurationSecondsOrDefault(info.DurationSeconds) if info.N <= 0 { @@ -142,7 +146,8 @@ func parseGrokMediaJSONRequest(body []byte, info *GrokMediaRequestInfo) { info.Model = strings.TrimSpace(gjson.GetBytes(body, "model").String()) info.Prompt = strings.TrimSpace(gjson.GetBytes(body, "prompt").String()) info.Size = strings.TrimSpace(gjson.GetBytes(body, "size").String()) - info.Resolution = strings.TrimSpace(gjson.GetBytes(body, "resolution").String()) + info.AspectRatio = strings.TrimSpace(gjson.GetBytes(body, "aspect_ratio").String()) + assignGrokMediaResolution(strings.TrimSpace(gjson.GetBytes(body, "resolution").String()), info) if duration := gjson.GetBytes(body, "duration"); duration.Exists() && duration.Type == gjson.Number { info.DurationSeconds = int(duration.Int()) } @@ -255,8 +260,10 @@ func parseGrokMediaMultipartRequest(contentType string, body []byte, info *GrokM info.Prompt = value case "size": info.Size = value + case "aspect_ratio": + info.AspectRatio = value case "resolution": - info.Resolution = value + assignGrokMediaResolution(value, info) case "duration": if duration, err := strconv.Atoi(value); err == nil { info.DurationSeconds = duration @@ -934,6 +941,12 @@ func prepareGrokMediaForwardBody(endpoint GrokMediaEndpoint, body []byte, conten if info.Size != "" { payload["size"] = info.Size } + if info.ImageResolution != "" { + payload["resolution"] = info.ImageResolution + } + if info.AspectRatio != "" { + payload["aspect_ratio"] = info.AspectRatio + } images := make([]map[string]string, 0, len(info.InputImageURLs)+len(info.Uploads)) for _, imageURL := range info.InputImageURLs { @@ -1106,10 +1119,7 @@ func sanitizeGrokMediaForwardBody(endpoint GrokMediaEndpoint, body []byte, conte } switch endpoint { case GrokMediaEndpointImagesGenerations, GrokMediaEndpointImagesEdits: - if !gjson.GetBytes(body, "size").Exists() { - return body, contentType, nil - } - out, err := sjson.DeleteBytes(body, "size") + out, err := applyGrokImagineImageGeometry(body) if err != nil { return nil, "", fmt.Errorf("sanitize grok media size: %w", err) } diff --git a/backend/internal/service/grok_media_image_geometry.go b/backend/internal/service/grok_media_image_geometry.go new file mode 100644 index 0000000000..51e2a6fd69 --- /dev/null +++ b/backend/internal/service/grok_media_image_geometry.go @@ -0,0 +1,149 @@ +package service + +import ( + "math" + "strconv" + "strings" + + "github.com/tidwall/gjson" + "github.com/tidwall/sjson" +) + +// Official Imagine image geometry: https://docs.x.ai/developers/model-capabilities/images/generation +var grokImagineAspectRatioValues = []struct { + label string + ratio float64 +}{ + {"1:1", 1}, + {"16:9", 16.0 / 9.0}, + {"9:16", 9.0 / 16.0}, + {"4:3", 4.0 / 3.0}, + {"3:4", 3.0 / 4.0}, + {"3:2", 1.5}, + {"2:3", 2.0 / 3.0}, + {"2:1", 2}, + {"1:2", 0.5}, + {"19.5:9", 19.5 / 9.0}, + {"9:19.5", 9.0 / 19.5}, + {"20:9", 20.0 / 9.0}, + {"9:20", 9.0 / 20.0}, +} + +func applyGrokImagineImageGeometry(body []byte) ([]byte, error) { + size := strings.TrimSpace(gjson.GetBytes(body, "size").String()) + resolution := grokImagineImageResolution(gjson.GetBytes(body, "resolution").String()) + aspect := strings.TrimSpace(gjson.GetBytes(body, "aspect_ratio").String()) + out := append([]byte(nil), body...) + + if resolution == "" { + if derived := grokImagineImageResolutionFromSize(size); derived != "" { + next, err := sjson.SetBytes(out, "resolution", derived) + if err != nil { + return nil, err + } + out = next + } + } else if gjson.GetBytes(body, "resolution").String() != resolution { + next, err := sjson.SetBytes(out, "resolution", resolution) + if err != nil { + return nil, err + } + out = next + } + + if aspect == "" { + if derived := grokImagineAspectRatioFromSize(size); derived != "" { + next, err := sjson.SetBytes(out, "aspect_ratio", derived) + if err != nil { + return nil, err + } + out = next + } + } + + if !gjson.GetBytes(out, "size").Exists() { + return out, nil + } + return sjson.DeleteBytes(out, "size") +} + +func assignGrokMediaResolution(value string, info *GrokMediaRequestInfo) { + if info == nil { + return + } + value = strings.TrimSpace(value) + if value == "" { + return + } + if img := grokImagineImageResolution(value); img != "" { + info.ImageResolution = img + return + } + info.Resolution = value +} + +func grokImagineImageResolution(value string) string { + switch strings.ToLower(strings.TrimSpace(value)) { + case "1k": + return "1k" + case "2k": + return "2k" + default: + return "" + } +} + +func grokImagineImageResolutionFromSize(size string) string { + if explicit := grokImagineImageResolution(size); explicit != "" { + return explicit + } + tier, ok := ClassifyImageBillingTier(size) + if !ok { + return "" + } + if tier == ImageBillingSize1K { + return "1k" + } + return "2k" +} + +func grokImagineAspectRatioFromSize(size string) string { + width, height, ok := parseImageBillingDimensions(strings.TrimSpace(size)) + if !ok || width <= 0 || height <= 0 { + return "" + } + div := grokImagineGCD(width, height) + exact := strconv.Itoa(width/div) + ":" + strconv.Itoa(height/div) + for _, candidate := range grokImagineAspectRatioValues { + if candidate.label == exact { + return exact + } + } + ratio := float64(width) / float64(height) + bestLabel := "" + bestDelta := math.MaxFloat64 + for _, candidate := range grokImagineAspectRatioValues { + delta := math.Abs(ratio - candidate.ratio) + if delta < bestDelta { + bestDelta = delta + bestLabel = candidate.label + } + } + return bestLabel +} + +func grokImagineGCD(a, b int) int { + if a < 0 { + a = -a + } + if b < 0 { + b = -b + } + for b != 0 { + a, b = b, a%b + } + if a == 0 { + return 1 + } + return a +} diff --git a/backend/internal/service/grok_media_image_geometry_test.go b/backend/internal/service/grok_media_image_geometry_test.go new file mode 100644 index 0000000000..cac26c3bd1 --- /dev/null +++ b/backend/internal/service/grok_media_image_geometry_test.go @@ -0,0 +1,60 @@ +package service + +import ( + "testing" + + "github.com/stretchr/testify/require" + "github.com/tidwall/gjson" +) + +func TestApplyGrokImagineImageGeometryMapsOpenAISize(t *testing.T) { + t.Parallel() + + out, err := applyGrokImagineImageGeometry([]byte(`{"model":"grok-imagine-image-2.0","prompt":"hi","size":"1152x1536"}`)) + require.NoError(t, err) + require.False(t, gjson.GetBytes(out, "size").Exists()) + require.Equal(t, "2k", gjson.GetBytes(out, "resolution").String()) + require.Equal(t, "3:4", gjson.GetBytes(out, "aspect_ratio").String()) +} + +func TestApplyGrokImagineImageGeometryKeepsClientGeometry(t *testing.T) { + t.Parallel() + + out, err := applyGrokImagineImageGeometry([]byte(`{"size":"1024x1024","resolution":"2K","aspect_ratio":"16:9"}`)) + require.NoError(t, err) + require.False(t, gjson.GetBytes(out, "size").Exists()) + require.Equal(t, "2k", gjson.GetBytes(out, "resolution").String()) + require.Equal(t, "16:9", gjson.GetBytes(out, "aspect_ratio").String()) +} + +func TestSanitizeGrokMediaForwardBodyConvertsImageSize(t *testing.T) { + t.Parallel() + + out, contentType, err := sanitizeGrokMediaForwardBody( + GrokMediaEndpointImagesGenerations, + []byte(`{"model":"grok-imagine-image","prompt":"hi","size":"1024x1024"}`), + "application/json", + ) + require.NoError(t, err) + require.Equal(t, "application/json", contentType) + require.False(t, gjson.GetBytes(out, "size").Exists()) + require.Equal(t, "1k", gjson.GetBytes(out, "resolution").String()) + require.Equal(t, "1:1", gjson.GetBytes(out, "aspect_ratio").String()) +} + +func TestParseGrokMediaRequestKeepsImageResolutionOutOfVideoNormalize(t *testing.T) { + t.Parallel() + + info := ParseGrokMediaRequest("application/json", []byte(`{"model":"grok-imagine-image-2.0","resolution":"2K","aspect_ratio":"16:9"}`)) + require.Equal(t, "2k", info.ImageResolution) + require.Equal(t, "16:9", info.AspectRatio) + require.Equal(t, VideoBillingResolution480P, info.Resolution) +} + +func TestGrokImagineAspectRatioFromSize(t *testing.T) { + t.Parallel() + require.Equal(t, "1:1", grokImagineAspectRatioFromSize("1024x1024")) + require.Equal(t, "3:4", grokImagineAspectRatioFromSize("1152x1536")) + require.Equal(t, "4:3", grokImagineAspectRatioFromSize("1536x1152")) + require.Equal(t, "16:9", grokImagineAspectRatioFromSize("1792x1024")) +} diff --git a/backend/internal/service/grok_upstream_errors.go b/backend/internal/service/grok_upstream_errors.go index 1d1bddc6d6..db204fc70b 100644 --- a/backend/internal/service/grok_upstream_errors.go +++ b/backend/internal/service/grok_upstream_errors.go @@ -114,8 +114,9 @@ func isGrokAccountAccessCode(value string) bool { "subscription_required", "entitlement_required", "not_entitled", - "plan_required", - "permission_denied": + "plan_required": + // permission-denied is omitted: xAI reuses it for both entitlement + // refusals and request-scoped safety blocks, so the message decides. return true default: return false @@ -171,6 +172,7 @@ func grokContentPolicyMessage(value string) bool { "prompt violates policy", "input violates content policy", "input violates policy", + "violates usage guidelines", } { if strings.Contains(lower, phrase) { return true diff --git a/backend/internal/service/grok_upstream_errors_test.go b/backend/internal/service/grok_upstream_errors_test.go index 0dee756b72..3bd5ad3e73 100644 --- a/backend/internal/service/grok_upstream_errors_test.go +++ b/backend/internal/service/grok_upstream_errors_test.go @@ -83,6 +83,24 @@ func TestIsGrokContentPolicyRejection(t *testing.T) { body: `{"error":{"code":"policy_violation","message":"request blocked by policy"}}`, want: true, }, + { + name: "permission-denied usage guidelines is request scoped", + status: http.StatusForbidden, + body: `{"code":"permission-denied","error":"Content violates usage guidelines. "}`, + want: true, + }, + { + name: "permission-denied entitlement stays on the account path", + status: http.StatusForbidden, + body: `{"code":"permission-denied","error":"Access to the chat endpoint is denied"}`, + want: false, + }, + { + name: "structured account code overrides usage guidelines phrase", + status: http.StatusForbidden, + body: `{"error":{"code":"account_suspended","message":"Content violates usage guidelines."}}`, + want: false, + }, { name: "wrong status", status: http.StatusBadRequest, @@ -279,6 +297,21 @@ func TestGrokContentPolicySSEErrorDoesNotMutateOrFailover(t *testing.T) { require.False(t, svc.isOpenAIAccountRuntimeBlocked(account)) } +func TestGrokPermissionDeniedContentRefusalDoesNotMutateOrFailover(t *testing.T) { + repo := &grokQuotaAccountRepo{} + svc := &OpenAIGatewayService{accountRepo: repo} + account := &Account{ID: 4785, Platform: PlatformGrok, Type: AccountTypeOAuth} + body := []byte(`{"code":"permission-denied","error":"Content violates usage guidelines. "}`) + + svc.handleGrokAccountUpstreamError(context.Background(), account, http.StatusForbidden, nil, body) + + require.Zero(t, repo.tempUnschedCalls) + require.Zero(t, repo.rateLimitedCalls) + require.Zero(t, repo.updateCalls) + require.False(t, svc.isOpenAIAccountRuntimeBlocked(account)) + require.False(t, svc.shouldFailoverGrokUpstreamError(http.StatusForbidden, body)) +} + func TestHandleGrokAccountUpstreamErrorEntitlement403KeepsDefaultCooldown(t *testing.T) { repo := &grokQuotaAccountRepo{} svc := &OpenAIGatewayService{accountRepo: repo} diff --git a/backend/internal/service/openai_gateway_grok.go b/backend/internal/service/openai_gateway_grok.go index 9a16c6c7a7..cca3b28ab3 100644 --- a/backend/internal/service/openai_gateway_grok.go +++ b/backend/internal/service/openai_gateway_grok.go @@ -856,33 +856,98 @@ func grokResponsesToolDedupKey(tool gjson.Result) string { return "json:" + normalizeCompatSeedJSON(json.RawMessage(tool.Raw)) } -// sanitizeGrokReasoningNullContent 删除 reasoning 项中的 "content": null。 -// xAI 的 untagged enum 反序列化器拒收该字段,返回 422。 +// sanitizeGrokReasoningNullContent drops explicit JSON nulls from Responses +// input items. xAI's untagged ModelInput decoder 422s on those fields. +// Compaction items stay unmodified per the compact contract. func sanitizeGrokReasoningNullContent(body []byte) ([]byte, error) { input := gjson.GetBytes(body, "input") - if !input.Exists() || !input.IsArray() { + if !input.Exists() || (!input.IsArray() && !input.IsObject()) { return body, nil } - items := input.Array() + var decoded map[string]any + decoder := json.NewDecoder(bytes.NewReader(body)) + decoder.UseNumber() + if err := decoder.Decode(&decoded); err != nil { + return body, nil + } + rawInput, ok := decoded["input"] + if !ok { + return body, nil + } + cleaned, changed := stripExplicitNullsFromGrokInput(rawInput) + if !changed { + return body, nil + } + decoded["input"] = cleaned + out, err := marshalOpenAIUpstreamJSON(decoded) + if err != nil { + return nil, err + } + return out, nil +} + +func stripExplicitNullsFromGrokInput(value any) (any, bool) { + switch node := value.(type) { + case []any: + changed := false + for i, item := range node { + itemMap, ok := item.(map[string]any) + if !ok { + next, childChanged := stripExplicitNullsFromGrokInput(item) + if childChanged { + node[i] = next + changed = true + } + continue + } + if isOpenAICompactionType(stringValue(itemMap["type"])) { + continue + } + next, childChanged := stripExplicitNullsFromJSONObject(itemMap) + if childChanged { + node[i] = next + changed = true + } + } + return node, changed + case map[string]any: + if isOpenAICompactionType(stringValue(node["type"])) { + return node, false + } + return stripExplicitNullsFromJSONObject(node) + default: + return value, false + } +} + +func stripExplicitNullsFromJSONObject(node map[string]any) (map[string]any, bool) { + if node == nil { + return node, false + } changed := false - for i := len(items) - 1; i >= 0; i-- { - item := items[i] - if strings.TrimSpace(item.Get("type").String()) != "reasoning" { + for key, child := range node { + if child == nil { + delete(node, key) + changed = true continue } - contentResult := item.Get("content") - if contentResult.Exists() && contentResult.Type == gjson.Null { - var err error - body, err = sjson.DeleteBytes(body, fmt.Sprintf("input.%d.content", i)) - if err != nil { - return nil, err + switch typed := child.(type) { + case map[string]any: + next, childChanged := stripExplicitNullsFromJSONObject(typed) + if childChanged { + node[key] = next + changed = true + } + case []any: + next, childChanged := stripExplicitNullsFromGrokInput(typed) + if childChanged { + node[key] = next + changed = true } - changed = true } } - _ = changed - return body, nil + return node, changed } var grokResponsesSupportedToolTypes = map[string]struct{}{ diff --git a/backend/internal/service/openai_gateway_grok_test.go b/backend/internal/service/openai_gateway_grok_test.go index 92f9901142..146b310176 100644 --- a/backend/internal/service/openai_gateway_grok_test.go +++ b/backend/internal/service/openai_gateway_grok_test.go @@ -1177,7 +1177,7 @@ func TestForwardGrokMediaAppliesAccountModelMappingAfterEndpointNormalization(t modelMapping: map[string]any{"grok-imagine-image-quality": "vendor-image-model"}, wantRequestModel: "grok-imagine-image-quality", wantUpstream: "vendor-image-model", - wantBody: `{"model":"vendor-image-model","prompt":"draw"}`, + wantBody: `{"model":"vendor-image-model","prompt":"draw","resolution":"1k","aspect_ratio":"1:1"}`, responseBody: `{"data":[{"url":"https://images.test/mapped.png"}]}`, }, { @@ -1300,7 +1300,8 @@ func TestForwardGrokMediaImagesGenerationStripsUnsupportedSize(t *testing.T) { result, err := svc.ForwardGrokMedia(context.Background(), c, account, GrokMediaEndpointImagesGenerations, "", body, "application/json") require.NoError(t, err) - require.JSONEq(t, `{"model":"grok-imagine-image","prompt":"draw a cat"}`, string(upstream.lastBody)) + require.JSONEq(t, `{"model":"grok-imagine-image","prompt":"draw a cat","resolution":"1k","aspect_ratio":"1:1"}`, string(upstream.lastBody)) + require.False(t, gjson.GetBytes(upstream.lastBody, "size").Exists()) require.Equal(t, ImageBillingSize1K, result.ImageSize) require.Equal(t, "1024x1024", result.ImageInputSize) } @@ -1361,6 +1362,58 @@ func TestForwardGrokMediaImagesEditMultipartConvertsToJSON(t *testing.T) { require.Equal(t, "vendor-image-edit", result.UpstreamModel) } +func TestForwardGrokMediaImagesEditMultipartPreservesExplicitGeometry(t *testing.T) { + t.Setenv(xai.EnvAllowUnsafeURLOverrides, "true") + gin.SetMode(gin.TestMode) + + var buf bytes.Buffer + writer := multipart.NewWriter(&buf) + require.NoError(t, writer.WriteField("model", "grok-imagine-edit")) + require.NoError(t, writer.WriteField("prompt", "edit this private image")) + require.NoError(t, writer.WriteField("size", "1024x1024")) + require.NoError(t, writer.WriteField("resolution", "2k")) + require.NoError(t, writer.WriteField("aspect_ratio", "16:9")) + partHeader := textproto.MIMEHeader{} + partHeader.Set("Content-Disposition", `form-data; name="image"; filename="input.png"`) + partHeader.Set("Content-Type", "image/png") + part, err := writer.CreatePart(partHeader) + require.NoError(t, err) + _, err = part.Write([]byte{0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a}) + require.NoError(t, err) + require.NoError(t, writer.Close()) + + recorder := httptest.NewRecorder() + c, _ := gin.CreateTestContext(recorder) + c.Request = httptest.NewRequest(http.MethodPost, "/v1/images/edits", bytes.NewReader(buf.Bytes())) + c.Request.Header.Set("Content-Type", writer.FormDataContentType()) + + account := &Account{ + ID: 67, + Name: "grok", + Platform: PlatformGrok, + Type: AccountTypeAPIKey, + Concurrency: 1, + Credentials: map[string]any{ + "api_key": "api-key", + "base_url": "https://xai.test/v1", + }, + } + upstream := &httpUpstreamRecorder{resp: &http.Response{ + StatusCode: http.StatusOK, + Header: http.Header{"Content-Type": []string{"application/json"}}, + Body: io.NopCloser(strings.NewReader(`{"data":[{"url":"https://images.test/edited.png"}]}`)), + }} + svc := &OpenAIGatewayService{httpUpstream: upstream} + + result, err := svc.ForwardGrokMedia(context.Background(), c, account, GrokMediaEndpointImagesEdits, "", buf.Bytes(), writer.FormDataContentType()) + require.NoError(t, err) + require.False(t, gjson.GetBytes(upstream.lastBody, "size").Exists()) + require.Equal(t, "2k", gjson.GetBytes(upstream.lastBody, "resolution").String()) + require.Equal(t, "16:9", gjson.GetBytes(upstream.lastBody, "aspect_ratio").String()) + require.Equal(t, ImageBillingSize1K, result.ImageSize) + require.Equal(t, "1024x1024", result.ImageInputSize) +} + func TestForwardGrokMediaVideoGenerationReturnsUsageAndResponseID(t *testing.T) { t.Setenv(xai.EnvAllowUnsafeURLOverrides, "true") gin.SetMode(gin.TestMode) @@ -3446,6 +3499,43 @@ func TestPatchGrokResponsesBody_StripsReasoningContentNull(t *testing.T) { require.False(t, reasoning.Get("content").Exists(), "content: null should be stripped") } +func TestPatchGrokResponsesBody_StripsNestedInputNulls(t *testing.T) { + t.Parallel() + + body := []byte(`{ + "model": "grok-4.6", + "input": [ + {"type":"message","role":"user","content":[{"type":"input_text","text":"hi","logprobs":null}]} + ] + }`) + patched, err := patchGrokResponsesBody(body, "grok-4.6") + require.NoError(t, err) + require.False(t, gjson.GetBytes(patched, "input.0.content.0.logprobs").Exists()) + require.Equal(t, "hi", gjson.GetBytes(patched, "input.0.content.0.text").String()) +} + +func TestStripExplicitNullsFromGrokInputSkipsCompaction(t *testing.T) { + t.Parallel() + + input := []any{ + map[string]any{"type": "message", "role": "user", "content": []any{map[string]any{"type": "input_text", "text": "hi", "logprobs": nil}}}, + map[string]any{"type": "compaction", "id": "cmp_1", "encrypted_content": "blob", "status": nil}, + } + out, changed := stripExplicitNullsFromGrokInput(input) + require.True(t, changed) + items, ok := out.([]any) + require.True(t, ok) + require.Len(t, items, 2) + msg := items[0].(map[string]any) + content := msg["content"].([]any)[0].(map[string]any) + _, hasLogprobs := content["logprobs"] + require.False(t, hasLogprobs) + compaction := items[1].(map[string]any) + require.Equal(t, "blob", compaction["encrypted_content"]) + _, hasStatus := compaction["status"] + require.True(t, hasStatus, "compaction items must stay unmodified") +} + func TestPatchGrokResponsesBody_KeepsReasoningContentNonNull(t *testing.T) { t.Parallel() diff --git a/backend/internal/service/openai_gateway_response_handling.go b/backend/internal/service/openai_gateway_response_handling.go index 45a8e06de6..3c5a64e5fe 100644 --- a/backend/internal/service/openai_gateway_response_handling.go +++ b/backend/internal/service/openai_gateway_response_handling.go @@ -15,6 +15,7 @@ import ( "github.com/Wei-Shaw/sub2api/internal/pkg/apicompat" "github.com/Wei-Shaw/sub2api/internal/pkg/logger" + "github.com/Wei-Shaw/sub2api/internal/pkg/xai" "github.com/Wei-Shaw/sub2api/internal/util/responseheaders" "github.com/gin-gonic/gin" "github.com/tidwall/gjson" @@ -1185,18 +1186,16 @@ func openAIUsageFromGJSON(value gjson.Result) (OpenAIUsage, bool) { if outputTokens == 0 { outputTokens = value.Get("completion_tokens").Int() } - // xAI may report reasoning_tokens separately from visible output tokens. - // Only add it when total_tokens proves it is an independent component; - // OpenAI's canonical completion_tokens already includes reasoning details. + // xAI reports visible output separately from reasoning_tokens; OpenAI + // folds reasoning into completion/output. Use total_tokens to tell them apart. reasoningTokens := max(int(firstPositiveGJSONInt( value.Get("completion_tokens_details.reasoning_tokens"), value.Get("output_tokens_details.reasoning_tokens"), )), 0) if reasoningTokens > 0 { - totalTokens := value.Get("total_tokens").Int() - if totalTokens > 0 && totalTokens == inputTokens+outputTokens+int64(reasoningTokens) { - outputTokens += int64(reasoningTokens) - } + outputTokens = xai.IncludeIndependentReasoningTokens( + inputTokens, outputTokens, value.Get("total_tokens").Int(), int64(reasoningTokens), + ) } cacheReadTokens := openAICacheReadTokensFromUsage(value) cacheCreationTokens := openAICacheCreationTokensFromUsage(value) diff --git a/backend/internal/service/openai_ws_v2/passthrough_relay.go b/backend/internal/service/openai_ws_v2/passthrough_relay.go index abc94e8f1c..2cad27d88f 100644 --- a/backend/internal/service/openai_ws_v2/passthrough_relay.go +++ b/backend/internal/service/openai_ws_v2/passthrough_relay.go @@ -13,6 +13,8 @@ import ( coderws "github.com/coder/websocket" "github.com/tidwall/gjson" + + "github.com/Wei-Shaw/sub2api/internal/pkg/xai" ) type FrameConn interface { @@ -948,6 +950,15 @@ func parseUsageAndAccumulate( // 解析失败时不做部分字段累加,避免计费 usage 出现“半有效”状态。 return Usage{} } + reasoningTokens := usageResult.Get("output_tokens_details.reasoning_tokens").Int() + if reasoningTokens == 0 { + reasoningTokens = usageResult.Get("completion_tokens_details.reasoning_tokens").Int() + } + if reasoningTokens > 0 { + outputTokens = int(xai.IncludeIndependentReasoningTokens( + int64(inputTokens), int64(outputTokens), usageResult.Get("total_tokens").Int(), reasoningTokens, + )) + } parsedUsage := Usage{ InputTokens: inputTokens, OutputTokens: outputTokens, diff --git a/backend/internal/service/openai_ws_v2/passthrough_relay_internal_test.go b/backend/internal/service/openai_ws_v2/passthrough_relay_internal_test.go index ebb2394a12..51f1afb6ee 100644 --- a/backend/internal/service/openai_ws_v2/passthrough_relay_internal_test.go +++ b/backend/internal/service/openai_ws_v2/passthrough_relay_internal_test.go @@ -324,6 +324,29 @@ func TestParseUsageAndEnrichCoverage(t *testing.T) { enrichResult(nil, state, 0) } +func TestParseUsageAndAccumulateIncludesIndependentReasoningTokens(t *testing.T) { + t.Parallel() + + state := &relayState{} + got := parseUsageAndAccumulate( + state, + []byte(`{"type":"response.completed","response":{"usage":{"input_tokens":32,"output_tokens":9,"total_tokens":151,"output_tokens_details":{"reasoning_tokens":110}}}}`), + "response.completed", + nil, + ) + require.Equal(t, 32, got.InputTokens) + require.Equal(t, 119, got.OutputTokens) + + state = &relayState{} + got = parseUsageAndAccumulate( + state, + []byte(`{"type":"response.completed","response":{"usage":{"input_tokens":32,"output_tokens":119,"total_tokens":151,"output_tokens_details":{"reasoning_tokens":110}}}}`), + "response.completed", + nil, + ) + require.Equal(t, 119, got.OutputTokens, "inclusive Responses output must not double-count reasoning") +} + func TestParseUsageAndAccumulateAcceptsChatUsageAliases(t *testing.T) { t.Parallel() From 1bff06ea502290ac1b8f6702d1ea5a85cc90ca5f Mon Sep 17 00:00:00 2001 From: IanShaw <131567472+IanShaw027@users.noreply.github.com> Date: Thu, 20 Aug 2026 09:50:23 -0700 Subject: [PATCH 074/204] =?UTF-8?q?=E4=BF=AE=E5=A4=8D=20Grok=20Realtime=20?= =?UTF-8?q?=E5=85=B3=E9=97=AD=E6=A3=80=E6=9F=A5=E4=B8=8E=20rollup=20?= =?UTF-8?q?=E6=97=B6=E5=8C=BA=E6=96=AD=E8=A8=80?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit golangci 要求检查 Realtime 上游 Close 返回值,并删除已无调用的 heavy-model 冷却函数。分组日汇总集成测试在 UTC 晚上跨上海零点时会把水位写成 UTC 日期,将会话时区钉到 Asia/Shanghai。 --- backend/internal/handler/grok_audio.go | 2 +- .../group_usage_rollup_trigger_integration_test.go | 7 +++++++ backend/internal/service/grok_audio.go | 2 +- backend/internal/service/openai_gateway_grok.go | 5 ----- 4 files changed, 9 insertions(+), 7 deletions(-) diff --git a/backend/internal/handler/grok_audio.go b/backend/internal/handler/grok_audio.go index c95b5ce559..28ae40a39b 100644 --- a/backend/internal/handler/grok_audio.go +++ b/backend/internal/handler/grok_audio.go @@ -121,7 +121,7 @@ func (h *OpenAIGatewayHandler) GrokRealtime(c *gin.Context) { return } defer release() - defer upstream.Close() + defer func() { _ = upstream.Close() }() conn, err := coderws.Accept(c.Writer, c.Request, &coderws.AcceptOptions{CompressionMode: coderws.CompressionContextTakeover}) if err != nil { diff --git a/backend/internal/repository/group_usage_rollup_trigger_integration_test.go b/backend/internal/repository/group_usage_rollup_trigger_integration_test.go index db182be495..32016e3c0a 100644 --- a/backend/internal/repository/group_usage_rollup_trigger_integration_test.go +++ b/backend/internal/repository/group_usage_rollup_trigger_integration_test.go @@ -151,6 +151,7 @@ func TestGroupUsageRollupTriggerSerializesInsertTransactionAcrossMidnight(t *tes insertTx := beginGroupUsageRollupTriggerTestTx(t, ctx, schema) defer func() { _ = insertTx.Rollback() }() + require.NoError(t, setGroupUsageRollupTriggerTimeZone(ctx, insertTx, "Asia/Shanghai")) var insertBackendPID int require.NoError(t, insertTx.QueryRowContext(ctx, "SELECT pg_backend_pid()").Scan(&insertBackendPID)) @@ -206,6 +207,7 @@ func TestGroupUsageRollupTriggerKeepsWatermarkForTodayInsert(t *testing.T) { tx := beginGroupUsageRollupTriggerTestTx(t, ctx, schema) defer func() { _ = tx.Rollback() }() + require.NoError(t, setGroupUsageRollupTriggerTimeZone(ctx, tx, "Asia/Shanghai")) _, err := tx.ExecContext(ctx, ` INSERT INTO groups (id) VALUES (10); INSERT INTO users (id) VALUES (1); @@ -476,6 +478,11 @@ func setGroupUsageRollupTriggerSearchPath(ctx context.Context, tx *sql.Tx, quote return err } +func setGroupUsageRollupTriggerTimeZone(ctx context.Context, tx *sql.Tx, name string) error { + _, err := tx.ExecContext(ctx, "SET LOCAL TIME ZONE "+pq.QuoteLiteral(name)) + return err +} + func waitForGroupUsageRollupStateLock( ctx context.Context, backendPID int, diff --git a/backend/internal/service/grok_audio.go b/backend/internal/service/grok_audio.go index 771cae09f4..0cd138cad5 100644 --- a/backend/internal/service/grok_audio.go +++ b/backend/internal/service/grok_audio.go @@ -133,7 +133,7 @@ func (s *OpenAIGatewayService) ProxyGrokRealtime(ctx context.Context, c *gin.Con if err != nil { return false, err } - defer upstream.Close() + defer func() { _ = upstream.Close() }() return s.ProxyGrokRealtimeConn(ctx, c, client, upstream) } diff --git a/backend/internal/service/openai_gateway_grok.go b/backend/internal/service/openai_gateway_grok.go index cca3b28ab3..7fed94eb13 100644 --- a/backend/internal/service/openai_gateway_grok.go +++ b/backend/internal/service/openai_gateway_grok.go @@ -1809,11 +1809,6 @@ func grokRequestedModelFromCtx(ctx context.Context) string { return strings.TrimSpace(model) } -func isGrokHeavyTransientModel(requestedModel string) bool { - model := strings.ToLower(strings.TrimSpace(xai.ResolveGrokTextResponsesModelID(requestedModel))) - return strings.Contains(model, "multi-agent") -} - func persistGrokTransientModelCooldown(account *Account, decision GrokUpstreamFailureDecision) bool { if account == nil { return false From f98a056f75e93c81e3ab1cc8623db9e17b3dc432 Mon Sep 17 00:00:00 2001 From: Hakunm <275509506+Hakunm@users.noreply.github.com> Date: Fri, 21 Aug 2026 02:33:00 +0800 Subject: [PATCH 075/204] fix(gemini): constrain Google One model catalog --- .../internal/handler/admin/account_handler.go | 8 +++- .../account_handler_available_models_test.go | 36 +++++++++++++++ backend/internal/pkg/geminicli/models.go | 19 ++++++++ backend/internal/pkg/geminicli/models_test.go | 21 +++++++++ backend/internal/service/account.go | 13 ++++++ .../internal/service/account_wildcard_test.go | 46 +++++++++++++++++++ 6 files changed, 142 insertions(+), 1 deletion(-) diff --git a/backend/internal/handler/admin/account_handler.go b/backend/internal/handler/admin/account_handler.go index 465c6a7816..93067da278 100644 --- a/backend/internal/handler/admin/account_handler.go +++ b/backend/internal/handler/admin/account_handler.go @@ -2614,8 +2614,14 @@ func (h *AccountHandler) GetAvailableModels(c *gin.Context) { // Handle Gemini accounts if account.IsGemini() { - // For OAuth accounts: return default Gemini models + // Consumer Google One OAuth still uses the legacy Gemini CLI / Code + // Assist channel. Do not advertise newer 3.x or image models that the + // channel cannot serve. if account.IsOAuth() { + if account.IsGeminiGoogleOne() { + response.Success(c, geminicli.GoogleOneModels) + return + } response.Success(c, geminicli.DefaultModels) return } diff --git a/backend/internal/handler/admin/account_handler_available_models_test.go b/backend/internal/handler/admin/account_handler_available_models_test.go index 880cb8c3ea..ef2f65d4e3 100644 --- a/backend/internal/handler/admin/account_handler_available_models_test.go +++ b/backend/internal/handler/admin/account_handler_available_models_test.go @@ -287,6 +287,42 @@ func TestAccountHandlerGetAvailableModels_OpenAISparkShadowReturnsMappingModels( }, ids, "影子可用模型由 model_mapping 派生(非写死)") } +func TestAccountHandlerGetAvailableModels_GeminiGoogleOneUsesConservativeCatalog(t *testing.T) { + svc := &availableModelsAdminService{ + stubAdminService: newStubAdminService(), + account: service.Account{ + ID: 45, + Name: "google-one", + Platform: service.PlatformGemini, + Type: service.AccountTypeOAuth, + Status: service.StatusActive, + Credentials: map[string]any{ + "oauth_type": "google_one", + }, + }, + } + router := setupAvailableModelsRouter(svc) + + rec := httptest.NewRecorder() + req := httptest.NewRequest(http.MethodGet, "/api/v1/admin/accounts/45/models", nil) + router.ServeHTTP(rec, req) + + require.Equal(t, http.StatusOK, rec.Code) + var resp struct { + Data []struct { + ID string `json:"id"` + } `json:"data"` + } + require.NoError(t, json.Unmarshal(rec.Body.Bytes(), &resp)) + ids := make([]string, 0, len(resp.Data)) + for _, model := range resp.Data { + ids = append(ids, model.ID) + } + require.ElementsMatch(t, []string{"gemini-2.0-flash", "gemini-2.5-flash", "gemini-2.5-pro"}, ids) + require.NotContains(t, ids, "gemini-3.5-flash") + require.NotContains(t, ids, "gemini-2.5-flash-image") +} + func TestAccountHandlerSyncUpstreamModels_ConfigErrorReturnsBadRequest(t *testing.T) { svc := &availableModelsAdminService{ stubAdminService: newStubAdminService(), diff --git a/backend/internal/pkg/geminicli/models.go b/backend/internal/pkg/geminicli/models.go index bbd9a6c464..cc9cbc80b2 100644 --- a/backend/internal/pkg/geminicli/models.go +++ b/backend/internal/pkg/geminicli/models.go @@ -22,5 +22,24 @@ var DefaultModels = []Model{ {ID: "gemini-3.1-flash-image", Type: "model", DisplayName: "Gemini 3.1 Flash Image", CreatedAt: ""}, } +// GoogleOneModels is the conservative model set exposed for legacy Google One +// OAuth accounts. Newer subscription models are served through Antigravity +// OAuth rather than the retired consumer Gemini CLI / Code Assist channel. +var GoogleOneModels = []Model{ + {ID: "gemini-2.5-flash", Type: "model", DisplayName: "Gemini 2.5 Flash", CreatedAt: ""}, + {ID: "gemini-2.5-pro", Type: "model", DisplayName: "Gemini 2.5 Pro", CreatedAt: ""}, + {ID: "gemini-2.0-flash", Type: "model", DisplayName: "Gemini 2.0 Flash", CreatedAt: ""}, +} + +// GoogleOneModelMapping returns a new whitelist map for each account so callers +// cannot mutate the package-level catalog. +func GoogleOneModelMapping() map[string]string { + mapping := make(map[string]string, len(GoogleOneModels)) + for _, model := range GoogleOneModels { + mapping[model.ID] = model.ID + } + return mapping +} + // DefaultTestModel is the default model to preselect in test flows. const DefaultTestModel = "gemini-2.0-flash" diff --git a/backend/internal/pkg/geminicli/models_test.go b/backend/internal/pkg/geminicli/models_test.go index c1884e2e10..e0cb57941f 100644 --- a/backend/internal/pkg/geminicli/models_test.go +++ b/backend/internal/pkg/geminicli/models_test.go @@ -21,3 +21,24 @@ func TestDefaultModels_ContainsImageModels(t *testing.T) { } } } + +func TestGoogleOneModels_ExcludeUnsupportedNewAndImageModels(t *testing.T) { + t.Parallel() + + mapping := GoogleOneModelMapping() + for _, id := range []string{"gemini-2.0-flash", "gemini-2.5-flash", "gemini-2.5-pro"} { + if mapping[id] != id { + t.Fatalf("expected Google One model %q to map to itself", id) + } + } + for _, id := range []string{"gemini-2.5-flash-image", "gemini-3.1-flash-image", "gemini-3.5-flash"} { + if _, ok := mapping[id]; ok { + t.Fatalf("did not expect unsupported Google One model %q", id) + } + } + + mapping["gemini-2.5-flash"] = "mutated" + if GoogleOneModelMapping()["gemini-2.5-flash"] != "gemini-2.5-flash" { + t.Fatal("GoogleOneModelMapping must return a defensive copy") + } +} diff --git a/backend/internal/service/account.go b/backend/internal/service/account.go index 20d4ec5823..4ee1a514f9 100644 --- a/backend/internal/service/account.go +++ b/backend/internal/service/account.go @@ -15,6 +15,7 @@ import ( "github.com/Wei-Shaw/sub2api/internal/config" "github.com/Wei-Shaw/sub2api/internal/domain" + "github.com/Wei-Shaw/sub2api/internal/pkg/geminicli" "github.com/Wei-Shaw/sub2api/internal/pkg/openai_compat" "github.com/Wei-Shaw/sub2api/internal/pkg/xai" ) @@ -324,6 +325,12 @@ func (a *Account) IsGeminiCodeAssist() bool { return oauthType == "code_assist" } +// IsGeminiGoogleOne reports whether this account uses the legacy consumer +// Gemini CLI / Code Assist OAuth channel. +func (a *Account) IsGeminiGoogleOne() bool { + return a.Platform == PlatformGemini && a.Type == AccountTypeOAuth && a.GeminiOAuthType() == "google_one" +} + func (a *Account) CanGetUsage() bool { return a.Type == AccountTypeOAuth } @@ -625,6 +632,9 @@ func (a *Account) resolveModelMapping(rawMapping map[string]any) map[string]stri return nil } if len(rawMapping) == 0 { + if a.IsGeminiGoogleOne() { + return geminicli.GoogleOneModelMapping() + } // Antigravity 平台使用默认映射 if a.Platform == domain.PlatformAntigravity { return domain.DefaultAntigravityModelMapping @@ -659,6 +669,9 @@ func (a *Account) resolveModelMapping(rawMapping map[string]any) map[string]stri } // Antigravity 平台使用默认映射 + if a.IsGeminiGoogleOne() { + return geminicli.GoogleOneModelMapping() + } if a.Platform == domain.PlatformAntigravity { return domain.DefaultAntigravityModelMapping } diff --git a/backend/internal/service/account_wildcard_test.go b/backend/internal/service/account_wildcard_test.go index 15c5a66fa1..3843237e10 100644 --- a/backend/internal/service/account_wildcard_test.go +++ b/backend/internal/service/account_wildcard_test.go @@ -537,6 +537,52 @@ func TestAccountGetModelMapping_AntigravityEnsuresGeminiDefaultPassthroughs(t *t } } +func TestAccountGetModelMapping_GoogleOneUsesConservativeDefaults(t *testing.T) { + account := &Account{ + Platform: PlatformGemini, + Type: AccountTypeOAuth, + Credentials: map[string]any{ + "oauth_type": "google_one", + }, + } + + mapping := account.GetModelMapping() + for _, model := range []string{"gemini-2.0-flash", "gemini-2.5-flash", "gemini-2.5-pro"} { + if mapping[model] != model { + t.Fatalf("expected Google One model %q to map to itself, got %q", model, mapping[model]) + } + } + for _, model := range []string{"gemini-2.5-flash-image", "gemini-3.1-flash-image", "gemini-3.5-flash"} { + if _, ok := mapping[model]; ok { + t.Fatalf("did not expect unsupported Google One model %q", model) + } + } + if account.IsModelSupported("gemini-3.5-flash") { + t.Fatal("Google One defaults must not treat unsupported models as eligible") + } +} + +func TestAccountGetModelMapping_GoogleOnePreservesExplicitMapping(t *testing.T) { + account := &Account{ + Platform: PlatformGemini, + Type: AccountTypeOAuth, + Credentials: map[string]any{ + "oauth_type": "google_one", + "model_mapping": map[string]any{ + "custom-model": "gemini-2.5-flash", + }, + }, + } + + mapping := account.GetModelMapping() + if mapping["custom-model"] != "gemini-2.5-flash" { + t.Fatalf("expected explicit Google One mapping to be preserved, got %v", mapping) + } + if _, ok := mapping["gemini-2.5-flash"]; ok { + t.Fatalf("did not expect defaults to overwrite an explicit mapping: %v", mapping) + } +} + func TestAccountGetModelMapping_AntigravityRespectsWildcardOverride(t *testing.T) { account := &Account{ Platform: PlatformAntigravity, From 7e9af4c100fe3f8d97a89925828516f8f8e7d8e6 Mon Sep 17 00:00:00 2001 From: IanShaw027 Date: Fri, 21 Aug 2026 08:55:04 +0800 Subject: [PATCH 076/204] =?UTF-8?q?=E5=B0=86=20compact=20fallback=20?= =?UTF-8?q?=E7=9A=84=E6=B5=81=E5=BC=8F=E9=87=8D=E8=AF=95=E6=94=B9=E4=B8=BA?= =?UTF-8?q?=E5=BE=AA=E7=8E=AF=EF=BC=8C=E9=81=BF=E5=85=8D=E9=80=92=E5=BD=92?= =?UTF-8?q?=E9=87=8D=E7=BD=AE=E5=8D=95=E6=AC=A1=E9=87=8D=E8=AF=95=E6=A0=87?= =?UTF-8?q?=E5=BF=97?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../service/openai_compact_fallback.go | 37 ++++ .../service/openai_compact_fallback_test.go | 38 ++++ .../service/openai_gateway_passthrough.go | 205 +++++++++--------- 3 files changed, 177 insertions(+), 103 deletions(-) diff --git a/backend/internal/service/openai_compact_fallback.go b/backend/internal/service/openai_compact_fallback.go index 79595adbb6..517a7e2e7b 100644 --- a/backend/internal/service/openai_compact_fallback.go +++ b/backend/internal/service/openai_compact_fallback.go @@ -5,6 +5,7 @@ import ( "net/http" "strings" + "github.com/Wei-Shaw/sub2api/internal/pkg/logger" "github.com/gin-gonic/gin" "github.com/tidwall/gjson" ) @@ -143,3 +144,39 @@ func (s *OpenAIGatewayService) prepareOpenAICompactFallbackRetry( } return retryBody, fallbackModel, true } + +func (s *OpenAIGatewayService) applyOpenAIPassthroughCompactFallbackFromSignal( + c *gin.Context, + account *Account, + requestedModel string, + body []byte, + err error, + alreadyRetried bool, + resp *http.Response, +) ([]byte, string, bool) { + signal, ok := asOpenAICompactFallbackSignal(err) + if !ok { + return body, "", false + } + retryBody, fallbackModel, retry := s.prepareOpenAICompactFallbackRetry( + c, account, requestedModel, body, http.StatusBadRequest, signal.message, signal.payload, alreadyRetried, + ) + if !retry { + return body, "", false + } + if resp != nil && resp.Body != nil { + _ = resp.Body.Close() + } + fromModel := strings.TrimSpace(gjson.GetBytes(body, "model").String()) + accountName := "" + if account != nil { + accountName = account.Name + } + SetOpsUpstreamModel(c, fallbackModel) + logger.LegacyPrintf( + "service.openai_gateway", + "[OpenAI passthrough] Retrying explicit compact request once with fallback model (account: %s, from: %s, to: %s, upstream_code: %s)", + accountName, fromModel, fallbackModel, extractUpstreamErrorCode(signal.payload), + ) + return retryBody, fallbackModel, true +} diff --git a/backend/internal/service/openai_compact_fallback_test.go b/backend/internal/service/openai_compact_fallback_test.go index 377dea2212..944f7e1cfd 100644 --- a/backend/internal/service/openai_compact_fallback_test.go +++ b/backend/internal/service/openai_compact_fallback_test.go @@ -272,3 +272,41 @@ func TestOpenAIGatewayForwardRetriesStreamingCompactFailureBeforeOutput(t *testi require.NotContains(t, recorder.Body.String(), "context_length_exceeded") require.Contains(t, recorder.Body.String(), "response.completed") } + +func TestOpenAIGatewayForwardDoesNotRecurseWhenCompactFallbackAlsoFails(t *testing.T) { + gin.SetMode(gin.TestMode) + body := []byte(`{"model":"gpt-5.5","stream":true,"instructions":"compact-test","input":[{"type":"message","role":"user","content":"hello"},{"type":"compaction_trigger"}]}`) + recorder := httptest.NewRecorder() + c, _ := gin.CreateTestContext(recorder) + c.Request = httptest.NewRequest(http.MethodPost, "/v1/responses", nil) + c.Request.Body = io.NopCloser(bytes.NewReader(body)) + c.Request.Header.Set("Content-Type", "application/json") + MarkOpenAINativeCompactionV2(c) + + failed := "event: response.failed\n" + + `data: {"type":"response.failed","response":{"status":"failed","error":{"code":"model_not_found","message":"model not found"}}}` + "\n\n" + upstream := &httpUpstreamRecorder{responses: []*http.Response{ + {StatusCode: http.StatusOK, Header: http.Header{"Content-Type": []string{"text/event-stream"}}, Body: io.NopCloser(strings.NewReader(failed))}, + {StatusCode: http.StatusOK, Header: http.Header{"Content-Type": []string{"text/event-stream"}}, Body: io.NopCloser(strings.NewReader(failed))}, + {StatusCode: http.StatusOK, Header: http.Header{"Content-Type": []string{"text/event-stream"}}, Body: io.NopCloser(strings.NewReader(failed))}, + {StatusCode: http.StatusOK, Header: http.Header{"Content-Type": []string{"text/event-stream"}}, Body: io.NopCloser(strings.NewReader(failed))}, + {StatusCode: http.StatusOK, Header: http.Header{"Content-Type": []string{"text/event-stream"}}, Body: io.NopCloser(strings.NewReader(failed))}, + }} + svc := &OpenAIGatewayService{ + cfg: &config.Config{Gateway: config.GatewayConfig{OpenAICompactModel: "gpt-5.4"}}, + httpUpstream: upstream, + } + account := &Account{ + ID: 1, Name: "openai-oauth", Platform: PlatformOpenAI, Type: AccountTypeOAuth, Concurrency: 1, + Credentials: map[string]any{"access_token": "oauth-token", "chatgpt_account_id": "chatgpt-account"}, + Status: StatusActive, Schedulable: true, + } + + result, err := svc.Forward(context.Background(), c, account, body) + + require.Error(t, err) + require.Nil(t, result) + require.Len(t, upstream.bodies, 2) + require.Equal(t, "gpt-5.5", gjson.GetBytes(upstream.bodies[0], "model").String()) + require.Equal(t, "gpt-5.4", gjson.GetBytes(upstream.bodies[1], "model").String()) +} diff --git a/backend/internal/service/openai_gateway_passthrough.go b/backend/internal/service/openai_gateway_passthrough.go index 40931138d4..06653094ce 100644 --- a/backend/internal/service/openai_gateway_passthrough.go +++ b/backend/internal/service/openai_gateway_passthrough.go @@ -326,6 +326,11 @@ func (s *OpenAIGatewayService) forwardOpenAIPassthrough( compactModelFallbackRetried := false rejectedFieldRetryState := openAIResponsesRejectedFieldRetryStateForRequest(c, body) var resp *http.Response + var usage *OpenAIUsage + var firstTokenMs *int + responseID := "" + imageCount := 0 + var imageOutputSizes []string for { actualModel := strings.TrimSpace(gjson.GetBytes(body, "model").String()) if actualModel == "" { @@ -347,116 +352,110 @@ func (s *OpenAIGatewayService) forwardOpenAIPassthrough( // a failover so the handler switches to a healthy account. return nil, s.handleOpenAIUpstreamTransportError(ctx, c, account, err, true) } - if resp.StatusCode < 400 { - break - } - - // Peek only to identify an invalid task. Restore the body so the existing - // passthrough error handling sees the same response after recovery fails. - probeBody := s.readUpstreamErrorBody(resp) - _ = resp.Body.Close() - resp.Body = io.NopCloser(bytes.NewReader(probeBody)) - if retryBody, reason, changed, retryErr := normalizeOpenAIResponsesRejectedFieldRetryBody(resp.StatusCode, body, probeBody); retryErr != nil { - return nil, fmt.Errorf("normalize passthrough rejected Responses field retry body: %w", retryErr) - } else if changed && rejectedFieldRetryState.Allow(retryBody) { - body = retryBody - logger.LegacyPrintf("service.openai_gateway", "[OpenAI] Retrying passthrough request after %s (account: %s)", reason, account.Name) - continue - } - if !agentTaskRecoveryTried && s.isAgentIdentityAccount(ctx, account) && isAgentIdentityTaskInvalidHTTPResponse(resp.StatusCode, probeBody) { - agentTaskRecoveryTried = true - expectedTaskID := account.GetCredential("task_id") - if recoveryErr := s.recoverAgentIdentityTask(ctx, account, expectedTaskID); recoveryErr != nil { - return nil, fmt.Errorf("agent identity task recovery failed: %w", recoveryErr) + if resp.StatusCode >= 400 { + // Peek only to identify an invalid task. Restore the body so the existing + // passthrough error handling sees the same response after recovery fails. + probeBody := s.readUpstreamErrorBody(resp) + _ = resp.Body.Close() + resp.Body = io.NopCloser(bytes.NewReader(probeBody)) + if retryBody, reason, changed, retryErr := normalizeOpenAIResponsesRejectedFieldRetryBody(resp.StatusCode, body, probeBody); retryErr != nil { + return nil, fmt.Errorf("normalize passthrough rejected Responses field retry body: %w", retryErr) + } else if changed && rejectedFieldRetryState.Allow(retryBody) { + body = retryBody + logger.LegacyPrintf("service.openai_gateway", "[OpenAI] Retrying passthrough request after %s (account: %s)", reason, account.Name) + continue } - continue - } - upstreamMsg := sanitizeUpstreamErrorMessage(strings.TrimSpace(extractUpstreamErrorMessage(probeBody))) - if retryBody, fallbackModel, retry := s.prepareOpenAICompactFallbackRetry( - c, account, requestedModel, body, resp.StatusCode, upstreamMsg, probeBody, compactModelFallbackRetried, - ); retry { - fromModel := strings.TrimSpace(gjson.GetBytes(body, "model").String()) - body = retryBody - upstreamPassthroughModel = fallbackModel - compactModelFallbackRetried = true - SetOpsUpstreamModel(c, fallbackModel) - logger.LegacyPrintf( - "service.openai_gateway", - "[OpenAI passthrough] Retrying explicit compact request once with fallback model (account: %s, from: %s, to: %s, upstream_code: %s)", - account.Name, fromModel, fallbackModel, extractUpstreamErrorCode(probeBody), - ) - continue + if !agentTaskRecoveryTried && s.isAgentIdentityAccount(ctx, account) && isAgentIdentityTaskInvalidHTTPResponse(resp.StatusCode, probeBody) { + agentTaskRecoveryTried = true + expectedTaskID := account.GetCredential("task_id") + if recoveryErr := s.recoverAgentIdentityTask(ctx, account, expectedTaskID); recoveryErr != nil { + return nil, fmt.Errorf("agent identity task recovery failed: %w", recoveryErr) + } + continue + } + upstreamMsg := sanitizeUpstreamErrorMessage(strings.TrimSpace(extractUpstreamErrorMessage(probeBody))) + if retryBody, fallbackModel, retry := s.prepareOpenAICompactFallbackRetry( + c, account, requestedModel, body, resp.StatusCode, upstreamMsg, probeBody, compactModelFallbackRetried, + ); retry { + fromModel := strings.TrimSpace(gjson.GetBytes(body, "model").String()) + body = retryBody + upstreamPassthroughModel = fallbackModel + compactModelFallbackRetried = true + SetOpsUpstreamModel(c, fallbackModel) + logger.LegacyPrintf( + "service.openai_gateway", + "[OpenAI passthrough] Retrying explicit compact request once with fallback model (account: %s, from: %s, to: %s, upstream_code: %s)", + account.Name, fromModel, fallbackModel, extractUpstreamErrorCode(probeBody), + ) + continue + } + + // 透传模式默认保持原样代理;容量错误以及 API-key 上游的瞬时 + // 5xx 应先触发多账号 failover,且此时尚未写入下游响应。 + // probeBody 已在上方任务探测时读取过一次,直接复用避免重复读取。 + if shouldFailoverOpenAIPassthroughResponse(account, resp.StatusCode, probeBody) { + return nil, s.handleFailoverErrorResponsePassthrough(ctx, resp, c, account, body, probeBody) + } + return nil, s.handleErrorResponsePassthrough(ctx, resp, c, account, body, probeBody) } - // 透传模式默认保持原样代理;容量错误以及 API-key 上游的瞬时 - // 5xx 应先触发多账号 failover,且此时尚未写入下游响应。 - // probeBody 已在上方任务探测时读取过一次,直接复用避免重复读取。 - if shouldFailoverOpenAIPassthroughResponse(account, resp.StatusCode, probeBody) { - return nil, s.handleFailoverErrorResponsePassthrough(ctx, resp, c, account, body, probeBody) + if mapping, ok := openAIResponsesClientToolMapping(c); ok && isEventStreamResponse(resp.Header) { + maxLineSize := defaultMaxLineSize + if s.cfg != nil && s.cfg.Gateway.MaxLineSize > 0 { + maxLineSize = s.cfg.Gateway.MaxLineSize + } + resp.Body = newGrokResponsesClientToolStreamBody(resp.Body, mapping, maxLineSize) } - return nil, s.handleErrorResponsePassthrough(ctx, resp, c, account, body, probeBody) + + // x-codex-turn-state 溯源:下游回传由 writeOpenAIPassthroughResponseHeaders + // 在各 handler 的写头点强制放行,铸造账号在此统一记录,供出站守卫剥离 + // failover 换号后的跨账号回带(openai_codex_turn_state.go)。 + if extractOpenAICodexTurnState(resp.Header) != "" { + s.noteOpenAICodexTurnStateProvenance(c, account) + } + + if reqStream { + result, handleErr := s.handleStreamingResponsePassthrough(ctx, resp, c, account, startTime, reqModel, upstreamPassthroughModel) + if handleErr != nil { + if retryBody, fallbackModel, retry := s.applyOpenAIPassthroughCompactFallbackFromSignal( + c, account, requestedModel, body, handleErr, compactModelFallbackRetried, resp, + ); retry { + body = retryBody + upstreamPassthroughModel = fallbackModel + compactModelFallbackRetried = true + continue + } + _ = resp.Body.Close() + return nil, handleErr + } + usage = result.usage + firstTokenMs = result.firstTokenMs + responseID = strings.TrimSpace(result.responseID) + imageCount = result.imageCount + imageOutputSizes = result.imageOutputSizes + } else { + result, handleErr := s.handleNonStreamingResponsePassthrough(ctx, resp, c, account, reqModel, upstreamPassthroughModel) + if handleErr != nil { + if retryBody, fallbackModel, retry := s.applyOpenAIPassthroughCompactFallbackFromSignal( + c, account, requestedModel, body, handleErr, compactModelFallbackRetried, resp, + ); retry { + body = retryBody + upstreamPassthroughModel = fallbackModel + compactModelFallbackRetried = true + continue + } + _ = resp.Body.Close() + return nil, handleErr + } + usage = result.usage + responseID = strings.TrimSpace(result.responseID) + imageCount = result.imageCount + imageOutputSizes = result.imageOutputSizes + } + break } defer func() { _ = resp.Body.Close() }() - if mapping, ok := openAIResponsesClientToolMapping(c); ok && isEventStreamResponse(resp.Header) { - maxLineSize := defaultMaxLineSize - if s.cfg != nil && s.cfg.Gateway.MaxLineSize > 0 { - maxLineSize = s.cfg.Gateway.MaxLineSize - } - resp.Body = newGrokResponsesClientToolStreamBody(resp.Body, mapping, maxLineSize) - } - serviceTier := extractOpenAIServiceTierFromBody(body) - - // x-codex-turn-state 溯源:下游回传由 writeOpenAIPassthroughResponseHeaders - // 在各 handler 的写头点强制放行,铸造账号在此统一记录,供出站守卫剥离 - // failover 换号后的跨账号回带(openai_codex_turn_state.go)。 - if extractOpenAICodexTurnState(resp.Header) != "" { - s.noteOpenAICodexTurnStateProvenance(c, account) - } - - var usage *OpenAIUsage - var firstTokenMs *int - responseID := "" - imageCount := 0 - var imageOutputSizes []string - if reqStream { - result, err := s.handleStreamingResponsePassthrough(ctx, resp, c, account, startTime, reqModel, upstreamPassthroughModel) - if err != nil { - if signal, ok := asOpenAICompactFallbackSignal(err); ok { - if retryBody, fallbackModel, retry := s.prepareOpenAICompactFallbackRetry( - c, account, requestedModel, body, http.StatusBadRequest, signal.message, signal.payload, compactModelFallbackRetried, - ); retry { - body = retryBody - SetOpsUpstreamModel(c, fallbackModel) - return s.forwardOpenAIPassthrough(ctx, c, account, body, canonicalImageIntentBody, requestedModel, true, reasoningEffort, reqStream, startTime) - } - } - return nil, err - } - usage = result.usage - firstTokenMs = result.firstTokenMs - responseID = strings.TrimSpace(result.responseID) - imageCount = result.imageCount - imageOutputSizes = result.imageOutputSizes - } else { - result, err := s.handleNonStreamingResponsePassthrough(ctx, resp, c, account, reqModel, upstreamPassthroughModel) - if err != nil { - if signal, ok := asOpenAICompactFallbackSignal(err); ok { - if retryBody, fallbackModel, retry := s.prepareOpenAICompactFallbackRetry( - c, account, requestedModel, body, http.StatusBadRequest, signal.message, signal.payload, compactModelFallbackRetried, - ); retry { - body = retryBody - SetOpsUpstreamModel(c, fallbackModel) - return s.forwardOpenAIPassthrough(ctx, c, account, body, canonicalImageIntentBody, requestedModel, true, reasoningEffort, reqStream, startTime) - } - } - return nil, err - } - usage = result.usage - responseID = strings.TrimSpace(result.responseID) - imageCount = result.imageCount - imageOutputSizes = result.imageOutputSizes - } s.bindHTTPResponseAccount(ctx, c, account, responseID) // 排除 spark 影子:其 codex_* 仅由 QueryUsage(/wham/usage bengalfox)更新(外审第7轮 P1)。 From 16b15e870d498f70a011b3e83b6ee59095108449 Mon Sep 17 00:00:00 2001 From: IanShaw <131567472+IanShaw027@users.noreply.github.com> Date: Thu, 20 Aug 2026 18:16:38 -0700 Subject: [PATCH 077/204] =?UTF-8?q?=E4=BF=AE=E5=A4=8D=205888=20=E4=B8=8E?= =?UTF-8?q?=205925=20=E7=9A=84=E5=90=8C=E5=8F=B7=E9=87=8D=E8=AF=95?= =?UTF-8?q?=E8=AF=AD=E4=B9=89=E5=86=B2=E7=AA=81?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- backend/internal/handler/failover_loop.go | 25 +++++++++------- .../internal/handler/failover_loop_test.go | 30 +++++++++++++++++-- backend/internal/handler/grok_media.go | 2 +- .../handler/openai_chat_completions.go | 2 +- .../handler/openai_gateway_handler.go | 7 +++-- backend/internal/handler/openai_images.go | 2 +- 6 files changed, 49 insertions(+), 19 deletions(-) diff --git a/backend/internal/handler/failover_loop.go b/backend/internal/handler/failover_loop.go index 45bea91b26..56c39af103 100644 --- a/backend/internal/handler/failover_loop.go +++ b/backend/internal/handler/failover_loop.go @@ -83,13 +83,21 @@ func sameAccountRetryAllowed(failoverErr *service.UpstreamFailoverError, retryCo if !sameAccountRetryDeadlineAllows(failoverErr) { return false } - // Deadline-window retries (OAuth 429) may pass retryLimit=0 and are not - // bound to pool_mode_retry_count. Pool-mode callers pass a positive limit. - if !failoverErr.SameAccountRetryDeadline.IsZero() && retryLimit <= 0 { - return true + // Error-specific caps (Grok capacity/stream-idle) remain hard limits even + // when the error also carries a freshly reconstructed deadline. + if failoverErr.SameAccountRetryMax > 0 { + if retryLimit <= 0 { + return false + } + if failoverErr.SameAccountRetryMax < retryLimit { + retryLimit = failoverErr.SameAccountRetryMax + } + return retryCount < retryLimit } - if failoverErr.SameAccountRetryMax > 0 && (retryLimit <= 0 || failoverErr.SameAccountRetryMax < retryLimit) { - retryLimit = failoverErr.SameAccountRetryMax + // OAuth 429 explicitly opts into a deadline window. It is intentionally not + // bounded by the ordinary/default pool retry count. + if !failoverErr.SameAccountRetryDeadline.IsZero() { + return true } return retryLimit > 0 && retryCount < retryLimit } @@ -202,10 +210,7 @@ func (s *FailoverState) HandleFailoverError( // 同账号重试不算切换账号,粘性会话仅在实际切换时强制缓存计费。 retryCount := s.SameAccountRetryCount[accountID] - if failoverErr.SameAccountRetryMax > 0 && failoverErr.SameAccountRetryMax < retryLimit { - retryLimit = failoverErr.SameAccountRetryMax - } - sameAccountRetry := failoverErr.RetryableOnSameAccount && retryLimit > 0 && retryCount < retryLimit && sameAccountRetryDeadlineAllows(failoverErr) + sameAccountRetry := sameAccountRetryAllowed(failoverErr, retryCount, retryLimit) if needForceCacheBilling(s.hasBoundSession, failoverErr, sameAccountRetry) { s.ForceCacheBilling = true } diff --git a/backend/internal/handler/failover_loop_test.go b/backend/internal/handler/failover_loop_test.go index 20ce869c01..d362682cd7 100644 --- a/backend/internal/handler/failover_loop_test.go +++ b/backend/internal/handler/failover_loop_test.go @@ -71,10 +71,32 @@ func TestSameAccountRetryAllowedUsesDeadlineInsteadOfPoolCount(t *testing.T) { SameAccountRetryDeadline: time.Now().Add(time.Minute), } require.True(t, sameAccountRetryAllowed(err, 100, 0)) + require.True(t, sameAccountRetryAllowed(err, 100, maxSameAccountRetries)) err.SameAccountRetryDeadline = time.Now().Add(-time.Second) require.False(t, sameAccountRetryAllowed(err, 0, 100)) } +func TestSameAccountRetryAllowedRequiresOptInAndDefaultsToCountLimit(t *testing.T) { + err := &service.UpstreamFailoverError{SameAccountRetryDeadline: time.Now().Add(time.Minute)} + require.False(t, sameAccountRetryAllowed(err, 0, maxSameAccountRetries)) + + err.RetryableOnSameAccount = true + err.SameAccountRetryDeadline = time.Time{} + require.True(t, sameAccountRetryAllowed(err, maxSameAccountRetries-1, maxSameAccountRetries)) + require.False(t, sameAccountRetryAllowed(err, maxSameAccountRetries, maxSameAccountRetries)) +} + +func TestSameAccountRetryAllowedHonorsErrorMaxBeforeDeadline(t *testing.T) { + err := &service.UpstreamFailoverError{ + RetryableOnSameAccount: true, + SameAccountRetryDeadline: time.Now().Add(time.Minute), + SameAccountRetryMax: 1, + } + require.True(t, sameAccountRetryAllowed(err, 0, maxSameAccountRetries)) + require.False(t, sameAccountRetryAllowed(err, 1, maxSameAccountRetries)) + require.False(t, sameAccountRetryAllowed(err, 0, 0), "an explicit zero retry budget remains disabled") +} + func TestSameAccountRetryDeadlineAllows(t *testing.T) { require.True(t, sameAccountRetryDeadlineAllows(&service.UpstreamFailoverError{})) require.True(t, sameAccountRetryDeadlineAllows(&service.UpstreamFailoverError{ @@ -352,7 +374,7 @@ func TestHandleFailoverError_CacheBilling(t *testing.T) { require.Zero(t, fs.SwitchCount) }) - t.Run("deadline存在但计数已耗尽时按切换处理并强制缓存计费", func(t *testing.T) { + t.Run("OAuth deadline存在时不按普通计数切换", func(t *testing.T) { mock := &mockTempUnscheduler{} fs := NewFailoverState(3, true) fs.SameAccountRetryCount[100] = maxSameAccountRetries @@ -362,8 +384,10 @@ func TestHandleFailoverError_CacheBilling(t *testing.T) { fs.HandleFailoverError(context.Background(), mock, 100, "openai", maxSameAccountRetries, err) - require.True(t, fs.ForceCacheBilling) - require.Equal(t, 1, fs.SwitchCount) + require.False(t, fs.ForceCacheBilling) + require.Zero(t, fs.SwitchCount) + require.Equal(t, maxSameAccountRetries+1, fs.SameAccountRetryCount[100]) + require.Empty(t, mock.calls) }) t.Run("同账号重试耗尽并实际切换时设置ForceCacheBilling", func(t *testing.T) { diff --git a/backend/internal/handler/grok_media.go b/backend/internal/handler/grok_media.go index 89845d0908..d3fbe9c847 100644 --- a/backend/internal/handler/grok_media.go +++ b/backend/internal/handler/grok_media.go @@ -362,7 +362,7 @@ func (h *OpenAIGatewayHandler) handleGrokMedia(c *gin.Context, endpoint service. } if failoverErr.RetryableOnSameAccount { retryLimit := effectiveSameAccountRetryLimit(failoverErr, account) - if sameAccountRetryCount[account.ID] < retryLimit && sameAccountRetryDeadlineAllows(failoverErr) { + if sameAccountRetryAllowed(failoverErr, sameAccountRetryCount[account.ID], retryLimit) { sameAccountRetryCount[account.ID]++ retryDelay := sameAccountRetryDelayFor(failoverErr, sameAccountRetryCount[account.ID]) reqLog.Warn("grok_media.pool_mode_same_account_retry", diff --git a/backend/internal/handler/openai_chat_completions.go b/backend/internal/handler/openai_chat_completions.go index 5eaa8b3514..7f83f9ba90 100644 --- a/backend/internal/handler/openai_chat_completions.go +++ b/backend/internal/handler/openai_chat_completions.go @@ -331,7 +331,7 @@ func (h *OpenAIGatewayHandler) ChatCompletions(c *gin.Context) { // Pool mode: retry on the same account if failoverErr.RetryableOnSameAccount { retryLimit := effectiveSameAccountRetryLimit(failoverErr, account) - if sameAccountRetryCount[account.ID] < retryLimit && sameAccountRetryDeadlineAllows(failoverErr) { + if sameAccountRetryAllowed(failoverErr, sameAccountRetryCount[account.ID], retryLimit) { sameAccountRetryCount[account.ID]++ retryDelay := sameAccountRetryDelayFor(failoverErr, sameAccountRetryCount[account.ID]) reqLog.Warn("openai_chat_completions.pool_mode_same_account_retry", diff --git a/backend/internal/handler/openai_gateway_handler.go b/backend/internal/handler/openai_gateway_handler.go index dd111267c4..89e00c8954 100644 --- a/backend/internal/handler/openai_gateway_handler.go +++ b/backend/internal/handler/openai_gateway_handler.go @@ -755,7 +755,7 @@ func (h *OpenAIGatewayHandler) Responses(c *gin.Context) { // 池模式:同账号重试 if failoverErr.RetryableOnSameAccount { retryLimit := effectiveSameAccountRetryLimit(failoverErr, account) - if sameAccountRetryCount[account.ID] < retryLimit && sameAccountRetryDeadlineAllows(failoverErr) { + if sameAccountRetryAllowed(failoverErr, sameAccountRetryCount[account.ID], retryLimit) { sameAccountRetryCount[account.ID]++ retryDelay := sameAccountRetryDelayFor(failoverErr, sameAccountRetryCount[account.ID]) reqLog.Warn("openai.pool_mode_same_account_retry", @@ -1310,7 +1310,7 @@ func (h *OpenAIGatewayHandler) Messages(c *gin.Context) { // 池模式:同账号重试 if failoverErr.RetryableOnSameAccount { retryLimit := effectiveSameAccountRetryLimit(failoverErr, account) - if sameAccountRetryCount[account.ID] < retryLimit && sameAccountRetryDeadlineAllows(failoverErr) { + if sameAccountRetryAllowed(failoverErr, sameAccountRetryCount[account.ID], retryLimit) { sameAccountRetryCount[account.ID]++ retryDelay := sameAccountRetryDelayFor(failoverErr, sameAccountRetryCount[account.ID]) reqLog.Warn("openai_messages.pool_mode_same_account_retry", @@ -1997,7 +1997,8 @@ func (h *OpenAIGatewayHandler) ResponsesWebSocket(c *gin.Context) { if account == nil || failoverErr == nil || failoverErr.StatusCode != http.StatusTooManyRequests || failoverErr.SameAccountRetryDeadline.IsZero() { return false } - if !sameAccountRetryAllowed(failoverErr, sameAccountRetryCount[account.ID], 0) { + retryLimit := effectiveSameAccountRetryLimit(failoverErr, account) + if !sameAccountRetryAllowed(failoverErr, sameAccountRetryCount[account.ID], retryLimit) { return false } sameAccountRetryCount[account.ID]++ diff --git a/backend/internal/handler/openai_images.go b/backend/internal/handler/openai_images.go index bac19329e2..18e1d59195 100644 --- a/backend/internal/handler/openai_images.go +++ b/backend/internal/handler/openai_images.go @@ -309,7 +309,7 @@ func (h *OpenAIGatewayHandler) Images(c *gin.Context) { } if failoverErr.RetryableOnSameAccount { retryLimit := effectiveSameAccountRetryLimit(failoverErr, account) - if sameAccountRetryCount[account.ID] < retryLimit && sameAccountRetryDeadlineAllows(failoverErr) { + if sameAccountRetryAllowed(failoverErr, sameAccountRetryCount[account.ID], retryLimit) { sameAccountRetryCount[account.ID]++ retryDelay := sameAccountRetryDelayFor(failoverErr, sameAccountRetryCount[account.ID]) reqLog.Warn("openai.images.pool_mode_same_account_retry", From 3548256745c2168caf63e68963f2791834353eef Mon Sep 17 00:00:00 2001 From: shaw Date: Fri, 21 Aug 2026 10:01:29 +0800 Subject: [PATCH 078/204] chore: update gitignore --- .gitignore | 1 + 1 file changed, 1 insertion(+) diff --git a/.gitignore b/.gitignore index 4ea6ff311b..d778c275ec 100644 --- a/.gitignore +++ b/.gitignore @@ -143,6 +143,7 @@ docs/* frontend/coverage/ aicodex output/ +.codegraph/ # Vitest / Vite cache at repo root .vite/ From b2b2adcf8d190352868a24e5d7d1e7be7b2ff39a Mon Sep 17 00:00:00 2001 From: IanShaw <131567472+IanShaw027@users.noreply.github.com> Date: Thu, 20 Aug 2026 21:06:48 -0700 Subject: [PATCH 079/204] =?UTF-8?q?=E4=BF=AE=E5=A4=8D=20PR=205888=20?= =?UTF-8?q?=E5=AE=A1=E6=9F=A5=E5=8F=91=E7=8E=B0=E7=9A=84=E5=85=BC=E5=AE=B9?= =?UTF-8?q?=E6=80=A7=E4=B8=8E=E7=AB=9E=E6=80=81=E9=97=AE=E9=A2=98?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- ...openai_gateway_credential_failover_test.go | 30 ++- .../handler/openai_gateway_handler.go | 20 ++ .../handler/openai_gateway_handler_test.go | 49 ++++ .../handler/ops_capture_writer_nil_test.go | 65 ++++++ backend/internal/handler/ops_error_logger.go | 211 ++++++++++++++++-- .../internal/handler/ops_error_logger_test.go | 57 ++++- backend/internal/repository/gateway_cache.go | 72 ++++-- .../repository/gateway_cache_cyber_test.go | 66 ++++++ .../internal/repository/temp_unsched_cache.go | 5 - .../temp_unsched_cache_health_test.go | 33 ++- .../openai_access_state_failover_test.go | 138 +++++++++++- .../openai_account_runtime_block_fastpath.go | 2 +- ...nai_account_runtime_block_fastpath_test.go | 52 ++++- .../internal/service/openai_alpha_search.go | 4 +- .../service/openai_apikey_health_breaker.go | 14 +- .../openai_apikey_health_breaker_test.go | 18 +- .../openai_codex_function_call_id_test.go | 22 ++ .../service/openai_codex_transform.go | 25 ++- .../service/openai_codex_transform_test.go | 20 ++ .../service/openai_compact_fallback.go | 125 ++++++++++- .../service/openai_compact_fallback_test.go | 93 ++++++++ .../service/openai_cyber_session_block.go | 10 +- .../openai_cyber_session_block_test.go | 56 ++++- .../service/openai_cyber_transcript.go | 34 ++- backend/internal/service/openai_embeddings.go | 2 +- .../openai_gateway_apikey_item_id_test.go | 7 +- .../service/openai_gateway_forward.go | 42 ++-- .../service/openai_gateway_passthrough.go | 28 ++- .../service/openai_gateway_request_body.go | 16 +- .../openai_gateway_response_flush_test.go | 62 ++++- .../openai_gateway_response_handling.go | 99 +++++++- .../service/openai_gateway_service_test.go | 17 ++ .../service/openai_gateway_upstream_errors.go | 75 +++---- backend/internal/service/openai_images.go | 2 +- ...nai_response_terminal_usage_compat_test.go | 23 ++ .../openai_responses_ingress_compat.go | 14 +- .../openai_responses_ingress_compat_test.go | 22 ++ .../service/openai_responses_item_id.go | 66 +----- .../service/openai_responses_item_id_test.go | 26 ++- .../service/openai_responses_tool_schema.go | 40 +++- .../openai_responses_tool_schema_test.go | 56 ++++- .../openai_upstream_client_error_test.go | 9 +- .../internal/service/openai_ws_http_bridge.go | 15 +- .../service/openai_ws_http_bridge_test.go | 34 +++ .../internal/service/openai_ws_state_store.go | 104 +++++++++ .../service/openai_ws_state_store_test.go | 21 ++ .../service/openai_ws_v2/passthrough_relay.go | 56 +++-- .../openai_ws_v2/passthrough_relay_test.go | 94 ++++++++ .../internal/service/ops_upstream_context.go | 13 +- backend/internal/service/temp_unsched.go | 1 - 50 files changed, 1832 insertions(+), 333 deletions(-) diff --git a/backend/internal/handler/openai_gateway_credential_failover_test.go b/backend/internal/handler/openai_gateway_credential_failover_test.go index 91a3881dfa..d94eae7fe9 100644 --- a/backend/internal/handler/openai_gateway_credential_failover_test.go +++ b/backend/internal/handler/openai_gateway_credential_failover_test.go @@ -326,12 +326,15 @@ func TestOpsRecoveredCredentialFailoverDoesNotCreateRequestError(t *testing.T) { router.ServeHTTP(recorder, httptest.NewRequest(http.MethodGet, "/openai/v1/responses", nil)) require.Equal(t, http.StatusOK, recorder.Code) - require.Zero(t, OpsErrorLogQueueLength()) - select { - case job := <-opsErrorLogQueue: - t.Fatalf("successful failover must not create ops error row: %+v", job.entry) - default: - } + require.Equal(t, int64(1), OpsErrorLogQueueLength()) + job := <-opsErrorLogQueue + require.Equal(t, http.StatusOK, job.entry.StatusCode) + require.Equal(t, string(service.GatewayFailureStageAccountAuth), job.entry.ErrorPhase) + require.NotNil(t, job.entry.UpstreamErrorsJSON) + events, err := service.ParseOpsUpstreamErrors(*job.entry.UpstreamErrorsJSON) + require.NoError(t, err) + require.Len(t, events, 2) + require.Equal(t, string(service.GatewayFailureStageAccountAuth), events[1].Stage) } func TestOpsWebSocketCredentialFailoverSuccessDoesNotCreateRequestError(t *testing.T) { @@ -354,12 +357,15 @@ func TestOpsWebSocketCredentialFailoverSuccessDoesNotCreateRequestError(t *testi router.ServeHTTP(recorder, request) require.Equal(t, http.StatusOK, recorder.Code) - require.Zero(t, OpsErrorLogQueueLength()) - select { - case job := <-opsErrorLogQueue: - t.Fatalf("successful websocket failover must not create ops error row: %+v", job.entry) - default: - } + require.Equal(t, int64(1), OpsErrorLogQueueLength()) + job := <-opsErrorLogQueue + require.Equal(t, http.StatusOK, job.entry.StatusCode) + require.Equal(t, string(service.GatewayFailureStageAccountAuth), job.entry.ErrorPhase) + require.NotNil(t, job.entry.UpstreamErrorsJSON) + events, err := service.ParseOpsUpstreamErrors(*job.entry.UpstreamErrorsJSON) + require.NoError(t, err) + require.Len(t, events, 1) + require.Equal(t, string(service.GatewayFailureStageAccountAuth), events[0].Stage) } func TestOpsWebSocketCredentialFailoverExhaustedIsRecorded(t *testing.T) { diff --git a/backend/internal/handler/openai_gateway_handler.go b/backend/internal/handler/openai_gateway_handler.go index 89e00c8954..45144479c7 100644 --- a/backend/internal/handler/openai_gateway_handler.go +++ b/backend/internal/handler/openai_gateway_handler.go @@ -409,7 +409,27 @@ func (h *OpenAIGatewayHandler) Responses(c *gin.Context) { h.errorResponse(c, http.StatusBadRequest, "invalid_request_error", "previous_response_id must be a response.id (resp_*), not a message id") return } + groupID := int64(0) + if apiKey.GroupID != nil { + groupID = *apiKey.GroupID + } + owned, ownershipErr := h.gatewayService.ValidateOpenAIHTTPResponseOwner( + c.Request.Context(), + groupID, + previousResponseID, + subject.UserID, + apiKey.ID, + ) + if ownershipErr != nil { + reqLog.Warn("openai.previous_response_owner_lookup_failed", zap.Error(ownershipErr)) + } + if !owned { + reqLog.Warn("openai.request_validation_failed", zap.String("reason", "previous_response_owner_mismatch")) + h.errorResponse(c, http.StatusBadRequest, "invalid_request_error", "previous_response_id is not available for this user") + return + } } + service.SetOpenAIHTTPResponseOwner(c, subject.UserID, apiKey.ID) setOpsRequestContext(c, reqModel, reqStream) setOpsEndpointContext(c, "", int16(service.RequestTypeFromLegacy(reqStream, false))) diff --git a/backend/internal/handler/openai_gateway_handler_test.go b/backend/internal/handler/openai_gateway_handler_test.go index 6cc0eaffe7..86c56d4901 100644 --- a/backend/internal/handler/openai_gateway_handler_test.go +++ b/backend/internal/handler/openai_gateway_handler_test.go @@ -877,12 +877,61 @@ func TestOpenAIResponses_AcceptsHTTPContinuationPreviousResponseIDBeforeRouting( }) h := newOpenAIHandlerForPreviousResponseIDValidation(t, nil) + require.NoError(t, h.gatewayService.BindOpenAIHTTPResponseOwner(context.Background(), groupID, "resp_123456", 1, 101)) h.Responses(c) require.NotEqual(t, http.StatusBadRequest, w.Code) require.NotContains(t, w.Body.String(), "Responses WebSocket v2") } +func TestOpenAIResponses_RejectsHTTPContinuationOwnedByAnotherUser(t *testing.T) { + gin.SetMode(gin.TestMode) + + w := httptest.NewRecorder() + c, _ := gin.CreateTestContext(w) + c.Request = httptest.NewRequest(http.MethodPost, "/openai/v1/responses", strings.NewReader( + `{"model":"gpt-5.1","stream":false,"previous_response_id":"resp_other_tenant","input":"hello"}`, + )) + c.Request.Header.Set("Content-Type", "application/json") + + groupID := int64(2) + c.Set(string(middleware.ContextKeyAPIKey), &service.APIKey{ + ID: 202, + UserID: 2, + GroupID: &groupID, + User: &service.User{ID: 2}, + }) + c.Set(string(middleware.ContextKeyUser), middleware.AuthSubject{UserID: 2, Concurrency: 1}) + + h := newOpenAIHandlerForPreviousResponseIDValidation(t, nil) + require.NoError(t, h.gatewayService.BindOpenAIHTTPResponseOwner(context.Background(), groupID, "resp_other_tenant", 1, 101)) + h.Responses(c) + + require.Equal(t, http.StatusBadRequest, w.Code) + require.Contains(t, w.Body.String(), "previous_response_id is not available for this user") +} + +func TestOpenAIResponses_RejectsUnownedHTTPContinuation(t *testing.T) { + gin.SetMode(gin.TestMode) + + w := httptest.NewRecorder() + c, _ := gin.CreateTestContext(w) + c.Request = httptest.NewRequest(http.MethodPost, "/openai/v1/responses", strings.NewReader( + `{"model":"gpt-5.1","stream":false,"previous_response_id":"resp_unknown","input":"hello"}`, + )) + c.Request.Header.Set("Content-Type", "application/json") + + groupID := int64(2) + c.Set(string(middleware.ContextKeyAPIKey), &service.APIKey{ID: 101, UserID: 1, GroupID: &groupID, User: &service.User{ID: 1}}) + c.Set(string(middleware.ContextKeyUser), middleware.AuthSubject{UserID: 1, Concurrency: 1}) + + h := newOpenAIHandlerForPreviousResponseIDValidation(t, nil) + h.Responses(c) + + require.Equal(t, http.StatusBadRequest, w.Code) + require.Contains(t, w.Body.String(), "previous_response_id is not available for this user") +} + func TestOpenAIResponses_FunctionCallOutputHTTPGuidanceDoesNotSuggestPreviousResponseReuse(t *testing.T) { gin.SetMode(gin.TestMode) diff --git a/backend/internal/handler/ops_capture_writer_nil_test.go b/backend/internal/handler/ops_capture_writer_nil_test.go index fce7680a16..38d3f1433b 100644 --- a/backend/internal/handler/ops_capture_writer_nil_test.go +++ b/backend/internal/handler/ops_capture_writer_nil_test.go @@ -12,6 +12,18 @@ import ( "github.com/stretchr/testify/require" ) +type blockingOpsResponseWriter struct { + gin.ResponseWriter + writeStarted chan struct{} + writeRelease chan struct{} +} + +func (w *blockingOpsResponseWriter) WriteString(s string) (int, error) { + close(w.writeStarted) + <-w.writeRelease + return w.ResponseWriter.WriteString(s) +} + type deterministicOpsCaptureWriterStatePool struct { states []*opsCaptureWriterState } @@ -144,3 +156,56 @@ func TestOpsCaptureWriter_StaleLeaseCannotReachReacquiredState(t *testing.T) { defer releaseOpsCaptureWriter(other) require.NotSame(t, current.state, other.state) } + +func TestOpsCaptureWriter_ReleaseWaitsForDelegatedWriteWithoutHoldingStateMutex(t *testing.T) { + gin.SetMode(gin.TestMode) + pool := &deterministicOpsCaptureWriterStatePool{} + recorder := httptest.NewRecorder() + ctx, _ := gin.CreateTestContext(recorder) + inner := &blockingOpsResponseWriter{ + ResponseWriter: ctx.Writer, + writeStarted: make(chan struct{}), + writeRelease: make(chan struct{}), + } + w := acquireOpsCaptureWriterFromPool(pool, inner) + + writeDone := make(chan struct{}) + go func() { + defer close(writeDone) + _, _ = w.WriteString("body") + }() + <-inner.writeStarted + + mutexAvailable := make(chan struct{}) + go func() { + w.state.mu.Lock() + w.state.mu.Unlock() + close(mutexAvailable) + }() + select { + case <-mutexAvailable: + case <-time.After(time.Second): + t.Fatal("state mutex remained held across the delegated network write") + } + + releaseDone := make(chan struct{}) + go func() { + releaseOpsCaptureWriter(w) + close(releaseDone) + }() + select { + case <-releaseDone: + t.Fatal("release returned while a delegated write was still active") + case <-time.After(20 * time.Millisecond): + } + require.Empty(t, pool.states) + + close(inner.writeRelease) + <-writeDone + select { + case <-releaseDone: + case <-time.After(time.Second): + t.Fatal("release did not finish after the delegated write returned") + } + require.Len(t, pool.states, 1) +} diff --git a/backend/internal/handler/ops_error_logger.go b/backend/internal/handler/ops_error_logger.go index 5498f59706..41cd2119b9 100644 --- a/backend/internal/handler/ops_error_logger.go +++ b/backend/internal/handler/ops_error_logger.go @@ -528,6 +528,7 @@ type opsCaptureWriter struct { type opsCaptureWriterState struct { mu sync.RWMutex + inFlight sync.WaitGroup generation uint64 responseWriter gin.ResponseWriter limit int @@ -605,9 +606,15 @@ func releaseOpsCaptureWriter(w *opsCaptureWriter) { state.mu.Unlock() return } + // Invalidate the lease before waiting. No new delegated calls can start for + // this handle, while calls that already copied the writer keep it alive via + // inFlight until their network operation returns. state.generation++ state.responseWriter = nil state.ctx = nil + state.mu.Unlock() + state.inFlight.Wait() + state.mu.Lock() state.limit = opsCaptureWriterLimit state.probe = state.probe[:0] state.lineProbe = state.lineProbe[:0] @@ -657,6 +664,27 @@ func (w *opsCaptureWriter) lockActiveWrite() (*opsCaptureWriterState, gin.Respon return state, state.responseWriter } +func (w *opsCaptureWriter) beginDelegatedCall() (*opsCaptureWriterState, gin.ResponseWriter) { + if w == nil || w.state == nil { + return nil, nil + } + state := w.state + state.mu.Lock() + if state.generation != w.generation || state.responseWriter == nil { + state.mu.Unlock() + return nil, nil + } + rw := state.responseWriter + state.inFlight.Add(1) + return state, rw +} + +func finishDelegatedCall(state *opsCaptureWriterState) { + if state != nil { + state.inFlight.Done() + } +} + func (w *opsCaptureWriter) setContext(ctx *gin.Context) { state, _ := w.lockActiveWrite() if state == nil { @@ -702,19 +730,21 @@ func (w *opsCaptureWriter) Header() http.Header { return rw.Header() } func (w *opsCaptureWriter) WriteHeader(code int) { - state, rw := w.lockActive() + state, rw := w.beginDelegatedCall() if state == nil { return } - defer state.mu.RUnlock() + state.mu.Unlock() + defer finishDelegatedCall(state) rw.WriteHeader(code) } func (w *opsCaptureWriter) WriteHeaderNow() { - state, rw := w.lockActive() + state, rw := w.beginDelegatedCall() if state == nil { return } - defer state.mu.RUnlock() + state.mu.Unlock() + defer finishDelegatedCall(state) rw.WriteHeaderNow() } func (w *opsCaptureWriter) Status() int { @@ -742,19 +772,21 @@ func (w *opsCaptureWriter) Written() bool { return rw.Written() } func (w *opsCaptureWriter) Flush() { - state, rw := w.lockActive() + state, rw := w.beginDelegatedCall() if state == nil { return } - defer state.mu.RUnlock() + state.mu.Unlock() + defer finishDelegatedCall(state) rw.Flush() } func (w *opsCaptureWriter) Hijack() (net.Conn, *bufio.ReadWriter, error) { - state, rw := w.lockActive() + state, rw := w.beginDelegatedCall() if state == nil { return nil, nil, errors.New("response writer released") } - defer state.mu.RUnlock() + state.mu.Unlock() + defer finishDelegatedCall(state) return rw.Hijack() } func (w *opsCaptureWriter) CloseNotify() <-chan bool { @@ -777,26 +809,28 @@ func (w *opsCaptureWriter) Pusher() http.Pusher { } func (w *opsCaptureWriter) Write(b []byte) (int, error) { - state, rw := w.lockActiveWrite() + state, rw := w.beginDelegatedCall() if state == nil { return 0, nil } - defer state.mu.Unlock() if state.shouldCapture() { state.captureResponseChunk(b, rw.Status()) } + state.mu.Unlock() + defer finishDelegatedCall(state) return rw.Write(b) } func (w *opsCaptureWriter) WriteString(s string) (int, error) { - state, rw := w.lockActiveWrite() + state, rw := w.beginDelegatedCall() if state == nil { return 0, nil } - defer state.mu.Unlock() if state.shouldCapture() { state.captureResponseChunk([]byte(s), rw.Status()) } + state.mu.Unlock() + defer finishDelegatedCall(state) return rw.WriteString(s) } @@ -887,6 +921,13 @@ func (state *opsCaptureWriterState) captureResponseChunk(chunk []byte, status in state.appendCapturedResponse(chunk) return } + // Most stream writes contain one or more complete successful SSE frames. + // Skip the byte-wise frame parser when the chunk cannot contain a terminal + // event and leaves no split frame to carry into the next write. + if len(state.probe) == 0 && len(state.lineProbe) == 0 && endsAtOpsSSEFrameBoundary(chunk) && + !mayContainOpsTerminalSSE(chunk) { + return + } for i, b := range chunk { if state.skipLF { state.skipLF = false @@ -952,6 +993,20 @@ func (state *opsCaptureWriterState) captureResponseChunk(chunk []byte, status in } } +func endsAtOpsSSEFrameBoundary(chunk []byte) bool { + return bytes.HasSuffix(chunk, []byte("\n\n")) || + bytes.HasSuffix(chunk, []byte("\r\n\r\n")) || + bytes.HasSuffix(chunk, []byte("\r\r")) +} + +func mayContainOpsTerminalSSE(chunk []byte) bool { + if bytes.Contains(chunk, []byte("response.failed")) { + return true + } + return bytes.Contains(chunk, []byte("error")) && + (bytes.Contains(chunk, []byte("event")) || bytes.Contains(chunk, []byte(`"type"`))) +} + func isOpsTerminalSSEEventLine(line []byte) bool { line = bytes.TrimSpace(line) field, value, found := bytes.Cut(line, []byte{':'}) @@ -1066,10 +1121,14 @@ func OpsErrorLoggerMiddleware(ops *service.OpsService) gin.HandlerFunc { if parsed.StreamFailure { status = inferStreamFailureStatus(c, parsed) } else { - // Locally generated in-band errors use an explicit context marker and - // may not have a capturable terminal frame. Preserve that fallback, - // but never turn recovered upstream attempts into request errors. - logOpsStreamError(c, ops, status) + // A marked in-band error is a visible request failure even though its + // wire status is already 200. Otherwise retain recovered attempts as a + // provider-health row whose 2xx status keeps it outside request SLA. + if len(service.GetOpsStreamErrors(c)) > 0 { + logOpsStreamError(c, ops, status) + } else { + logOpsRecoveredUpstream(c, ops, status) + } return } } @@ -1214,6 +1273,126 @@ func OpsErrorLoggerMiddleware(ops *service.OpsService) gin.HandlerFunc { } } +func logOpsRecoveredUpstream(c *gin.Context, ops *service.OpsService, finalStatus int) { + if c == nil || ops == nil || finalStatus >= 400 { + return + } + + entry := &service.OpsInsertErrorLogInput{StatusCode: finalStatus} + applyOpsUpstreamFieldsFromContext(c, entry) + if entry.UpstreamStatusCode == nil && entry.UpstreamErrorMessage == nil && + entry.UpstreamErrorDetail == nil && len(entry.UpstreamErrors) == 0 { + return + } + + lastStatus := 0 + if entry.UpstreamStatusCode != nil { + lastStatus = *entry.UpstreamStatusCode + } + lastStage := "" + for i := len(entry.UpstreamErrors) - 1; i >= 0; i-- { + if event := entry.UpstreamErrors[i]; event != nil { + lastStage = event.Stage + if event.AccountID > 0 { + accountID := event.AccountID + entry.AccountID = &accountID + } + break + } + } + if entry.AccountID == nil { + if accountID, ok := c.Get(opsAccountIDKey); ok { + if value, ok := accountID.(int64); ok && value > 0 { + entry.AccountID = &value + } + } + } + + entry.ErrorPhase = "upstream" + entry.ErrorType = "upstream_error" + entry.ErrorSource = "upstream_http" + entry.ErrorOwner = "provider" + entry.Severity = classifyOpsSeverity(entry.ErrorType, lastStatus) + entry.IsCountTokens = isCountTokensRequest(c) + entry.CreatedAt = time.Now() + entry.ErrorMessage = "Recovered upstream error" + if lastStage == string(service.GatewayFailureStageAccountAuth) { + entry.ErrorPhase = string(service.GatewayFailureStageAccountAuth) + entry.ErrorMessage = "Recovered account authentication failure" + } else if lastStatus > 0 { + entry.ErrorMessage += " " + strconv.Itoa(lastStatus) + } + if entry.UpstreamErrorMessage != nil && strings.TrimSpace(*entry.UpstreamErrorMessage) != "" { + entry.ErrorMessage += ": " + strings.TrimSpace(*entry.UpstreamErrorMessage) + } + entry.ErrorMessage = truncateString(entry.ErrorMessage, 2048) + + if c.Request != nil { + entry.UserAgent = c.GetHeader("User-Agent") + if c.Request.URL != nil { + entry.RequestPath = c.Request.URL.Path + } + if c.Request.Context() != nil { + entry.ClientRequestID, _ = c.Request.Context().Value(ctxkey.ClientRequestID).(string) + entry.RequestID, _ = c.Request.Context().Value(ctxkey.RequestID).(string) + } + } + entry.RequestID = strings.TrimSpace(entry.RequestID) + if entry.RequestID == "" { + entry.RequestID = c.Writer.Header().Get("X-Request-Id") + } + entry.Model = c.GetString(opsModelKey) + entry.RequestedModel = entry.Model + entry.Stream = c.GetBool(opsStreamKey) + entry.InboundEndpoint = GetInboundEndpoint(c) + entry.UpstreamModel = c.GetString(opsUpstreamModelKey) + entry.RequestType = opsRequestTypeFromContext(c) + + apiKey := getOpsAPIKey(c) + fallbackPlatform := guessPlatformFromPath(entry.RequestPath) + var requestContext context.Context = context.Background() + if c.Request != nil { + requestContext = c.Request.Context() + } + entry.Platform = resolveOpsPlatform(requestContext, apiKey, fallbackPlatform) + entry.UpstreamEndpoint = GetUpstreamEndpoint(c, entry.Platform) + if apiKey != nil { + entry.APIKeyID = &apiKey.ID + entry.APIKeyPrefix = keyPrefix(apiKey.Key, 8) + if apiKey.User != nil { + entry.UserID = &apiKey.User.ID + } + if apiKey.GroupID != nil { + entry.GroupID = apiKey.GroupID + } + if apiKey.Group != nil && apiKey.Group.Platform != "" { + entry.Platform = apiKey.Group.Platform + } + } + if clientIP := strings.TrimSpace(ip.GetClientIP(c)); clientIP != "" { + entry.ClientIP = &clientIP + } + applyOpsLatencyFieldsFromContext(c, entry) + enqueueOpsErrorLog(ops, entry) +} + +func opsRequestTypeFromContext(c *gin.Context) *int16 { + if c == nil { + return nil + } + if value, ok := c.Get(opsRequestTypeKey); ok { + switch typed := value.(type) { + case int16: + result := typed + return &result + case int: + result := int16(typed) + return &result + } + } + return nil +} + // logOpsStreamError 记录一次挂在已固化 HTTP 200 SSE 流上的就地错误。 // 由于 wire 状态码停留在 200,常规的 status>=400 捕获路径永远不会触发; // handleStreamingAwareError 通过 service.MarkOpsStreamError 标记这类错误, diff --git a/backend/internal/handler/ops_error_logger_test.go b/backend/internal/handler/ops_error_logger_test.go index 1956ad2776..38176cb1b0 100644 --- a/backend/internal/handler/ops_error_logger_test.go +++ b/backend/internal/handler/ops_error_logger_test.go @@ -38,15 +38,18 @@ func (r *ingressRejectSettingRepo) Set(context.Context, string, string) error { type ingressRejectOpsRepo struct { service.OpsRepository insertCalls int + entries []*service.OpsInsertErrorLogInput } -func (r *ingressRejectOpsRepo) InsertErrorLog(context.Context, *service.OpsInsertErrorLogInput) (int64, error) { +func (r *ingressRejectOpsRepo) InsertErrorLog(_ context.Context, entry *service.OpsInsertErrorLogInput) (int64, error) { r.insertCalls++ + r.entries = append(r.entries, entry) return 0, nil } -func (r *ingressRejectOpsRepo) BatchInsertErrorLogs(context.Context, []*service.OpsInsertErrorLogInput) (int64, error) { +func (r *ingressRejectOpsRepo) BatchInsertErrorLogs(_ context.Context, entries []*service.OpsInsertErrorLogInput) (int64, error) { r.insertCalls++ + r.entries = append(r.entries, entries...) return 0, nil } @@ -328,11 +331,12 @@ func TestOpsErrorLoggerMiddleware_OrdinaryPermissionStillRecords(t *testing.T) { require.Equal(t, http.StatusForbidden, job.entry.StatusCode) } -func TestOpsErrorLoggerMiddleware_SkipsRecoveredUpstreamErrorOnSuccessfulRequest(t *testing.T) { +func TestOpsErrorLoggerMiddleware_RecordsRecoveredUpstreamTelemetryOutsideFailureSLA(t *testing.T) { setupOpsErrorLogTestQueue(t, 2) gin.SetMode(gin.TestMode) - ops := service.NewOpsService(nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil) + repo := &ingressRejectOpsRepo{} + ops := service.NewOpsService(repo, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil) router := gin.New() router.Use(OpsErrorLoggerMiddleware(ops)) router.POST("/v1/responses", func(c *gin.Context) { @@ -347,7 +351,50 @@ func TestOpsErrorLoggerMiddleware_SkipsRecoveredUpstreamErrorOnSuccessfulRequest router.ServeHTTP(recorder, httptest.NewRequest(http.MethodPost, "/v1/responses", nil)) require.Equal(t, http.StatusOK, recorder.Code) - require.Zero(t, OpsErrorLogQueueLength()) + require.Equal(t, int64(1), OpsErrorLogQueueLength()) + job := <-opsErrorLogQueue + require.Nil(t, job.entry.UpstreamErrors, "raw attempts must be released before async queueing") + require.NotNil(t, job.entry.UpstreamErrorsJSON) + queuedEvents, err := service.ParseOpsUpstreamErrors(*job.entry.UpstreamErrorsJSON) + require.NoError(t, err) + require.Len(t, queuedEvents, 1) + require.Equal(t, http.StatusTooManyRequests, queuedEvents[0].UpstreamStatusCode) + + flushOpsErrorLogBatch([]opsErrorLogJob{job}) + require.Equal(t, 1, repo.insertCalls) + require.Len(t, repo.entries, 1) + persisted := repo.entries[0] + require.Equal(t, http.StatusOK, persisted.StatusCode, "recovered telemetry must remain outside failed-request SLA") + require.Equal(t, "upstream", persisted.ErrorPhase) + require.Equal(t, "upstream_error", persisted.ErrorType) + require.Equal(t, "Recovered upstream error 429: earlier attempt was rate limited", persisted.ErrorMessage) + require.NotNil(t, persisted.UpstreamErrorsJSON) + persistedEvents, err := service.ParseOpsUpstreamErrors(*persisted.UpstreamErrorsJSON) + require.NoError(t, err) + require.Len(t, persistedEvents, 1) + require.Equal(t, http.StatusTooManyRequests, persistedEvents[0].UpstreamStatusCode) +} + +func TestOpsErrorLoggerMiddleware_IntermediateSkipMonitoringDoesNotHideFinalVisibleFailure(t *testing.T) { + setupOpsErrorLogTestQueue(t, 2) + gin.SetMode(gin.TestMode) + ops := service.NewOpsService(nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil) + router := gin.New() + router.Use(OpsErrorLoggerMiddleware(ops)) + router.POST("/v1/responses", func(c *gin.Context) { + c.Set(service.OpsUpstreamErrorsKey, []*service.OpsUpstreamErrorEvent{ + {UpstreamStatusCode: http.StatusBadGateway, Message: "hidden retry", SkipMonitoring: true}, + {UpstreamStatusCode: http.StatusServiceUnavailable, Message: "visible final"}, + }) + c.JSON(http.StatusServiceUnavailable, gin.H{"error": gin.H{"type": "upstream_error", "message": "visible final"}}) + }) + + recorder := httptest.NewRecorder() + router.ServeHTTP(recorder, httptest.NewRequest(http.MethodPost, "/v1/responses", nil)) + require.Equal(t, int64(1), OpsErrorLogQueueLength()) + job := <-opsErrorLogQueue + require.Equal(t, http.StatusServiceUnavailable, job.entry.StatusCode) + require.Equal(t, "visible final", job.entry.ErrorMessage) } func TestOpsErrorLoggerMiddleware_CapturesSplitResponsesFailedSSE(t *testing.T) { diff --git a/backend/internal/repository/gateway_cache.go b/backend/internal/repository/gateway_cache.go index f67e92b263..36935160da 100644 --- a/backend/internal/repository/gateway_cache.go +++ b/backend/internal/repository/gateway_cache.go @@ -270,27 +270,47 @@ func (c *gatewayCache) GetReasoningContent(ctx context.Context, itemID string) ( } const ( - cyberSessionBlockPrefix = "cyber_session_block:" - cyberSessionScopePrefix = "cyber_session_scope:" + cyberSessionBlockPrefix = "cyber_session_block:" + cyberSessionScopePrefix = "cyber_session_scope:" + cyberSessionRedisCommandMaxKeys = 128 ) -// SetCyberSessionBlocked atomically writes all exact blocks and their optional -// coarse source scope with the same TTL. +// SetCyberSessionBlocked writes exact blocks in bounded transactions. The +// coarse scope is activated only after all exact blocks have been stored. func (c *gatewayCache) SetCyberSessionBlocked(ctx context.Context, scopeKey string, keys []string, ttl time.Duration) error { if len(keys) == 0 { return nil } - pipe := c.rdb.TxPipeline() - for _, key := range keys { - if key != "" { + exactKeys := make([]string, 0, cyberSessionRedisCommandMaxKeys) + flush := func() error { + if len(exactKeys) == 0 { + return nil + } + pipe := c.rdb.TxPipeline() + for _, key := range exactKeys { pipe.Set(ctx, cyberSessionBlockPrefix+key, "1", ttl) } + _, err := pipe.Exec(ctx) + exactKeys = exactKeys[:0] + return err + } + for _, key := range keys { + if key != "" { + exactKeys = append(exactKeys, key) + if len(exactKeys) == cyberSessionRedisCommandMaxKeys { + if err := flush(); err != nil { + return err + } + } + } + } + if err := flush(); err != nil { + return err } if scopeKey != "" { - pipe.Set(ctx, cyberSessionScopePrefix+scopeKey, "1", ttl) + return c.rdb.Set(ctx, cyberSessionScopePrefix+scopeKey, "1", ttl).Err() } - _, err := pipe.Exec(ctx) - return err + return nil } func (c *gatewayCache) IsCyberSessionScopeActive(ctx context.Context, scopeKey string) (bool, error) { @@ -301,23 +321,29 @@ func (c *gatewayCache) IsCyberSessionScopeActive(ctx context.Context, scopeKey s return n > 0, nil } -// FindCyberSessionBlocked checks transcript-prefix candidates in one Redis -// round trip and returns the first blocked key in caller order. +// FindCyberSessionBlocked checks bounded batches in caller order and stops at +// the first blocked key, preserving the original earliest-match behavior. func (c *gatewayCache) FindCyberSessionBlocked(ctx context.Context, keys []string) (string, error) { if len(keys) == 0 { return "", nil } - redisKeys := make([]string, len(keys)) - for i, key := range keys { - redisKeys[i] = cyberSessionBlockPrefix + key - } - values, err := c.rdb.MGet(ctx, redisKeys...).Result() - if err != nil { - return "", err - } - for i, value := range values { - if value != nil { - return keys[i], nil + for start := 0; start < len(keys); start += cyberSessionRedisCommandMaxKeys { + end := start + cyberSessionRedisCommandMaxKeys + if end > len(keys) { + end = len(keys) + } + redisKeys := make([]string, end-start) + for i, key := range keys[start:end] { + redisKeys[i] = cyberSessionBlockPrefix + key + } + values, err := c.rdb.MGet(ctx, redisKeys...).Result() + if err != nil { + return "", err + } + for i, value := range values { + if value != nil { + return keys[start+i], nil + } } } return "", nil diff --git a/backend/internal/repository/gateway_cache_cyber_test.go b/backend/internal/repository/gateway_cache_cyber_test.go index 40396e7c26..03f29e82a1 100644 --- a/backend/internal/repository/gateway_cache_cyber_test.go +++ b/backend/internal/repository/gateway_cache_cyber_test.go @@ -2,6 +2,8 @@ package repository import ( "context" + "strconv" + "sync" "testing" "time" @@ -11,6 +13,42 @@ import ( "github.com/stretchr/testify/require" ) +type cyberRedisCommandHook struct { + mu sync.Mutex + mgetKeyCounts []int + setBatchSizes []int +} + +func (h *cyberRedisCommandHook) DialHook(next redis.DialHook) redis.DialHook { return next } + +func (h *cyberRedisCommandHook) ProcessHook(next redis.ProcessHook) redis.ProcessHook { + return func(ctx context.Context, cmd redis.Cmder) error { + if cmd.Name() == "mget" { + h.mu.Lock() + h.mgetKeyCounts = append(h.mgetKeyCounts, len(cmd.Args())-1) + h.mu.Unlock() + } + return next(ctx, cmd) + } +} + +func (h *cyberRedisCommandHook) ProcessPipelineHook(next redis.ProcessPipelineHook) redis.ProcessPipelineHook { + return func(ctx context.Context, cmds []redis.Cmder) error { + setCount := 0 + for _, cmd := range cmds { + if cmd.Name() == "set" { + setCount++ + } + } + if setCount > 0 { + h.mu.Lock() + h.setBatchSizes = append(h.setBatchSizes, setCount) + h.mu.Unlock() + } + return next(ctx, cmds) + } +} + func TestGatewayCacheCyberBlockWritesScopeAndExactKeysTogether(t *testing.T) { server := miniredis.RunT(t) client := redis.NewClient(&redis.Options{Addr: server.Addr()}) @@ -29,3 +67,31 @@ func TestGatewayCacheCyberBlockWritesScopeAndExactKeysTogether(t *testing.T) { require.Greater(t, server.TTL(cyberSessionScopePrefix+"scope-1"), time.Duration(0)) require.Equal(t, server.TTL(cyberSessionBlockPrefix+"block-1"), server.TTL(cyberSessionBlockPrefix+"block-2")) } + +func TestGatewayCacheCyberBlockCommandsAreBoundedAndLookupShortCircuits(t *testing.T) { + server := miniredis.RunT(t) + client := redis.NewClient(&redis.Options{Addr: server.Addr()}) + t.Cleanup(func() { _ = client.Close() }) + hook := &cyberRedisCommandHook{} + client.AddHook(hook) + store, ok := NewGatewayCache(client).(service.CyberSessionBlockStore) + require.True(t, ok) + + keys := make([]string, cyberSessionRedisCommandMaxKeys*2+44) + for i := range keys { + keys[i] = "block-" + strconv.Itoa(i) + } + ctx := context.Background() + require.NoError(t, store.SetCyberSessionBlocked(ctx, "large-scope", keys, time.Minute)) + require.Equal(t, []int{cyberSessionRedisCommandMaxKeys, cyberSessionRedisCommandMaxKeys, 44}, hook.setBatchSizes) + + lookup := make([]string, len(keys)) + for i := range lookup { + lookup[i] = "missing-" + strconv.Itoa(i) + } + lookup[cyberSessionRedisCommandMaxKeys+3] = keys[cyberSessionRedisCommandMaxKeys+3] + matched, err := store.FindCyberSessionBlocked(ctx, lookup) + require.NoError(t, err) + require.Equal(t, keys[cyberSessionRedisCommandMaxKeys+3], matched) + require.Equal(t, []int{cyberSessionRedisCommandMaxKeys, cyberSessionRedisCommandMaxKeys}, hook.mgetKeyCounts) +} diff --git a/backend/internal/repository/temp_unsched_cache.go b/backend/internal/repository/temp_unsched_cache.go index c145a30476..42c2fd648c 100644 --- a/backend/internal/repository/temp_unsched_cache.go +++ b/backend/internal/repository/temp_unsched_cache.go @@ -141,8 +141,3 @@ func (c *tempUnschedCache) RecordOpenAIAPIKeyHealthFailure(ctx context.Context, } return count, tripped == 1, nil } - -func (c *tempUnschedCache) ResetOpenAIAPIKeyHealthFailures(ctx context.Context, accountID int64) error { - key := c.openAIAPIKeyHealthKey(accountID) - return c.rdb.Del(ctx, key, key+":sequence").Err() -} diff --git a/backend/internal/repository/temp_unsched_cache_health_test.go b/backend/internal/repository/temp_unsched_cache_health_test.go index 092b85ac6b..1b8a1f10c6 100644 --- a/backend/internal/repository/temp_unsched_cache_health_test.go +++ b/backend/internal/repository/temp_unsched_cache_health_test.go @@ -3,6 +3,7 @@ package repository import ( "context" "testing" + "time" "github.com/Wei-Shaw/sub2api/internal/service" "github.com/alicebob/miniredis/v2" @@ -10,7 +11,7 @@ import ( "github.com/stretchr/testify/require" ) -func TestOpenAIAPIKeyHealthCacheTripsAndSuccessResetsWindow(t *testing.T) { +func TestOpenAIAPIKeyHealthCacheTripsWithinRollingWindow(t *testing.T) { server := miniredis.RunT(t) client := redis.NewClient(&redis.Options{Addr: server.Addr()}) t.Cleanup(func() { _ = client.Close() }) @@ -18,14 +19,6 @@ func TestOpenAIAPIKeyHealthCacheTripsAndSuccessResetsWindow(t *testing.T) { require.True(t, ok) ctx := context.Background() - for attempt := 1; attempt <= 2; attempt++ { - count, tripped, err := store.RecordOpenAIAPIKeyHealthFailure(ctx, 42, 1, 3) - require.NoError(t, err) - require.EqualValues(t, attempt, count) - require.False(t, tripped) - } - require.NoError(t, store.ResetOpenAIAPIKeyHealthFailures(ctx, 42)) - for attempt := 1; attempt <= 3; attempt++ { count, tripped, err := store.RecordOpenAIAPIKeyHealthFailure(ctx, 42, 1, 3) require.NoError(t, err) @@ -33,3 +26,25 @@ func TestOpenAIAPIKeyHealthCacheTripsAndSuccessResetsWindow(t *testing.T) { require.Equal(t, attempt == 3, tripped) } } + +func TestOpenAIAPIKeyHealthCacheDropsFailuresOutsideRollingWindow(t *testing.T) { + server := miniredis.RunT(t) + now := time.Unix(1_700_000_000, 0) + server.SetTime(now) + client := redis.NewClient(&redis.Options{Addr: server.Addr()}) + t.Cleanup(func() { _ = client.Close() }) + store, ok := NewTempUnschedCache(client).(service.OpenAIAPIKeyHealthCache) + require.True(t, ok) + + ctx := context.Background() + count, tripped, err := store.RecordOpenAIAPIKeyHealthFailure(ctx, 42, 1, 3) + require.NoError(t, err) + require.EqualValues(t, 1, count) + require.False(t, tripped) + + server.SetTime(now.Add(61 * time.Second)) + count, tripped, err = store.RecordOpenAIAPIKeyHealthFailure(ctx, 42, 1, 3) + require.NoError(t, err) + require.EqualValues(t, 1, count) + require.False(t, tripped) +} diff --git a/backend/internal/service/openai_access_state_failover_test.go b/backend/internal/service/openai_access_state_failover_test.go index 0acaa26182..a46f9ca571 100644 --- a/backend/internal/service/openai_access_state_failover_test.go +++ b/backend/internal/service/openai_access_state_failover_test.go @@ -24,22 +24,59 @@ func (r *openAIStream403AccountRepo) SetError(context.Context, int64, string) er return nil } +type openAIAuthPolicyAccountRepo struct { + AccountRepository + tempCalls int + setErrorCalls int +} + +func (r *openAIAuthPolicyAccountRepo) SetTempUnschedulable(context.Context, int64, time.Time, string) error { + r.tempCalls++ + return nil +} + +func (r *openAIAuthPolicyAccountRepo) SetError(context.Context, int64, string) error { + r.setErrorCalls++ + return nil +} + +type openAIAuthPolicy403Counter struct { + counts []int64 +} + +func (s *openAIAuthPolicy403Counter) IncrementOpenAI403Count(context.Context, int64, int) (int64, error) { + if len(s.counts) == 0 { + return 1, nil + } + count := s.counts[0] + s.counts = s.counts[1:] + return count, nil +} + +func (*openAIAuthPolicy403Counter) ResetOpenAI403Count(context.Context, int64) error { + return nil +} + func TestOpenAIUpstreamAccessStateClassification(t *testing.T) { tests := []struct { name string body string + want bool }{ - {"workspace_code", `{"detail":{"code":"deactivated_workspace"}}`}, - {"disabled_account", `{"error":{"message":"Your account is disabled"}}`}, - {"suspended_workspace", `{"response":{"error":{"message":"This workspace has been suspended"}}}`}, - {"deactivated_organization", `{"detail":{"message":"The organization is deactivated"}}`}, - {"scalar_detail", `{"detail":"This workspace has been disabled"}`}, - {"suspended_org_code", `{"error":{"code":"org_suspended"}}`}, + {"workspace_code", `{"detail":{"code":"deactivated_workspace"}}`, true}, + {"disabled_account_message", `{"error":{"message":"Your account is disabled"}}`, false}, + {"suspended_workspace_message", `{"response":{"error":{"message":"This workspace has been suspended"}}}`, false}, + {"deactivated_organization_message", `{"detail":{"message":"The organization is deactivated"}}`, false}, + {"scalar_detail", `{"detail":"This workspace has been disabled"}`, false}, + {"suspended_org_code", `{"error":{"code":"org_suspended"}}`, true}, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { body := []byte(tt.body) - require.True(t, isOpenAIUpstreamAccessStateError("", body)) + require.Equal(t, tt.want, isOpenAIUpstreamAccessStateError("", body)) + if !tt.want { + return + } require.True(t, (&OpenAIGatewayService{}).shouldFailoverOpenAIUpstreamResponse(http.StatusForbidden, "", body)) require.True(t, shouldFailoverOpenAIPassthroughResponse(&Account{Type: AccountTypeOAuth}, http.StatusForbidden, body)) @@ -62,6 +99,93 @@ func TestOpenAIUpstreamAccessStateDoesNotScanEchoedJSON(t *testing.T) { require.False(t, shouldFailoverOpenAIPassthroughResponse(&Account{Type: AccountTypeOAuth}, http.StatusBadRequest, body)) } +func TestOpenAIHTTPAccessStateDoesNotTrustBadRequestMessage(t *testing.T) { + body := []byte(`{"error":{"type":"invalid_request_error","code":"unknown_parameter","message":"Unknown parameter: account disabled"}}`) + svc := &OpenAIGatewayService{} + + require.False(t, isOpenAIUpstreamAccessStateError("", body), "free-form stream messages are not durable account evidence") + require.False(t, isOpenAIHTTPUpstreamAccessStateError(http.StatusBadRequest, "", body)) + require.False(t, svc.shouldFailoverOpenAIUpstreamResponse(http.StatusBadRequest, "", body)) + require.False(t, shouldFailoverOpenAIPassthroughResponse(&Account{Type: AccountTypeOAuth}, http.StatusBadRequest, body)) + + err := newOpenAIUpstreamFailoverError(http.StatusBadRequest, nil, body, "", false) + require.False(t, err.IsCredentialFailure()) +} + +func TestOpenAIHTTPAccessStateBadRequestDoesNotDisableAccount(t *testing.T) { + repo := &openAIStream403AccountRepo{} + svc := &OpenAIGatewayService{rateLimitService: &RateLimitService{accountRepo: repo}} + account := &Account{ID: 925, Platform: PlatformOpenAI, Type: AccountTypeOAuth, Status: StatusActive, Schedulable: true} + body := []byte(`{"error":{"code":"unknown_parameter","message":"Unknown parameter: account disabled"}}`) + + disabled := svc.handleOpenAIAccountUpstreamError(context.Background(), account, http.StatusBadRequest, nil, body) + + require.False(t, disabled) + require.Zero(t, repo.setErrorCalls) + require.False(t, svc.isOpenAIAccountRuntimeBlocked(account)) +} + +func TestOpenAIStreamEchoedAccessStateMessageDoesNotDisableOrFailover(t *testing.T) { + repo := &openAIStream403AccountRepo{} + svc := &OpenAIGatewayService{rateLimitService: &RateLimitService{accountRepo: repo}} + account := &Account{ID: 926, Platform: PlatformOpenAI, Type: AccountTypeOAuth, Status: StatusActive, Schedulable: true} + payload := []byte(`{"type":"response.failed","response":{"error":{"type":"invalid_request_error","code":"unknown_parameter","message":"Unknown parameter: account disabled"}}}`) + message := extractOpenAISSEErrorMessage(payload) + + require.False(t, isOpenAIUpstreamAccessStateError(message, payload)) + require.False(t, openAIStreamFailedEventShouldFailover(payload, message)) + status, disabled := svc.handleOpenAIStreamTerminalAccountSideEffects(nil, account, payload, message, nil) + require.Equal(t, http.StatusBadGateway, status) + require.False(t, disabled) + require.Zero(t, repo.setErrorCalls) + require.False(t, svc.isOpenAIAccountRuntimeBlocked(account)) +} + +func TestOpenAIHTTPAccessStateTrustsStructuredCode(t *testing.T) { + repo := &openAIStream403AccountRepo{} + svc := &OpenAIGatewayService{rateLimitService: &RateLimitService{accountRepo: repo}} + account := &Account{ID: 930, Platform: PlatformOpenAI, Type: AccountTypeOAuth, Status: StatusActive, Schedulable: true} + body := []byte(`{"error":{"code":"organization_deactivated","message":"request rejected"}}`) + + require.True(t, isOpenAIHTTPUpstreamAccessStateError(http.StatusBadRequest, "", body)) + require.True(t, svc.shouldFailoverOpenAIUpstreamResponse(http.StatusBadRequest, "", body)) + require.True(t, svc.handleOpenAIAccountUpstreamError(context.Background(), account, http.StatusBadRequest, nil, body)) + require.Equal(t, 1, repo.setErrorCalls) + require.True(t, svc.isOpenAIAccountRuntimeBlocked(account)) +} + +func TestOpenAIHTTPAuthMessagesUseExistingStatusPolicies(t *testing.T) { + t.Run("oauth 401 remains recoverable", func(t *testing.T) { + repo := &openAIAuthPolicyAccountRepo{} + rateLimits := NewRateLimitService(repo, nil, &config.Config{}, nil, nil) + svc := &OpenAIGatewayService{rateLimitService: rateLimits} + account := &Account{ID: 931, Platform: PlatformOpenAI, Type: AccountTypeOAuth, Status: StatusActive, Schedulable: true, + Credentials: map[string]any{"refresh_token": "refreshable"}} + body := []byte(`{"error":{"message":"account is disabled"}}`) + + require.False(t, isOpenAIHTTPUpstreamAccessStateError(http.StatusUnauthorized, "", body)) + require.True(t, svc.handleOpenAIAccountUpstreamError(context.Background(), account, http.StatusUnauthorized, nil, body)) + require.Zero(t, repo.setErrorCalls) + require.Equal(t, 1, repo.tempCalls) + }) + + t.Run("403 uses counter cooldown", func(t *testing.T) { + repo := &openAIAuthPolicyAccountRepo{} + counter := &openAIAuthPolicy403Counter{counts: []int64{1}} + rateLimits := NewRateLimitService(repo, nil, &config.Config{}, nil, nil) + rateLimits.openAI403CounterCache = counter + svc := &OpenAIGatewayService{rateLimitService: rateLimits} + rateLimits.SetAccountRuntimeBlocker(svc) + account := &Account{ID: 932, Platform: PlatformOpenAI, Type: AccountTypeOAuth, Status: StatusActive, Schedulable: true} + body := []byte(`{"error":{"message":"workspace has been suspended"}}`) + + require.False(t, isOpenAIHTTPUpstreamAccessStateError(http.StatusForbidden, "", body)) + require.True(t, svc.handleOpenAIAccountUpstreamError(context.Background(), account, http.StatusForbidden, nil, body)) + require.Zero(t, repo.setErrorCalls) + require.Equal(t, 1, repo.tempCalls) + }) +} + func TestOpenAICyberPolicyWrapped5xxNeverFailsOver(t *testing.T) { body := []byte(`{"error":{"code":"cyber_policy","message":"blocked"}}`) svc := &OpenAIGatewayService{} diff --git a/backend/internal/service/openai_account_runtime_block_fastpath.go b/backend/internal/service/openai_account_runtime_block_fastpath.go index a25d78c697..1d8da95913 100644 --- a/backend/internal/service/openai_account_runtime_block_fastpath.go +++ b/backend/internal/service/openai_account_runtime_block_fastpath.go @@ -65,7 +65,7 @@ func (s *OpenAIGatewayService) handleOpenAIAccountUpstreamError(ctx context.Cont } stateCtx, cancel := openAIAccountStateContext(ctx) defer cancel() - if account != nil && account.Platform == PlatformOpenAI && isOpenAIUpstreamAccessStateError("", responseBody) { + if account != nil && account.Platform == PlatformOpenAI && isOpenAIHTTPUpstreamAccessStateError(statusCode, "", responseBody) { message := "OpenAI upstream account or workspace is unavailable" if upstreamMsg := strings.TrimSpace(extractUpstreamErrorMessage(responseBody)); upstreamMsg != "" { message = upstreamMsg diff --git a/backend/internal/service/openai_account_runtime_block_fastpath_test.go b/backend/internal/service/openai_account_runtime_block_fastpath_test.go index 97bfae0eee..db620cc5b8 100644 --- a/backend/internal/service/openai_account_runtime_block_fastpath_test.go +++ b/backend/internal/service/openai_account_runtime_block_fastpath_test.go @@ -15,11 +15,13 @@ import ( type oauth429RateLimitRepo struct { AccountRepository - setRateLimitedCalls int + setRateLimitedCalls int + lastRateLimitedUntil time.Time } -func (r *oauth429RateLimitRepo) SetRateLimited(context.Context, int64, time.Time) error { +func (r *oauth429RateLimitRepo) SetRateLimited(_ context.Context, _ int64, until time.Time) error { r.setRateLimitedCalls++ + r.lastRateLimitedUntil = until return nil } @@ -60,6 +62,52 @@ func TestOpenAI429FastPath_BlocksOAuthOnlyAfterRetryWindow(t *testing.T) { require.False(t, svc.shouldRetryOpenAIOAuth429OnSameAccount(account, http.StatusTooManyRequests, false)) } +func TestOpenAIStream429IgnoresSuccessfulQuotaSnapshotHeaders(t *testing.T) { + repo := &oauth429RateLimitRepo{} + rateLimits := NewRateLimitService(repo, nil, &config.Config{}, nil, nil) + svc := &OpenAIGatewayService{rateLimitService: rateLimits} + rateLimits.SetAccountRuntimeBlocker(svc) + account := &Account{ID: 421, Platform: PlatformOpenAI, Type: AccountTypeOAuth} + svc.openaiOAuth429RetryStartedAt.Store(account.ID, time.Now().Add(-openAIOAuth429RetryWindow-time.Second)) + headers := http.Header{} + headers.Set("x-codex-primary-used-percent", "37") + headers.Set("x-codex-primary-reset-after-seconds", "604800") + headers.Set("x-codex-primary-window-minutes", "10080") + payload := []byte(`{"type":"error","error":{"type":"rate_limit_error","code":"rate_limit_exceeded","message":"slow down"}}`) + + status, disabled := svc.handleOpenAIStreamTerminalAccountSideEffects(nil, account, payload, "slow down", headers) + + require.Equal(t, http.StatusTooManyRequests, status) + require.False(t, disabled) + require.True(t, svc.isOpenAIAccountRuntimeBlocked(account)) + value, ok := svc.openaiAccountRuntimeBlockUntil.Load(account.ID) + require.True(t, ok) + blockedUntil, ok := value.(time.Time) + require.True(t, ok) + require.Less(t, time.Until(blockedUntil), time.Minute, "stream 429 must not inherit the normal seven-day quota snapshot") + if !repo.lastRateLimitedUntil.IsZero() { + require.Less(t, time.Until(repo.lastRateLimitedUntil), time.Minute) + } +} + +func TestOpenAIHTTP429StillUsesQuotaResetHeaders(t *testing.T) { + svc := &OpenAIGatewayService{rateLimitService: &RateLimitService{}} + account := &Account{ID: 422, Platform: PlatformOpenAI, Type: AccountTypeOAuth} + svc.openaiOAuth429RetryStartedAt.Store(account.ID, time.Now().Add(-openAIOAuth429RetryWindow-time.Second)) + headers := http.Header{} + headers.Set("x-codex-primary-used-percent", "37") + headers.Set("x-codex-primary-reset-after-seconds", "604800") + headers.Set("x-codex-primary-window-minutes", "10080") + + svc.markOpenAIOAuth429RateLimited(context.Background(), account, headers, nil) + + value, ok := svc.openaiAccountRuntimeBlockUntil.Load(account.ID) + require.True(t, ok) + blockedUntil, ok := value.(time.Time) + require.True(t, ok) + require.Greater(t, time.Until(blockedUntil), 6*24*time.Hour, "real HTTP 429 must retain the upstream quota reset") +} + func TestOpenAI429RetryDelayHonorsBoundedRetryAfter(t *testing.T) { deadline := time.Now().Add(openAIOAuth429RetryWindow) require.Equal(t, openAIOAuth429RetryDelay, openAIOAuth429SameAccountRetryDelay(nil, deadline)) diff --git a/backend/internal/service/openai_alpha_search.go b/backend/internal/service/openai_alpha_search.go index 1954dc2670..c22545f5f1 100644 --- a/backend/internal/service/openai_alpha_search.go +++ b/backend/internal/service/openai_alpha_search.go @@ -104,7 +104,7 @@ func (s *OpenAIGatewayService) ForwardAlphaSearch(ctx context.Context, c *gin.Co if account.IsOpenAIOAuthLike() && resp.StatusCode == http.StatusTooManyRequests { return nil, s.newOpenAIAccountFailoverError(account, resp.StatusCode, resp.Header, respBody, upstreamMessage, shouldDisable, retryableOnSameAccount) } - if isOpenAIUpstreamAccessStateError(upstreamMessage, respBody) { + if isOpenAIHTTPUpstreamAccessStateError(resp.StatusCode, upstreamMessage, respBody) { return nil, newOpenAIUpstreamFailoverError(resp.StatusCode, resp.Header, respBody, upstreamMessage, retryableOnSameAccount) } return nil, &UpstreamFailoverError{StatusCode: resp.StatusCode, ResponseBody: respBody, RetryableOnSameAccount: retryableOnSameAccount} @@ -182,7 +182,7 @@ func (s *OpenAIGatewayService) forwardAlphaSearchViaResponsesWebSearch( if account.IsOpenAIOAuthLike() && resp.StatusCode == http.StatusTooManyRequests { return nil, s.newOpenAIAccountFailoverError(account, resp.StatusCode, resp.Header, respBody, upstreamMessage, shouldDisable, retryableOnSameAccount) } - if isOpenAIUpstreamAccessStateError(upstreamMessage, respBody) { + if isOpenAIHTTPUpstreamAccessStateError(resp.StatusCode, upstreamMessage, respBody) { return nil, newOpenAIUpstreamFailoverError(resp.StatusCode, resp.Header, respBody, upstreamMessage, retryableOnSameAccount) } return nil, &UpstreamFailoverError{StatusCode: resp.StatusCode, ResponseBody: respBody, RetryableOnSameAccount: retryableOnSameAccount} diff --git a/backend/internal/service/openai_apikey_health_breaker.go b/backend/internal/service/openai_apikey_health_breaker.go index c898cf1124..65581ae3d2 100644 --- a/backend/internal/service/openai_apikey_health_breaker.go +++ b/backend/internal/service/openai_apikey_health_breaker.go @@ -124,15 +124,7 @@ func (s *RateLimitService) ObserveOpenAIAPIKeyHealthFailure(ctx context.Context, return true } -func (s *RateLimitService) ObserveOpenAIAPIKeyHealthSuccess(ctx context.Context, account *Account) { - if s == nil || s.openAIAPIKeyHealth == nil || s.settingService == nil || !isOpenAIAPIKeyHealthBreakerAccount(account) { - return - } - settings, err := s.settingService.GetOpenAIAPIKeyHealthBreakerSettings(ctx) - if err != nil || settings == nil || !settings.Enabled { - return - } - if err := s.openAIAPIKeyHealth.ResetOpenAIAPIKeyHealthFailures(ctx, account.ID); err != nil { - logger.L().Warn("openai.apikey_health_breaker_reset_failed", zap.Int64("account_id", account.ID), zap.Error(err)) - } +func (s *RateLimitService) ObserveOpenAIAPIKeyHealthSuccess(context.Context, *Account) { + // Health failures are accumulated in a rolling time window. A success does + // not reset that window and must not add a Redis round trip to the hot path. } diff --git a/backend/internal/service/openai_apikey_health_breaker_test.go b/backend/internal/service/openai_apikey_health_breaker_test.go index a6e7aaad00..4c58ed1b4a 100644 --- a/backend/internal/service/openai_apikey_health_breaker_test.go +++ b/backend/internal/service/openai_apikey_health_breaker_test.go @@ -13,10 +13,12 @@ import ( type openAIAPIKeyHealthSettingRepo struct { SettingRepository - value string + value string + getCalls int } func (r *openAIAPIKeyHealthSettingRepo) GetValue(context.Context, string) (string, error) { + r.getCalls++ return r.value, nil } @@ -35,7 +37,6 @@ func (r *openAIAPIKeyHealthAccountRepo) SetTempUnschedulable(_ context.Context, type openAIAPIKeyHealthCacheStub struct { TempUnschedCache recordCalls int - resetCalls int setCalls int tripped bool } @@ -45,11 +46,6 @@ func (c *openAIAPIKeyHealthCacheStub) RecordOpenAIAPIKeyHealthFailure(context.Co return 3, c.tripped, nil } -func (c *openAIAPIKeyHealthCacheStub) ResetOpenAIAPIKeyHealthFailures(context.Context, int64) error { - c.resetCalls++ - return nil -} - func (c *openAIAPIKeyHealthCacheStub) SetTempUnsched(context.Context, int64, *TempUnschedState) error { c.setCalls++ return nil @@ -127,10 +123,11 @@ func TestOpenAIAPIKeyHealthBreakerTripsPersistedAndRuntimeState(t *testing.T) { require.Contains(t, repo.reason, openAIAPIKeyHealthBreakerReason) } -func TestOpenAIAPIKeyHealthSuccessResetsOnlyEligiblePoolAccount(t *testing.T) { +func TestOpenAIAPIKeyHealthSuccessDoesNotTouchSettingsOrCache(t *testing.T) { encoded, err := json.Marshal(OpenAIAPIKeyHealthBreakerSettings{Enabled: true, WindowMinutes: 1, FailureThreshold: 3, CooldownMinutes: 5}) require.NoError(t, err) - settings := NewSettingService(&openAIAPIKeyHealthSettingRepo{value: string(encoded)}, &config.Config{}) + settingRepo := &openAIAPIKeyHealthSettingRepo{value: string(encoded)} + settings := NewSettingService(settingRepo, &config.Config{}) cache := &openAIAPIKeyHealthCacheStub{} svc := NewRateLimitService(&openAIAPIKeyHealthAccountRepo{}, nil, &config.Config{}, nil, cache) svc.SetSettingService(settings) @@ -138,5 +135,6 @@ func TestOpenAIAPIKeyHealthSuccessResetsOnlyEligiblePoolAccount(t *testing.T) { svc.ObserveOpenAIAPIKeyHealthSuccess(context.Background(), openAIHealthPoolAccount()) svc.ObserveOpenAIAPIKeyHealthSuccess(context.Background(), &Account{ID: 43, Platform: PlatformOpenAI, Type: AccountTypeAPIKey}) - require.Equal(t, 1, cache.resetCalls) + require.Zero(t, settingRepo.getCalls) + require.Zero(t, cache.recordCalls) } diff --git a/backend/internal/service/openai_codex_function_call_id_test.go b/backend/internal/service/openai_codex_function_call_id_test.go index 1d798eec5e..18b2df3153 100644 --- a/backend/internal/service/openai_codex_function_call_id_test.go +++ b/backend/internal/service/openai_codex_function_call_id_test.go @@ -151,6 +151,28 @@ func TestFilterCodexInput_ExistingItemIDWinsOverLegacyCallIDMapping(t *testing.T require.Equal(t, "call_shared", filtered[2].(map[string]any)["id"]) } +func TestFilterCodexInput_NormalizesCrossTurnLegacyCallReference(t *testing.T) { + input := []any{ + map[string]any{"type": "item_reference", "id": "call_previous_turn"}, + } + + filtered := filterCodexInputWithOptions(input, codexInputFilterOptions{PreserveReferences: true}) + + require.Equal(t, "fc_previous_turn", filtered[0].(map[string]any)["id"]) +} + +func TestFilterCodexInput_PreservesNativeRemoteItemReferences(t *testing.T) { + for _, id := range []string{"fc_remote", "ctc_remote", "tsc_remote", "msg_remote", "rs_remote", "vendor_remote"} { + t.Run(id, func(t *testing.T) { + input := []any{map[string]any{"type": "item_reference", "id": id}} + + filtered := filterCodexInputWithOptions(input, codexInputFilterOptions{PreserveReferences: true}) + + require.Equal(t, id, filtered[0].(map[string]any)["id"]) + }) + } +} + // TestFilterCodexInput_StripsItemIDFromAllToolCallInputTypes verifies that // item_* ids are stripped from all call-input types (not output types). func TestFilterCodexInput_StripsItemIDFromAllToolCallInputTypes(t *testing.T) { diff --git a/backend/internal/service/openai_codex_transform.go b/backend/internal/service/openai_codex_transform.go index bd24f29c66..fbd14ba967 100644 --- a/backend/internal/service/openai_codex_transform.go +++ b/backend/internal/service/openai_codex_transform.go @@ -1562,10 +1562,25 @@ func codexInputItemIDs(input []any) map[string]struct{} { return itemIDs } +func codexInputCallIDs(input []any) map[string]struct{} { + callIDs := make(map[string]struct{}) + for _, rawItem := range input { + item, ok := rawItem.(map[string]any) + if !ok || !isCodexToolCallItemType(strings.TrimSpace(firstNonEmptyString(item["type"]))) { + continue + } + if callID := strings.TrimSpace(firstNonEmptyString(item["call_id"])); callID != "" { + callIDs[callID] = struct{}{} + } + } + return callIDs +} + func filterCodexInputWithOptions(input []any, opts codexInputFilterOptions) []any { filtered := make([]any, 0, len(input)) referenceIDMappings := codexItemReferenceIDMappings(input, opts.PreserveCallIDs) inputItemIDs := codexInputItemIDs(input) + inputCallIDs := codexInputCallIDs(input) for _, item := range input { m, ok := item.(map[string]any) if !ok { @@ -1629,8 +1644,14 @@ func filterCodexInputWithOptions(input []any, opts codexInputFilterOptions) []an if id, ok := newItem["id"].(string); ok && strings.HasPrefix(strings.TrimSpace(id), "call_") { trimmedID := strings.TrimSpace(id) _, referencesExistingItem := inputItemIDs[trimmedID] - if normalizedID, mapped := referenceIDMappings[trimmedID]; mapped && !referencesExistingItem { - newItem["id"] = normalizedID + if !referencesExistingItem { + if normalizedID, mapped := referenceIDMappings[trimmedID]; mapped { + newItem["id"] = normalizedID + } else if _, hasSameTurnCall := inputCallIDs[trimmedID]; !hasSameTurnCall { + // A bare call_* reference is a legacy function-call identifier. + // Normalize it even when its call item lives in an earlier turn. + newItem["id"] = normalizeCodexCallID(trimmedID) + } } } filtered = append(filtered, newItem) diff --git a/backend/internal/service/openai_codex_transform_test.go b/backend/internal/service/openai_codex_transform_test.go index 56be9570b0..7895b03cc3 100644 --- a/backend/internal/service/openai_codex_transform_test.go +++ b/backend/internal/service/openai_codex_transform_test.go @@ -127,6 +127,26 @@ func TestApplyCodexOAuthTransform_ToolContinuationNormalizesToolReferenceIDsOnly require.Equal(t, "fc_1", second["call_id"]) } +func TestApplyCodexOAuthTransform_NormalizesIsolatedLegacyReferenceAcrossTurns(t *testing.T) { + reqBody := map[string]any{ + "model": "gpt-5.2", + "input": []any{ + map[string]any{"type": "item_reference", "id": "call_previous_turn"}, + map[string]any{"type": "item_reference", "id": "fc_remote_item"}, + map[string]any{"type": "item_reference", "id": "vendor_remote_item"}, + }, + } + + applyCodexOAuthTransform(reqBody, false, false) + + input, ok := reqBody["input"].([]any) + require.True(t, ok) + require.Len(t, input, 3) + require.Equal(t, "fc_previous_turn", input[0].(map[string]any)["id"]) + require.Equal(t, "fc_remote_item", input[1].(map[string]any)["id"]) + require.Equal(t, "vendor_remote_item", input[2].(map[string]any)["id"]) +} + func TestApplyCodexOAuthTransform_BoundsLongCallIDsAndPreservesPairing(t *testing.T) { suffix := strings.Repeat("z", 62) for _, tc := range []struct { diff --git a/backend/internal/service/openai_compact_fallback.go b/backend/internal/service/openai_compact_fallback.go index 517a7e2e7b..389a4e8beb 100644 --- a/backend/internal/service/openai_compact_fallback.go +++ b/backend/internal/service/openai_compact_fallback.go @@ -1,7 +1,10 @@ package service import ( + "bytes" + "encoding/json" "errors" + "io" "net/http" "strings" @@ -89,11 +92,7 @@ func isOpenAICompactModelFailure(statusCode int, upstreamMsg string, upstreamBod case "model_not_found", "model_not_available", "unsupported_model", "invalid_model": return true } - if strings.Contains(value, "model") && (strings.Contains(value, "not found") || - strings.Contains(value, "does not exist") || - strings.Contains(value, "unavailable") || - strings.Contains(value, "unsupported") || - strings.Contains(value, "not supported")) { + if isExplicitOpenAIModelAvailabilityMessage(value) { return true } } @@ -115,6 +114,121 @@ func isOpenAICompactModelFailure(statusCode int, upstreamMsg string, upstreamBod return false } +func isExplicitOpenAIModelAvailabilityMessage(value string) bool { + value = strings.ToLower(strings.TrimSpace(value)) + if value == "" { + return false + } + for _, phrase := range []string{ + "model not found", + "model does not exist", + "model is unavailable", + "model is not available", + "model is unsupported", + "model is not supported", + "unsupported model", + } { + if strings.Contains(value, phrase) { + return true + } + } + // OpenAI commonly identifies the missing model between the word "model" + // and the terminal availability phrase, for example: "The model `x` does + // not exist". Requiring the message to start with the model subject avoids + // treating unrelated feature errors such as "model output is not supported" + // as a signal to change models. + if strings.HasPrefix(value, "the model ") || strings.HasPrefix(value, "model ") { + return strings.Contains(value, " does not exist") || + strings.Contains(value, " was not found") || + strings.Contains(value, " is unavailable") || + strings.Contains(value, " is not available") + } + return false +} + +func openAICompactFallbackErrorResponse(resp *http.Response, signal *openAICompactFallbackSignal) (*http.Response, []byte) { + headers := make(http.Header) + if resp != nil { + headers = resp.Header.Clone() + } + if headers.Get("Content-Type") == "" { + headers.Set("Content-Type", "application/json") + } + payload := normalizeOpenAICompactFallbackHTTPErrorPayload(signal) + return &http.Response{ + StatusCode: http.StatusBadRequest, + Header: headers, + Body: io.NopCloser(bytes.NewReader(payload)), + }, payload +} + +func normalizeOpenAICompactFallbackHTTPErrorPayload(signal *openAICompactFallbackSignal) []byte { + if signal == nil { + return nil + } + payload := append([]byte(nil), signal.payload...) + var terminal struct { + Error json.RawMessage `json:"error"` + Response struct { + Error json.RawMessage `json:"error"` + } `json:"response"` + } + if json.Unmarshal(payload, &terminal) != nil || len(bytes.TrimSpace(terminal.Response.Error)) == 0 || + bytes.Equal(bytes.TrimSpace(terminal.Response.Error), []byte("null")) { + return payload + } + // Standard HTTP error handlers consume error.message/type/code. A streamed + // response.failed terminal nests the same object under response.error, so + // normalize only that envelope at the stream-to-HTTP boundary. + normalized, err := json.Marshal(struct { + Error json.RawMessage `json:"error"` + }{Error: terminal.Response.Error}) + if err != nil { + return payload + } + return normalized +} + +func (s *OpenAIGatewayService) appendOpenAICompactFallbackRetryOps( + c *gin.Context, + account *Account, + resp *http.Response, + payload []byte, + message string, + passthrough bool, +) { + if account == nil { + return + } + statusCode := http.StatusBadRequest + requestID := "" + if resp != nil { + statusCode = resp.StatusCode + requestID = resp.Header.Get("x-request-id") + } + detail := "" + if s != nil && s.cfg != nil && s.cfg.Gateway.LogUpstreamErrorBody { + maxBytes := s.cfg.Gateway.LogUpstreamErrorBodyMaxBytes + if maxBytes <= 0 { + maxBytes = 2048 + } + detail = truncateString(string(payload), maxBytes) + } + appendOpsUpstreamError(c, OpsUpstreamErrorEvent{ + Platform: account.Platform, + AccountID: account.ID, + AccountName: account.Name, + UpstreamStatusCode: statusCode, + UpstreamRequestID: requestID, + Passthrough: passthrough, + Kind: "retry", + Reason: "compact_model_fallback", + Message: sanitizeUpstreamErrorMessage(strings.TrimSpace(message)), + Detail: detail, + UpstreamResponseBody: detail, + }) +} + // prepareOpenAICompactFallbackRetry returns a body for one safe, same-account // retry. Callers invoke it only before any downstream response has been // written; it changes the model and deliberately leaves path, trigger, and @@ -164,6 +278,7 @@ func (s *OpenAIGatewayService) applyOpenAIPassthroughCompactFallbackFromSignal( if !retry { return body, "", false } + s.appendOpenAICompactFallbackRetryOps(c, account, resp, signal.payload, signal.message, true) if resp != nil && resp.Body != nil { _ = resp.Body.Close() } diff --git a/backend/internal/service/openai_compact_fallback_test.go b/backend/internal/service/openai_compact_fallback_test.go index 944f7e1cfd..2e4c7050eb 100644 --- a/backend/internal/service/openai_compact_fallback_test.go +++ b/backend/internal/service/openai_compact_fallback_test.go @@ -3,11 +3,14 @@ package service import ( "bytes" "context" + "errors" "io" "net/http" "net/http/httptest" + "strconv" "strings" "testing" + "time" "github.com/Wei-Shaw/sub2api/internal/config" "github.com/gin-gonic/gin" @@ -138,6 +141,29 @@ func TestPrepareOpenAICompactFallbackRetryDoesNotHideSpecificBusinessFailure(t * require.Equal(t, body, retryBody) } +func TestIsOpenAICompactModelFailureRequiresExplicitModelAvailabilityMessage(t *testing.T) { + tests := []struct { + name string + message string + want bool + }{ + {name: "explicit unsupported model", message: "The requested model is not supported", want: true}, + {name: "named missing model", message: "The model `gpt-5.5` does not exist", want: true}, + {name: "unsupported model code-like message", message: "unsupported model: gpt-5.5", want: true}, + {name: "unsupported model feature", message: "This model output format is not supported", want: false}, + {name: "unsupported parameter for model", message: "Parameter tools is not supported for this model", want: false}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + require.Equal(t, tt.want, isOpenAICompactModelFailure( + http.StatusBadRequest, + tt.message, + []byte(`{"error":{"message":`+strconv.Quote(tt.message)+`}}`), + )) + }) + } +} + func TestPrepareOpenAICompactFallbackRetrySkipsSameModel(t *testing.T) { gin.SetMode(gin.TestMode) svc := &OpenAIGatewayService{cfg: &config.Config{Gateway: config.GatewayConfig{OpenAICompactModel: "gpt-5.5"}}} @@ -191,6 +217,14 @@ func TestOpenAIGatewayForwardRetriesExplicitNativeCompactHTTPFailureOnce(t *test require.True(t, HasCompactionTriggerInInput(upstream.bodies[1])) require.Equal(t, upstream.requests[0].URL.Path, upstream.requests[1].URL.Path) require.NotContains(t, upstream.requests[1].URL.Path, "/compact") + rawEvents, ok := c.Get(OpsUpstreamErrorsKey) + require.True(t, ok) + events, ok := rawEvents.([]*OpsUpstreamErrorEvent) + require.True(t, ok) + require.Len(t, events, 1) + require.Equal(t, "retry", events[0].Kind) + require.Equal(t, "compact_model_fallback", events[0].Reason) + require.Equal(t, http.StatusBadRequest, events[0].UpstreamStatusCode) } func TestOpenAIGatewayForwardRetriesExplicitNativeCompactSSEFailureBeforeOutput(t *testing.T) { @@ -309,4 +343,63 @@ func TestOpenAIGatewayForwardDoesNotRecurseWhenCompactFallbackAlsoFails(t *testi require.Len(t, upstream.bodies, 2) require.Equal(t, "gpt-5.5", gjson.GetBytes(upstream.bodies[0], "model").String()) require.Equal(t, "gpt-5.4", gjson.GetBytes(upstream.bodies[1], "model").String()) + var compactSignal *openAICompactFallbackSignal + require.False(t, errors.As(err, &compactSignal)) + require.Equal(t, http.StatusBadRequest, recorder.Code) + require.Contains(t, recorder.Body.String(), "model not found") + rawEvents, ok := c.Get(OpsUpstreamErrorsKey) + require.True(t, ok) + events, ok := rawEvents.([]*OpsUpstreamErrorEvent) + require.True(t, ok) + require.Len(t, events, 2) + require.Equal(t, "retry", events[0].Kind) + require.Equal(t, "compact_model_fallback", events[0].Reason) + require.Equal(t, "http_error", events[1].Kind) +} + +func TestOpenAIPassthroughCompactFallbackSecondStreamFailureUsesStandardErrorPath(t *testing.T) { + gin.SetMode(gin.TestMode) + body := []byte(`{"model":"gpt-5.5","stream":true,"input":[{"type":"compaction_trigger"}]}`) + recorder := httptest.NewRecorder() + c, _ := gin.CreateTestContext(recorder) + c.Request = httptest.NewRequest(http.MethodPost, "/v1/responses", nil) + c.Request.Header.Set("Content-Type", "application/json") + MarkOpenAINativeCompactionV2(c) + + failed := "event: response.failed\n" + + `data: {"type":"response.failed","response":{"status":"failed","error":{"code":"context_length_exceeded","message":"context window exceeded"}}}` + "\n\n" + upstream := &httpUpstreamRecorder{responses: []*http.Response{ + {StatusCode: http.StatusOK, Header: http.Header{"Content-Type": []string{"text/event-stream"}}, Body: io.NopCloser(strings.NewReader(failed))}, + {StatusCode: http.StatusOK, Header: http.Header{"Content-Type": []string{"text/event-stream"}}, Body: io.NopCloser(strings.NewReader(failed))}, + }} + svc := &OpenAIGatewayService{ + cfg: &config.Config{Gateway: config.GatewayConfig{OpenAICompactModel: "gpt-5.4"}}, + httpUpstream: upstream, + } + account := &Account{ + ID: 1, Name: "openai-oauth", Platform: PlatformOpenAI, Type: AccountTypeOAuth, Concurrency: 1, + Credentials: map[string]any{"access_token": "oauth-token", "chatgpt_account_id": "chatgpt-account"}, + Status: StatusActive, Schedulable: true, + } + + result, err := svc.forwardOpenAIPassthrough( + context.Background(), c, account, body, body, "gpt-5.5", false, nil, true, time.Now(), + ) + + require.Error(t, err) + require.Nil(t, result) + require.Len(t, upstream.bodies, 2) + var compactSignal *openAICompactFallbackSignal + require.False(t, errors.As(err, &compactSignal)) + require.Equal(t, http.StatusBadRequest, recorder.Code) + require.Contains(t, recorder.Body.String(), "context window exceeded") + rawEvents, ok := c.Get(OpsUpstreamErrorsKey) + require.True(t, ok) + events, ok := rawEvents.([]*OpsUpstreamErrorEvent) + require.True(t, ok) + require.Len(t, events, 2) + require.Equal(t, "retry", events[0].Kind) + require.Equal(t, "compact_model_fallback", events[0].Reason) + require.Equal(t, "http_error", events[1].Kind) + require.True(t, events[1].Passthrough) } diff --git a/backend/internal/service/openai_cyber_session_block.go b/backend/internal/service/openai_cyber_session_block.go index 797e746561..44c3ece444 100644 --- a/backend/internal/service/openai_cyber_session_block.go +++ b/backend/internal/service/openai_cyber_session_block.go @@ -21,6 +21,8 @@ type CyberSessionBlockStore interface { FindCyberSessionBlocked(ctx context.Context, keys []string) (string, error) } +const cyberSessionTranscriptLookupOverflowBlockKey = "transcript_lookup_limit_exceeded" + // CyberSessionExplicitBlockKey returns an inexpensive exact key when the // client supplies a stable session signal. func CyberSessionExplicitBlockKey(apiKeyID int64, c *gin.Context, body []byte) string { @@ -142,7 +144,13 @@ func (s *OpenAIGatewayService) FindCyberSessionBlockedForRequest(ctx context.Con if !active { return "" } - keys := CyberSessionTranscriptLookupKeys(apiKeyID, body) + transcript := deriveOpenAICyberTranscriptBlockKeys(apiKeyID, body) + if transcript.lookupKeysTruncated { + // Once the coarse scope is active, silently dropping old candidates would + // let a blocked client evade prefix matching by appending dummy items. + return cyberSessionTranscriptLookupOverflowBlockKey + } + keys := transcript.lookupKeys if len(keys) == 0 { return "" } diff --git a/backend/internal/service/openai_cyber_session_block_test.go b/backend/internal/service/openai_cyber_session_block_test.go index 7080450042..aff46df25d 100644 --- a/backend/internal/service/openai_cyber_session_block_test.go +++ b/backend/internal/service/openai_cyber_session_block_test.go @@ -2,8 +2,10 @@ package service import ( "context" + "encoding/json" "errors" "net/http/httptest" + "strconv" "strings" "testing" "time" @@ -75,11 +77,32 @@ func TestCyberTranscriptBlockKeysWebSocketResponseCreate(t *testing.T) { require.Len(t, CyberSessionTranscriptBlockKeys(88, body), 2) } +func TestCyberTranscriptLookupKeysAreBoundedAndKeepNewestOrder(t *testing.T) { + messages := make([]map[string]string, maxOpenAICyberTranscriptLookupKeys+44) + for i := range messages { + messages[i] = map[string]string{"role": "user", "content": "message-" + strconv.Itoa(i)} + } + body, err := json.Marshal(map[string]any{"messages": messages}) + require.NoError(t, err) + + keys := CyberSessionTranscriptLookupKeys(77, body) + require.Len(t, keys, maxOpenAICyberTranscriptLookupKeys) + + firstRetainedBody, err := json.Marshal(map[string]any{"messages": messages[:45]}) + require.NoError(t, err) + firstRetainedPrefix := CyberSessionTranscriptLookupKeys(77, firstRetainedBody) + require.Equal(t, firstRetainedPrefix[len(firstRetainedPrefix)-1], keys[0]) + + fullKey := CyberSessionTranscriptBlockKeys(77, body)[0] + require.Equal(t, fullKey, keys[len(keys)-1]) +} + // --- fakes --- type fakeCyberBlockStore struct { - blocked map[string]bool - scopes map[string]bool + blocked map[string]bool + scopes map[string]bool + findCalls int } var _ CyberSessionBlockStore = (*fakeCyberBlockStore)(nil) @@ -105,6 +128,7 @@ func (f *fakeCyberBlockStore) IsCyberSessionScopeActive(_ context.Context, scope } func (f *fakeCyberBlockStore) FindCyberSessionBlocked(_ context.Context, keys []string) (string, error) { + f.findCalls++ for _, key := range keys { if f.blocked[key] { return key, nil @@ -271,6 +295,34 @@ func TestFindCyberSessionBlockedForRequestUsesScopeForTranscript(t *testing.T) { require.Equal(t, blockKey, svc.FindCyberSessionBlockedForRequest(ctx, 9, nextCtx, nextBody, clientIP, "Codex CLI 1.2.4")) } +func TestFindCyberSessionBlockedForRequestFailsClosedOnScopedTranscriptOverflow(t *testing.T) { + settingSvc := &SettingService{settingRepo: &fakeSettingRepo{vals: map[string]string{ + SettingKeyCyberSessionBlockEnabled: "true", + SettingKeyCyberSessionBlockTTLSeconds: "60", + }}} + combo := &comboCacheAndStore{} + svc := &OpenAIGatewayService{cache: combo, settingService: settingSvc} + ctx := context.Background() + const apiKeyID = int64(9) + const clientIP = "203.0.113.20" + const userAgent = "Codex CLI 1.2.3" + + messages := make([]map[string]string, maxOpenAICyberTranscriptLookupKeys+1) + for i := range messages { + messages[i] = map[string]string{"role": "user", "content": "message-" + strconv.Itoa(i)} + } + body, err := json.Marshal(map[string]any{"messages": messages}) + require.NoError(t, err) + c, _ := newCyberBlockTestCtx(nil, string(body)) + require.Empty(t, svc.FindCyberSessionBlockedForRequest(ctx, apiKeyID, c, body, clientIP, userAgent), + "overflow alone must not bypass the scope gate") + combo.store.scopes = map[string]bool{CyberSessionScopeKey(apiKeyID, clientIP, userAgent): true} + + require.Equal(t, cyberSessionTranscriptLookupOverflowBlockKey, + svc.FindCyberSessionBlockedForRequest(ctx, apiKeyID, c, body, clientIP, userAgent)) + require.Zero(t, combo.store.findCalls, "overflow must not issue an unbounded Redis lookup") +} + func TestCyberSessionScopeKeyNormalizesUserAgentVersion(t *testing.T) { base := CyberSessionScopeKey(7, "203.0.113.10", "Codex CLI 1.2.3") require.NotEmpty(t, base) diff --git a/backend/internal/service/openai_cyber_transcript.go b/backend/internal/service/openai_cyber_transcript.go index 1314d54c51..b286c04769 100644 --- a/backend/internal/service/openai_cyber_transcript.go +++ b/backend/internal/service/openai_cyber_transcript.go @@ -11,10 +11,15 @@ import ( ) type openAICyberTranscriptBlockKeys struct { - lookupKeys []string - preLatestUserKey string + lookupKeys []string + preLatestUserKey string + lookupKeysTruncated bool } +// Bound the Redis lookup work for a single request while retaining the most +// recent transcript prefixes, where a continuation is most likely to match. +const maxOpenAICyberTranscriptLookupKeys = 256 + // deriveOpenAICyberTranscriptBlockKeys returns cumulative semantic-history // hashes plus the context key immediately before the latest user turn. The // context key requires model-generated history so shared first-turn templates @@ -53,8 +58,11 @@ func deriveOpenAICyberTranscriptBlockKeys(apiKeyID int64, body []byte) openAICyb return openAICyberTranscriptBlockKeys{} } result := openAICyberTranscriptBlockKeys{ - lookupKeys: make([]string, 0, int(sequence.Get("#").Int())), + lookupKeys: make([]string, 0, maxOpenAICyberTranscriptLookupKeys), } + nextLookupKey := 0 + lookupKeysRotated := false + lastLookupKey := "" // This is an entropy heuristic, not provenance proof: authenticated // server-side history would be required to distinguish fixed few-shot // assistant items perfectly. @@ -71,17 +79,31 @@ func deriveOpenAICyberTranscriptBlockKeys(apiKeyID int64, body []byte) openAICyb if strings.TrimSpace(canonical) == "" { return true } - if openAICyberTranscriptItemStartsUserTurn(item) && hasModelGeneratedItem && len(result.lookupKeys) > 0 { - result.preLatestUserKey = result.lookupKeys[len(result.lookupKeys)-1] + if openAICyberTranscriptItemStartsUserTurn(item) && hasModelGeneratedItem && lastLookupKey != "" { + result.preLatestUserKey = lastLookupKey } _, _ = h.Write([]byte("|item=")) _, _ = h.Write([]byte(canonical)) - result.lookupKeys = append(result.lookupKeys, hex.EncodeToString(h.Sum(nil))) + lastLookupKey = hex.EncodeToString(h.Sum(nil)) + if len(result.lookupKeys) < maxOpenAICyberTranscriptLookupKeys { + result.lookupKeys = append(result.lookupKeys, lastLookupKey) + } else { + result.lookupKeys[nextLookupKey] = lastLookupKey + nextLookupKey = (nextLookupKey + 1) % maxOpenAICyberTranscriptLookupKeys + lookupKeysRotated = true + result.lookupKeysTruncated = true + } if openAICyberTranscriptItemIsModelGenerated(item) { hasModelGeneratedItem = true } return true }) + if lookupKeysRotated { + ordered := make([]string, 0, len(result.lookupKeys)) + ordered = append(ordered, result.lookupKeys[nextLookupKey:]...) + ordered = append(ordered, result.lookupKeys[:nextLookupKey]...) + result.lookupKeys = ordered + } return result } diff --git a/backend/internal/service/openai_embeddings.go b/backend/internal/service/openai_embeddings.go index ef0c88b2d7..366e11a22f 100644 --- a/backend/internal/service/openai_embeddings.go +++ b/backend/internal/service/openai_embeddings.go @@ -140,7 +140,7 @@ func (s *OpenAIGatewayService) ForwardEmbeddings( if account.IsOpenAIOAuth() && resp.StatusCode == http.StatusTooManyRequests { return nil, s.newOpenAIAccountFailoverError(account, resp.StatusCode, resp.Header, respBody, upstreamMsg, shouldDisable, retryableOnSameAccount) } - if isOpenAIUpstreamAccessStateError(upstreamMsg, respBody) { + if isOpenAIHTTPUpstreamAccessStateError(resp.StatusCode, upstreamMsg, respBody) { return nil, newOpenAIUpstreamFailoverError(resp.StatusCode, resp.Header, respBody, upstreamMsg, retryableOnSameAccount) } return nil, &UpstreamFailoverError{StatusCode: resp.StatusCode, ResponseBody: respBody, RetryableOnSameAccount: retryableOnSameAccount} diff --git a/backend/internal/service/openai_gateway_apikey_item_id_test.go b/backend/internal/service/openai_gateway_apikey_item_id_test.go index 9605a0acee..e3a93bebb3 100644 --- a/backend/internal/service/openai_gateway_apikey_item_id_test.go +++ b/backend/internal/service/openai_gateway_apikey_item_id_test.go @@ -258,7 +258,7 @@ func TestSanitizeOpenAIResponsesInputItemIDs_AllocationGrowthIsLinear(t *testing "10x more input items must not cause quadratic whole-body allocation growth") } -func TestNormalizeOpenAIResponsesWebSocketCompatibilityBodyClosesInvalidIDReferences(t *testing.T) { +func TestNormalizeOpenAIResponsesWebSocketCompatibilityBodyPreservesOpaqueReferences(t *testing.T) { body := []byte(`{"type":"response.create","input":[ {"type":"custom_tool_call","id":"ctc_call","call_id":"call_custom","name":"apply_patch","input":"patch"}, {"type":"custom_tool_call_output","id":"ctco_bad","call_id":"call_custom","output":"done"}, @@ -275,11 +275,12 @@ func TestNormalizeOpenAIResponsesWebSocketCompatibilityBodyClosesInvalidIDRefere require.NoError(t, err) require.True(t, changed) - require.Len(t, gjson.GetBytes(normalized, "input").Array(), 3) + require.Len(t, gjson.GetBytes(normalized, "input").Array(), 4) require.Equal(t, "ctc_call", gjson.GetBytes(normalized, "input.0.id").String()) require.Equal(t, "call_custom", gjson.GetBytes(normalized, "input.1.call_id").String()) require.False(t, gjson.GetBytes(normalized, "input.1.id").Exists()) - require.Equal(t, "item_future", gjson.GetBytes(normalized, "input.2.id").String()) + require.Equal(t, "ctco_bad", gjson.GetBytes(normalized, "input.2.id").String()) + require.Equal(t, "item_future", gjson.GetBytes(normalized, "input.3.id").String()) second, changedAgain, err := normalizeOpenAIResponsesWebSocketCompatibilityBody(normalized, &Account{ Platform: PlatformOpenAI, diff --git a/backend/internal/service/openai_gateway_forward.go b/backend/internal/service/openai_gateway_forward.go index 1d2c9f5f39..99d89a7fac 100644 --- a/backend/internal/service/openai_gateway_forward.go +++ b/backend/internal/service/openai_gateway_forward.go @@ -59,21 +59,10 @@ func (s *OpenAIGatewayService) Forward(ctx context.Context, c *gin.Context, acco // 在分流到 passthrough / Codex transform / 原生 ChatCompletions 之前统一修正 // 显式为 null 的工具 Schema type,否则 upstream 的 400 会被归一成可重试的 502, // 同一份坏定义在账号池里反复重放。 - if shouldSanitizeOpenAIResponsesToolSchemas(account.Platform) { - sanitizedToolBody, toolSchemaSanitized, toolSchemaErr := sanitizeOpenAIResponsesToolParameterTypes(body) - if toolSchemaErr != nil { - return nil, fmt.Errorf("sanitize OpenAI Responses tool parameters: %w", toolSchemaErr) - } - if toolSchemaSanitized { - body = sanitizedToolBody - } - patternSanitizedBody, patternSanitized, patternErr := sanitizeOpenAIResponsesToolSchemaPatterns(body) - if patternErr != nil { - return nil, fmt.Errorf("sanitize OpenAI Responses tool schema patterns: %w", patternErr) - } - if patternSanitized { - body = patternSanitizedBody - } + if sanitizedToolBody, toolSchemaSanitized, toolSchemaErr := sanitizeOpenAIResponsesToolSchemasForPlatform(body, account.Platform); toolSchemaErr != nil { + return nil, toolSchemaErr + } else if toolSchemaSanitized { + body = sanitizedToolBody } if account.IsOpenAIOAuthLike() { reasoningBody, reasoningChanged, reasoningErr := normalizeOpenAIResponsesReasoningMode(body) @@ -1015,6 +1004,7 @@ func (s *OpenAIGatewayService) Forward(ctx context.Context, c *gin.Context, acco if retryBody, fallbackModel, retry := s.prepareOpenAICompactFallbackRetry( c, account, requestedModel, body, resp.StatusCode, upstreamMsg, respBody, compactModelFallbackRetried, ); retry { + s.appendOpenAICompactFallbackRetryOps(c, account, resp, respBody, upstreamMsg, false) fromModel := strings.TrimSpace(gjson.GetBytes(body, "model").String()) body = retryBody requestView = newOpenAIRequestView(body) @@ -1082,6 +1072,7 @@ func (s *OpenAIGatewayService) Forward(ctx context.Context, c *gin.Context, acco if retryBody, fallbackModel, retry := s.prepareOpenAICompactFallbackRetry( c, account, requestedModel, body, http.StatusBadRequest, signal.message, signal.payload, compactModelFallbackRetried, ); retry { + s.appendOpenAICompactFallbackRetryOps(c, account, resp, signal.payload, signal.message, false) body = retryBody requestView = newOpenAIRequestView(body) upstreamModel = fallbackModel @@ -1089,6 +1080,27 @@ func (s *OpenAIGatewayService) Forward(ctx context.Context, c *gin.Context, acco SetOpsUpstreamModel(c, fallbackModel) continue } + if resp.Body != nil { + _ = resp.Body.Close() + } + compactResp, compactBody := openAICompactFallbackErrorResponse(resp, signal) + if s.shouldFailoverOpenAIUpstreamResponse(compactResp.StatusCode, signal.message, compactBody) { + appendOpsUpstreamError(c, OpsUpstreamErrorEvent{ + Platform: account.Platform, + AccountID: account.ID, + AccountName: account.Name, + UpstreamStatusCode: compactResp.StatusCode, + UpstreamRequestID: compactResp.Header.Get("x-request-id"), + Kind: "failover", + Message: signal.message, + }) + shouldDisable := s.handleFailoverSideEffects(ctx, compactResp, account, compactBody, upstreamModel) + return nil, s.newOpenAIAccountFailoverError( + account, compactResp.StatusCode, compactResp.Header, compactBody, signal.message, shouldDisable, + !shouldDisable && account.IsPoolMode() && (account.IsPoolModeRetryableStatus(compactResp.StatusCode) || isOpenAITransientProcessingError(compactResp.StatusCode, signal.message, compactBody)), + ) + } + return s.handleErrorResponse(ctx, compactResp, c, account, body, resolveOpenAIErrorSchedulingModel(billingModel, upstreamModel)) } return nil, err } diff --git a/backend/internal/service/openai_gateway_passthrough.go b/backend/internal/service/openai_gateway_passthrough.go index 06653094ce..f5c8cfe106 100644 --- a/backend/internal/service/openai_gateway_passthrough.go +++ b/backend/internal/service/openai_gateway_passthrough.go @@ -377,6 +377,7 @@ func (s *OpenAIGatewayService) forwardOpenAIPassthrough( if retryBody, fallbackModel, retry := s.prepareOpenAICompactFallbackRetry( c, account, requestedModel, body, resp.StatusCode, upstreamMsg, probeBody, compactModelFallbackRetried, ); retry { + s.appendOpenAICompactFallbackRetryOps(c, account, resp, probeBody, upstreamMsg, true) fromModel := strings.TrimSpace(gjson.GetBytes(body, "model").String()) body = retryBody upstreamPassthroughModel = fallbackModel @@ -425,6 +426,14 @@ func (s *OpenAIGatewayService) forwardOpenAIPassthrough( compactModelFallbackRetried = true continue } + if signal, ok := asOpenAICompactFallbackSignal(handleErr); ok { + _ = resp.Body.Close() + compactResp, compactBody := openAICompactFallbackErrorResponse(resp, signal) + if shouldFailoverOpenAIPassthroughResponse(account, compactResp.StatusCode, compactBody) { + return nil, s.handleFailoverErrorResponsePassthrough(ctx, compactResp, c, account, body, compactBody) + } + return nil, s.handleErrorResponsePassthrough(ctx, compactResp, c, account, body, compactBody) + } _ = resp.Body.Close() return nil, handleErr } @@ -444,6 +453,14 @@ func (s *OpenAIGatewayService) forwardOpenAIPassthrough( compactModelFallbackRetried = true continue } + if signal, ok := asOpenAICompactFallbackSignal(handleErr); ok { + _ = resp.Body.Close() + compactResp, compactBody := openAICompactFallbackErrorResponse(resp, signal) + if shouldFailoverOpenAIPassthroughResponse(account, compactResp.StatusCode, compactBody) { + return nil, s.handleFailoverErrorResponsePassthrough(ctx, compactResp, c, account, body, compactBody) + } + return nil, s.handleErrorResponsePassthrough(ctx, compactResp, c, account, body, compactBody) + } _ = resp.Body.Close() return nil, handleErr } @@ -713,7 +730,7 @@ func shouldFailoverOpenAIPassthroughResponse(account *Account, statusCode int, r if isOpenAIContextWindowError("", responseBody) { return false } - if isOpenAIUpstreamAccessStateError("", responseBody) { + if isOpenAIHTTPUpstreamAccessStateError(statusCode, "", responseBody) { return true } if isOpenAIRequestBodyTooLargeError(statusCode, "", responseBody) { @@ -1520,7 +1537,14 @@ func (s *OpenAIGatewayService) handleOpenAIStreamTerminalAccountSideEffects( if c != nil && c.Request != nil { ctx = c.Request.Context() } - return statusCode, s.handleOpenAIAccountUpstreamError(ctx, account, statusCode, headers, payload) + accountHeaders := headers + if statusCode == http.StatusTooManyRequests { + // The enclosing HTTP response succeeded. Its quota snapshot describes + // normal account state and must not become the reset for a semantic 429 + // carried by a stream terminal event. + accountHeaders = nil + } + return statusCode, s.handleOpenAIAccountUpstreamError(ctx, account, statusCode, accountHeaders, payload) default: return statusCode, false } diff --git a/backend/internal/service/openai_gateway_request_body.go b/backend/internal/service/openai_gateway_request_body.go index e07e041ced..79ee4c4284 100644 --- a/backend/internal/service/openai_gateway_request_body.go +++ b/backend/internal/service/openai_gateway_request_body.go @@ -1033,17 +1033,11 @@ func normalizeOpenAIResponsesWebSocketCompatibilityBody(body []byte, account *Ac changed = true } } - if account != nil && shouldSanitizeOpenAIResponsesToolSchemas(account.Platform) { - if toolBody, toolChanged, err := sanitizeOpenAIResponsesToolParameterTypes(normalized); err != nil { - return body, false, fmt.Errorf("normalize websocket tool parameter types: %w", err) - } else if toolChanged { - normalized = toolBody - changed = true - } - if patternBody, patternChanged, err := sanitizeOpenAIResponsesToolSchemaPatterns(normalized); err != nil { - return body, false, fmt.Errorf("normalize websocket tool schema patterns: %w", err) - } else if patternChanged { - normalized = patternBody + if account != nil { + if schemaBody, schemaChanged, err := sanitizeOpenAIResponsesToolSchemasForPlatform(normalized, account.Platform); err != nil { + return body, false, fmt.Errorf("normalize websocket tool schemas: %w", err) + } else if schemaChanged { + normalized = schemaBody changed = true } } diff --git a/backend/internal/service/openai_gateway_response_flush_test.go b/backend/internal/service/openai_gateway_response_flush_test.go index 16483567ad..fe6e3ea6b2 100644 --- a/backend/internal/service/openai_gateway_response_flush_test.go +++ b/backend/internal/service/openai_gateway_response_flush_test.go @@ -441,6 +441,62 @@ func TestOpenAIResponseFlush_FailedAndErrorEventsFlushAtBoundaries(t *testing.T) }) } +func TestOpenAIResponseFlush_BareErrorFollowedByCompletedUsesCompletedTerminal(t *testing.T) { + body := "data: {\"type\":\"error\",\"error\":{\"code\":\"transient\",\"message\":\"retrying\"}}\n\n" + + "data: {\"type\":\"response.completed\",\"response\":{\"id\":\"resp_recovered\",\"status\":\"completed\",\"output\":[],\"usage\":{\"input_tokens\":7,\"output_tokens\":3}}}\n\n" + recorder := newOpenAIResponseFlushRecorder() + + result, err := runOpenAIResponseFlushTest(recorder, io.NopCloser(strings.NewReader(body)), config.GatewayConfig{}) + + require.NoError(t, err) + require.NotNil(t, result) + require.Equal(t, 7, result.usage.InputTokens) + require.Equal(t, 3, result.usage.OutputTokens) + gotBody, _ := recorder.snapshot() + require.NotContains(t, gotBody, `"type":"error"`) + require.NotContains(t, gotBody, `"type":"response.failed"`) + require.Contains(t, gotBody, `"type":"response.completed"`) +} + +func TestOpenAIResponseFlush_CompatibleAPIKeyDoesNotUseCodexBareErrorSynthesis(t *testing.T) { + body := "data: {\"type\":\"error\",\"error\":{\"code\":\"provider_error\",\"message\":\"provider failed\"}}\n\n" + recorder := newOpenAIResponseFlushRecorder() + account := &Account{ID: 2, Platform: PlatformOpenAI, Type: AccountTypeAPIKey} + + result, err := runOpenAIResponseFlushTestWithAccount(recorder, io.NopCloser(strings.NewReader(body)), config.GatewayConfig{}, account) + + require.Error(t, err) + require.NotNil(t, result) + gotBody, _ := recorder.snapshot() + require.Contains(t, gotBody, `"type":"error"`) + require.NotContains(t, gotBody, `"type":"response.failed"`) +} + +func TestOpenAIResponseFlush_RecentBareErrorAllowsCompletedBeforeIdleTimeout(t *testing.T) { + reader, writer := io.Pipe() + defer func() { _ = writer.Close() }() + recorder := newOpenAIResponseFlushRecorder() + resultCh, errCh := runOpenAIResponseFlushTestAsync(recorder, reader, config.GatewayConfig{StreamDataIntervalTimeout: 1}) + + // Place the bare error shortly before the first ticker firing. It is fresh + // data, so the ticker must leave the stream open for an authoritative event. + time.Sleep(700 * time.Millisecond) + _, err := io.WriteString(writer, "data: {\"type\":\"error\",\"error\":{\"code\":\"transient\",\"message\":\"retrying\"}}\n\n") + require.NoError(t, err) + time.Sleep(500 * time.Millisecond) + _, err = io.WriteString(writer, "data: {\"type\":\"response.completed\",\"response\":{\"id\":\"resp_late\",\"status\":\"completed\",\"output\":[],\"usage\":{\"input_tokens\":5,\"output_tokens\":1}}}\n\n") + require.NoError(t, err) + require.NoError(t, writer.Close()) + + require.NoError(t, <-errCh) + result := <-resultCh + require.NotNil(t, result) + require.Equal(t, 5, result.usage.InputTokens) + gotBody, _ := recorder.snapshot() + require.Contains(t, gotBody, `"type":"response.completed"`) + require.NotContains(t, gotBody, `"type":"response.failed"`) +} + func TestOpenAIResponseFlush_BareErrorTimeoutSynthesizesFailed(t *testing.T) { tests := []struct { name string @@ -534,6 +590,10 @@ func TestOpenAIResponseFlush_ClientDisconnectStillDrainsUsage(t *testing.T) { } func runOpenAIResponseFlushTest(recorder *openAIResponseFlushRecorder, body io.ReadCloser, gatewayCfg config.GatewayConfig) (*openaiStreamingResult, error) { + return runOpenAIResponseFlushTestWithAccount(recorder, body, gatewayCfg, &Account{ID: 1, Platform: PlatformOpenAI, Type: AccountTypeOAuth}) +} + +func runOpenAIResponseFlushTestWithAccount(recorder *openAIResponseFlushRecorder, body io.ReadCloser, gatewayCfg config.GatewayConfig, account *Account) (*openaiStreamingResult, error) { gin.SetMode(gin.TestMode) c, _ := gin.CreateTestContext(recorder) c.Request = httptest.NewRequest(http.MethodPost, "/v1/responses", nil) @@ -546,7 +606,7 @@ func runOpenAIResponseFlushTest(recorder *openAIResponseFlushRecorder, body io.R Header: http.Header{"Content-Type": []string{"text/event-stream"}}, Body: body, } - return svc.handleStreamingResponse(context.Background(), resp, c, &Account{ID: 1, Platform: PlatformOpenAI}, time.Now(), "gpt-5", "gpt-5") + return svc.handleStreamingResponse(context.Background(), resp, c, account, time.Now(), "gpt-5", "gpt-5") } func runOpenAIResponseFlushTestAsync(recorder *openAIResponseFlushRecorder, body io.ReadCloser, gatewayCfg config.GatewayConfig) (<-chan *openaiStreamingResult, <-chan error) { diff --git a/backend/internal/service/openai_gateway_response_handling.go b/backend/internal/service/openai_gateway_response_handling.go index 45d08e86f3..2675ebb995 100644 --- a/backend/internal/service/openai_gateway_response_handling.go +++ b/backend/internal/service/openai_gateway_response_handling.go @@ -251,7 +251,7 @@ func (s *OpenAIGatewayService) handleStreamingResponseWithReasoning(ctx context. capacityFailoverSuppressedLogged := false failedMessage := "" clientOutputStarted := false - codexFailureTerminal := account != nil && account.Platform == PlatformOpenAI + codexFailureTerminal := account != nil && account.IsOpenAIOAuthLike() upstreamRequestID := strings.TrimSpace(resp.Header.Get("x-request-id")) var streamEarlyErr error terminalFailurePending := false @@ -478,6 +478,18 @@ func (s *OpenAIGatewayService) handleStreamingResponseWithReasoning(ctx context. if data, ok := extractOpenAISSEDataLine(line); ok { dataBytes := []byte(data) eventType := effectiveOpenAISSEEventType(dataBytes, pendingSSEEventType) + if codexFailureTerminal && sawBareError && !sawResponseFailed && + (eventType == "response.completed" || eventType == "response.done") { + // A later successful terminal is authoritative over a pending bare + // error. Keep its usage and terminal visible to the client. + sawBareError = false + sawFailedEvent = false + terminalFailurePending = false + suppressCurrentEvent = false + bareErrorPayload = nil + bareErrorAccountSideEffectsPending = false + failedMessage = "" + } if codexFailureTerminal && sawBareError && !sawResponseFailed && eventType != "response.failed" { suppressCurrentEvent = true } @@ -862,10 +874,6 @@ func (s *OpenAIGatewayService) handleStreamingResponseWithReasoning(ctx context. } case <-intervalCh: - if codexFailureTerminal && sawBareError && !sawResponseFailed { - _ = resp.Body.Close() - return finalizeStream() - } if failureDelivered { return resultWithUsage(), fmt.Errorf("upstream response failed: %s", failedMessage) } @@ -873,6 +881,10 @@ func (s *OpenAIGatewayService) handleStreamingResponseWithReasoning(ctx context. if time.Since(lastRead) < streamInterval { continue } + if codexFailureTerminal && sawBareError && !sawResponseFailed { + _ = resp.Body.Close() + return finalizeStream() + } if clientDisconnected { return resultWithUsage(), fmt.Errorf("stream usage incomplete after timeout") } @@ -899,7 +911,7 @@ func (s *OpenAIGatewayService) handleStreamingResponseWithReasoning(ctx context. stopFirstOutputTimer() continue } - if codexFailureTerminal && sawBareError && !sawResponseFailed { + if codexFailureTerminal && sawBareError && !sawResponseFailed && len(events) == 0 { _ = resp.Body.Close() return finalizeStream() } @@ -1181,6 +1193,12 @@ func (s *OpenAIGatewayService) parseSSEUsageBytesWithType(data []byte, eventType if usage == nil || len(data) == 0 || bytes.Equal(bytes.TrimSpace(data), []byte("[DONE]")) { return } + // Usage is absent from nearly every delta event. Avoid full JSON validation + // and four gjson path scans on that hot path while retaining progressive + // usage from compatible upstreams on any event type. + if !bytes.Contains(data, []byte(`"usage"`)) { + return + } parsedUsage, ok := extractOpenAIUsageFromJSONBytes(data) if !ok { return @@ -1368,6 +1386,57 @@ func extractOpenAIResponseIDFromJSONBytes(body []byte) string { return strings.TrimSpace(gjson.GetBytes(body, "response.id").String()) } +const openAIHTTPResponseOwnerContextKey = "openai_http_response_owner" + +type openAIHTTPResponseOwner struct { + userID int64 + apiKeyID int64 +} + +// SetOpenAIHTTPResponseOwner marks the authenticated downstream owner whose +// successful Responses IDs may be used for later HTTP continuations. +func SetOpenAIHTTPResponseOwner(c *gin.Context, userID, apiKeyID int64) { + if c == nil || userID <= 0 || apiKeyID <= 0 { + return + } + c.Set(openAIHTTPResponseOwnerContextKey, openAIHTTPResponseOwner{userID: userID, apiKeyID: apiKeyID}) +} + +// ValidateOpenAIHTTPResponseOwner authorizes a continuation by downstream +// tenant. API key identity is retained in the binding, while keys owned by the +// same user remain interoperable. +func (s *OpenAIGatewayService) ValidateOpenAIHTTPResponseOwner( + ctx context.Context, + groupID int64, + responseID string, + userID, apiKeyID int64, +) (bool, error) { + if s == nil || strings.TrimSpace(responseID) == "" || userID <= 0 || apiKeyID <= 0 { + return false, nil + } + ownerUserID, ownerAPIKeyID, found, err := s.getOpenAIWSStateStore().GetHTTPResponseOwner(ctx, groupID, responseID) + if err != nil || !found { + return false, err + } + return ownerUserID == userID || (ownerUserID <= 0 && ownerAPIKeyID == apiKeyID), nil +} + +// BindOpenAIHTTPResponseOwner records an HTTP continuation owner independently +// from the upstream account selected for that response. +func (s *OpenAIGatewayService) BindOpenAIHTTPResponseOwner( + ctx context.Context, + groupID int64, + responseID string, + userID, apiKeyID int64, +) error { + if s == nil { + return nil + } + return s.getOpenAIWSStateStore().BindHTTPResponseOwner( + ctx, groupID, responseID, userID, apiKeyID, s.openAIWSResponseStickyTTL(), + ) +} + func (s *OpenAIGatewayService) bindHTTPResponseAccount(ctx context.Context, c *gin.Context, account *Account, responseID string) { if s == nil || account == nil || account.ID <= 0 { return @@ -1383,6 +1452,21 @@ func (s *OpenAIGatewayService) bindHTTPResponseAccount(ctx context.Context, c *g groupID := getOpenAIGroupIDFromContext(c) ttl := s.openAIWSResponseStickyTTL() logOpenAIWSBindResponseAccountWarn(groupID, account.ID, responseID, store.BindResponseAccount(ctx, groupID, responseID, account.ID, ttl)) + if rawOwner, ok := c.Get(openAIHTTPResponseOwnerContextKey); ok { + if owner, ok := rawOwner.(openAIHTTPResponseOwner); ok && owner.userID > 0 && owner.apiKeyID > 0 { + if err := s.BindOpenAIHTTPResponseOwner(ctx, groupID, responseID, owner.userID, owner.apiKeyID); err != nil { + logger.L().Warn( + "openai.http_bind_response_owner_failed", + zap.Int64("group_id", groupID), + zap.Int64("account_id", account.ID), + zap.Int64("user_id", owner.userID), + zap.Int64("api_key_id", owner.apiKeyID), + zap.String("response_id", truncateOpenAIWSLogValue(responseID, openAIWSIDValueMaxLen)), + zap.Error(err), + ) + } + } + } } func openAIUsageFromGJSON(value gjson.Result) (OpenAIUsage, bool) { @@ -1665,9 +1749,6 @@ func extractOpenAISSETerminalEvent(body string) (string, []byte, bool) { var terminalType string var terminalPayload []byte forEachOpenAISSEFrame(body, func(eventType string, data []byte) { - if terminalPayload != nil { - return - } switch eventType { case "response.completed", "response.done", "response.failed", "response.incomplete", "response.cancelled", "response.canceled", "error": terminalType = eventType diff --git a/backend/internal/service/openai_gateway_service_test.go b/backend/internal/service/openai_gateway_service_test.go index 122a542964..1e41298cc1 100644 --- a/backend/internal/service/openai_gateway_service_test.go +++ b/backend/internal/service/openai_gateway_service_test.go @@ -536,6 +536,7 @@ func TestOpenAIGatewayService_BindHTTPResponseAccount(t *testing.T) { c.Request = httptest.NewRequest(http.MethodPost, "/openai/v1/responses", nil) groupID := int64(4201) c.Set("api_key", &APIKey{ID: 501, GroupID: &groupID}) + SetOpenAIHTTPResponseOwner(c, 601, 501) svc := &OpenAIGatewayService{} account := &Account{ID: 37001, Platform: PlatformOpenAI, Type: AccountTypeAPIKey} @@ -544,6 +545,22 @@ func TestOpenAIGatewayService_BindHTTPResponseAccount(t *testing.T) { got, err := svc.getOpenAIWSStateStore().GetResponseAccount(context.Background(), groupID, "resp_http_001") require.NoError(t, err) require.Equal(t, account.ID, got) + + owned, err := svc.ValidateOpenAIHTTPResponseOwner(context.Background(), groupID, "resp_http_001", 601, 501) + require.NoError(t, err) + require.True(t, owned) + + owned, err = svc.ValidateOpenAIHTTPResponseOwner(context.Background(), groupID, "resp_http_001", 601, 502) + require.NoError(t, err) + require.True(t, owned, "API keys owned by the same downstream user remain interoperable") + + owned, err = svc.ValidateOpenAIHTTPResponseOwner(context.Background(), groupID, "resp_http_001", 602, 501) + require.NoError(t, err) + require.False(t, owned) + + owned, err = svc.ValidateOpenAIHTTPResponseOwner(context.Background(), groupID, "resp_unknown", 601, 501) + require.NoError(t, err) + require.False(t, owned) } func TestOpenAIGatewayService_GenerateExplicitSessionHash_SkipsContentFallback(t *testing.T) { diff --git a/backend/internal/service/openai_gateway_upstream_errors.go b/backend/internal/service/openai_gateway_upstream_errors.go index 62add58e24..4a4e9ab7fc 100644 --- a/backend/internal/service/openai_gateway_upstream_errors.go +++ b/backend/internal/service/openai_gateway_upstream_errors.go @@ -260,7 +260,7 @@ func (s *OpenAIGatewayService) shouldFailoverOpenAIUpstreamResponse(statusCode i if isOpenAIContextWindowError(upstreamMsg, upstreamBody) { return false } - if isOpenAIUpstreamAccessStateError(upstreamMsg, upstreamBody) { + if isOpenAIHTTPUpstreamAccessStateError(statusCode, upstreamMsg, upstreamBody) { return true } if isOpenAIRequestBodyTooLargeError(statusCode, upstreamMsg, upstreamBody) { @@ -306,7 +306,7 @@ func newOpenAIUpstreamFailoverError( failoverErr.ClientStatusCode = http.StatusRequestEntityTooLarge failoverErr.ClientMessage = OpenAIRequestBodyTooLargeClientMessage } - if isOpenAIUpstreamAccessStateError(upstreamMsg, responseBody) { + if isOpenAIHTTPUpstreamAccessStateError(statusCode, upstreamMsg, responseBody) { failoverErr.RetryableOnSameAccount = false failoverErr.RequestScopedTransient = false failoverErr.Stage = GatewayFailureStageAccountAuth @@ -359,59 +359,42 @@ const ( ) // isOpenAIUpstreamAccessStateError recognizes provider-side credential state -// failures from explicit structured fields. Valid JSON is never scanned as a -// blob because it may contain echoed user input with the same words. -func isOpenAIUpstreamAccessStateError(upstreamMsg string, body []byte) bool { - matchCode := func(value string) bool { - value = strings.ToLower(strings.TrimSpace(value)) - if value == "deactivated_workspace" { - return true - } - for _, subject := range []string{"workspace", "account", "organization", "org"} { - for _, state := range []string{"deactivated", "disabled", "suspended"} { - if value == subject+"_"+state || value == state+"_"+subject { - return true - } - } - } +// failures only from explicit structured codes. Free-form messages may contain +// echoed user input, including inside stream terminal error.message fields. +func isOpenAIUpstreamAccessStateError(_ string, body []byte) bool { + if len(body) == 0 || !gjson.ValidBytes(body) { return false } - matchMessage := func(value string) bool { - value = strings.ToLower(strings.TrimSpace(value)) - for _, subject := range []string{"workspace", "account", "organization", "org"} { - for _, state := range []string{"deactivated", "disabled", "suspended"} { - if strings.Contains(value, subject+" is "+state) || - strings.Contains(value, subject+" has been "+state) || - strings.Contains(value, subject+" "+state) { - return true - } - } - } - return false - } - - if matchMessage(upstreamMsg) { - return true - } - if len(body) == 0 { - return false - } - if !gjson.ValidBytes(body) { - return matchMessage(string(body)) || matchCode(string(body)) - } for _, path := range []string{"error.code", "response.error.code", "detail.code", "code"} { - if matchCode(gjson.GetBytes(body, path).String()) { - return true - } - } - for _, path := range []string{"error.message", "response.error.message", "detail.message", "detail", "message"} { - if matchMessage(gjson.GetBytes(body, path).String()) { + if isOpenAIUpstreamAccessStateCode(gjson.GetBytes(body, path).String()) { return true } } return false } +func isOpenAIUpstreamAccessStateCode(value string) bool { + value = strings.ToLower(strings.TrimSpace(value)) + if value == "deactivated_workspace" { + return true + } + for _, subject := range []string{"workspace", "account", "organization", "org"} { + for _, state := range []string{"deactivated", "disabled", "suspended"} { + if value == subject+"_"+state || value == state+"_"+subject { + return true + } + } + } + return false +} + +// isOpenAIHTTPUpstreamAccessStateError is deliberately status-independent: +// known provider codes are durable evidence, while 401/403 messages without +// such a code must flow through the existing authentication/403 policies. +func isOpenAIHTTPUpstreamAccessStateError(_ int, _ string, body []byte) bool { + return isOpenAIUpstreamAccessStateError("", body) +} + func openAICapacityShedClientMessage(upstreamMsg string, body []byte) string { for _, candidate := range []string{ upstreamMsg, diff --git a/backend/internal/service/openai_images.go b/backend/internal/service/openai_images.go index c29af50016..08f94fca67 100644 --- a/backend/internal/service/openai_images.go +++ b/backend/internal/service/openai_images.go @@ -663,7 +663,7 @@ func (s *OpenAIGatewayService) forwardOpenAIImagesAPIKey( if account.IsOpenAIOAuthLike() && resp.StatusCode == http.StatusTooManyRequests { return nil, s.newOpenAIAccountFailoverError(account, resp.StatusCode, resp.Header, respBody, upstreamMsg, shouldDisable, retryableOnSameAccount) } - if isOpenAIUpstreamAccessStateError(upstreamMsg, respBody) { + if isOpenAIHTTPUpstreamAccessStateError(resp.StatusCode, upstreamMsg, respBody) { return nil, newOpenAIUpstreamFailoverError(resp.StatusCode, resp.Header, respBody, upstreamMsg, retryableOnSameAccount) } return nil, &UpstreamFailoverError{StatusCode: resp.StatusCode, ResponseBody: respBody, RetryableOnSameAccount: retryableOnSameAccount} diff --git a/backend/internal/service/openai_response_terminal_usage_compat_test.go b/backend/internal/service/openai_response_terminal_usage_compat_test.go index f6dc899e09..5a24f0addb 100644 --- a/backend/internal/service/openai_response_terminal_usage_compat_test.go +++ b/backend/internal/service/openai_response_terminal_usage_compat_test.go @@ -9,6 +9,7 @@ import ( "github.com/Wei-Shaw/sub2api/internal/pkg/apicompat" "github.com/stretchr/testify/require" + "github.com/tidwall/gjson" ) func TestEffectiveOpenAISSEEventTypePrefersPayload(t *testing.T) { @@ -31,6 +32,17 @@ func TestExtractOpenAISSETerminalEventUsesEventField(t *testing.T) { require.Equal(t, "provider failed", extractOpenAISSEErrorMessage(payload)) } +func TestExtractOpenAISSETerminalEventUsesFinalAuthoritativeTerminal(t *testing.T) { + t.Parallel() + + body := "data: {\"type\":\"error\",\"error\":{\"message\":\"recovering\"}}\n\n" + + "data: {\"type\":\"response.completed\",\"response\":{\"id\":\"resp_1\",\"status\":\"completed\"}}\n\n" + eventType, payload, ok := extractOpenAISSETerminalEvent(body) + require.True(t, ok) + require.Equal(t, "response.completed", eventType) + require.Equal(t, "resp_1", gjson.GetBytes(payload, "response.id").String()) +} + func TestParseSSEUsageEffectiveTerminalRules(t *testing.T) { t.Parallel() @@ -47,6 +59,17 @@ func TestParseSSEUsageEffectiveTerminalRules(t *testing.T) { require.Equal(t, OpenAIUsage{InputTokens: 2}, *usage) } +func BenchmarkParseSSEUsageNoUsageDelta(b *testing.B) { + svc := &OpenAIGatewayService{} + usage := &OpenAIUsage{} + payload := []byte(`{"type":"response.output_text.delta","delta":"hello"}`) + b.ReportAllocs() + b.ResetTimer() + for i := 0; i < b.N; i++ { + svc.parseSSEUsageBytesWithType(payload, "response.output_text.delta", usage) + } +} + func TestOpenAICompatTerminalResponseSynthesizesBareError(t *testing.T) { t.Parallel() diff --git a/backend/internal/service/openai_responses_ingress_compat.go b/backend/internal/service/openai_responses_ingress_compat.go index c9ae11c0ae..f3162b3b02 100644 --- a/backend/internal/service/openai_responses_ingress_compat.go +++ b/backend/internal/service/openai_responses_ingress_compat.go @@ -46,11 +46,17 @@ func normalizeOpenAIResponsesLegacyIngress(body []byte) ([]byte, bool, error) { } if prompt, hasPrompt := request["prompt"]; hasPrompt { - if input, hasInput := request["input"]; (!hasInput || input == nil) && prompt != nil { - request["input"] = prompt + // Only the legacy string alias is unambiguously equivalent to Responses + // input. Objects are native reusable prompt templates and must remain in + // prompt; arrays and other shapes are left for upstream validation rather + // than being relabeled as a structurally different input value. + if promptText, isLegacyString := prompt.(string); isLegacyString { + if input, hasInput := request["input"]; !hasInput || input == nil { + request["input"] = promptText + } + delete(request, "prompt") + changed = true } - delete(request, "prompt") - changed = true } if _, hasCommands := request["commands"]; hasCommands { delete(request, "commands") diff --git a/backend/internal/service/openai_responses_ingress_compat_test.go b/backend/internal/service/openai_responses_ingress_compat_test.go index 3e898f03e6..acd2c202c0 100644 --- a/backend/internal/service/openai_responses_ingress_compat_test.go +++ b/backend/internal/service/openai_responses_ingress_compat_test.go @@ -70,3 +70,25 @@ func TestNormalizeOpenAIResponsesLegacyIngressKeepsPromptAliasAndDropsCommands(t require.False(t, gjson.GetBytes(normalized, "prompt").Exists()) require.False(t, gjson.GetBytes(normalized, "commands").Exists()) } + +func TestNormalizeOpenAIResponsesLegacyIngressPreservesNativePromptTemplate(t *testing.T) { + body := []byte(`{"model":"gpt-5.4","prompt":{"id":"pmpt_abc","version":"7","variables":{"topic":"ownership"}}}`) + + normalized, changed, err := normalizeOpenAIResponsesLegacyIngress(body) + require.NoError(t, err) + require.False(t, changed) + require.JSONEq(t, string(body), string(normalized)) + require.Equal(t, "pmpt_abc", gjson.GetBytes(normalized, "prompt.id").String()) + require.False(t, gjson.GetBytes(normalized, "input").Exists()) +} + +func TestNormalizeOpenAIResponsesLegacyIngressPreservesUnknownPromptShapeWhileDroppingCommands(t *testing.T) { + body := []byte(`{"model":"gpt-5.4","prompt":["one","two"],"commands":[{"name":"legacy"}]}`) + + normalized, changed, err := normalizeOpenAIResponsesLegacyIngress(body) + require.NoError(t, err) + require.True(t, changed) + require.Equal(t, int64(2), gjson.GetBytes(normalized, "prompt.#").Int()) + require.False(t, gjson.GetBytes(normalized, "input").Exists()) + require.False(t, gjson.GetBytes(normalized, "commands").Exists()) +} diff --git a/backend/internal/service/openai_responses_item_id.go b/backend/internal/service/openai_responses_item_id.go index f4621aa395..3a10966e89 100644 --- a/backend/internal/service/openai_responses_item_id.go +++ b/backend/internal/service/openai_responses_item_id.go @@ -70,35 +70,20 @@ func sanitizeOpenAIResponsesInputItemIDs(body []byte) ([]byte, bool, error) { type inputItem struct { body []byte - itemType string - id string - callID string stripID bool stripCallID bool - drop bool - isObject bool } items := make([]inputItem, 0) - strippedIDs := make(map[string]struct{}) - validCallIDs := make(map[string]struct{}) input.ForEach(func(_, item gjson.Result) bool { - parsed := inputItem{body: []byte(item.Raw), isObject: item.IsObject()} + parsed := inputItem{body: []byte(item.Raw)} if item.IsObject() { itemType := item.Get("type") id := item.Get("id") - parsed.itemType = strings.TrimSpace(itemType.String()) - parsed.callID = strings.TrimSpace(item.Get("call_id").String()) - parsed.stripCallID = item.Get("call_id").Exists() && shouldStripOpenAIResponsesNonPairCallID(parsed.itemType) + trimmedItemType := strings.TrimSpace(itemType.String()) + parsed.stripCallID = item.Get("call_id").Exists() && shouldStripOpenAIResponsesNonPairCallID(trimmedItemType) if id.Type == gjson.String { - parsed.id = id.String() - parsed.stripID = shouldStripOpenAIResponsesInputItemID(parsed.itemType, parsed.id) - if parsed.stripID && parsed.id != "" { - strippedIDs[parsed.id] = struct{}{} - } - } - if isCodexToolCallContextItemType(parsed.itemType) && parsed.callID != "" { - validCallIDs[parsed.callID] = struct{}{} + parsed.stripID = shouldStripOpenAIResponsesInputItemID(trimmedItemType, id.String()) } } items = append(items, parsed) @@ -115,51 +100,8 @@ func sanitizeOpenAIResponsesInputItemIDs(body []byte) ([]byte, bool, error) { return body, false, nil } - // First decide which outputs become dangling because their call_id points at - // an item ID that is being removed and no call item owns that call_id. This - // must happen before computing retained IDs: a dropped output cannot keep an - // item_reference alive merely because it used to have the same id. - for index := range items { - item := &items[index] - if !item.isObject || !isCodexToolCallOutputItemType(item.itemType) { - continue - } - if _, pointsAtStrippedID := strippedIDs[item.callID]; !pointsAtStrippedID { - continue - } - if _, hasMatchingCallID := validCallIDs[item.callID]; !hasMatchingCallID { - item.drop = true - } - } - - removedItemIDs := make(map[string]struct{}, len(strippedIDs)) - retainedItemIDs := make(map[string]struct{}, len(items)) - for _, item := range items { - if item.id == "" || item.itemType == "item_reference" { - continue - } - if item.stripID || item.drop { - removedItemIDs[item.id] = struct{}{} - continue - } - retainedItemIDs[item.id] = struct{}{} - } - for id := range retainedItemIDs { - delete(removedItemIDs, id) - } - rebuiltItems := make([][]byte, 0, len(items)) for index, item := range items { - if item.isObject { - if item.itemType == "item_reference" { - if _, dangling := removedItemIDs[item.id]; dangling { - continue - } - } - if item.drop { - continue - } - } itemBody := item.body if item.stripID { var err error diff --git a/backend/internal/service/openai_responses_item_id_test.go b/backend/internal/service/openai_responses_item_id_test.go index 17a0b2f9bc..b300b22a2e 100644 --- a/backend/internal/service/openai_responses_item_id_test.go +++ b/backend/internal/service/openai_responses_item_id_test.go @@ -45,11 +45,11 @@ func TestOpenAIResponsesInputItemIDPrefixUsesObservedOutputContracts(t *testing. } } -func TestSanitizeOpenAIResponsesInputItemIDsKeepsReferenceGraphConsistent(t *testing.T) { +func TestSanitizeOpenAIResponsesInputItemIDsDoesNotCascadeAcrossIDNamespaces(t *testing.T) { body := []byte(`{"input":[ {"type":"function_call","id":"item_bad_call","call_id":"call_valid","name":"lookup","arguments":"{}"}, {"type":"function_call_output","call_id":"call_valid","output":"preserve paired output"}, - {"type":"function_call_output","call_id":"item_bad_call","output":"drop dangling output"}, + {"type":"function_call_output","call_id":"item_bad_call","output":"preserve opaque output"}, {"type":"item_reference","id":"item_bad_call"}, {"type":"item_reference","id":"remote_valid"}, {"type":"custom_tool_call","id":"ctc_valid","call_id":"ctco_bad_output","name":"apply_patch","input":"patch"}, @@ -61,14 +61,16 @@ func TestSanitizeOpenAIResponsesInputItemIDsKeepsReferenceGraphConsistent(t *tes require.NoError(t, err) require.True(t, changed) items := gjson.GetBytes(sanitized, "input").Array() - require.Len(t, items, 5) + require.Len(t, items, 7) require.False(t, items[0].Get("id").Exists()) require.Equal(t, "call_valid", items[0].Get("call_id").String()) require.Equal(t, "preserve paired output", items[1].Get("output").String()) - require.Equal(t, "remote_valid", items[2].Get("id").String()) - require.Equal(t, "ctc_valid", items[3].Get("id").String()) - require.False(t, items[4].Get("id").Exists()) - require.Equal(t, "ctco_bad_output", items[4].Get("call_id").String()) + require.Equal(t, "preserve opaque output", items[2].Get("output").String()) + require.Equal(t, "item_bad_call", items[3].Get("id").String()) + require.Equal(t, "remote_valid", items[4].Get("id").String()) + require.Equal(t, "ctc_valid", items[5].Get("id").String()) + require.False(t, items[6].Get("id").Exists()) + require.Equal(t, "ctco_bad_output", items[6].Get("call_id").String()) } func TestSanitizeOpenAIResponsesInputItemIDsLeavesUnrelatedReferencesUntouched(t *testing.T) { @@ -93,7 +95,7 @@ func TestSanitizeOpenAIResponsesInputItemIDsPreservesReferenceToDuplicateRetaine require.Equal(t, "ctc_shared", gjson.GetBytes(sanitized, "input.2.id").String()) } -func TestSanitizeOpenAIResponsesInputItemIDsClosesReferencesAfterDroppingOutput(t *testing.T) { +func TestSanitizeOpenAIResponsesInputItemIDsPreservesOpaqueOutputsAndReferences(t *testing.T) { body := []byte(`{"input":[ {"type":"function_call","id":"item_shared","call_id":"call_real"}, {"type":"function_call_output","id":"item_shared","call_id":"item_shared","output":"dangling"}, @@ -106,10 +108,12 @@ func TestSanitizeOpenAIResponsesInputItemIDsClosesReferencesAfterDroppingOutput( require.NoError(t, err) require.True(t, changed) - require.Len(t, gjson.GetBytes(sanitized, "input").Array(), 3) + require.Len(t, gjson.GetBytes(sanitized, "input").Array(), 5) require.False(t, gjson.GetBytes(sanitized, "input.0.id").Exists()) - require.Equal(t, "kept_output", gjson.GetBytes(sanitized, "input.1.id").String()) - require.Equal(t, "kept_output", gjson.GetBytes(sanitized, "input.2.id").String()) + require.Equal(t, "dangling", gjson.GetBytes(sanitized, "input.1.output").String()) + require.Equal(t, "item_shared", gjson.GetBytes(sanitized, "input.2.id").String()) + require.Equal(t, "kept_output", gjson.GetBytes(sanitized, "input.3.id").String()) + require.Equal(t, "kept_output", gjson.GetBytes(sanitized, "input.4.id").String()) second, changedAgain, err := sanitizeOpenAIResponsesInputItemIDs(sanitized) require.NoError(t, err) diff --git a/backend/internal/service/openai_responses_tool_schema.go b/backend/internal/service/openai_responses_tool_schema.go index 08c9ecc2d6..c77640d0e3 100644 --- a/backend/internal/service/openai_responses_tool_schema.go +++ b/backend/internal/service/openai_responses_tool_schema.go @@ -26,13 +26,45 @@ const ( var errOpenAIResponsesToolSchemaLimit = errors.New("OpenAI Responses tool schema safety limit exceeded") -// shouldSanitizeOpenAIResponsesToolSchemas centralizes the platform boundary -// for callers. These rewrites describe OpenAI Responses constraints, not the -// behavior of every provider routed through the generic OpenAI gateway. -func shouldSanitizeOpenAIResponsesToolSchemas(platform string) bool { +// shouldRepairOpenAIResponsesNullToolSchemaType reports whether the upstream +// path requires a concrete object type at a function tool's parameter root. +// This defect is shared by the OpenAI, Anthropic, and CN-compatible paths. +func shouldRepairOpenAIResponsesNullToolSchemaType(platform string) bool { + return platform == PlatformOpenAI || platform == PlatformAnthropic || IsCNProvider(platform) +} + +// shouldSanitizeOpenAIResponsesToolSchemaPatterns is intentionally narrower: +// regex lookaround rejection is an OpenAI-specific schema constraint. +func shouldSanitizeOpenAIResponsesToolSchemaPatterns(platform string) bool { return platform == PlatformOpenAI } +func sanitizeOpenAIResponsesToolSchemasForPlatform(body []byte, platform string) ([]byte, bool, error) { + normalized := body + changed := false + if shouldRepairOpenAIResponsesNullToolSchemaType(platform) { + next, repaired, err := sanitizeOpenAIResponsesToolParameterTypes(normalized) + if err != nil { + return body, false, fmt.Errorf("sanitize OpenAI Responses tool parameters: %w", err) + } + if repaired { + normalized = next + changed = true + } + } + if shouldSanitizeOpenAIResponsesToolSchemaPatterns(platform) { + next, sanitized, err := sanitizeOpenAIResponsesToolSchemaPatterns(normalized) + if err != nil { + return body, false, fmt.Errorf("sanitize OpenAI Responses tool schema patterns: %w", err) + } + if sanitized { + normalized = next + changed = true + } + } + return normalized, changed, nil +} + // sanitizeOpenAIResponsesToolSchemaPatterns removes only schema constraints // containing regex lookaround, which OpenAI rejects. It deliberately does not // descend into instance-valued keywords such as default, examples, const, or diff --git a/backend/internal/service/openai_responses_tool_schema_test.go b/backend/internal/service/openai_responses_tool_schema_test.go index eeb9cf5dab..cf676645e1 100644 --- a/backend/internal/service/openai_responses_tool_schema_test.go +++ b/backend/internal/service/openai_responses_tool_schema_test.go @@ -239,11 +239,59 @@ func TestSanitizeOpenAIResponsesToolSchemas_InvalidAndTrailingJSON(t *testing.T) } } -func TestShouldSanitizeOpenAIResponsesToolSchemas_PlatformBoundary(t *testing.T) { - require.True(t, shouldSanitizeOpenAIResponsesToolSchemas(PlatformOpenAI)) - for _, platform := range []string{PlatformGrok, PlatformKimi, PlatformZhipu, PlatformDeepseek, PlatformComposite, ""} { - require.False(t, shouldSanitizeOpenAIResponsesToolSchemas(platform), platform) +func TestOpenAIResponsesToolSchemaCapabilities_PlatformBoundary(t *testing.T) { + tests := []struct { + platform string + repairNullType bool + removeLookaround bool + }{ + {PlatformOpenAI, true, true}, + {PlatformAnthropic, true, false}, + {PlatformKimi, true, false}, + {PlatformZhipu, true, false}, + {PlatformDeepseek, true, false}, + {PlatformGrok, false, false}, + {PlatformGemini, false, false}, + {PlatformAntigravity, false, false}, + {PlatformComposite, false, false}, + {"", false, false}, } + for _, tt := range tests { + t.Run(tt.platform, func(t *testing.T) { + require.Equal(t, tt.repairNullType, shouldRepairOpenAIResponsesNullToolSchemaType(tt.platform)) + require.Equal(t, tt.removeLookaround, shouldSanitizeOpenAIResponsesToolSchemaPatterns(tt.platform)) + }) + } +} + +func TestSanitizeOpenAIResponsesToolSchemasForPlatform_ReplayBoundary(t *testing.T) { + body := []byte(`{"tools":[{"type":"function","parameters":{"type":null,"properties":{"query":{"type":"string","pattern":"(?=keep)"}}}}]}`) + + // A malformed tool definition may be replayed after account failover. Every + // compatible account must repair it, while non-OpenAI providers retain their + // supported regex semantics. + for _, platform := range []string{PlatformAnthropic, PlatformKimi, PlatformZhipu, PlatformDeepseek} { + t.Run(platform, func(t *testing.T) { + for attempt := 0; attempt < 2; attempt++ { + normalized, changed, err := sanitizeOpenAIResponsesToolSchemasForPlatform(body, platform) + require.NoError(t, err) + require.True(t, changed) + require.Equal(t, "object", gjson.GetBytes(normalized, "tools.0.parameters.type").String()) + require.Equal(t, "(?=keep)", gjson.GetBytes(normalized, "tools.0.parameters.properties.query.pattern").String()) + } + }) + } + + openAI, changed, err := sanitizeOpenAIResponsesToolSchemasForPlatform(body, PlatformOpenAI) + require.NoError(t, err) + require.True(t, changed) + require.Equal(t, "object", gjson.GetBytes(openAI, "tools.0.parameters.type").String()) + require.False(t, gjson.GetBytes(openAI, "tools.0.parameters.properties.query.pattern").Exists()) + + unsupported, changed, err := sanitizeOpenAIResponsesToolSchemasForPlatform(body, PlatformGrok) + require.NoError(t, err) + require.False(t, changed) + require.Equal(t, string(body), string(unsupported)) } // 索引映射:只有坏条目被改,前后兄弟条目按原下标保持不变。 diff --git a/backend/internal/service/openai_upstream_client_error_test.go b/backend/internal/service/openai_upstream_client_error_test.go index 2b6ed51967..291c1c491e 100644 --- a/backend/internal/service/openai_upstream_client_error_test.go +++ b/backend/internal/service/openai_upstream_client_error_test.go @@ -164,6 +164,7 @@ func TestHandleErrorResponse_NonDeterministicStatusesKeepGeneric502(t *testing.T {"unprocessable", http.StatusUnprocessableEntity, `{"error":{"message":"Invalid schema for field messages"}}`, http.StatusBadGateway, "upstream_error", "Upstream request failed"}, // 401/402/403 是网关运营方的凭据/账单问题,必须继续对客户端屏蔽上游账号状态。 + // 403 的自由文本不能升级成 durable access-state typed failover;只有明确结构化 code 才可以。 {"unauthorized", http.StatusUnauthorized, `{"error":{"message":"Incorrect API key provided: sk-abc"}}`, http.StatusBadGateway, "upstream_error", "Upstream authentication failed, please contact administrator"}, {"forbidden", http.StatusForbidden, `{"error":{"message":"Your account is deactivated"}}`, @@ -183,15 +184,11 @@ func TestHandleErrorResponse_NonDeterministicStatusesKeepGeneric502(t *testing.T newOpenAIUpstreamErrorResponse(tc.statusCode, tc.body), c, newOpenAIUpstreamErrorTestAccount(), nil, ) + require.Error(t, err) if tc.name == "forbidden" { var failoverErr *UpstreamFailoverError - require.ErrorAs(t, err, &failoverErr) - require.Equal(t, http.StatusForbidden, failoverErr.StatusCode) - require.False(t, c.Writer.Written()) - return + require.False(t, errors.As(err, &failoverErr)) } - - require.Error(t, err) require.Equal(t, tc.wantStatus, rec.Code) require.Equal(t, tc.wantType, gjson.Get(rec.Body.String(), "error.type").String()) require.Equal(t, tc.wantMsg, gjson.Get(rec.Body.String(), "error.message").String()) diff --git a/backend/internal/service/openai_ws_http_bridge.go b/backend/internal/service/openai_ws_http_bridge.go index ae41c3bbbd..3f5d1e57b5 100644 --- a/backend/internal/service/openai_ws_http_bridge.go +++ b/backend/internal/service/openai_ws_http_bridge.go @@ -489,6 +489,7 @@ func (s *OpenAIGatewayService) proxyOpenAIWSHTTPBridgeTurn( pendingClientMessageBytes := int64(0) capacityFailoverSuppressedLogged := false clientDisconnected := false + officialOpenAIResponses := account != nil && account.Platform == PlatformOpenAI bareErrorPending := false var bareErrorPayload []byte bareErrorMessage := "" @@ -642,7 +643,15 @@ func (s *OpenAIGatewayService) proxyOpenAIWSHTTPBridgeTurn( replayCollector.AddEvent(eventType, upstreamMessage) var upstreamEventErr error - suppressClientMessage := bareErrorPending && eventType != "response.failed" + if officialOpenAIResponses && bareErrorPending && (eventType == "response.completed" || eventType == "response.done") { + // Some upstreams emit a recoverable bare error before the authoritative + // successful terminal. Do not replace that terminal with a synthetic + // failure or retain side effects from the superseded error. + bareErrorPending = false + bareErrorPayload = nil + bareErrorMessage = "" + } + suppressClientMessage := officialOpenAIResponses && bareErrorPending && eventType != "response.failed" if eventType == "error" || eventType == "response.failed" { errMessage := extractOpenAISSEErrorMessage(upstreamMessage) if errMessage == "" { @@ -677,7 +686,7 @@ func (s *OpenAIGatewayService) proxyOpenAIWSHTTPBridgeTurn( return nil, s.newOpenAIStreamFailoverError(c, account, true, resp.Header.Get("x-request-id"), upstreamMessage, errMessage, resp.Header) } if account.Platform != PlatformGrok && !failureAccountSideEffectsApplied { - if eventType == "response.failed" || (shouldFailover && !requestScopedCapacity) { + if eventType == "response.failed" || (!officialOpenAIResponses && shouldFailover && !requestScopedCapacity) { failureAccountSideEffectsApplied = s.handleOpenAIWSFailureAccountSideEffects(ctx, account, mappedModel, resp.Header, upstreamMessage) } } @@ -685,7 +694,7 @@ func (s *OpenAIGatewayService) proxyOpenAIWSHTTPBridgeTurn( logOpenAICapacityFailoverSuppressed(ctx, account, "ws_http_bridge", resp.Header.Get("x-request-id"), eventType) capacityFailoverSuppressedLogged = true } - if eventType == "error" && account.Platform == PlatformGrok { + if eventType == "error" && !officialOpenAIResponses { upstreamEventErr = errors.New(errMessage) } else if eventType == "error" { bareErrorPending = true diff --git a/backend/internal/service/openai_ws_http_bridge_test.go b/backend/internal/service/openai_ws_http_bridge_test.go index a8c10cf893..4aec9d7d8a 100644 --- a/backend/internal/service/openai_ws_http_bridge_test.go +++ b/backend/internal/service/openai_ws_http_bridge_test.go @@ -758,6 +758,40 @@ func TestProxyOpenAIWSHTTPBridgeTurnBareErrorEOFSynthesizesFailed(t *testing.T) require.Equal(t, "resp_eof", gjson.GetBytes(writes[1], "response.id").String()) } +func TestProxyOpenAIWSHTTPBridgeTurnBareErrorFollowedByCompletedUsesCompleted(t *testing.T) { + gin.SetMode(gin.TestMode) + body := strings.Join([]string{ + `data: {"type":"response.created","response":{"id":"resp_recovered","status":"in_progress"}}`, + ``, + `data: {"type":"error","error":{"code":"transient","message":"retrying"}}`, + ``, + `data: {"type":"response.completed","response":{"id":"resp_recovered","status":"completed","output":[],"usage":{"input_tokens":8,"output_tokens":4}}}`, + ``, + }, "\n") + upstream := &httpUpstreamRecorder{resp: &http.Response{StatusCode: http.StatusOK, Header: make(http.Header), Body: io.NopCloser(strings.NewReader(body))}} + svc := &OpenAIGatewayService{cfg: &config.Config{}, httpUpstream: upstream} + account := &Account{ID: 113, Platform: PlatformOpenAI, Type: AccountTypeOAuth, Concurrency: 1} + recorder := httptest.NewRecorder() + c, _ := gin.CreateTestContext(recorder) + c.Request = httptest.NewRequest(http.MethodGet, "/v1/responses", nil) + payload := []byte(`{"type":"response.create","model":"gpt-5","input":"hi"}`) + var writes [][]byte + + result, err := svc.proxyOpenAIWSHTTPBridgeTurn(context.Background(), c, account, "sk-test", payload, len(payload), "gpt-5", "", "", "", "", 2, func(message []byte) error { + writes = append(writes, append([]byte(nil), message...)) + return nil + }) + + require.NoError(t, err) + require.NotNil(t, result) + require.Equal(t, "response.completed", result.UpstreamTerminalEvent) + require.Equal(t, 8, result.Usage.InputTokens) + require.Equal(t, 4, result.Usage.OutputTokens) + require.Len(t, writes, 2) + require.Equal(t, "response.created", gjson.GetBytes(writes[0], "type").String()) + require.Equal(t, "response.completed", gjson.GetBytes(writes[1], "type").String()) +} + func TestProxyOpenAIWSHTTPBridgeTurnStagesMetadataBeforeCapacityFailover(t *testing.T) { gin.SetMode(gin.TestMode) body := strings.Join([]string{ diff --git a/backend/internal/service/openai_ws_state_store.go b/backend/internal/service/openai_ws_state_store.go index d3b6891b0a..fe4ee54926 100644 --- a/backend/internal/service/openai_ws_state_store.go +++ b/backend/internal/service/openai_ws_state_store.go @@ -13,6 +13,8 @@ import ( const ( openAIWSResponseAccountCachePrefix = "openai:response:" + openAIHTTPResponseOwnerUserPrefix = "openai:http-response-owner:user:" + openAIHTTPResponseOwnerKeyPrefix = "openai:http-response-owner:key:" openAIWSStateStoreCleanupInterval = time.Minute openAIWSStateStoreCleanupMaxPerMap = 512 openAIWSStateStoreMaxEntriesPerMap = 65536 @@ -24,6 +26,12 @@ type openAIWSAccountBinding struct { expiresAt time.Time } +type openAIHTTPResponseOwnerBinding struct { + userID int64 + apiKeyID int64 + expiresAt time.Time +} + type openAIWSConnBinding struct { connID string expiresAt time.Time @@ -49,6 +57,8 @@ type OpenAIWSStateStore interface { BindResponseAccount(ctx context.Context, groupID int64, responseID string, accountID int64, ttl time.Duration) error GetResponseAccount(ctx context.Context, groupID int64, responseID string) (int64, error) DeleteResponseAccount(ctx context.Context, groupID int64, responseID string) error + BindHTTPResponseOwner(ctx context.Context, groupID int64, responseID string, userID, apiKeyID int64, ttl time.Duration) error + GetHTTPResponseOwner(ctx context.Context, groupID int64, responseID string) (userID, apiKeyID int64, found bool, err error) BindResponseConn(responseID, connID string, ttl time.Duration) GetResponseConn(responseID string) (string, bool) @@ -68,6 +78,8 @@ type defaultOpenAIWSStateStore struct { responseToAccountMu sync.RWMutex responseToAccount map[string]openAIWSAccountBinding + responseOwnerMu sync.RWMutex + responseOwners map[string]openAIHTTPResponseOwnerBinding responseToConnMu sync.RWMutex responseToConn map[string]openAIWSConnBinding sessionToTurnStateMu sync.RWMutex @@ -83,6 +95,7 @@ func NewOpenAIWSStateStore(cache GatewayCache) OpenAIWSStateStore { store := &defaultOpenAIWSStateStore{ cache: cache, responseToAccount: make(map[string]openAIWSAccountBinding, 256), + responseOwners: make(map[string]openAIHTTPResponseOwnerBinding, 256), responseToConn: make(map[string]openAIWSConnBinding, 256), sessionToTurnState: make(map[string]openAIWSTurnStateBinding, 256), sessionToConn: make(map[string]openAIWSSessionConnBinding, 256), @@ -91,6 +104,72 @@ func NewOpenAIWSStateStore(cache GatewayCache) OpenAIWSStateStore { return store } +func (s *defaultOpenAIWSStateStore) BindHTTPResponseOwner(ctx context.Context, groupID int64, responseID string, userID, apiKeyID int64, ttl time.Duration) error { + id := normalizeOpenAIWSResponseID(responseID) + if id == "" || userID <= 0 || apiKeyID <= 0 { + return nil + } + ttl = normalizeOpenAIWSTTL(ttl) + s.maybeCleanup() + + mapKey := openAIWSResponseAccountMapKey(groupID, id) + s.responseOwnerMu.Lock() + ensureBindingCapacity(s.responseOwners, mapKey, openAIWSStateStoreMaxEntriesPerMap) + s.responseOwners[mapKey] = openAIHTTPResponseOwnerBinding{ + userID: userID, apiKeyID: apiKeyID, expiresAt: time.Now().Add(ttl), + } + s.responseOwnerMu.Unlock() + + if s.cache == nil { + return nil + } + cacheCtx, cancel := withOpenAIWSStateStoreRedisTimeout(ctx) + defer cancel() + if err := s.cache.SetSessionAccountID(cacheCtx, groupID, openAIHTTPResponseOwnerCacheKey(openAIHTTPResponseOwnerUserPrefix, id), userID, ttl); err != nil { + return err + } + return s.cache.SetSessionAccountID(cacheCtx, groupID, openAIHTTPResponseOwnerCacheKey(openAIHTTPResponseOwnerKeyPrefix, id), apiKeyID, ttl) +} + +func (s *defaultOpenAIWSStateStore) GetHTTPResponseOwner(ctx context.Context, groupID int64, responseID string) (int64, int64, bool, error) { + id := normalizeOpenAIWSResponseID(responseID) + if id == "" { + return 0, 0, false, nil + } + s.maybeCleanup() + + now := time.Now() + mapKey := openAIWSResponseAccountMapKey(groupID, id) + s.responseOwnerMu.RLock() + if binding, ok := s.responseOwners[mapKey]; ok && now.Before(binding.expiresAt) { + s.responseOwnerMu.RUnlock() + return binding.userID, binding.apiKeyID, true, nil + } + s.responseOwnerMu.RUnlock() + + if s.cache == nil { + return 0, 0, false, nil + } + cacheCtx, cancel := withOpenAIWSStateStoreRedisTimeout(ctx) + defer cancel() + userID, err := s.cache.GetSessionAccountID(cacheCtx, groupID, openAIHTTPResponseOwnerCacheKey(openAIHTTPResponseOwnerUserPrefix, id)) + if err != nil || userID <= 0 { + return 0, 0, false, err + } + apiKeyID, err := s.cache.GetSessionAccountID(cacheCtx, groupID, openAIHTTPResponseOwnerCacheKey(openAIHTTPResponseOwnerKeyPrefix, id)) + if err != nil || apiKeyID <= 0 { + return 0, 0, false, err + } + + s.responseOwnerMu.Lock() + ensureBindingCapacity(s.responseOwners, mapKey, openAIWSStateStoreMaxEntriesPerMap) + s.responseOwners[mapKey] = openAIHTTPResponseOwnerBinding{ + userID: userID, apiKeyID: apiKeyID, expiresAt: now.Add(time.Minute), + } + s.responseOwnerMu.Unlock() + return userID, apiKeyID, true, nil +} + func (s *defaultOpenAIWSStateStore) BindResponseAccount(ctx context.Context, groupID int64, responseID string, accountID int64, ttl time.Duration) error { id := normalizeOpenAIWSResponseID(responseID) if id == "" || accountID <= 0 { @@ -115,6 +194,22 @@ func (s *defaultOpenAIWSStateStore) BindResponseAccount(ctx context.Context, gro return s.cache.SetSessionAccountID(cacheCtx, groupID, cacheKey, accountID, ttl) } +func cleanupExpiredHTTPResponseOwnerBindings(bindings map[string]openAIHTTPResponseOwnerBinding, now time.Time, maxScan int) { + if len(bindings) == 0 || maxScan <= 0 { + return + } + scanned := 0 + for key, binding := range bindings { + if now.After(binding.expiresAt) { + delete(bindings, key) + } + scanned++ + if scanned >= maxScan { + break + } + } +} + func (s *defaultOpenAIWSStateStore) GetResponseAccount(ctx context.Context, groupID int64, responseID string) (int64, error) { id := normalizeOpenAIWSResponseID(responseID) if id == "" { @@ -319,6 +414,10 @@ func (s *defaultOpenAIWSStateStore) maybeCleanup() { cleanupExpiredAccountBindings(s.responseToAccount, now, openAIWSStateStoreCleanupMaxPerMap) s.responseToAccountMu.Unlock() + s.responseOwnerMu.Lock() + cleanupExpiredHTTPResponseOwnerBindings(s.responseOwners, now, openAIWSStateStoreCleanupMaxPerMap) + s.responseOwnerMu.Unlock() + s.responseToConnMu.Lock() cleanupExpiredConnBindings(s.responseToConn, now, openAIWSStateStoreCleanupMaxPerMap) s.responseToConnMu.Unlock() @@ -419,6 +518,11 @@ func openAIWSResponseAccountCacheKey(responseID string) string { return openAIWSResponseAccountCachePrefix + hex.EncodeToString(sum[:]) } +func openAIHTTPResponseOwnerCacheKey(prefix, responseID string) string { + sum := sha256.Sum256([]byte(responseID)) + return prefix + hex.EncodeToString(sum[:]) +} + // openAIWSResponseAccountMapKey 本地热缓存按分组隔离的 key,与 Redis 层保持一致,避免跨组命中。 func openAIWSResponseAccountMapKey(groupID int64, responseID string) string { return fmt.Sprintf("%d:%s", groupID, responseID) diff --git a/backend/internal/service/openai_ws_state_store_test.go b/backend/internal/service/openai_ws_state_store_test.go index 869e5e0fd6..6b20a95507 100644 --- a/backend/internal/service/openai_ws_state_store_test.go +++ b/backend/internal/service/openai_ws_state_store_test.go @@ -28,6 +28,27 @@ func TestOpenAIWSStateStore_BindGetDeleteResponseAccount(t *testing.T) { require.Zero(t, accountID) } +func TestOpenAIWSStateStore_HTTPResponseOwnerPersistsAcrossStoreInstances(t *testing.T) { + cache := &stubGatewayCache{} + ctx := context.Background() + groupID := int64(8) + writer := NewOpenAIWSStateStore(cache) + + require.NoError(t, writer.BindHTTPResponseOwner(ctx, groupID, "resp_owned", 201, 301, time.Minute)) + userID, apiKeyID, found, err := writer.GetHTTPResponseOwner(ctx, groupID, "resp_owned") + require.NoError(t, err) + require.True(t, found) + require.Equal(t, int64(201), userID) + require.Equal(t, int64(301), apiKeyID) + + reader := NewOpenAIWSStateStore(cache) + userID, apiKeyID, found, err = reader.GetHTTPResponseOwner(ctx, groupID, "resp_owned") + require.NoError(t, err) + require.True(t, found) + require.Equal(t, int64(201), userID) + require.Equal(t, int64(301), apiKeyID) +} + func TestOpenAIWSStateStore_ResponseConnTTL(t *testing.T) { store := NewOpenAIWSStateStore(nil) store.BindResponseConn("resp_conn", "conn_1", 30*time.Millisecond) diff --git a/backend/internal/service/openai_ws_v2/passthrough_relay.go b/backend/internal/service/openai_ws_v2/passthrough_relay.go index e5e2633644..67c26f3e96 100644 --- a/backend/internal/service/openai_ws_v2/passthrough_relay.go +++ b/backend/internal/service/openai_ws_v2/passthrough_relay.go @@ -270,30 +270,34 @@ func Relay( if !options.StartClientAfterFirstDownstream { startClientReader() } - go runUpstreamToClient( - relayCtx, - upstreamConn, - writeClient, - startAt, - nowFn, - state, - options.OnUsageParseFailure, - options.OnTurnComplete, - options.BeforeWriteClient, - options.BeforeClientWrite, - options.AfterClientWrite, - func(msgType coderws.MessageType, payload []byte) { - if options.StartClientAfterFirstDownstream { - startClientReader() - } - }, - &dropDownstreamWrites, - upstreamToClientFrames, - droppedDownstreamFrames, - markActivity, - onTrace, - exitCh, - ) + upstreamDone := make(chan struct{}) + go func() { + defer close(upstreamDone) + runUpstreamToClient( + relayCtx, + upstreamConn, + writeClient, + startAt, + nowFn, + state, + options.OnUsageParseFailure, + options.OnTurnComplete, + options.BeforeWriteClient, + options.BeforeClientWrite, + options.AfterClientWrite, + func(msgType coderws.MessageType, payload []byte) { + if options.StartClientAfterFirstDownstream { + startClientReader() + } + }, + &dropDownstreamWrites, + upstreamToClientFrames, + droppedDownstreamFrames, + markActivity, + onTrace, + exitCh, + ) + }() go runIdleWatchdog(relayCtx, nowFn, options.IdleTimeout, &lastActivity, onTrace, exitCh) firstExit := <-exitCh @@ -347,6 +351,10 @@ func Relay( relayCancel() _ = upstreamConn.Close() + // ReadFrame observes relayCtx cancellation and Close is the transport-level + // fallback. Join the reader before touching relayState or firing the final + // turn callback; otherwise a late read can race Relay's result settlement. + <-upstreamDone emitTurnComplete(options.OnTurnComplete, state, finalizePendingBareError(state, nowFn())) enrichResult(&result, state, nowFn().Sub(startAt)) diff --git a/backend/internal/service/openai_ws_v2/passthrough_relay_test.go b/backend/internal/service/openai_ws_v2/passthrough_relay_test.go index 3bca8bf0ab..28b896f248 100644 --- a/backend/internal/service/openai_ws_v2/passthrough_relay_test.go +++ b/backend/internal/service/openai_ws_v2/passthrough_relay_test.go @@ -41,6 +41,16 @@ type closeSpyFrameConn struct { closeCalls atomic.Int32 } +type cancelJoinProbeFrameConn struct { + readStarted chan struct{} + readCanceled chan struct{} + allowReturn chan struct{} + readReturned chan struct{} + startOnce sync.Once + cancelOnce sync.Once + returnOnce sync.Once +} + func newPassthroughTestFrameConn(frames []passthroughTestFrame, autoClose bool) *passthroughTestFrameConn { c := &passthroughTestFrameConn{ readCh: make(chan passthroughTestFrame, len(frames)+1), @@ -179,6 +189,38 @@ func (c *closeSpyFrameConn) CloseCalls() int32 { return c.closeCalls.Load() } +func newCancelJoinProbeFrameConn() *cancelJoinProbeFrameConn { + return &cancelJoinProbeFrameConn{ + readStarted: make(chan struct{}), + readCanceled: make(chan struct{}), + allowReturn: make(chan struct{}), + readReturned: make(chan struct{}), + } +} + +func (c *cancelJoinProbeFrameConn) ReadFrame(ctx context.Context) (coderws.MessageType, []byte, error) { + c.startOnce.Do(func() { close(c.readStarted) }) + <-ctx.Done() + c.cancelOnce.Do(func() { close(c.readCanceled) }) + <-c.allowReturn + c.returnOnce.Do(func() { close(c.readReturned) }) + return coderws.MessageText, nil, ctx.Err() +} + +func (c *cancelJoinProbeFrameConn) WriteFrame(ctx context.Context, _ coderws.MessageType, _ []byte) error { + if ctx == nil { + ctx = context.Background() + } + select { + case <-ctx.Done(): + return ctx.Err() + default: + return nil + } +} + +func (c *cancelJoinProbeFrameConn) Close() error { return nil } + func TestRelay_BasicRelayAndUsage(t *testing.T) { t.Parallel() @@ -372,6 +414,58 @@ func TestRelay_IdleTimeoutDoesNotCloseClientOnError(t *testing.T) { require.GreaterOrEqual(t, upstreamConn.CloseCalls(), int32(1)) } +func TestRelay_JoinsUpstreamReaderBeforeReturning(t *testing.T) { + t.Parallel() + + clientConn := &closeSpyFrameConn{} + upstreamConn := newCancelJoinProbeFrameConn() + ctx, cancel := context.WithCancel(context.Background()) + resultCh := make(chan *RelayExit, 1) + + go func() { + _, relayExit := Relay( + ctx, + clientConn, + upstreamConn, + []byte(`{"type":"response.create","model":"gpt-4o","input":[]}`), + RelayOptions{}, + ) + resultCh <- relayExit + }() + + select { + case <-upstreamConn.readStarted: + case <-time.After(time.Second): + t.Fatal("upstream reader did not start") + } + cancel() + select { + case <-upstreamConn.readCanceled: + case <-time.After(time.Second): + t.Fatal("upstream reader did not observe relay cancellation") + } + select { + case <-resultCh: + t.Fatal("Relay returned before the upstream reader exited") + case <-time.After(50 * time.Millisecond): + } + + close(upstreamConn.allowReturn) + select { + case relayExit := <-resultCh: + require.NotNil(t, relayExit) + require.ErrorIs(t, relayExit.Err, context.Canceled) + case <-time.After(time.Second): + t.Fatal("Relay did not return after the upstream reader exited") + } + select { + case <-upstreamConn.readReturned: + default: + t.Fatal("Relay returned before the upstream reader completion signal") + } + require.Zero(t, clientConn.CloseCalls(), "错误路径不应提前关闭客户端连接") +} + func TestRelay_NilConnections(t *testing.T) { t.Parallel() diff --git a/backend/internal/service/ops_upstream_context.go b/backend/internal/service/ops_upstream_context.go index b4919b7809..509620fa1b 100644 --- a/backend/internal/service/ops_upstream_context.go +++ b/backend/internal/service/ops_upstream_context.go @@ -388,7 +388,9 @@ type OpsUpstreamErrorEvent struct { Detail string `json:"detail,omitempty"` // SkipMonitoring is request-local rule state. It is intentionally excluded - // from persisted attempt JSON and only lets the final attempt control Ops. + // from persisted attempt JSON. The logger consults it only when this event is + // the final client-visible failure; recovered attempts remain provider-health + // telemetry and do not count as failed requests. SkipMonitoring bool `json:"-"` } @@ -427,11 +429,10 @@ func appendOpsUpstreamError(c *gin.Context, ev OpsUpstreamErrorEvent) { checkSkipMonitoringForUpstreamEvent(c, &evCopy) } -// checkSkipMonitoringForUpstreamEvent checks whether the upstream error event -// matches a passthrough rule with skip_monitoring=true and, if so, sets the -// OpsSkipPassthroughKey on the context. This ensures intermediate retry / -// failover errors (which never go through the final applyErrorPassthroughRule -// path) can still suppress ops_error_logs recording. +// checkSkipMonitoringForUpstreamEvent snapshots whether this attempt matches a +// skip_monitoring passthrough rule. The final failure decides whether the +// request error is hidden; an intermediate recovered attempt cannot suppress a +// later client-visible failure. func checkSkipMonitoringForUpstreamEvent(c *gin.Context, ev *OpsUpstreamErrorEvent) { if ev.UpstreamStatusCode == 0 { return diff --git a/backend/internal/service/temp_unsched.go b/backend/internal/service/temp_unsched.go index 9b120c5775..92b7da3f72 100644 --- a/backend/internal/service/temp_unsched.go +++ b/backend/internal/service/temp_unsched.go @@ -29,7 +29,6 @@ type TempUnschedCache interface { // aggregate pool API-key failures across gateway instances. type OpenAIAPIKeyHealthCache interface { RecordOpenAIAPIKeyHealthFailure(ctx context.Context, accountID int64, windowMinutes, threshold int) (count int64, tripped bool, err error) - ResetOpenAIAPIKeyHealthFailures(ctx context.Context, accountID int64) error } // TimeoutCounterCache 超时计数器缓存接口 From 1429e8f714e7c875f4cb6f1fd3c1656b928df7f3 Mon Sep 17 00:00:00 2001 From: IanShaw <131567472+IanShaw027@users.noreply.github.com> Date: Thu, 20 Aug 2026 22:01:20 -0700 Subject: [PATCH 080/204] =?UTF-8?q?=E4=BF=AE=E5=A4=8D=20PR=205888=20?= =?UTF-8?q?=E5=89=A9=E4=BD=99=E5=AE=A1=E8=AE=A1=E9=97=AE=E9=A2=98?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../handler/openai_gateway_count_tokens.go | 76 +---------------- .../handler/openai_gateway_handler.go | 4 + .../openai_responses_input_tokens_test.go | 83 ------------------ .../handler/ops_capture_writer_nil_test.go | 11 +-- backend/internal/handler/ops_error_logger.go | 85 ++++++++++--------- .../internal/handler/ops_error_logger_test.go | 50 +++++++++++ backend/internal/service/error_policy_test.go | 32 ++++++- .../service/openai_account_scheduler_test.go | 53 ++++++++++++ .../service/openai_codex_transform_test.go | 8 +- .../service/openai_gateway_scheduling.go | 27 ++++++ .../service/openai_ws_forwarder_ingress.go | 25 +----- .../service/openai_ws_session_preemption.go | 44 ++++++++++ .../openai_ws_session_preemption_test.go | 41 +++++++++ .../service/overload_cooldown_test.go | 32 ++++++- backend/internal/service/ratelimit_service.go | 29 ++++--- 15 files changed, 351 insertions(+), 249 deletions(-) diff --git a/backend/internal/handler/openai_gateway_count_tokens.go b/backend/internal/handler/openai_gateway_count_tokens.go index 126100b349..2df4f4f2d0 100644 --- a/backend/internal/handler/openai_gateway_count_tokens.go +++ b/backend/internal/handler/openai_gateway_count_tokens.go @@ -96,18 +96,12 @@ func (h *OpenAIGatewayHandler) ResponsesInputTokens(c *gin.Context) { requestPlatform := openAICompatibleRequestPlatform(c.Request.Context(), apiKey) sessionHash := h.gatewayService.GenerateSessionHash(c, body) requestStart := time.Now() - selection, _, err := h.gatewayService.SelectAccountWithSchedulerForCapability( + account, err := h.gatewayService.SelectAccountForTokenCount( c.Request.Context(), apiKey.GroupID, - "", sessionHash, routingModel, - nil, - service.OpenAIUpstreamTransportAny, service.OpenAIEndpointCapabilityChatCompletions, - false, - false, - false, requestPlatform, ) service.SetOpsLatencyMs(c, service.OpsAuthLatencyMsKey, time.Since(requestStart).Milliseconds()) @@ -120,7 +114,7 @@ func (h *OpenAIGatewayHandler) ResponsesInputTokens(c *gin.Context) { h.errorResponse(c, cls.Status, cls.ErrType, cls.Message) return } - if selection == nil || selection.Account == nil { + if account == nil { cls := classifyOpenAICompatibleNoAccountErrorFromGin(c, h.gatewayService, apiKey, routingModel, reqModel) if !cls.ModelNotFound { markOpsRoutingCapacityLimited(c) @@ -129,16 +123,7 @@ func (h *OpenAIGatewayHandler) ResponsesInputTokens(c *gin.Context) { return } - account := selection.Account setOpsSelectedAccount(c, account.ID, account.Platform) - accountRelease, acquired := h.acquireCountTokensAccountSlot(c, apiKey.GroupID, sessionHash, selection, false, reqLog) - if !acquired { - return - } - if accountRelease != nil { - defer accountRelease() - } - account = selection.Account if err := h.gatewayService.ForwardResponsesInputTokens(c.Request.Context(), c, account, forwardBody); err != nil { reqLog.Error("openai_input_tokens.forward_failed", zap.Int64("account_id", account.ID), zap.Error(err)) } @@ -283,18 +268,12 @@ func (h *OpenAIGatewayHandler) CountTokens(c *gin.Context) { if preferredMappedModel != "" { currentRoutingModel = preferredMappedModel } - selection, _, err := h.gatewayService.SelectAccountWithSchedulerForCapability( + account, err := h.gatewayService.SelectAccountForTokenCount( c.Request.Context(), apiKey.GroupID, - "", sessionHash, currentRoutingModel, - nil, - service.OpenAIUpstreamTransportAny, service.OpenAIEndpointCapabilityChatCompletions, - false, - false, - false, openAICompatibleRequestPlatform(c.Request.Context(), apiKey), ) service.SetOpsLatencyMs(c, service.OpsAuthLatencyMsKey, time.Since(requestStart).Milliseconds()) @@ -308,7 +287,7 @@ func (h *OpenAIGatewayHandler) CountTokens(c *gin.Context) { h.anthropicErrorResponse(c, cls.Status, cls.ErrType, cls.Message) return } - if selection == nil || selection.Account == nil { + if account == nil { cls := classifyOpenAICompatibleNoAccountErrorFromGin(c, h.gatewayService, apiKey, currentRoutingModel, reqModel) if !cls.ModelNotFound { markOpsRoutingCapacityLimited(c) @@ -317,16 +296,7 @@ func (h *OpenAIGatewayHandler) CountTokens(c *gin.Context) { return } - account := selection.Account setOpsSelectedAccount(c, account.ID, account.Platform) - accountRelease, acquired := h.acquireCountTokensAccountSlot(c, apiKey.GroupID, sessionHash, selection, true, reqLog) - if !acquired { - return - } - if accountRelease != nil { - defer accountRelease() - } - account = selection.Account forwardBody := mappedBodyForMessages(channelMapping.Mapped, channelMapping.MappedModel) defaultMappedModel := preferredMappedModel @@ -334,41 +304,3 @@ func (h *OpenAIGatewayHandler) CountTokens(c *gin.Context) { reqLog.Error("openai_count_tokens.forward_failed", zap.Int64("account_id", account.ID), zap.Error(err)) } } - -func (h *OpenAIGatewayHandler) acquireCountTokensAccountSlot( - c *gin.Context, - groupID *int64, - sessionHash string, - selection *service.AccountSelectionResult, - anthropicResponse bool, - reqLog *zap.Logger, -) (func(), bool) { - writeError := func(status int, errType, message string) { - if anthropicResponse { - h.anthropicErrorResponse(c, status, errType, message) - return - } - h.errorResponse(c, status, errType, message) - } - streamStarted := false - release, result := h.acquireOpenAIAccountSlot( - c, - groupID, - sessionHash, - selection, - false, - &streamStarted, - reqLog, - writeError, - ) - if result == openAISlotAcquireOK { - return release, true - } - // Token-count requests suppress the profit gate before selection, so this - // is defensive only. Never forward without a slot if a stale gate appears. - if result == openAISlotAcquireProfitVetoed { - markOpsRoutingCapacityLimited(c) - writeError(http.StatusServiceUnavailable, "api_error", "No available accounts") - } - return nil, false -} diff --git a/backend/internal/handler/openai_gateway_handler.go b/backend/internal/handler/openai_gateway_handler.go index 45144479c7..9c8ea82a08 100644 --- a/backend/internal/handler/openai_gateway_handler.go +++ b/backend/internal/handler/openai_gateway_handler.go @@ -2466,6 +2466,10 @@ func (h *OpenAIGatewayHandler) ResponsesWebSocket(c *gin.Context) { // WebSocket 首包可能很大,hash 必须在 hooks 外算成字符串,避免 AfterTurn 闭包保活请求体。 requestPayloadHash = service.HashUsageRequestPayload(wsFirstMessage) + if preemptCtx, cleanupPreempt, armed := h.gatewayService.BeginOpenAIWSIngressSessionPreemption(ctx, c, account, wsFirstMessage); armed { + ctx = preemptCtx + defer cleanupPreempt() + } for { err := h.gatewayService.ProxyResponsesWebSocketFromClient(ctx, c, wsConn, account, token, wsFirstMessage, hooks) diff --git a/backend/internal/handler/openai_responses_input_tokens_test.go b/backend/internal/handler/openai_responses_input_tokens_test.go index c9c8aaa625..b3260fc2ad 100644 --- a/backend/internal/handler/openai_responses_input_tokens_test.go +++ b/backend/internal/handler/openai_responses_input_tokens_test.go @@ -1,17 +1,12 @@ package handler import ( - "context" "net/http" "net/http/httptest" - "sync/atomic" "testing" - "time" - "github.com/Wei-Shaw/sub2api/internal/service" "github.com/gin-gonic/gin" "github.com/stretchr/testify/require" - "go.uber.org/zap" ) func TestResponsesInputTokensIsClassifiedAsTokenCountRequest(t *testing.T) { @@ -24,81 +19,3 @@ func TestResponsesInputTokensIsClassifiedAsTokenCountRequest(t *testing.T) { require.True(t, isTokenCountRequestPath("/responses/input_tokens")) require.False(t, isTokenCountRequestPath("/v1/responses")) } - -func TestCountTokensAccountSlot_CancellationStopsBeforeForward(t *testing.T) { - gin.SetMode(gin.TestMode) - - for _, tt := range []struct { - name string - anthropic bool - }{ - {name: "responses input tokens", anthropic: false}, - {name: "anthropic count tokens", anthropic: true}, - } { - t.Run(tt.name, func(t *testing.T) { - cache := &concurrencyCacheMock{ - acquireAccountSlotFn: func(context.Context, int64, int, string) (bool, error) { - return false, nil - }, - } - h := &OpenAIGatewayHandler{ - gatewayService: &service.OpenAIGatewayService{}, - concurrencyHelper: NewConcurrencyHelper(service.NewConcurrencyService(cache), SSEPingFormatNone, time.Second), - } - ctx, cancel := context.WithCancel(context.Background()) - cancel() - recorder := httptest.NewRecorder() - c, _ := gin.CreateTestContext(recorder) - c.Request = httptest.NewRequest(http.MethodPost, "/v1/count_tokens", nil).WithContext(ctx) - groupID := int64(41) - selection := &service.AccountSelectionResult{ - Account: &service.Account{ID: 42, Platform: service.PlatformOpenAI}, - WaitPlan: &service.AccountWaitPlan{ - AccountID: 42, - MaxConcurrency: 1, - MaxWaiting: 1, - Timeout: time.Second, - }, - } - - release, acquired := h.acquireCountTokensAccountSlot(c, &groupID, "", selection, tt.anthropic, zap.NewNop()) - forwarded := false - if acquired { - forwarded = true - if release != nil { - release() - } - } - - require.False(t, acquired) - require.Nil(t, release) - require.False(t, forwarded, "a canceled WaitPlan must stop before count-token forwarding") - require.Zero(t, atomic.LoadInt32(&cache.releaseAccountCalled)) - }) - } -} - -func TestCountTokensAccountSlot_SelectionReleaseRunsExactlyOnce(t *testing.T) { - gin.SetMode(gin.TestMode) - - var released atomic.Int32 - ctx, cancel := context.WithCancel(context.Background()) - recorder := httptest.NewRecorder() - c, _ := gin.CreateTestContext(recorder) - c.Request = httptest.NewRequest(http.MethodPost, "/v1/responses/input_tokens", nil).WithContext(ctx) - h := &OpenAIGatewayHandler{gatewayService: &service.OpenAIGatewayService{}} - groupID := int64(51) - selection := &service.AccountSelectionResult{ - Account: &service.Account{ID: 52, Platform: service.PlatformOpenAI}, - Acquired: true, - ReleaseFunc: func() { released.Add(1) }, - } - - release, acquired := h.acquireCountTokensAccountSlot(c, &groupID, "", selection, false, zap.NewNop()) - require.True(t, acquired) - require.NotNil(t, release) - release() - cancel() - require.Eventually(t, func() bool { return released.Load() == 1 }, time.Second, 10*time.Millisecond) - require.Equal(t, int32(1), released.Load()) -} diff --git a/backend/internal/handler/ops_capture_writer_nil_test.go b/backend/internal/handler/ops_capture_writer_nil_test.go index 38d3f1433b..8b6cd6533f 100644 --- a/backend/internal/handler/ops_capture_writer_nil_test.go +++ b/backend/internal/handler/ops_capture_writer_nil_test.go @@ -176,17 +176,10 @@ func TestOpsCaptureWriter_ReleaseWaitsForDelegatedWriteWithoutHoldingStateMutex( }() <-inner.writeStarted - mutexAvailable := make(chan struct{}) - go func() { - w.state.mu.Lock() - w.state.mu.Unlock() - close(mutexAvailable) - }() - select { - case <-mutexAvailable: - case <-time.After(time.Second): + if !w.state.mu.TryLock() { t.Fatal("state mutex remained held across the delegated network write") } + w.state.mu.Unlock() releaseDone := make(chan struct{}) go func() { diff --git a/backend/internal/handler/ops_error_logger.go b/backend/internal/handler/ops_error_logger.go index 41cd2119b9..41a1ea0583 100644 --- a/backend/internal/handler/ops_error_logger.go +++ b/backend/internal/handler/ops_error_logger.go @@ -1280,6 +1280,18 @@ func logOpsRecoveredUpstream(c *gin.Context, ops *service.OpsService, finalStatu entry := &service.OpsInsertErrorLogInput{StatusCode: finalStatus} applyOpsUpstreamFieldsFromContext(c, entry) + if len(entry.UpstreamErrors) > 0 { + visibleEvents := make([]*service.OpsUpstreamErrorEvent, 0, len(entry.UpstreamErrors)) + for _, event := range entry.UpstreamErrors { + if event != nil && !event.SkipMonitoring { + visibleEvents = append(visibleEvents, event) + } + } + if len(visibleEvents) == 0 { + return + } + applyOpsUpstreamErrorEvents(entry, visibleEvents) + } if entry.UpstreamStatusCode == nil && entry.UpstreamErrorMessage == nil && entry.UpstreamErrorDetail == nil && len(entry.UpstreamErrors) == 0 { return @@ -1350,7 +1362,7 @@ func logOpsRecoveredUpstream(c *gin.Context, ops *service.OpsService, finalStatu apiKey := getOpsAPIKey(c) fallbackPlatform := guessPlatformFromPath(entry.RequestPath) - var requestContext context.Context = context.Background() + requestContext := context.Background() if c.Request != nil { requestContext = c.Request.Context() } @@ -1668,49 +1680,42 @@ func applyOpsUpstreamFieldsFromContext(c *gin.Context, entry *service.OpsInsertE } if v, ok := c.Get(service.OpsUpstreamErrorsKey); ok { if events, ok := v.([]*service.OpsUpstreamErrorEvent); ok && len(events) > 0 { - entry.UpstreamErrors = events - var last *service.OpsUpstreamErrorEvent - for i := len(events) - 1; i >= 0; i-- { - if events[i] != nil { - last = events[i] - break - } - } - if last == nil { - return - } - if last.Stage == string(service.GatewayFailureStageAccountAuth) { - code := 0 - entry.UpstreamStatusCode = &code - entry.UpstreamErrorMessage = nil - if message := strings.TrimSpace(last.Message); message != "" { - entry.UpstreamErrorMessage = &message - } - entry.UpstreamErrorDetail = nil - if detail := strings.TrimSpace(last.Detail); detail != "" { - entry.UpstreamErrorDetail = &detail - } - } else { - entry.UpstreamStatusCode = nil - if last.UpstreamStatusCode > 0 { - code := last.UpstreamStatusCode - entry.UpstreamStatusCode = &code - } - entry.UpstreamErrorMessage = nil - if strings.TrimSpace(last.Message) != "" { - message := strings.TrimSpace(last.Message) - entry.UpstreamErrorMessage = &message - } - entry.UpstreamErrorDetail = nil - if strings.TrimSpace(last.Detail) != "" { - detail := strings.TrimSpace(last.Detail) - entry.UpstreamErrorDetail = &detail - } - } + applyOpsUpstreamErrorEvents(entry, events) } } } +func applyOpsUpstreamErrorEvents(entry *service.OpsInsertErrorLogInput, events []*service.OpsUpstreamErrorEvent) { + entry.UpstreamErrors = events + var last *service.OpsUpstreamErrorEvent + for i := len(events) - 1; i >= 0; i-- { + if events[i] != nil { + last = events[i] + break + } + } + if last == nil { + return + } + + entry.UpstreamStatusCode = nil + entry.UpstreamErrorMessage = nil + entry.UpstreamErrorDetail = nil + if last.Stage == string(service.GatewayFailureStageAccountAuth) { + code := 0 + entry.UpstreamStatusCode = &code + } else if last.UpstreamStatusCode > 0 { + code := last.UpstreamStatusCode + entry.UpstreamStatusCode = &code + } + if message := strings.TrimSpace(last.Message); message != "" { + entry.UpstreamErrorMessage = &message + } + if detail := strings.TrimSpace(last.Detail); detail != "" { + entry.UpstreamErrorDetail = &detail + } +} + func suppressOpsUpstreamAttributionForLocalModelConfiguration(c *gin.Context, entry *service.OpsInsertErrorLogInput) { if entry == nil || !service.HasOpsClientBusinessLimited(c) || service.OpsClientBusinessLimitedReason(c) != service.OpsClientBusinessLimitedReasonLocalModelConfiguration { return diff --git a/backend/internal/handler/ops_error_logger_test.go b/backend/internal/handler/ops_error_logger_test.go index 38176cb1b0..640e8efa91 100644 --- a/backend/internal/handler/ops_error_logger_test.go +++ b/backend/internal/handler/ops_error_logger_test.go @@ -375,6 +375,56 @@ func TestOpsErrorLoggerMiddleware_RecordsRecoveredUpstreamTelemetryOutsideFailur require.Equal(t, http.StatusTooManyRequests, persistedEvents[0].UpstreamStatusCode) } +func TestOpsErrorLoggerMiddleware_RecoveredTelemetryFiltersSkipMonitoringAttempts(t *testing.T) { + setupOpsErrorLogTestQueue(t, 2) + gin.SetMode(gin.TestMode) + + ops := service.NewOpsService(nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil) + router := gin.New() + router.Use(OpsErrorLoggerMiddleware(ops)) + router.POST("/v1/responses", func(c *gin.Context) { + c.Set(service.OpsUpstreamErrorsKey, []*service.OpsUpstreamErrorEvent{ + {UpstreamStatusCode: http.StatusTooManyRequests, Message: "visible retry"}, + {UpstreamStatusCode: http.StatusBadGateway, Message: "hidden retry", SkipMonitoring: true}, + }) + c.JSON(http.StatusOK, gin.H{"status": "completed"}) + }) + + recorder := httptest.NewRecorder() + router.ServeHTTP(recorder, httptest.NewRequest(http.MethodPost, "/v1/responses", nil)) + + require.Equal(t, int64(1), OpsErrorLogQueueLength()) + job := <-opsErrorLogQueue + require.Equal(t, "Recovered upstream error 429: visible retry", job.entry.ErrorMessage) + require.NotNil(t, job.entry.UpstreamErrorsJSON) + events, err := service.ParseOpsUpstreamErrors(*job.entry.UpstreamErrorsJSON) + require.NoError(t, err) + require.Len(t, events, 1) + require.Equal(t, "visible retry", events[0].Message) +} + +func TestOpsErrorLoggerMiddleware_RecoveredTelemetrySkipsAllHiddenAttempts(t *testing.T) { + setupOpsErrorLogTestQueue(t, 2) + gin.SetMode(gin.TestMode) + + ops := service.NewOpsService(nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil) + router := gin.New() + router.Use(OpsErrorLoggerMiddleware(ops)) + router.POST("/v1/responses", func(c *gin.Context) { + c.Set(service.OpsUpstreamErrorsKey, []*service.OpsUpstreamErrorEvent{{ + UpstreamStatusCode: http.StatusTooManyRequests, + Message: "hidden retry", + SkipMonitoring: true, + }}) + c.JSON(http.StatusOK, gin.H{"status": "completed"}) + }) + + recorder := httptest.NewRecorder() + router.ServeHTTP(recorder, httptest.NewRequest(http.MethodPost, "/v1/responses", nil)) + + require.Equal(t, int64(0), OpsErrorLogQueueLength()) +} + func TestOpsErrorLoggerMiddleware_IntermediateSkipMonitoringDoesNotHideFinalVisibleFailure(t *testing.T) { setupOpsErrorLogTestQueue(t, 2) gin.SetMode(gin.TestMode) diff --git a/backend/internal/service/error_policy_test.go b/backend/internal/service/error_policy_test.go index de3d03300b..74cbacf9a2 100644 --- a/backend/internal/service/error_policy_test.go +++ b/backend/internal/service/error_policy_test.go @@ -67,7 +67,7 @@ func TestCheckErrorPolicy(t *testing.T) { expected: ErrorPolicySkipped, }, { - name: "global_529_bypasses_custom_error_code_filter", + name: "custom_error_codes_excluding_529_skip_global_cooldown", account: &Account{ ID: 33, Type: AccountTypeAPIKey, @@ -79,10 +79,10 @@ func TestCheckErrorPolicy(t *testing.T) { }, statusCode: 529, body: []byte(`{"error":{"message":"overloaded"}}`), - expected: ErrorPolicyMatched, + expected: ErrorPolicySkipped, }, { - name: "global_529_bypasses_pool_mode", + name: "pool_mode_skips_global_529_cooldown", account: &Account{ ID: 34, Type: AccountTypeAPIKey, @@ -93,6 +93,32 @@ func TestCheckErrorPolicy(t *testing.T) { }, statusCode: 529, body: []byte(`{"error":{"message":"overloaded"}}`), + expected: ErrorPolicySkipped, + }, + { + name: "ordinary_account_uses_global_529_cooldown", + account: &Account{ + ID: 35, + Type: AccountTypeAPIKey, + Platform: PlatformOpenAI, + }, + statusCode: 529, + body: []byte(`{"error":{"message":"overloaded"}}`), + expected: ErrorPolicyMatched, + }, + { + name: "custom_error_codes_including_529_take_precedence", + account: &Account{ + ID: 36, + Type: AccountTypeAPIKey, + Platform: PlatformOpenAI, + Credentials: map[string]any{ + "custom_error_codes_enabled": true, + "custom_error_codes": []any{float64(529)}, + }, + }, + statusCode: 529, + body: []byte(`{"error":{"message":"overloaded"}}`), expected: ErrorPolicyMatched, }, { diff --git a/backend/internal/service/openai_account_scheduler_test.go b/backend/internal/service/openai_account_scheduler_test.go index 62dde1ee8c..3e8c241b2a 100644 --- a/backend/internal/service/openai_account_scheduler_test.go +++ b/backend/internal/service/openai_account_scheduler_test.go @@ -620,6 +620,59 @@ func TestOpenAIGatewayService_SelectAccountWithScheduler_DefaultDisabled_Embeddi require.Equal(t, openAIAccountScheduleLayerLoadBalance, decision.Layer) } +func TestOpenAIGatewayService_SelectAccountForTokenCount_DoesNotAcquireGenerationSlot(t *testing.T) { + ctx := context.Background() + groupID := int64(10115) + acquiredIDs := make([]int64, 0) + accounts := []Account{ + { + ID: 36501, Platform: PlatformOpenAI, Type: AccountTypeAPIKey, + Status: StatusActive, Schedulable: true, Concurrency: 1, Priority: 0, + Credentials: map[string]any{"openai_capabilities": []any{"chat_completions"}}, + }, + { + ID: 36502, Platform: PlatformOpenAI, Type: AccountTypeAPIKey, + Status: StatusActive, Schedulable: true, Concurrency: 1, Priority: 5, + Credentials: map[string]any{"openai_capabilities": []any{"embeddings"}}, + }, + { + ID: 36503, Platform: PlatformGrok, Type: AccountTypeAPIKey, + Status: StatusActive, Schedulable: true, Concurrency: 1, Priority: 10, + Credentials: map[string]any{"openai_capabilities": []any{"chat_completions"}}, + }, + { + ID: 36504, Platform: PlatformOpenAI, Type: AccountTypeAPIKey, + Status: StatusActive, Schedulable: true, Concurrency: 1, Priority: 15, + Credentials: map[string]any{ + "openai_capabilities": []any{"chat_completions"}, + "model_mapping": map[string]any{"gpt-4o": "gpt-4o"}, + }, + }, + } + svc := &OpenAIGatewayService{ + accountRepo: schedulerTestOpenAIAccountRepo{accounts: accounts}, + cache: &schedulerTestGatewayCache{}, + cfg: &config.Config{}, + concurrencyService: NewConcurrencyService(schedulerTestConcurrencyCache{ + acquireResults: map[int64]bool{36501: false}, + acquiredIDs: &acquiredIDs, + }), + } + + account, err := svc.SelectAccountForTokenCount( + ctx, + &groupID, + "", + "gpt-5.1", + OpenAIEndpointCapabilityChatCompletions, + PlatformOpenAI, + ) + require.NoError(t, err) + require.NotNil(t, account) + require.Equal(t, int64(36501), account.ID) + require.Empty(t, acquiredIDs, "token counting must not acquire a generation slot") +} + // 生图意图的 /v1/responses 请求要求 OpenAIEndpointCapabilityResponses:探测确认 // 不支持 Responses API 的 APIKey 账号必须被排除,避免 forward 阶段降级为无法生图 // 的 Chat Completions 直转(#4417)。 diff --git a/backend/internal/service/openai_codex_transform_test.go b/backend/internal/service/openai_codex_transform_test.go index 7895b03cc3..96e7715d5d 100644 --- a/backend/internal/service/openai_codex_transform_test.go +++ b/backend/internal/service/openai_codex_transform_test.go @@ -142,9 +142,11 @@ func TestApplyCodexOAuthTransform_NormalizesIsolatedLegacyReferenceAcrossTurns(t input, ok := reqBody["input"].([]any) require.True(t, ok) require.Len(t, input, 3) - require.Equal(t, "fc_previous_turn", input[0].(map[string]any)["id"]) - require.Equal(t, "fc_remote_item", input[1].(map[string]any)["id"]) - require.Equal(t, "vendor_remote_item", input[2].(map[string]any)["id"]) + for i, expectedID := range []string{"fc_previous_turn", "fc_remote_item", "vendor_remote_item"} { + item, itemOK := input[i].(map[string]any) + require.True(t, itemOK) + require.Equal(t, expectedID, item["id"]) + } } func TestApplyCodexOAuthTransform_BoundsLongCallIDsAndPreservesPairing(t *testing.T) { diff --git a/backend/internal/service/openai_gateway_scheduling.go b/backend/internal/service/openai_gateway_scheduling.go index 8ecdd45eb4..435ec6545a 100644 --- a/backend/internal/service/openai_gateway_scheduling.go +++ b/backend/internal/service/openai_gateway_scheduling.go @@ -257,6 +257,33 @@ func (s *OpenAIGatewayService) SelectAccountForModelWithExclusions(ctx context.C return s.selectAccountForModelWithExclusions(s.withOpenAIQuotaAutoPauseContext(ctx), groupID, PlatformOpenAI, sessionHash, requestedModel, excludedIDs, false, 0, "", false) } +// SelectAccountForTokenCount selects an account for a non-billable token-count +// request. It applies the normal platform, model, capability, and runtime +// eligibility checks without acquiring or waiting for a generation slot. +func (s *OpenAIGatewayService) SelectAccountForTokenCount( + ctx context.Context, + groupID *int64, + sessionHash string, + requestedModel string, + requiredCapability OpenAIEndpointCapability, + platform string, +) (*Account, error) { + ctx = WithOpenAIProfitControlSuppressed(ctx) + ctx = s.withOpenAIQuotaAutoPauseContext(ctx) + return s.selectAccountForModelWithExclusions( + ctx, + groupID, + platform, + sessionHash, + requestedModel, + nil, + false, + 0, + requiredCapability, + false, + ) +} + // NormalizeOpenAICompatiblePlatform 保留 grok 与国产 OpenAI 兼容供应商(kimi/zhipu/ // deepseek)的原值,其他值一律归一为 openai。调度器据此对账号与请求做精确平台匹配: // kimi 分组请求只命中 kimi 账号,语义与 openai/grok 一致。 diff --git a/backend/internal/service/openai_ws_forwarder_ingress.go b/backend/internal/service/openai_ws_forwarder_ingress.go index 81e5847fa5..19de862623 100644 --- a/backend/internal/service/openai_ws_forwarder_ingress.go +++ b/backend/internal/service/openai_ws_forwarder_ingress.go @@ -99,22 +99,9 @@ func (s *OpenAIGatewayService) ProxyResponsesWebSocketFromClient( } } - // Only persistent inbound WebSocket sessions participate in preemption. - // HTTP ingress that opportunistically uses an upstream WS is handled by - // forwardOpenAIWSV2 and deliberately never reaches this registration. - preemptSessionHash := "" - preemptGroupID := getOpenAIGroupIDFromContext(c) - if account.Platform == PlatformOpenAI && account.Type == AccountTypeOAuth { - preemptSessionHash = s.GenerateSessionHash(c, firstClientMessage) - } - if preemptCtx, cleanupPreempt, armed, preemptedPrevious := s.beginOpenAIWSSessionPreemptContext( - ctx, - account, - preemptGroupID, - getAPIKeyIDFromContext(c), - preemptSessionHash, - false, - ); armed { + // The handler normally owns this registration across retry attempts. Direct + // callers still get the same session-scoped preemption behavior here. + if preemptCtx, cleanupPreempt, armed := s.BeginOpenAIWSIngressSessionPreemption(ctx, c, account, firstClientMessage); armed { ctx = preemptCtx defer cleanupPreempt() defer func() { @@ -122,12 +109,6 @@ func (s *OpenAIGatewayService) ProxyResponsesWebSocketFromClient( returnErr = errOpenAIWSSessionPreempted } }() - if preemptedPrevious { - if stateStore := s.getOpenAIWSStateStore(); stateStore != nil { - stateStore.DeleteSessionTurnState(preemptGroupID, preemptSessionHash) - stateStore.DeleteSessionConn(preemptGroupID, preemptSessionHash) - } - } } wsDecision := s.getOpenAIWSProtocolResolver().Resolve(account) diff --git a/backend/internal/service/openai_ws_session_preemption.go b/backend/internal/service/openai_ws_session_preemption.go index 1f69426da4..54da7f7a1d 100644 --- a/backend/internal/service/openai_ws_session_preemption.go +++ b/backend/internal/service/openai_ws_session_preemption.go @@ -8,6 +8,7 @@ import ( "sync" "time" + "github.com/gin-gonic/gin" "github.com/google/uuid" ) @@ -38,6 +39,49 @@ type openAIWSSessionPreemptKey struct { sessionHash string } +type openAIWSSessionPreemptContextKey struct{} + +// BeginOpenAIWSIngressSessionPreemption keeps a persistent inbound WS session +// registered across upstream retry attempts. Nested forwarding calls reuse the +// registration so returning from one attempt cannot create a preemption gap. +func (s *OpenAIGatewayService) BeginOpenAIWSIngressSessionPreemption( + ctx context.Context, + c *gin.Context, + account *Account, + firstClientMessage []byte, +) (context.Context, func(), bool) { + if ctx == nil { + ctx = context.Background() + } + if armed, _ := ctx.Value(openAIWSSessionPreemptContextKey{}).(bool); armed { + return ctx, func() {}, true + } + + preemptSessionHash := "" + preemptGroupID := getOpenAIGroupIDFromContext(c) + if account != nil && account.Platform == PlatformOpenAI && account.Type == AccountTypeOAuth { + preemptSessionHash = s.GenerateSessionHash(c, firstClientMessage) + } + preemptCtx, cleanup, armed, preemptedPrevious := s.beginOpenAIWSSessionPreemptContext( + ctx, + account, + preemptGroupID, + getAPIKeyIDFromContext(c), + preemptSessionHash, + false, + ) + if !armed { + return ctx, func() {}, false + } + if preemptedPrevious { + if stateStore := s.getOpenAIWSStateStore(); stateStore != nil { + stateStore.DeleteSessionTurnState(preemptGroupID, preemptSessionHash) + stateStore.DeleteSessionConn(preemptGroupID, preemptSessionHash) + } + } + return context.WithValue(preemptCtx, openAIWSSessionPreemptContextKey{}, true), cleanup, true +} + func newOpenAIWSSessionPreemptKey(groupID, apiKeyID int64, sessionHash string) (openAIWSSessionPreemptKey, bool) { sessionHash = strings.TrimSpace(sessionHash) if groupID <= 0 || apiKeyID <= 0 || sessionHash == "" { diff --git a/backend/internal/service/openai_ws_session_preemption_test.go b/backend/internal/service/openai_ws_session_preemption_test.go index 42b5b308bf..9df9465944 100644 --- a/backend/internal/service/openai_ws_session_preemption_test.go +++ b/backend/internal/service/openai_ws_session_preemption_test.go @@ -5,10 +5,13 @@ package service import ( "context" "fmt" + "net/http" + "net/http/httptest" "sync" "testing" "time" + "github.com/gin-gonic/gin" "github.com/stretchr/testify/require" ) @@ -110,6 +113,44 @@ func TestOpenAIWSSessionPreemptContextEligibilityAndLocalCancellation(t *testing secondCleanup() } +func TestOpenAIWSIngressSessionPreemptionSurvivesNestedForwardCleanup(t *testing.T) { + gin.SetMode(gin.TestMode) + groupID := int64(7) + newContext := func() *gin.Context { + c, _ := gin.CreateTestContext(httptest.NewRecorder()) + c.Request = httptest.NewRequest(http.MethodGet, "/v1/responses", nil) + c.Set("api_key", &APIKey{ID: 11, GroupID: &groupID}) + return c + } + + svc := &OpenAIGatewayService{} + account := &Account{ID: 1, Platform: PlatformOpenAI, Type: AccountTypeOAuth} + firstMessage := []byte(`{"type":"response.create","prompt_cache_key":"session-1","input":"hello"}`) + + firstCtx, firstCleanup, armed := svc.BeginOpenAIWSIngressSessionPreemption( + context.Background(), newContext(), account, firstMessage, + ) + require.True(t, armed) + defer firstCleanup() + + // ProxyResponsesWebSocketFromClient enters the same helper for each upstream + // attempt. Its cleanup must not release the handler-owned registration. + nestedCtx, nestedCleanup, armed := svc.BeginOpenAIWSIngressSessionPreemption( + firstCtx, newContext(), account, firstMessage, + ) + require.True(t, armed) + require.Equal(t, firstCtx, nestedCtx) + nestedCleanup() + require.NoError(t, firstCtx.Err()) + + _, secondCleanup, armed := svc.BeginOpenAIWSIngressSessionPreemption( + context.Background(), newContext(), account, firstMessage, + ) + require.True(t, armed) + defer secondCleanup() + require.True(t, IsOpenAIWSSessionPreemptedError(context.Cause(firstCtx))) +} + func TestOpenAIWSSessionPreemptRemoteClaimAndStaleReleaseAreAtomic(t *testing.T) { cache := &openAIWSSessionPreemptCacheStub{} svc := &OpenAIGatewayService{cache: cache} diff --git a/backend/internal/service/overload_cooldown_test.go b/backend/internal/service/overload_cooldown_test.go index 58dc13177c..92fc743d1e 100644 --- a/backend/internal/service/overload_cooldown_test.go +++ b/backend/internal/service/overload_cooldown_test.go @@ -36,10 +36,16 @@ func (r *errSettingRepo) Get(_ context.Context, _ string) (*Setting, error) { type overloadAccountRepoStub struct { mockAccountRepoForGemini overloadCalls int + errorCalls int lastOverloadID int64 lastOverloadEnd time.Time } +func (r *overloadAccountRepoStub) SetError(_ context.Context, _ int64, _ string) error { + r.errorCalls++ + return nil +} + func (r *overloadAccountRepoStub) SetOverloaded(_ context.Context, id int64, until time.Time) error { r.overloadCalls++ r.lastOverloadID = id @@ -269,7 +275,7 @@ func TestHandle529_DBReadError_FallsBackToConfig(t *testing.T) { require.WithinDuration(t, before.Add(7*time.Minute), accountRepo.lastOverloadEnd, 2*time.Second) } -func TestHandleUpstreamError_529BypassesPoolAndCustomCodeGates(t *testing.T) { +func TestHandleUpstreamError_529RespectsAccountPolicies(t *testing.T) { tests := []struct { name string credentials map[string]any @@ -301,12 +307,32 @@ func TestHandleUpstreamError_529BypassesPoolAndCustomCodeGates(t *testing.T) { shouldDisable := svc.HandleUpstreamError(context.Background(), account, 529, nil, []byte(`{"error":{"message":"overloaded"}}`)) require.False(t, shouldDisable) - require.Equal(t, 1, repo.overloadCalls) - require.Equal(t, account.ID, repo.lastOverloadID) + require.Zero(t, repo.overloadCalls) + require.Zero(t, repo.errorCalls) }) } } +func TestHandleUpstreamError_529CustomCodeDisablesInsteadOfOverloadCooldown(t *testing.T) { + repo := &overloadAccountRepoStub{} + svc := NewRateLimitService(repo, nil, &config.Config{}, nil, nil) + account := &Account{ + ID: 102, + Platform: PlatformOpenAI, + Type: AccountTypeAPIKey, + Credentials: map[string]any{ + "custom_error_codes_enabled": true, + "custom_error_codes": []any{float64(529)}, + }, + } + + shouldDisable := svc.HandleUpstreamError(context.Background(), account, 529, nil, []byte(`{"error":{"message":"overloaded"}}`)) + + require.True(t, shouldDisable) + require.Equal(t, 1, repo.errorCalls) + require.Zero(t, repo.overloadCalls) +} + // =========================================================================== // Model: defaults & JSON round-trip // =========================================================================== diff --git a/backend/internal/service/ratelimit_service.go b/backend/internal/service/ratelimit_service.go index 4e4068eb98..2c42b810b6 100644 --- a/backend/internal/service/ratelimit_service.go +++ b/backend/internal/service/ratelimit_service.go @@ -252,11 +252,6 @@ const ( // 自定义错误码开启时覆盖后续所有逻辑(包括临时不可调度)。 func (s *RateLimitService) CheckErrorPolicy(ctx context.Context, account *Account, statusCode int, responseBody []byte, requestedModel ...string) ErrorPolicyResult { ctx = withTempUnschedulableModel(ctx, requestedModel) - // 529 is governed by the global overload cooldown. Return Matched before - // local pool/custom-code filters so every caller reaches HandleUpstreamError. - if statusCode == 529 { - return ErrorPolicyMatched - } if account.IsCustomErrorCodesEnabled() { if account.ShouldHandleErrorCode(statusCode) { return ErrorPolicyMatched @@ -272,6 +267,11 @@ func (s *RateLimitService) CheckErrorPolicy(ctx context.Context, account *Accoun } return ErrorPolicySkipped } + // The global overload cooldown is the default for ordinary accounts. Explicit + // account policies above retain precedence over this fallback. + if statusCode == 529 { + return ErrorPolicyMatched + } if s.tryTempUnschedulable(ctx, account, statusCode, responseBody, firstRequestedModel(requestedModel)) { return ErrorPolicyTempUnscheduled } @@ -287,14 +287,6 @@ func (s *RateLimitService) HandleUpstreamError(ctx context.Context, account *Acc s.maybeHandleOpenAITeamLinkedError(ctx, account, statusCode, responseBody) customErrorCodesEnabled := account.IsCustomErrorCodesEnabled() - // The configured 529 cooldown is a global overload policy. Apply it before - // pool-mode and custom-code gates so those local retry policies cannot leave - // an overloaded account eligible for new requests. - if statusCode == 529 { - s.handle529(ctx, account) - return false - } - // 池模式默认不标记本地账号状态;但管理员显式配置的临时不可调度规则优先。 // 401 保留现有认证错误语义,不在这里改变池模式的认证处理。 if account.IsPoolMode() && !customErrorCodesEnabled { @@ -312,6 +304,15 @@ func (s *RateLimitService) HandleUpstreamError(ctx context.Context, account *Acc return false } + if statusCode == 529 { + if customErrorCodesEnabled { + s.handleCustomErrorCode(ctx, account, statusCode, extractUpstreamErrorMessage(responseBody)) + return true + } + s.handle529(ctx, account) + return false + } + if len(requestedModel) > 0 && s.HandleUpstreamModelNotFound(ctx, account, requestedModel[0], statusCode, responseBody) { return true } @@ -499,7 +500,7 @@ func (s *RateLimitService) HandleUpstreamError(ctx context.Context, account *Acc s.handle429(ctx, account, headers, responseBody) shouldDisable = false case 529: - // Handled before pool/custom-code policy gates above. + // Handled after pool/custom-code policy gates above. shouldDisable = false default: // 自定义错误码启用时:在列表中的错误码都应该停止调度 From d5824f6a5bfe19af7ffee945f9dfd862f729a455 Mon Sep 17 00:00:00 2001 From: haruka <1628615876@qq.com> Date: Fri, 21 Aug 2026 14:24:17 +0800 Subject: [PATCH 081/204] fix: preserve native max reasoning effort --- .../gateway_forward_as_chat_completions.go | 10 +++++--- ...ateway_forward_as_chat_completions_test.go | 18 ++++++++++++- .../service/gateway_forward_as_responses.go | 10 +++++--- .../gateway_forward_as_responses_test.go | 14 ++++++++++- .../gemini_chat_completions_compat_service.go | 2 +- ...teway_chat_completions_anthropic_native.go | 2 +- .../service/openai_gateway_request_body.go | 25 ++++++++++++++++++- ...enai_gateway_responses_anthropic_native.go | 2 +- .../openai_gateway_service_hotpath_test.go | 9 ++++++- .../internal/service/openai_gpt56_max_test.go | 3 ++- 10 files changed, 81 insertions(+), 14 deletions(-) diff --git a/backend/internal/service/gateway_forward_as_chat_completions.go b/backend/internal/service/gateway_forward_as_chat_completions.go index 93da85a7b2..d03cf53531 100644 --- a/backend/internal/service/gateway_forward_as_chat_completions.go +++ b/backend/internal/service/gateway_forward_as_chat_completions.go @@ -179,7 +179,7 @@ func (s *GatewayService) ForwardAsChatCompletions( } // 13. Extract reasoning effort from CC request body - reasoningEffort := extractCCReasoningEffortFromBody(body) + reasoningEffort := extractCCReasoningEffortFromBody(body, mappedModel, originalModel) // 国产模型默认 effort 补充:本路径是客户端 CC 请求 → Anthropic 上游, // 如果上游是 passback-required 国产模型 (Kimi-anthropic / GLM-anthropic / MiniMax) // 且客户端在 body 里传了 thinking.type=enabled,补中默认 effort。 @@ -201,7 +201,7 @@ func (s *GatewayService) ForwardAsChatCompletions( // extractCCReasoningEffortFromBody reads reasoning effort from a Chat Completions // request body. It checks both nested (reasoning.effort) and flat (reasoning_effort) // formats used by OpenAI-compatible clients. -func extractCCReasoningEffortFromBody(body []byte) *string { +func extractCCReasoningEffortFromBody(body []byte, modelCandidates ...string) *string { raw := strings.TrimSpace(gjson.GetBytes(body, "reasoning.effort").String()) if raw == "" { raw = strings.TrimSpace(gjson.GetBytes(body, "reasoning_effort").String()) @@ -209,7 +209,11 @@ func extractCCReasoningEffortFromBody(body []byte) *string { if raw == "" { return nil } - normalized := normalizeOpenAIReasoningEffort(raw) + model := firstNonEmpty(modelCandidates...) + if model == "" { + model = strings.TrimSpace(gjson.GetBytes(body, "model").String()) + } + normalized := normalizeOpenAIReasoningEffortForModel(raw, model) if normalized == "" { return nil } diff --git a/backend/internal/service/gateway_forward_as_chat_completions_test.go b/backend/internal/service/gateway_forward_as_chat_completions_test.go index d1047bdc9b..a5a5cbf913 100644 --- a/backend/internal/service/gateway_forward_as_chat_completions_test.go +++ b/backend/internal/service/gateway_forward_as_chat_completions_test.go @@ -30,7 +30,23 @@ func TestExtractCCReasoningEffortFromBody(t *testing.T) { }) t.Run("DeepSeek max", func(t *testing.T) { - got := extractCCReasoningEffortFromBody([]byte(`{"reasoning_effort":"Max"}`)) + got := extractCCReasoningEffortFromBody([]byte(`{"model":"deepseek-v4-flash","reasoning_effort":"Max"}`)) + require.NotNil(t, got) + require.Equal(t, "max", *got) + }) + + t.Run("mapped Kimi alias max", func(t *testing.T) { + got := extractCCReasoningEffortFromBody( + []byte(`{"model":"public-alias","reasoning_effort":"max"}`), + "kimi-k3", + "public-alias", + ) + require.NotNil(t, got) + require.Equal(t, "max", *got) + }) + + t.Run("legacy model max", func(t *testing.T) { + got := extractCCReasoningEffortFromBody([]byte(`{"model":"gpt-5.5","reasoning_effort":"max"}`)) require.NotNil(t, got) require.Equal(t, "xhigh", *got) }) diff --git a/backend/internal/service/gateway_forward_as_responses.go b/backend/internal/service/gateway_forward_as_responses.go index 2aa5255c29..b0ca29c1c2 100644 --- a/backend/internal/service/gateway_forward_as_responses.go +++ b/backend/internal/service/gateway_forward_as_responses.go @@ -63,7 +63,6 @@ func (s *GatewayService) ForwardAsResponses( // 4. Model mapping mappedModel := originalModel - reasoningEffort := ExtractResponsesReasoningEffortFromBody(body) if account.Type == AccountTypeAPIKey || account.Type == AccountTypeServiceAccount { mappedModel = account.GetMappedModel(originalModel) } @@ -78,6 +77,7 @@ func (s *GatewayService) ForwardAsResponses( mappedModel = normalized } } + reasoningEffort := ExtractResponsesReasoningEffortFromBody(body, mappedModel, originalModel) // 国产模型默认 effort 补充:需要 mappedModel 判定,推迟到 mapping 完成之后。 reasoningEffort = ApplyThinkingEnabledFallback(reasoningEffort, body, mappedModel) anthropicReq.Model = mappedModel @@ -255,12 +255,16 @@ func liftResponsesAdditionalTools(requestBody map[string]any) (bool, error) { // ExtractResponsesReasoningEffortFromBody reads Responses API reasoning.effort // and normalizes it for usage logging. -func ExtractResponsesReasoningEffortFromBody(body []byte) *string { +func ExtractResponsesReasoningEffortFromBody(body []byte, modelCandidates ...string) *string { raw := strings.TrimSpace(gjson.GetBytes(body, "reasoning.effort").String()) if raw == "" { return nil } - normalized := normalizeOpenAIReasoningEffort(raw) + model := firstNonEmpty(modelCandidates...) + if model == "" { + model = strings.TrimSpace(gjson.GetBytes(body, "model").String()) + } + normalized := normalizeOpenAIReasoningEffortForModel(raw, model) if normalized == "" { return nil } diff --git a/backend/internal/service/gateway_forward_as_responses_test.go b/backend/internal/service/gateway_forward_as_responses_test.go index 6784e7c7a5..262d588629 100644 --- a/backend/internal/service/gateway_forward_as_responses_test.go +++ b/backend/internal/service/gateway_forward_as_responses_test.go @@ -143,7 +143,19 @@ func TestExtractResponsesReasoningEffortFromBody(t *testing.T) { maxGot := ExtractResponsesReasoningEffortFromBody([]byte(`{"model":"deepseek-v4-pro","reasoning":{"effort":"max"}}`)) require.NotNil(t, maxGot) - require.Equal(t, "xhigh", *maxGot) + require.Equal(t, "max", *maxGot) + + mappedMax := ExtractResponsesReasoningEffortFromBody( + []byte(`{"model":"public-alias","reasoning":{"effort":"max"}}`), + "provider/glm-5.2", + "public-alias", + ) + require.NotNil(t, mappedMax) + require.Equal(t, "max", *mappedMax) + + legacyMax := ExtractResponsesReasoningEffortFromBody([]byte(`{"model":"gpt-5.5","reasoning":{"effort":"max"}}`)) + require.NotNil(t, legacyMax) + require.Equal(t, "xhigh", *legacyMax) require.Nil(t, ExtractResponsesReasoningEffortFromBody([]byte(`{"model":"claude-sonnet-4.5"}`))) } diff --git a/backend/internal/service/gemini_chat_completions_compat_service.go b/backend/internal/service/gemini_chat_completions_compat_service.go index 3ee7a4af9e..a56a1b3ebc 100644 --- a/backend/internal/service/gemini_chat_completions_compat_service.go +++ b/backend/internal/service/gemini_chat_completions_compat_service.go @@ -204,7 +204,7 @@ func (s *GeminiMessagesCompatService) forwardClaudeBodyAsChatCompletions( c.Header("x-request-id", requestID) } - reasoningEffort := extractCCReasoningEffortFromBody(originalChatBody) + reasoningEffort := extractCCReasoningEffortFromBody(originalChatBody, mappedModel) // 国产模型默认 effort 补充(本路径上游是 Gemini,不会命中 passback-required)。 // 保持与 OpenAI 网关路径调用模式一致,便于未来上游变异时语义一致。 reasoningEffort = ApplyThinkingEnabledFallback(reasoningEffort, originalChatBody, mappedModel) diff --git a/backend/internal/service/openai_gateway_chat_completions_anthropic_native.go b/backend/internal/service/openai_gateway_chat_completions_anthropic_native.go index b41bc644c6..d4000f9289 100644 --- a/backend/internal/service/openai_gateway_chat_completions_anthropic_native.go +++ b/backend/internal/service/openai_gateway_chat_completions_anthropic_native.go @@ -132,7 +132,7 @@ func (s *OpenAIGatewayService) forwardChatCompletionsViaNativeAnthropic( return nil, fmt.Errorf("upstream error: %d %s", resp.StatusCode, upstreamMsg) } - reasoningEffort := extractCCReasoningEffortFromBody(body) + reasoningEffort := extractCCReasoningEffortFromBody(body, upstreamModel, billingModel, originalModel) reasoningEffort = ApplyThinkingEnabledFallback(reasoningEffort, body, billingModel) if clientStream { diff --git a/backend/internal/service/openai_gateway_request_body.go b/backend/internal/service/openai_gateway_request_body.go index 59199cea05..ad9b6abaea 100644 --- a/backend/internal/service/openai_gateway_request_body.go +++ b/backend/internal/service/openai_gateway_request_body.go @@ -1507,8 +1507,31 @@ func normalizeOpenAIReasoningEffort(raw string) string { } func normalizeOpenAIReasoningEffortForModel(raw, model string) string { - if strings.EqualFold(strings.TrimSpace(raw), "max") && isOpenAIGPT56Model(model) { + if strings.EqualFold(strings.TrimSpace(raw), "max") && supportsOpenAIReasoningEffortMax(model) { return "max" } return normalizeOpenAIReasoningEffort(raw) } + +// supportsOpenAIReasoningEffortMax reports model families whose upstream scale +// has a distinct max level. Other models keep the legacy max -> xhigh behavior. +func supportsOpenAIReasoningEffortMax(model string) bool { + if isOpenAIGPT56Model(model) { + return true + } + + normalized := strings.ToLower(lastOpenAIModelSegment(model)) + normalized = strings.ReplaceAll(normalized, "_", "-") + switch { + case strings.HasPrefix(normalized, "deepseek-v4"): + return true + case strings.HasPrefix(normalized, "glm-"): + return true + case strings.HasPrefix(normalized, "kimi-"), strings.HasPrefix(normalized, "moonshot-"): + return true + case normalized == "k3" || strings.HasPrefix(normalized, "k3-"): + return true + default: + return false + } +} diff --git a/backend/internal/service/openai_gateway_responses_anthropic_native.go b/backend/internal/service/openai_gateway_responses_anthropic_native.go index 04cd7fc274..88cf83310a 100644 --- a/backend/internal/service/openai_gateway_responses_anthropic_native.go +++ b/backend/internal/service/openai_gateway_responses_anthropic_native.go @@ -75,7 +75,7 @@ func (s *OpenAIGatewayService) forwardResponsesViaNativeAnthropic( upstreamModel := normalizeOpenAIModelForUpstream(account, billingModel) anthropicReq.Model = upstreamModel - reasoningEffort := ExtractResponsesReasoningEffortFromBody(body) + reasoningEffort := ExtractResponsesReasoningEffortFromBody(body, upstreamModel, billingModel, originalModel) reasoningEffort = ApplyThinkingEnabledFallback(reasoningEffort, body, billingModel) // 5. Force upstream streaming(客户端原始终决定响应格式; diff --git a/backend/internal/service/openai_gateway_service_hotpath_test.go b/backend/internal/service/openai_gateway_service_hotpath_test.go index a51f58bf56..b6c3abca35 100644 --- a/backend/internal/service/openai_gateway_service_hotpath_test.go +++ b/backend/internal/service/openai_gateway_service_hotpath_test.go @@ -920,10 +920,17 @@ func TestExtractOpenAIReasoningEffortFromBody(t *testing.T) { wantValue: "xhigh", }, { - name: "DeepSeek max 归一化为 xhigh", + name: "DeepSeek V4 保留 max", body: []byte(`{"reasoning_effort":"max"}`), model: "deepseek-v4-pro", wantNil: false, + wantValue: "max", + }, + { + name: "旧模型仍将 max 归一化为 xhigh", + body: []byte(`{"reasoning_effort":"max"}`), + model: "gpt-5.5", + wantNil: false, wantValue: "xhigh", }, { diff --git a/backend/internal/service/openai_gpt56_max_test.go b/backend/internal/service/openai_gpt56_max_test.go index cbca2ff3ee..9dc865295c 100644 --- a/backend/internal/service/openai_gpt56_max_test.go +++ b/backend/internal/service/openai_gpt56_max_test.go @@ -24,7 +24,8 @@ func TestNormalizeOpenAIReasoningEffortForGPT56(t *testing.T) { {name: "Sol 保留 max", raw: "max", model: "gpt-5.6-sol", want: "max"}, {name: "Terra 保留 max", raw: "max", model: "openai/gpt-5.6-terra", want: "max"}, {name: "Luna 后缀保留 max", raw: "max", model: "gpt-5.6-luna-2026-07-09", want: "max"}, - {name: "其他模型沿用 xhigh", raw: "max", model: "deepseek-v4-pro", want: "xhigh"}, + {name: "DeepSeek V4 保留 max", raw: "max", model: "deepseek-v4-pro", want: "max"}, + {name: "旧 GPT 模型沿用 xhigh", raw: "max", model: "gpt-5.5", want: "xhigh"}, } for _, tt := range tests { From 2e279c81d2b58c912719013b3dff0ad2d4e6e2c3 Mon Sep 17 00:00:00 2001 From: heyx Date: Fri, 21 Aug 2026 16:23:11 +0800 Subject: [PATCH 082/204] fix(frontend): make CN provider quota/balance refresh affordance explicit MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The quota cell used the noun label "5-hour window/weekly window" and the balance cell the balance value itself as the click target for a manual refresh. Both read as passive captions, so users could not discover the manual probe and reported the feature as missing ("only OpenAI has a refresh button"). - Split data display from the refresh action: bars/balance render as static rows (snapshot already paints on mount), with a dedicated action button below, aligned with the OpenAI "Query" and Grok "Probe" buttons (same icon, blue action styling). - Label the control with a verb (cnProviders.probe: 查询 / Query) and give the balance cell a tooltip (it previously had none). - Keep the tier/label layout classes and data-test hooks intact. - Extend the quota cell spec and add a balance cell spec covering snapshot rendering, explicit action labeling and failure passthrough. --- .../account/CNProviderBalanceCell.vue | 40 ++++++---- .../account/CNProviderQuotaCell.vue | 63 +++++++-------- .../__tests__/CNProviderBalanceCell.spec.ts | 76 +++++++++++++++++++ .../__tests__/CNProviderQuotaCell.spec.ts | 19 +++++ .../src/i18n/locales/en/admin/accounts.ts | 2 + .../src/i18n/locales/zh/admin/accounts.ts | 2 + 6 files changed, 158 insertions(+), 44 deletions(-) create mode 100644 frontend/src/components/account/__tests__/CNProviderBalanceCell.spec.ts diff --git a/frontend/src/components/account/CNProviderBalanceCell.vue b/frontend/src/components/account/CNProviderBalanceCell.vue index 2ad2cbf3ab..52b5fb15e2 100644 --- a/frontend/src/components/account/CNProviderBalanceCell.vue +++ b/frontend/src/components/account/CNProviderBalanceCell.vue @@ -1,13 +1,35 @@ - + - + @@ -377,6 +379,13 @@ const requestDetailsPreset = ref({ sort: 'created_at_desc' }) +// 记录单条错误详情来自哪个列表,便于"返回列表"时重新打开对应弹窗并保留状态。 +type DetailReturnTarget = 'errorList' | 'requestList' | null +const detailReturnTarget = ref(null) + +// 从详情返回时,列表弹窗应保留上一次的筛选/分页状态而非重置。 +const resumeListState = ref(false) + const showSettingsDialog = ref(false) const showAlertRulesCard = ref(false) @@ -508,12 +517,34 @@ function onQueryModeChange(v: string | number | boolean | null) { function openError(id: number) { selectedErrorId.value = id + // 记录来源列表,便于详情页"返回列表"。 + detailReturnTarget.value = showRequestDetails.value ? 'requestList' : showErrorDetails.value ? 'errorList' : null // Ensure only one modal visible at a time. showErrorDetails.value = false showRequestDetails.value = false showErrorModal.value = true } +// 从单条错误详情返回其来源列表,重新打开关联弹窗(保留筛选/分页状态)。 +function handleBackToList() { + const target = detailReturnTarget.value + resumeListState.value = true + if (target === 'requestList') { + showErrorModal.value = false + showErrorDetails.value = false + showRequestDetails.value = true + } else if (target === 'errorList') { + showErrorModal.value = false + showRequestDetails.value = false + showErrorDetails.value = true + } + detailReturnTarget.value = null + // 子组件 watch 在本次 show 变化中消费 resumeState 后复位,保证下次手动打开仍会重置筛选。 + window.setTimeout(() => { + resumeListState.value = false + }, 0) +} + function buildApiParams() { const params: any = { platform: platform.value || undefined, diff --git a/frontend/src/views/admin/ops/components/OpsErrorDetailModal.vue b/frontend/src/views/admin/ops/components/OpsErrorDetailModal.vue index 407c671ca9..8b0dc388f8 100644 --- a/frontend/src/views/admin/ops/components/OpsErrorDetailModal.vue +++ b/frontend/src/views/admin/ops/components/OpsErrorDetailModal.vue @@ -211,6 +211,16 @@
+ @@ -228,10 +238,12 @@ interface Props { show: boolean errorId: number | null errorType?: 'request' | 'upstream' + backToList?: boolean } interface Emits { (e: 'update:show', value: boolean): void + (e: 'back'): void } const props = defineProps() @@ -363,6 +375,11 @@ function close() { emit('update:show', false) } +function goBack() { + emit('update:show', false) + emit('back') +} + function prettyJSON(raw?: string): string { if (!raw) return 'N/A' try { diff --git a/frontend/src/views/admin/ops/components/OpsErrorDetailsModal.vue b/frontend/src/views/admin/ops/components/OpsErrorDetailsModal.vue index 0c513a5f1d..e97e919f6a 100644 --- a/frontend/src/views/admin/ops/components/OpsErrorDetailsModal.vue +++ b/frontend/src/views/admin/ops/components/OpsErrorDetailsModal.vue @@ -15,6 +15,7 @@ interface Props { platform?: string groupId?: number | null errorType: 'request' | 'upstream' + resumeState?: boolean } const props = defineProps() @@ -167,6 +168,7 @@ watch( () => props.show, (open) => { if (!open) return + if (props.resumeState) return page.value = 1 pageSize.value = 10 resetFilters() diff --git a/frontend/src/views/admin/ops/components/OpsRequestDetailsModal.vue b/frontend/src/views/admin/ops/components/OpsRequestDetailsModal.vue index 33ce058149..2d8e885a0c 100644 --- a/frontend/src/views/admin/ops/components/OpsRequestDetailsModal.vue +++ b/frontend/src/views/admin/ops/components/OpsRequestDetailsModal.vue @@ -23,6 +23,7 @@ interface Props { preset: OpsRequestDetailsPreset platform?: string groupId?: number | null + resumeState?: boolean } const props = defineProps() @@ -98,6 +99,7 @@ watch( () => props.modelValue, (open) => { if (open) { + if (props.resumeState) return page.value = 1 pageSize.value = 10 fetchData() @@ -142,7 +144,6 @@ async function handleCopyRequestId(requestId: string) { function openErrorDetail(errorId: number | null | undefined) { if (!errorId) return - close() emit('openErrorDetail', errorId) } From f06bf181d205682ad341ca42b1046193068c997a Mon Sep 17 00:00:00 2001 From: alfadb Date: Mon, 24 Aug 2026 10:08:28 +0800 Subject: [PATCH 139/204] feat(openai): support Fast mode service_tier across responses/chat/WS paths - Accept fast|priority (canonical priority), flex|auto|default|scale on /v1/responses and /v1/chat/completions; reject unknown/empty/non-string with HTTP 400; omitted and null stay compatible. - Propagate service_tier through JSON/SSE, Responses<->Chat conversions, fallback paths and HTTP->upstream WebSocket bridge. - Billing prefers the upstream terminal tier; the outbound (policy- transformed) tier is used only when upstream omits the field. Explicit upstream default bills Standard even when Fast was requested. - Pricing: Fast premium 2x Standard for gpt-5.6-sol/terra/luna and gpt-5.4; 2.5x for gpt-5.5; channel FastMultiplier stays authoritative. - Live verification (official Codex 0.149.0 + gateway, HTTP & WS): upstream ChatGPT backend may return terminal default even when the account catalog advertises priority; billing follows the actual tier. --- .../handler/openai_chat_completions.go | 4 + .../handler/openai_gateway_handler.go | 4 + .../openai_service_tier_validation_test.go | 127 +++ .../chatcompletions_responses_bridge.go | 32 +- .../apicompat/responses_to_chatcompletions.go | 60 +- .../service_tier_passthrough_test.go | 175 ++++ backend/internal/pkg/apicompat/types.go | 13 +- backend/internal/service/billing_service.go | 39 +- .../service/openai_fast_service_tier_test.go | 834 ++++++++++++++++++ .../service/openai_gateway_cc_pipeline.go | 9 + .../openai_gateway_chat_completions.go | 14 +- .../openai_gateway_chat_completions_raw.go | 10 +- .../service/openai_gateway_forward.go | 2 +- .../service/openai_gateway_messages.go | 8 +- .../openai_gateway_messages_chat_fallback.go | 8 +- .../service/openai_gateway_passthrough.go | 2 +- .../service/openai_gateway_request_body.go | 51 ++ .../openai_gateway_responses_chat_fallback.go | 18 +- .../service/openai_gateway_service.go | 6 +- .../service/openai_ws_forwarder_v2.go | 2 +- .../service/openai_ws_forwarder_v2_test.go | 96 ++ .../internal/service/openai_ws_http_bridge.go | 2 +- .../service/openai_ws_http_bridge_test.go | 39 + .../service/upstream_response_model.go | 33 +- .../model_prices_and_context_window.json | 12 +- 25 files changed, 1518 insertions(+), 82 deletions(-) create mode 100644 backend/internal/handler/openai_service_tier_validation_test.go create mode 100644 backend/internal/pkg/apicompat/service_tier_passthrough_test.go create mode 100644 backend/internal/service/openai_fast_service_tier_test.go create mode 100644 backend/internal/service/openai_ws_forwarder_v2_test.go diff --git a/backend/internal/handler/openai_chat_completions.go b/backend/internal/handler/openai_chat_completions.go index 7f83f9ba90..aa2b610d70 100644 --- a/backend/internal/handler/openai_chat_completions.go +++ b/backend/internal/handler/openai_chat_completions.go @@ -89,6 +89,10 @@ func (h *OpenAIGatewayHandler) ChatCompletions(c *gin.Context) { h.errorResponse(c, http.StatusBadRequest, "invalid_request_error", invalidStreamFieldTypeMessage) return } + if _, err := service.ValidateOpenAIServiceTierField(body); err != nil { + h.errorResponse(c, http.StatusBadRequest, "invalid_request_error", err.Error()) + return + } if service.IsGPTImageGenerationModel(reqModel) { h.errorResponse(c, http.StatusBadRequest, "invalid_request_error", "This model is not supported on the Chat Completions endpoint") return diff --git a/backend/internal/handler/openai_gateway_handler.go b/backend/internal/handler/openai_gateway_handler.go index d9da0bef71..32cea2f073 100644 --- a/backend/internal/handler/openai_gateway_handler.go +++ b/backend/internal/handler/openai_gateway_handler.go @@ -392,6 +392,10 @@ func (h *OpenAIGatewayHandler) Responses(c *gin.Context) { h.errorResponse(c, http.StatusBadRequest, "invalid_request_error", invalidStreamFieldTypeMessage) return } + if _, err := service.ValidateOpenAIServiceTierField(body); err != nil { + h.errorResponse(c, http.StatusBadRequest, "invalid_request_error", err.Error()) + return + } reqLog = reqLog.With(zap.String("model", reqModel), zap.Bool("stream", reqStream)) previousResponseID := strings.TrimSpace(gjson.GetBytes(body, "previous_response_id").String()) if previousResponseID != "" { diff --git a/backend/internal/handler/openai_service_tier_validation_test.go b/backend/internal/handler/openai_service_tier_validation_test.go new file mode 100644 index 0000000000..b912f812f8 --- /dev/null +++ b/backend/internal/handler/openai_service_tier_validation_test.go @@ -0,0 +1,127 @@ +package handler + +import ( + "net/http" + "net/http/httptest" + "strings" + "testing" + + "github.com/Wei-Shaw/sub2api/internal/config" + middleware2 "github.com/Wei-Shaw/sub2api/internal/server/middleware" + "github.com/Wei-Shaw/sub2api/internal/service" + "github.com/gin-gonic/gin" + "github.com/stretchr/testify/require" +) + +// 非法 service_tier 必须在两个 OpenAI 端点(/v1/responses、/v1/chat/completions) +// 上以 OpenAI 兼容错误结构返回 HTTP 400;合法值(fast/priority)不被拒绝。 + +func newServiceTierHandlerTest(t *testing.T) *OpenAIGatewayHandler { + t.Helper() + return &OpenAIGatewayHandler{ + gatewayService: &service.OpenAIGatewayService{}, + billingCacheService: service.NewBillingCacheService(nil, nil, nil, nil, nil, nil, &config.Config{RunMode: config.RunModeSimple}, nil), + apiKeyService: &service.APIKeyService{}, + concurrencyHelper: &ConcurrencyHelper{concurrencyService: service.NewConcurrencyService( + &helperConcurrencyCacheStub{userSeq: []bool{true}}, + )}, + cfg: &config.Config{}, + imageLimiter: &imageConcurrencyLimiter{}, + } +} + +func runOpenAIHandlerServiceTierTest(t *testing.T, path, body string, handler func(h *OpenAIGatewayHandler, c *gin.Context)) *httptest.ResponseRecorder { + t.Helper() + gin.SetMode(gin.TestMode) + rec := httptest.NewRecorder() + c, _ := gin.CreateTestContext(rec) + c.Request = httptest.NewRequest(http.MethodPost, path, strings.NewReader(body)) + c.Request.Header.Set("Content-Type", "application/json") + + groupID := int64(6401) + userID := int64(6402) + c.Set(string(middleware2.ContextKeyAPIKey), &service.APIKey{ + ID: 6403, + GroupID: &groupID, + Group: &service.Group{ + ID: groupID, + Platform: service.PlatformOpenAI, + }, + User: &service.User{ID: userID, Status: service.StatusActive}, + }) + c.Set(string(middleware2.ContextKeyUser), middleware2.AuthSubject{UserID: userID, Concurrency: 1}) + + handler(newServiceTierHandlerTest(t), c) + return rec +} + +func TestOpenAIGatewayHandlerResponses_InvalidServiceTierRejected400(t *testing.T) { + for _, body := range []string{ + `{"model":"gpt-5.5","input":"hi","service_tier":"turbo"}`, + `{"model":"gpt-5.5","input":"hi","service_tier":"SPEED"}`, + `{"model":"gpt-5.5","input":"hi","service_tier":""}`, + `{"model":"gpt-5.5","input":"hi","service_tier":123}`, + `{"model":"gpt-5.5","input":"hi","service_tier":{}}`, + } { + rec := runOpenAIHandlerServiceTierTest(t, "/v1/responses", body, func(h *OpenAIGatewayHandler, c *gin.Context) { + h.Responses(c) + }) + require.Equal(t, http.StatusBadRequest, rec.Code, "body=%s", body) + require.Contains(t, rec.Body.String(), "invalid_request_error", "body=%s", body) + require.Contains(t, rec.Body.String(), "invalid service_tier", "body=%s", body) + } +} + +func TestOpenAIGatewayHandlerResponses_ValidServiceTierNotRejected(t *testing.T) { + for _, tier := range []string{"fast", "priority", "flex"} { + body := `{"model":"gpt-5.5","input":"hi","service_tier":"` + tier + `"}` + rec := runOpenAIHandlerServiceTierTest(t, "/v1/responses", body, func(h *OpenAIGatewayHandler, c *gin.Context) { + h.Responses(c) + }) + require.NotEqual(t, http.StatusBadRequest, rec.Code, "tier=%s must not be rejected as invalid", tier) + require.NotContains(t, rec.Body.String(), "invalid service_tier", "tier=%s", tier) + } +} + +func TestOpenAIGatewayHandlerResponses_ServiceTierOmittedKeepsCurrentBehavior(t *testing.T) { + body := `{"model":"gpt-5.5","input":"hi"}` + rec := runOpenAIHandlerServiceTierTest(t, "/v1/responses", body, func(h *OpenAIGatewayHandler, c *gin.Context) { + h.Responses(c) + }) + require.NotContains(t, rec.Body.String(), "invalid service_tier") +} + +func TestOpenAIGatewayHandlerChatCompletions_InvalidServiceTierRejected400(t *testing.T) { + for _, body := range []string{ + `{"model":"gpt-5.5","messages":[{"role":"user","content":"hi"}],"service_tier":"turbo"}`, + `{"model":"gpt-5.5","messages":[{"role":"user","content":"hi"}],"service_tier":"ultra"}`, + `{"model":"gpt-5.5","messages":[{"role":"user","content":"hi"}],"service_tier":""}`, + `{"model":"gpt-5.5","messages":[{"role":"user","content":"hi"}],"service_tier":["priority"]}`, + } { + rec := runOpenAIHandlerServiceTierTest(t, "/v1/chat/completions", body, func(h *OpenAIGatewayHandler, c *gin.Context) { + h.ChatCompletions(c) + }) + require.Equal(t, http.StatusBadRequest, rec.Code, "body=%s", body) + require.Contains(t, rec.Body.String(), "invalid_request_error", "body=%s", body) + require.Contains(t, rec.Body.String(), "invalid service_tier", "body=%s", body) + } +} + +func TestOpenAIGatewayHandlerChatCompletions_ValidServiceTierNotRejected(t *testing.T) { + for _, tier := range []string{"fast", "priority", "auto", "default", "scale", "flex"} { + body := `{"model":"gpt-5.5","messages":[{"role":"user","content":"hi"}],"service_tier":"` + tier + `"}` + rec := runOpenAIHandlerServiceTierTest(t, "/v1/chat/completions", body, func(h *OpenAIGatewayHandler, c *gin.Context) { + h.ChatCompletions(c) + }) + require.NotEqual(t, http.StatusBadRequest, rec.Code, "tier=%q must not be rejected as invalid", tier) + require.NotContains(t, rec.Body.String(), "invalid service_tier", "tier=%q", tier) + } +} + +func TestOpenAIGatewayHandlerChatCompletions_ServiceTierOmittedKeepsCurrentBehavior(t *testing.T) { + body := `{"model":"gpt-5.5","messages":[{"role":"user","content":"hi"}]}` + rec := runOpenAIHandlerServiceTierTest(t, "/v1/chat/completions", body, func(h *OpenAIGatewayHandler, c *gin.Context) { + h.ChatCompletions(c) + }) + require.NotContains(t, rec.Body.String(), "invalid service_tier") +} diff --git a/backend/internal/pkg/apicompat/chatcompletions_responses_bridge.go b/backend/internal/pkg/apicompat/chatcompletions_responses_bridge.go index de2b803012..fd84af7824 100644 --- a/backend/internal/pkg/apicompat/chatcompletions_responses_bridge.go +++ b/backend/internal/pkg/apicompat/chatcompletions_responses_bridge.go @@ -1212,10 +1212,11 @@ func ChatCompletionsResponseToResponses(resp *ChatCompletionsResponse, model str } out := &ResponsesResponse{ - ID: id, - Object: "response", - Model: model, - Status: "completed", + ID: id, + Object: "response", + Model: model, + Status: "completed", + ServiceTier: chatServiceTier(resp), } if resp == nil { out.Output = []ResponsesOutput{emptyResponsesMessageOutput()} @@ -1242,6 +1243,13 @@ func ChatCompletionsResponseToResponses(resp *ChatCompletionsResponse, model str return out } +func chatServiceTier(resp *ChatCompletionsResponse) string { + if resp == nil { + return "" + } + return resp.ServiceTier +} + func chatMessageToResponsesOutput(message ChatMessage, customTools, functionTools map[string]bool, toolSearch bool, namespaceTools map[string]NamespacedToolName) []ResponsesOutput { var outputs []ResponsesOutput reasoning := message.reasoningText() @@ -1414,6 +1422,7 @@ type ChatCompletionsToResponsesStreamState struct { ResponseID string Model string Created int64 + ServiceTier string // upstream Chat chunk service_tier, echoed on response events SequenceNumber int CreatedSent bool CompletedSent bool @@ -1545,6 +1554,9 @@ func ChatCompletionsChunkToResponsesEvents( if state.Model == "" && chunk.Model != "" { state.Model = chunk.Model } + if chunk.ServiceTier != "" { + state.ServiceTier = chunk.ServiceTier + } if chunk.Usage != nil { state.Usage = ChatUsageToResponsesUsage(chunk.Usage) } @@ -1701,6 +1713,7 @@ func FinalizeChatCompletionsResponsesStream(state *ChatCompletionsToResponsesStr Object: "response", Model: state.Model, Status: status, + ServiceTier: state.ServiceTier, Output: state.chatOutput(), Usage: state.Usage, IncompleteDetails: incompleteDetails, @@ -1716,11 +1729,12 @@ func ensureChatToResponsesCreated(state *ChatCompletionsToResponsesStreamState) state.CreatedSent = true return []ResponsesStreamEvent{chatToResponsesEvent(state, "response.created", &ResponsesStreamEvent{ Response: &ResponsesResponse{ - ID: state.ResponseID, - Object: "response", - Model: state.Model, - Status: "in_progress", - Output: []ResponsesOutput{}, + ID: state.ResponseID, + Object: "response", + Model: state.Model, + Status: "in_progress", + ServiceTier: state.ServiceTier, + Output: []ResponsesOutput{}, }, })} } diff --git a/backend/internal/pkg/apicompat/responses_to_chatcompletions.go b/backend/internal/pkg/apicompat/responses_to_chatcompletions.go index a89a1b4203..d288b31bea 100644 --- a/backend/internal/pkg/apicompat/responses_to_chatcompletions.go +++ b/backend/internal/pkg/apicompat/responses_to_chatcompletions.go @@ -23,10 +23,11 @@ func ResponsesToChatCompletions(resp *ResponsesResponse, model string) *ChatComp } out := &ChatCompletionsResponse{ - ID: id, - Object: "chat.completion", - Created: time.Now().Unix(), - Model: model, + ID: id, + Object: "chat.completion", + Created: time.Now().Unix(), + Model: model, + ServiceTier: resp.ServiceTier, } var contentText string @@ -118,6 +119,7 @@ type ResponsesEventToChatState struct { ID string Model string Created int64 + ServiceTier string // upstream tier observed on response events; echoed on chunks SentRole bool SawToolCall bool SawText bool @@ -187,12 +189,13 @@ func FinalizeResponsesChatStream(state *ResponsesEventToChatState) []ChatComplet if state.IncludeUsage && state.Usage != nil { chunks = append(chunks, ChatCompletionsChunk{ - ID: state.ID, - Object: "chat.completion.chunk", - Created: state.Created, - Model: state.Model, - Choices: []ChatChunkChoice{}, - Usage: state.Usage, + ID: state.ID, + Object: "chat.completion.chunk", + Created: state.Created, + Model: state.Model, + ServiceTier: state.ServiceTier, + Choices: []ChatChunkChoice{}, + Usage: state.Usage, }) } @@ -218,6 +221,9 @@ func resToChatHandleCreated(evt *ResponsesStreamEvent, state *ResponsesEventToCh if state.Model == "" && evt.Response.Model != "" { state.Model = evt.Response.Model } + if evt.Response.ServiceTier != "" { + state.ServiceTier = evt.Response.ServiceTier + } } // Emit the role chunk. if state.SentRole { @@ -301,6 +307,9 @@ func resToChatHandleCompleted(evt *ResponsesStreamEvent, state *ResponsesEventTo if evt.Response.Usage != nil { state.Usage = chatUsageFromResponsesUsage(evt.Response.Usage) } + if evt.Response.ServiceTier != "" { + state.ServiceTier = evt.Response.ServiceTier + } switch evt.Response.Status { case "incomplete": @@ -326,12 +335,13 @@ func resToChatHandleCompleted(evt *ResponsesStreamEvent, state *ResponsesEventTo if state.IncludeUsage && state.Usage != nil { chunks = append(chunks, ChatCompletionsChunk{ - ID: state.ID, - Object: "chat.completion.chunk", - Created: state.Created, - Model: state.Model, - Choices: []ChatChunkChoice{}, - Usage: state.Usage, + ID: state.ID, + Object: "chat.completion.chunk", + Created: state.Created, + Model: state.Model, + ServiceTier: state.ServiceTier, + Choices: []ChatChunkChoice{}, + Usage: state.Usage, }) } @@ -401,10 +411,11 @@ func completionDetailsFromResponses(src *ResponsesOutputTokensDetails) *ChatToke func makeChatDeltaChunk(state *ResponsesEventToChatState, delta ChatDelta) ChatCompletionsChunk { return ChatCompletionsChunk{ - ID: state.ID, - Object: "chat.completion.chunk", - Created: state.Created, - Model: state.Model, + ID: state.ID, + Object: "chat.completion.chunk", + Created: state.Created, + Model: state.Model, + ServiceTier: state.ServiceTier, Choices: []ChatChunkChoice{{ Index: 0, Delta: delta, @@ -416,10 +427,11 @@ func makeChatDeltaChunk(state *ResponsesEventToChatState, delta ChatDelta) ChatC func makeChatFinishChunk(state *ResponsesEventToChatState, finishReason string) ChatCompletionsChunk { empty := "" return ChatCompletionsChunk{ - ID: state.ID, - Object: "chat.completion.chunk", - Created: state.Created, - Model: state.Model, + ID: state.ID, + Object: "chat.completion.chunk", + Created: state.Created, + Model: state.Model, + ServiceTier: state.ServiceTier, Choices: []ChatChunkChoice{{ Index: 0, Delta: ChatDelta{Content: &empty}, diff --git a/backend/internal/pkg/apicompat/service_tier_passthrough_test.go b/backend/internal/pkg/apicompat/service_tier_passthrough_test.go new file mode 100644 index 0000000000..58d3c83e07 --- /dev/null +++ b/backend/internal/pkg/apicompat/service_tier_passthrough_test.go @@ -0,0 +1,175 @@ +package apicompat + +import ( + "encoding/json" + "testing" + + "github.com/stretchr/testify/require" +) + +// 上游响应中的 service_tier 必须如实回传,不被重写/丢弃: +// 非流式(ResponsesResponse → ChatCompletionsResponse)与流式 chunk 均覆盖。 + +func TestResponsesToChatCompletions_PreservesUpstreamServiceTier(t *testing.T) { + resp := &ResponsesResponse{ + ID: "resp_1", + Object: "response", + Model: "gpt-5.5", + Status: "completed", + ServiceTier: "priority", + Output: []ResponsesOutput{{ + Type: "message", + Role: "assistant", + Content: []ResponsesContentPart{{ + Type: "output_text", + Text: "hi", + }}, + }}, + Usage: &ResponsesUsage{InputTokens: 1, OutputTokens: 1}, + } + + chat := ResponsesToChatCompletions(resp, "gpt-5.5") + require.Equal(t, "priority", chat.ServiceTier) + + // 序列化后字段仍在(omitempty 不丢非空值)。 + raw, err := json.Marshal(chat) + require.NoError(t, err) + require.Contains(t, string(raw), `"service_tier":"priority"`) +} + +func TestResponsesToChatCompletions_OmitsMissingServiceTier(t *testing.T) { + resp := &ResponsesResponse{ID: "resp_1", Model: "gpt-5.5", Status: "completed"} + chat := ResponsesToChatCompletions(resp, "gpt-5.5") + require.Empty(t, chat.ServiceTier) + raw, err := json.Marshal(chat) + require.NoError(t, err) + require.NotContains(t, string(raw), "service_tier") +} + +func TestResponsesEventToChatChunks_PreservesUpstreamServiceTier(t *testing.T) { + state := NewResponsesEventToChatState() + state.IncludeUsage = true + + created := &ResponsesStreamEvent{Type: "response.created"} + require.NoError(t, json.Unmarshal([]byte(`{"type":"response.created","response":{"id":"resp_s1","model":"gpt-5.5","service_tier":"priority","status":"in_progress"}}`), created)) + + chunks := ResponsesEventToChatChunks(created, state) + require.NotEmpty(t, chunks) + for _, chunk := range chunks { + require.Equal(t, "priority", chunk.ServiceTier) + } + + // 后续 delta chunk 继续携带(OpenAI 流式 chunk 的 service_tier 语义)。 + delta := &ResponsesStreamEvent{Type: "response.output_text.delta", Delta: "hi"} + chunks = ResponsesEventToChatChunks(delta, state) + require.NotEmpty(t, chunks) + require.Equal(t, "priority", chunks[0].ServiceTier) + + // 终止事件同样携带。 + completed := &ResponsesStreamEvent{Type: "response.completed", Response: &ResponsesResponse{ + ID: "resp", Model: "gpt-5.5", Status: "completed", + Usage: &ResponsesUsage{InputTokens: 1, OutputTokens: 1}, + }} + chunks = ResponsesEventToChatChunks(completed, state) + require.NotEmpty(t, chunks) + for _, chunk := range chunks { + require.Equal(t, "priority", chunk.ServiceTier) + } +} + +func TestResponsesEventToChatChunks_NoServiceTierStaysClean(t *testing.T) { + state := NewResponsesEventToChatState() + created := &ResponsesStreamEvent{Type: "response.created", Response: &ResponsesResponse{ID: "resp", Model: "gpt-5.5"}} + chunks := ResponsesEventToChatChunks(created, state) + require.NotEmpty(t, chunks) + require.Empty(t, chunks[0].ServiceTier) + raw, err := json.Marshal(chunks[0]) + require.NoError(t, err) + require.NotContains(t, string(raw), "service_tier") +} + +// 上游 JSON 反序列化时 service_tier 进入 ResponsesResponse(缓冲桥读取链路)。 +func TestResponsesResponse_UnmarshalPreservesServiceTier(t *testing.T) { + var resp ResponsesResponse + require.NoError(t, json.Unmarshal([]byte(`{"id":"resp_1","object":"response","model":"gpt-5.5","status":"completed","service_tier":"flex","output":[]}`), &resp)) + require.Equal(t, "flex", resp.ServiceTier) +} + +// --------------------------------------------------------------------------- +// 反向转换(Chat-only fallback):CC 响应/流 chunk 的 service_tier 保留到 +// Responses 形态,客户端与计费都能拿到上游回显。 +// --------------------------------------------------------------------------- + +func TestChatCompletionsResponseToResponses_PreservesServiceTier(t *testing.T) { + cc := &ChatCompletionsResponse{ + ID: "chatcmpl-1", + Model: "gpt-5.5", + ServiceTier: "default", + Choices: []ChatChoice{{ + Index: 0, + Message: ChatMessage{Role: "assistant", Content: json.RawMessage(`"hi"`)}, + FinishReason: "stop", + }}, + Usage: &ChatUsage{PromptTokens: 1, CompletionTokens: 1, TotalTokens: 2}, + } + resp := ChatCompletionsResponseToResponses(cc, "gpt-5.5", nil, false, nil) + require.Equal(t, "default", resp.ServiceTier) + + raw, err := json.Marshal(resp) + require.NoError(t, err) + require.Contains(t, string(raw), `"service_tier":"default"`) +} + +func TestChatCompletionsResponseToResponses_NilRespOmitsServiceTier(t *testing.T) { + resp := ChatCompletionsResponseToResponses(nil, "gpt-5.5", nil, false, nil) + require.Empty(t, resp.ServiceTier) +} + +func TestChatCompletionsChunkToResponsesEvents_PreservesServiceTier(t *testing.T) { + state := NewChatCompletionsToResponsesStreamState("gpt-5.5") + chunk := &ChatCompletionsChunk{ + ID: "chatcmpl-2", + Model: "gpt-5.5", + ServiceTier: "flex", + Choices: []ChatChunkChoice{{ + Index: 0, + Delta: ChatDelta{Content: strPtr("hi")}, + }}, + } + events := ChatCompletionsChunkToResponsesEvents(chunk, state) + require.NotEmpty(t, events) + + // response.created 携带 service_tier。 + created := findEvent(events, "response.created") + require.NotNil(t, created) + require.NotNil(t, created.Response) + require.Equal(t, "flex", created.Response.ServiceTier) + + // 终止事件同样携带。 + final := FinalizeChatCompletionsResponsesStream(state) + completed := findEvent(final, "response.completed") + require.NotNil(t, completed) + require.NotNil(t, completed.Response) + require.Equal(t, "flex", completed.Response.ServiceTier) +} + +func TestChatCompletionsChunkToResponsesEvents_NoTierStaysClean(t *testing.T) { + state := NewChatCompletionsToResponsesStreamState("gpt-5.5") + chunk := &ChatCompletionsChunk{ID: "chatcmpl-3", Model: "gpt-5.5"} + events := ChatCompletionsChunkToResponsesEvents(chunk, state) + created := findEvent(events, "response.created") + require.NotNil(t, created) + require.Empty(t, created.Response.ServiceTier) + raw, err := json.Marshal(created) + require.NoError(t, err) + require.NotContains(t, string(raw), "service_tier") +} + +func findEvent(events []ResponsesStreamEvent, eventType string) *ResponsesStreamEvent { + for i := range events { + if events[i].Type == eventType { + return &events[i] + } + } + return nil +} diff --git a/backend/internal/pkg/apicompat/types.go b/backend/internal/pkg/apicompat/types.go index b96d16b911..af56263033 100644 --- a/backend/internal/pkg/apicompat/types.go +++ b/backend/internal/pkg/apicompat/types.go @@ -344,12 +344,13 @@ func (t *ResponsesTool) UnmarshalJSON(data []byte) error { // ResponsesResponse is the non-streaming response from POST /v1/responses. type ResponsesResponse struct { - ID string `json:"id"` - Object string `json:"object"` // "response" - Model string `json:"model"` - Status string `json:"status"` // "completed" | "incomplete" | "failed" - Output []ResponsesOutput `json:"output"` - Usage *ResponsesUsage `json:"usage,omitempty"` + ID string `json:"id"` + Object string `json:"object"` // "response" + Model string `json:"model"` + Status string `json:"status"` // "completed" | "incomplete" | "failed" + Output []ResponsesOutput `json:"output"` + Usage *ResponsesUsage `json:"usage,omitempty"` + ServiceTier string `json:"service_tier,omitempty"` // upstream tier, echoed back verbatim // incomplete_details is present when status="incomplete" IncompleteDetails *ResponsesIncompleteDetails `json:"incomplete_details,omitempty"` diff --git a/backend/internal/service/billing_service.go b/backend/internal/service/billing_service.go index 6345f2c40e..42dd06c03c 100644 --- a/backend/internal/service/billing_service.go +++ b/backend/internal/service/billing_service.go @@ -1475,7 +1475,8 @@ func (s *BillingService) applyModelSpecificPricingPolicy(model string, pricing * (pricing.LongContextInputThreshold <= 0 || pricing.LongContextInputMultiplier <= 0 || pricing.LongContextOutputMultiplier <= 0) needsCacheCreationPolicy := isGPT56 && !pricing.CacheCreationPriceExplicit && (pricing.CacheCreationPricePerToken <= 0 || (pricing.InputPricePerTokenPriority > 0 && pricing.CacheCreationPricePerTokenPriority <= 0)) - if !needsLongContextPolicy && !needsCacheCreationPolicy { + fastRatio := openAIModelFastPricingRatio(normalized) + if !needsLongContextPolicy && !needsCacheCreationPolicy && fastRatio <= 0 { return pricing } cloned := *pricing @@ -1498,9 +1499,45 @@ func (s *BillingService) applyModelSpecificPricingPolicy(model string, pricing * cloned.LongContextOutputMultiplier = openAIGPT54LongContextOutputMultiplier } } + if fastRatio > 0 { + enforceOpenAIFastPricingRatio(&cloned, fastRatio) + } return &cloned } +// openAIModelFastPricingRatio 返回业务口径下 OpenAI GPT-5.x 模型 Fast/priority +// 的标准价倍率:gpt-5.6 系列与 gpt-5.4 为 2x,gpt-5.5 为 2.5x。未定义 Fast +// 档的模型(如 gpt-5.5-pro、gpt-5.4-mini/nano)返回 0。 +func openAIModelFastPricingRatio(normalized string) float64 { + switch normalized { + case "gpt-5.4", "gpt-5.6-sol", "gpt-5.6-terra", "gpt-5.6-luna": + return 2.0 + case "gpt-5.5": + return 2.5 + default: + return 0 + } +} + +// enforceOpenAIFastPricingRatio 把 priority 档价格改写为「标准价 × ratio」。 +// 本地/远程 LiteLLM 目录可能只带官方旧口径(如 gpt-5.5 priority 仍标 2x), +// 直接采用会导致 Fast 模式少计费;这里按业务倍率兜底修正,且对已正确的 +// fallback 条目(2x/2.5x)是幂等的。computeTokenBreakdown 在 priority 价格 +// 存在时走显式档位价、不再叠加通用 tier 倍率,因此不会重复乘价。 +func enforceOpenAIFastPricingRatio(pricing *ModelPricing, ratio float64) { + if pricing == nil || ratio <= 0 { + return + } + pricing.InputPricePerTokenPriority = pricing.InputPricePerToken * ratio + pricing.OutputPricePerTokenPriority = pricing.OutputPricePerToken * ratio + if pricing.CacheReadPricePerToken > 0 { + pricing.CacheReadPricePerTokenPriority = pricing.CacheReadPricePerToken * ratio + } + if pricing.CacheCreationPricePerToken > 0 { + pricing.CacheCreationPricePerTokenPriority = pricing.CacheCreationPricePerToken * ratio + } +} + func (s *BillingService) shouldApplySessionLongContextPricing(tokens UsageTokens, pricing *ModelPricing) bool { if pricing == nil || pricing.LongContextInputThreshold <= 0 { return false diff --git a/backend/internal/service/openai_fast_service_tier_test.go b/backend/internal/service/openai_fast_service_tier_test.go new file mode 100644 index 0000000000..31b500c8ba --- /dev/null +++ b/backend/internal/service/openai_fast_service_tier_test.go @@ -0,0 +1,834 @@ +package service + +import ( + "bytes" + "context" + "encoding/json" + "errors" + "io" + "net/http" + "net/http/httptest" + "strings" + "testing" + + "github.com/Wei-Shaw/sub2api/internal/config" + "github.com/gin-gonic/gin" + "github.com/stretchr/testify/require" + "github.com/tidwall/gjson" +) + +// --------------------------------------------------------------------------- +// 请求侧:service_tier 校验(fast/priority 等价、非法值拒绝、省略保持现状) +// --------------------------------------------------------------------------- + +func TestValidateOpenAIServiceTierField(t *testing.T) { + t.Parallel() + + t.Run("fast normalizes to priority", func(t *testing.T) { + norm, err := ValidateOpenAIServiceTierField([]byte(`{"model":"gpt-5.5","service_tier":"fast"}`)) + require.NoError(t, err) + require.Equal(t, "priority", norm) + }) + + t.Run("priority passes through", func(t *testing.T) { + norm, err := ValidateOpenAIServiceTierField([]byte(`{"model":"gpt-5.5","service_tier":"priority"}`)) + require.NoError(t, err) + require.Equal(t, "priority", norm) + }) + + t.Run("case and whitespace insensitive", func(t *testing.T) { + norm, err := ValidateOpenAIServiceTierField([]byte(`{"model":"gpt-5.5","service_tier":" FAST "}`)) + require.NoError(t, err) + require.Equal(t, "priority", norm) + }) + + t.Run("official tiers pass through", func(t *testing.T) { + for _, tier := range []string{"flex", "auto", "default", "scale"} { + norm, err := ValidateOpenAIServiceTierField([]byte(`{"model":"gpt-5.5","service_tier":"` + tier + `"}`)) + require.NoError(t, err, "tier %q must be accepted", tier) + require.Equal(t, tier, norm) + } + }) + + t.Run("invalid tier rejected", func(t *testing.T) { + _, err := ValidateOpenAIServiceTierField([]byte(`{"model":"gpt-5.5","service_tier":"turbo"}`)) + require.Error(t, err) + var invalid *ErrInvalidOpenAIServiceTier + require.True(t, errors.As(err, &invalid)) + require.Equal(t, "turbo", invalid.Value) + require.Contains(t, err.Error(), "invalid service_tier") + require.Contains(t, err.Error(), "fast", "allowed-value hint must mention fast") + }) + + t.Run("omitted field stays valid", func(t *testing.T) { + norm, err := ValidateOpenAIServiceTierField([]byte(`{"model":"gpt-5.5","input":"hi"}`)) + require.NoError(t, err) + require.Empty(t, norm) + }) + + t.Run("null value keeps omission semantics", func(t *testing.T) { + norm, err := ValidateOpenAIServiceTierField([]byte(`{"model":"gpt-5.5","service_tier":null}`)) + require.NoError(t, err) + require.Empty(t, norm) + }) + + t.Run("explicit empty string rejected as invalid enum value", func(t *testing.T) { + _, err := ValidateOpenAIServiceTierField([]byte(`{"model":"gpt-5.5","service_tier":""}`)) + require.Error(t, err) + var invalid *ErrInvalidOpenAIServiceTier + require.True(t, errors.As(err, &invalid)) + }) + + t.Run("non-string service_tier rejected", func(t *testing.T) { + // service_tier 必须为字符串;数字/布尔/对象/数组等类型同样按非法值拒绝。 + for _, raw := range []string{ + `{"model":"gpt-5.5","service_tier":123}`, + `{"model":"gpt-5.5","service_tier":true}`, + `{"model":"gpt-5.5","service_tier":{}}`, + `{"model":"gpt-5.5","service_tier":["priority"]}`, + } { + _, err := ValidateOpenAIServiceTierField([]byte(raw)) + require.Error(t, err, "raw=%s must be rejected", raw) + var invalid *ErrInvalidOpenAIServiceTier + require.True(t, errors.As(err, &invalid), "raw=%s", raw) + require.Equal(t, "", invalid.Value, "raw=%s", raw) + require.Contains(t, err.Error(), "invalid service_tier") + } + }) + + t.Run("oversized unknown string is truncated", func(t *testing.T) { + blob := strings.Repeat("z", 4096) + _, err := ValidateOpenAIServiceTierField([]byte(`{"model":"gpt-5.5","service_tier":"` + blob + `"}`)) + require.Error(t, err) + require.Contains(t, err.Error(), "invalid service_tier") + require.NotContains(t, err.Error(), blob) + require.Less(t, len(err.Error()), 200) + var invalid *ErrInvalidOpenAIServiceTier + require.True(t, errors.As(err, &invalid)) + require.Equal(t, strings.Repeat("z", 64)+"...", invalid.Value) + }) + + t.Run("non-string large object/array is not echoed", func(t *testing.T) { + blob := strings.Repeat("x", 4096) + payloads := []string{ + `{"model":"gpt-5.5","service_tier":{"blob":"` + blob + `"}}`, + `{"model":"gpt-5.5","service_tier":["` + blob + `"]}`, + } + for _, raw := range payloads { + _, err := ValidateOpenAIServiceTierField([]byte(raw)) + require.Error(t, err) + require.Contains(t, err.Error(), "invalid service_tier") + require.NotContains(t, err.Error(), blob) + require.Less(t, len(err.Error()), 200) + var invalid *ErrInvalidOpenAIServiceTier + require.True(t, errors.As(err, &invalid)) + require.Equal(t, "", invalid.Value) + } + }) +} + +// --------------------------------------------------------------------------- +// 计费:gpt-5.6 系列 / gpt-5.4 按标准价 2x,gpt-5.5 按标准价 2.5x +// --------------------------------------------------------------------------- + +func TestApplyModelSpecificPricingPolicy_EnforcesOpenAIFastRatios(t *testing.T) { + t.Parallel() + + svc := &BillingService{} + + t.Run("gpt-5.5 catalog 2x priority is corrected to 2.5x", func(t *testing.T) { + // 模拟本地 LiteLLM 目录仍携带官方旧口径(gpt-5.5 priority = 2x)。 + catalog := &ModelPricing{ + InputPricePerToken: 5e-6, + InputPricePerTokenPriority: 10e-6, + OutputPricePerToken: 30e-6, + OutputPricePerTokenPriority: 60e-6, + CacheReadPricePerToken: 0.5e-6, + CacheReadPricePerTokenPriority: 1e-6, + } + got := svc.applyModelSpecificPricingPolicy("gpt-5.5", catalog) + require.InDelta(t, 12.5e-6, got.InputPricePerTokenPriority, 1e-12) + require.InDelta(t, 75e-6, got.OutputPricePerTokenPriority, 1e-12) + require.InDelta(t, 1.25e-6, got.CacheReadPricePerTokenPriority, 1e-12) + // 标准价不被改动。 + require.InDelta(t, 5e-6, got.InputPricePerToken, 1e-12) + // 原始指针不被污染。 + require.InDelta(t, 10e-6, catalog.InputPricePerTokenPriority, 1e-12) + }) + + t.Run("gpt-5.4 keeps 2x", func(t *testing.T) { + got := svc.applyModelSpecificPricingPolicy("gpt-5.4", &ModelPricing{ + InputPricePerToken: 2.5e-6, + InputPricePerTokenPriority: 5e-6, + OutputPricePerToken: 15e-6, + OutputPricePerTokenPriority: 30e-6, + }) + require.InDelta(t, 5e-6, got.InputPricePerTokenPriority, 1e-12) + require.InDelta(t, 30e-6, got.OutputPricePerTokenPriority, 1e-12) + }) + + t.Run("gpt-5.6 family keeps 2x", func(t *testing.T) { + for _, model := range []string{"gpt-5.6", "gpt-5.6-sol", "gpt-5.6-terra", "gpt-5.6-luna", "gpt-5.6-max", "gpt-5.6-sol-preview"} { + got := svc.applyModelSpecificPricingPolicy(model, &ModelPricing{ + InputPricePerToken: 5e-6, + InputPricePerTokenPriority: 10e-6, + OutputPricePerToken: 30e-6, + OutputPricePerTokenPriority: 60e-6, + CacheReadPricePerToken: 0.5e-6, + CacheReadPricePerTokenPriority: 1e-6, + }) + require.InDelta(t, 10e-6, got.InputPricePerTokenPriority, 1e-12, "model %s", model) + require.InDelta(t, 60e-6, got.OutputPricePerTokenPriority, 1e-12, "model %s", model) + } + }) + + t.Run("missing priority prices are backfilled from standard", func(t *testing.T) { + got := svc.applyModelSpecificPricingPolicy("gpt-5.5", &ModelPricing{ + InputPricePerToken: 5e-6, + OutputPricePerToken: 30e-6, + CacheReadPricePerToken: 0.5e-6, + CacheCreationPricePerToken: 5e-6, + }) + require.InDelta(t, 12.5e-6, got.InputPricePerTokenPriority, 1e-12) + require.InDelta(t, 75e-6, got.OutputPricePerTokenPriority, 1e-12) + require.InDelta(t, 1.25e-6, got.CacheReadPricePerTokenPriority, 1e-12) + require.InDelta(t, 12.5e-6, got.CacheCreationPricePerTokenPriority, 1e-12) + }) + + t.Run("gpt-5.5-pro has no mandated fast tier", func(t *testing.T) { + got := svc.applyModelSpecificPricingPolicy("gpt-5.5-pro", &ModelPricing{ + InputPricePerToken: 30e-6, + InputPricePerTokenPriority: 60e-6, + OutputPricePerToken: 180e-6, + }) + require.InDelta(t, 60e-6, got.InputPricePerTokenPriority, 1e-12) + }) + + t.Run("unrelated models untouched", func(t *testing.T) { + got := svc.applyModelSpecificPricingPolicy("claude-opus-5", &ModelPricing{InputPricePerToken: 1, OutputPricePerToken: 2}) + require.InDelta(t, 1, got.InputPricePerToken, 1e-12) + require.Zero(t, got.InputPricePerTokenPriority) + }) +} + +func TestOpenAIFastBillingMultiplier_2xAnd25x(t *testing.T) { + t.Parallel() + + // 目录数据携带官方旧口径(gpt-5.5 priority=2x);修正后 fast 必须按 2.5x 计费。 + catalog := map[string]*LiteLLMModelPricing{ + "gpt-5.4": { + InputCostPerToken: 2.5e-6, + InputCostPerTokenPriority: 5e-6, + OutputCostPerToken: 15e-6, + OutputCostPerTokenPriority: 30e-6, + CacheReadInputTokenCost: 0.25e-6, + CacheReadInputTokenCostPriority: 0.5e-6, + }, + "gpt-5.5": { + InputCostPerToken: 5e-6, + InputCostPerTokenPriority: 10e-6, + OutputCostPerToken: 30e-6, + OutputCostPerTokenPriority: 60e-6, + CacheReadInputTokenCost: 0.5e-6, + CacheReadInputTokenCostPriority: 1e-6, + }, + "gpt-5.6-sol": { + InputCostPerToken: 5e-6, + InputCostPerTokenPriority: 10e-6, + OutputCostPerToken: 30e-6, + OutputCostPerTokenPriority: 60e-6, + CacheReadInputTokenCost: 0.5e-6, + CacheReadInputTokenCostPriority: 1e-6, + }, + } + billing := NewBillingService(&config.Config{}, &PricingService{pricingData: catalog}) + tokens := UsageTokens{InputTokens: 1_000_000, OutputTokens: 1_000_000} + + standard := func(model string) *CostBreakdown { + cost, err := billing.CalculateCost(model, tokens, 1) + require.NoError(t, err) + return cost + } + fast := func(model, tier string) *CostBreakdown { + cost, err := billing.CalculateCostWithServiceTier(model, tokens, 1, tier) + require.NoError(t, err) + return cost + } + + tests := []struct { + model string + ratio float64 + }{ + {model: "gpt-5.4", ratio: 2.0}, + {model: "gpt-5.5", ratio: 2.5}, + {model: "gpt-5.6-sol", ratio: 2.0}, + {model: "gpt-5.6-terra", ratio: 2.0}, + {model: "gpt-5.6-luna", ratio: 2.0}, + } + for _, tt := range tests { + t.Run(tt.model+"/fast", func(t *testing.T) { + base := standard(tt.model) + fastCost := fast(tt.model, "fast") + require.InDelta(t, base.TotalCost*tt.ratio, fastCost.TotalCost, 1e-9, + "fast total must be %.1fx standard", tt.ratio) + }) + t.Run(tt.model+"/priority_alias", func(t *testing.T) { + fastCost := fast(tt.model, "fast") + priorityCost := fast(tt.model, "priority") + require.InDelta(t, fastCost.TotalCost, priorityCost.TotalCost, 1e-12, + "client alias fast must bill identically to priority") + require.InDelta(t, standard(tt.model).TotalCost*tt.ratio, priorityCost.TotalCost, 1e-9) + }) + t.Run(tt.model+"/no_tier_unchanged", func(t *testing.T) { + base := standard(tt.model) + noTier, err := billing.CalculateCostWithServiceTier(tt.model, tokens, 1, "") + require.NoError(t, err) + require.InDelta(t, base.TotalCost, noTier.TotalCost, 1e-12) + }) + t.Run(tt.model+"/default_equals_standard", func(t *testing.T) { + base := standard(tt.model) + defaultCost, err := billing.CalculateCostWithServiceTier(tt.model, tokens, 1, "default") + require.NoError(t, err) + require.InDelta(t, base.TotalCost, defaultCost.TotalCost, 1e-12) + require.InDelta(t, base.InputCost, defaultCost.InputCost, 1e-12) + require.InDelta(t, base.OutputCost, defaultCost.OutputCost, 1e-12) + require.InDelta(t, base.CacheReadCost, defaultCost.CacheReadCost, 1e-12) + }) + } +} + +func TestOpenAIFastBilling_FastMultiplierOverridesEnforcedRatio(t *testing.T) { + t.Parallel() + + svc := &BillingService{} + catalog := &ModelPricing{ + InputPricePerToken: 5e-6, + InputPricePerTokenPriority: 10e-6, + OutputPricePerToken: 30e-6, + OutputPricePerTokenPriority: 60e-6, + CacheReadPricePerToken: 0.5e-6, + CacheReadPricePerTokenPriority: 1e-6, + } + pricing := svc.applyModelSpecificPricingPolicy("gpt-5.5", catalog) + require.InDelta(t, 12.5e-6, pricing.InputPricePerTokenPriority, 1e-12, "enforce must still write 2.5x priority prices") + require.InDelta(t, 75e-6, pricing.OutputPricePerTokenPriority, 1e-12) + + multiplier := 1.7 + pricing.FastMultiplier = &multiplier + + tokens := UsageTokens{InputTokens: 1_000_000, OutputTokens: 1_000_000, CacheReadTokens: 1_000_000} + standard := svc.computeTokenBreakdown(pricing, tokens, 1, "", false) + fast := svc.computeTokenBreakdown(pricing, tokens, 1, "fast", false) + priority := svc.computeTokenBreakdown(pricing, tokens, 1, "priority", false) + + require.InDelta(t, standard.TotalCost*1.7, fast.TotalCost, 1e-9) + require.InDelta(t, fast.TotalCost, priority.TotalCost, 1e-12) + + withoutOverride := *pricing + withoutOverride.FastMultiplier = nil + enforced := svc.computeTokenBreakdown(&withoutOverride, tokens, 1, "fast", false) + require.InDelta(t, standard.TotalCost*2.5, enforced.TotalCost, 1e-9, + "without FastMultiplier the same enforced prices still bill 2.5x") +} + +// --------------------------------------------------------------------------- +// 上游 payload:fast 归一化为 priority 并确实到达上游 +// --------------------------------------------------------------------------- + +func TestForwardAsChatCompletions_ServiceTierFastNormalizedToPriorityUpstream(t *testing.T) { + gin.SetMode(gin.TestMode) + + rec := httptest.NewRecorder() + c, _ := gin.CreateTestContext(rec) + body := []byte(`{"model":"gpt-5.5","messages":[{"role":"user","content":"hello"}],"service_tier":"fast","stream":false}`) + c.Request = httptest.NewRequest(http.MethodPost, "/v1/chat/completions", bytes.NewReader(body)) + c.Request.Header.Set("Content-Type", "application/json") + + upstream := &httpUpstreamRecorder{resp: &http.Response{ + StatusCode: http.StatusBadRequest, + Header: http.Header{"Content-Type": []string{"application/json"}, "x-request-id": []string{"rid-chat-st"}}, + Body: io.NopCloser(strings.NewReader(`{"error":{"type":"invalid_request_error","message":"stop"}}`)), + }} + + svc := &OpenAIGatewayService{ + cfg: &config.Config{}, + httpUpstream: upstream, + settingService: NewSettingService(&openAIFastPolicyRepoStub{values: map[string]string{}}, &config.Config{}), + } + account := &Account{ + ID: 21, + Name: "openai-compatible", + Platform: PlatformOpenAI, + Type: AccountTypeAPIKey, + Concurrency: 1, + Credentials: map[string]any{"api_key": "sk-compatible"}, + Extra: map[string]any{"openai_responses_supported": true}, + } + + _, err := svc.ForwardAsChatCompletions(context.Background(), c, account, body, "", "gpt-5.5") + require.Error(t, err) // upstream 400 → 错误返回,但请求体已被 recorder 捕获 + require.NotNil(t, upstream.lastBody) + require.Equal(t, "priority", gjson.GetBytes(upstream.lastBody, "service_tier").String(), + "client alias fast must reach upstream as priority") +} + +func TestForwardAsChatCompletions_ServiceTierPriorityPreservedUpstream(t *testing.T) { + gin.SetMode(gin.TestMode) + + rec := httptest.NewRecorder() + c, _ := gin.CreateTestContext(rec) + body := []byte(`{"model":"gpt-5.5","messages":[{"role":"user","content":"hello"}],"service_tier":"priority","stream":false}`) + c.Request = httptest.NewRequest(http.MethodPost, "/v1/chat/completions", bytes.NewReader(body)) + c.Request.Header.Set("Content-Type", "application/json") + + upstream := &httpUpstreamRecorder{resp: &http.Response{ + StatusCode: http.StatusBadRequest, + Header: http.Header{"Content-Type": []string{"application/json"}, "x-request-id": []string{"rid-chat-st2"}}, + Body: io.NopCloser(strings.NewReader(`{"error":{"type":"invalid_request_error","message":"stop"}}`)), + }} + + svc := &OpenAIGatewayService{ + cfg: &config.Config{}, + httpUpstream: upstream, + settingService: NewSettingService(&openAIFastPolicyRepoStub{values: map[string]string{}}, &config.Config{}), + } + account := &Account{ + ID: 2, + Name: "openai-compatible", + Platform: PlatformOpenAI, + Type: AccountTypeAPIKey, + Concurrency: 1, + Credentials: map[string]any{"api_key": "sk-compatible"}, + Extra: map[string]any{"openai_responses_supported": true}, + } + + _, err := svc.ForwardAsChatCompletions(context.Background(), c, account, body, "", "gpt-5.5") + require.Error(t, err) + require.NotNil(t, upstream.lastBody) + require.Equal(t, "priority", gjson.GetBytes(upstream.lastBody, "service_tier").String()) +} + +func TestForward_ResponsesServiceTierFastNormalizedToPriorityUpstream(t *testing.T) { + gin.SetMode(gin.TestMode) + + rec := httptest.NewRecorder() + c, _ := gin.CreateTestContext(rec) + body := []byte(`{"model":"gpt-5.5","service_tier":"fast","input":"hello","stream":false}`) + c.Request = httptest.NewRequest(http.MethodPost, "/v1/responses", bytes.NewReader(body)) + c.Request.Header.Set("Content-Type", "application/json") + + upstream := &httpUpstreamRecorder{resp: &http.Response{ + StatusCode: http.StatusOK, + Header: http.Header{"Content-Type": []string{"application/json"}, "x-request-id": []string{"rid-resp-st"}}, + Body: io.NopCloser(strings.NewReader( + `{"id":"resp_1","object":"response","status":"completed","model":"gpt-5.5","output":[],"usage":{"input_tokens":1,"output_tokens":1}}`, + )), + }} + + svc := &OpenAIGatewayService{ + cfg: &config.Config{Security: config.SecurityConfig{URLAllowlist: config.URLAllowlistConfig{Enabled: false}}}, + httpUpstream: upstream, + settingService: NewSettingService(&openAIFastPolicyRepoStub{values: map[string]string{}}, &config.Config{}), + } + account := &Account{ + ID: 7, + Name: "openai-apikey", + Platform: PlatformOpenAI, + Type: AccountTypeAPIKey, + Concurrency: 1, + Credentials: map[string]any{"api_key": "sk-test"}, + Extra: map[string]any{"openai_responses_supported": true}, + Status: StatusActive, + Schedulable: true, + } + + result, err := svc.Forward(context.Background(), c, account, body) + require.NoError(t, err) + require.NotNil(t, result) + require.NotNil(t, upstream.lastBody) + require.Equal(t, "priority", gjson.GetBytes(upstream.lastBody, "service_tier").String(), + "client alias fast must reach the upstream as priority") + // 计费上下文:result 携带归一化后的 tier。 + require.NotNil(t, result.ServiceTier) + require.Equal(t, "priority", *result.ServiceTier) +} + +func TestForward_ResponsesServiceTierOmittedStaysOmitted(t *testing.T) { + gin.SetMode(gin.TestMode) + + rec := httptest.NewRecorder() + c, _ := gin.CreateTestContext(rec) + body := []byte(`{"model":"gpt-5.5","input":"hello","stream":false}`) + c.Request = httptest.NewRequest(http.MethodPost, "/v1/responses", bytes.NewReader(body)) + c.Request.Header.Set("Content-Type", "application/json") + + upstream := &httpUpstreamRecorder{resp: &http.Response{ + StatusCode: http.StatusOK, + Header: http.Header{"Content-Type": []string{"application/json"}, "x-request-id": []string{"rid-resp-st2"}}, + Body: io.NopCloser(strings.NewReader( + `{"id":"resp_2","object":"response","status":"completed","model":"gpt-5.5","output":[],"usage":{"input_tokens":1,"output_tokens":1}}`, + )), + }} + + svc := &OpenAIGatewayService{ + cfg: &config.Config{Security: config.SecurityConfig{URLAllowlist: config.URLAllowlistConfig{Enabled: false}}}, + httpUpstream: upstream, + settingService: NewSettingService(&openAIFastPolicyRepoStub{values: map[string]string{}}, &config.Config{}), + } + account := &Account{ + ID: 7, + Name: "openai-apikey", + Platform: PlatformOpenAI, + Type: AccountTypeAPIKey, + Concurrency: 1, + Credentials: map[string]any{"api_key": "sk-test"}, + Extra: map[string]any{"openai_responses_supported": true}, + Status: StatusActive, + Schedulable: true, + } + + result, err := svc.Forward(context.Background(), c, account, body) + require.NoError(t, err) + require.NotNil(t, result) + require.NotNil(t, upstream.lastBody) + require.False(t, gjson.GetBytes(upstream.lastBody, "service_tier").Exists(), + "omitted service_tier must stay omitted") + require.Nil(t, result.ServiceTier) +} + +// --------------------------------------------------------------------------- +// 流式计费上下文:service_tier 需要从请求体传到 usage 计费 +// --------------------------------------------------------------------------- + +func TestForwardStreaming_ServiceTierPropagatedToResult(t *testing.T) { + gin.SetMode(gin.TestMode) + + rec := httptest.NewRecorder() + c, _ := gin.CreateTestContext(rec) + body := []byte(`{"model":"gpt-5.5","service_tier":"fast","input":"hello","stream":true}`) + c.Request = httptest.NewRequest(http.MethodPost, "/v1/responses", bytes.NewReader(body)) + c.Request.Header.Set("Content-Type", "application/json") + + streamPayload := "data: {\"type\":\"response.created\",\"response\":{\"id\":\"resp_s1\",\"object\":\"response\",\"model\":\"gpt-5.5\",\"status\":\"in_progress\"}}\n\n" + + "data: {\"type\":\"response.output_text.delta\",\"item_id\":\"it_1\",\"output_index\":0,\"delta\":\"hi\"}\n\n" + + "data: {\"type\":\"response.completed\",\"response\":{\"id\":\"resp_s1\",\"object\":\"response\",\"model\":\"gpt-5.5\",\"status\":\"completed\",\"output\":[],\"usage\":{\"input_tokens\":1,\"output_tokens\":1}}}\n\n" + + "data: [DONE]\n\n" + + upstream := &httpUpstreamRecorder{resp: &http.Response{ + StatusCode: http.StatusOK, + Header: http.Header{"Content-Type": []string{"text/event-stream"}, "x-request-id": []string{"rid-resp-stream-st"}}, + Body: io.NopCloser(strings.NewReader(streamPayload)), + }} + + svc := &OpenAIGatewayService{ + cfg: &config.Config{Security: config.SecurityConfig{URLAllowlist: config.URLAllowlistConfig{Enabled: false}}}, + httpUpstream: upstream, + settingService: NewSettingService(&openAIFastPolicyRepoStub{values: map[string]string{}}, &config.Config{}), + } + account := &Account{ + ID: 7, + Name: "openai-apikey", + Platform: PlatformOpenAI, + Type: AccountTypeAPIKey, + Concurrency: 1, + Credentials: map[string]any{"api_key": "sk-test"}, + Extra: map[string]any{"openai_responses_supported": true}, + Status: StatusActive, + Schedulable: true, + } + + result, err := svc.Forward(context.Background(), c, account, body) + require.NoError(t, err) + require.NotNil(t, result) + require.NotNil(t, result.ServiceTier) + require.Equal(t, "priority", *result.ServiceTier, "streaming billing context must carry the normalized tier") + // /v1/responses 流是上游 SSE 原样透传:上游没回 service_tier 就不该出现; + // 网关只在计费结果里携带请求侧 tier,不往下游流里注入。 + require.Contains(t, rec.Body.String(), `"delta":"hi"`, "streamed content must reach the client") + require.NotContains(t, rec.Body.String(), `"service_tier"`, "upstream did not return service_tier, client stream must stay untouched") +} + +// --------------------------------------------------------------------------- +// 上游回显优先:请求 fast 但上游真实返回 default → 计费按标准价 +// --------------------------------------------------------------------------- + +func TestForward_ResponsesUpstreamEchoesDefault_OverridesRequestFast(t *testing.T) { + gin.SetMode(gin.TestMode) + + rec := httptest.NewRecorder() + c, _ := gin.CreateTestContext(rec) + body := []byte(`{"model":"gpt-5.5","service_tier":"fast","input":"hello","stream":false}`) + c.Request = httptest.NewRequest(http.MethodPost, "/v1/responses", bytes.NewReader(body)) + c.Request.Header.Set("Content-Type", "application/json") + + // 上游回显 service_tier=default(例如请求实际被降级)。 + upstream := &httpUpstreamRecorder{resp: &http.Response{ + StatusCode: http.StatusOK, + Header: http.Header{"Content-Type": []string{"application/json"}, "x-request-id": []string{"rid-resp-echo"}}, + Body: io.NopCloser(strings.NewReader( + `{"id":"resp_1","object":"response","status":"completed","model":"gpt-5.5","service_tier":"default","output":[],"usage":{"input_tokens":1,"output_tokens":1}}`, + )), + }} + + svc := &OpenAIGatewayService{ + cfg: &config.Config{Security: config.SecurityConfig{URLAllowlist: config.URLAllowlistConfig{Enabled: false}}}, + httpUpstream: upstream, + settingService: NewSettingService(&openAIFastPolicyRepoStub{values: map[string]string{}}, &config.Config{}), + } + account := &Account{ + ID: 7, + Name: "openai-apikey", + Platform: PlatformOpenAI, + Type: AccountTypeAPIKey, + Concurrency: 1, + Credentials: map[string]any{"api_key": "sk-test"}, + Extra: map[string]any{"openai_responses_supported": true}, + Status: StatusActive, + Schedulable: true, + } + + result, err := svc.Forward(context.Background(), c, account, body) + require.NoError(t, err) + require.NotNil(t, result) + require.NotNil(t, result.ServiceTier) + require.Equal(t, "default", *result.ServiceTier, + "upstream-echoed default must override the client-requested fast tier for billing") + // 非流式响应原样透传:客户端同样看到 default。 + require.Contains(t, rec.Body.String(), `"service_tier":"default"`) + require.NotContains(t, rec.Body.String(), `"service_tier":"priority"`) +} + +func TestForwardStreaming_UpstreamEchoesDefault_OverridesRequestFast(t *testing.T) { + gin.SetMode(gin.TestMode) + + rec := httptest.NewRecorder() + c, _ := gin.CreateTestContext(rec) + body := []byte(`{"model":"gpt-5.5","service_tier":"fast","input":"hello","stream":true}`) + c.Request = httptest.NewRequest(http.MethodPost, "/v1/responses", bytes.NewReader(body)) + c.Request.Header.Set("Content-Type", "application/json") + + streamPayload := "data: {\"type\":\"response.created\",\"response\":{\"id\":\"resp_s1\",\"object\":\"response\",\"model\":\"gpt-5.5\",\"status\":\"in_progress\"}}\n\n" + + "data: {\"type\":\"response.completed\",\"response\":{\"id\":\"resp_s1\",\"object\":\"response\",\"model\":\"gpt-5.5\",\"status\":\"completed\",\"service_tier\":\"default\",\"output\":[],\"usage\":{\"input_tokens\":1,\"output_tokens\":1}}}\n\n" + + "data: [DONE]\n\n" + + upstream := &httpUpstreamRecorder{resp: &http.Response{ + StatusCode: http.StatusOK, + Header: http.Header{"Content-Type": []string{"text/event-stream"}, "x-request-id": []string{"rid-resp-echo-stream"}}, + Body: io.NopCloser(strings.NewReader(streamPayload)), + }} + + svc := &OpenAIGatewayService{ + cfg: &config.Config{Security: config.SecurityConfig{URLAllowlist: config.URLAllowlistConfig{Enabled: false}}}, + httpUpstream: upstream, + settingService: NewSettingService(&openAIFastPolicyRepoStub{values: map[string]string{}}, &config.Config{}), + } + account := &Account{ + ID: 7, + Name: "openai-apikey", + Platform: PlatformOpenAI, + Type: AccountTypeAPIKey, + Concurrency: 1, + Credentials: map[string]any{"api_key": "sk-test"}, + Extra: map[string]any{"openai_responses_supported": true}, + Status: StatusActive, + Schedulable: true, + } + + result, err := svc.Forward(context.Background(), c, account, body) + require.NoError(t, err) + require.NotNil(t, result) + require.NotNil(t, result.ServiceTier) + require.Equal(t, "default", *result.ServiceTier, + "terminal SSE event's upstream-echoed default must win for billing") + // 流式原样透传:客户端在终止事件里看到 default。 + require.Contains(t, rec.Body.String(), `"service_tier":"default"`) +} + +func TestForwardAsChatCompletions_UpstreamEchoesDefault_BillsStandard(t *testing.T) { + gin.SetMode(gin.TestMode) + + rec := httptest.NewRecorder() + c, _ := gin.CreateTestContext(rec) + body := []byte(`{"model":"gpt-5.5","messages":[{"role":"user","content":"hello"}],"service_tier":"fast","stream":false}`) + c.Request = httptest.NewRequest(http.MethodPost, "/v1/chat/completions", bytes.NewReader(body)) + c.Request.Header.Set("Content-Type", "application/json") + + streamPayload := "data: {\"type\":\"response.created\",\"response\":{\"id\":\"resp_c1\",\"object\":\"response\",\"model\":\"gpt-5.5\",\"status\":\"in_progress\"}}\n\n" + + "data: {\"type\":\"response.output_text.delta\",\"item_id\":\"it_1\",\"output_index\":0,\"delta\":\"hi\"}\n\n" + + "data: {\"type\":\"response.completed\",\"response\":{\"id\":\"resp_c1\",\"object\":\"response\",\"model\":\"gpt-5.5\",\"status\":\"completed\",\"service_tier\":\"default\",\"output\":[],\"usage\":{\"input_tokens\":1,\"output_tokens\":1}}}\n\n" + + "data: [DONE]\n\n" + + upstream := &httpUpstreamRecorder{resp: &http.Response{ + StatusCode: http.StatusOK, + Header: http.Header{"Content-Type": []string{"text/event-stream"}, "x-request-id": []string{"rid-chat-echo"}}, + Body: io.NopCloser(strings.NewReader(streamPayload)), + }} + + svc := &OpenAIGatewayService{ + cfg: &config.Config{Security: config.SecurityConfig{URLAllowlist: config.URLAllowlistConfig{Enabled: false}}}, + httpUpstream: upstream, + settingService: NewSettingService(&openAIFastPolicyRepoStub{values: map[string]string{}}, &config.Config{}), + } + account := &Account{ + ID: 21, + Name: "openai-compatible", + Platform: PlatformOpenAI, + Type: AccountTypeAPIKey, + Concurrency: 1, + Credentials: map[string]any{"api_key": "sk-compatible"}, + Extra: map[string]any{"openai_responses_supported": true}, + Status: StatusActive, + Schedulable: true, + } + + result, err := svc.ForwardAsChatCompletions(context.Background(), c, account, body, "", "gpt-5.5") + require.NoError(t, err) + require.NotNil(t, result) + require.NotNil(t, result.ServiceTier) + require.Equal(t, "default", *result.ServiceTier, + "CC bridge must bill on the upstream-echoed default, not the requested fast") + // 缓冲转回 Chat Completions:客户端响应里如实回显 default。 + require.Contains(t, rec.Body.String(), `"service_tier":"default"`) + require.NotContains(t, rec.Body.String(), `"service_tier":"priority"`) +} + +// --------------------------------------------------------------------------- +// policy filter:删除 service_tier 后不得再按原请求 Fast 计费 +// --------------------------------------------------------------------------- + +func TestForward_ServiceTierFilteredByPolicyBillsStandard(t *testing.T) { + gin.SetMode(gin.TestMode) + + rec := httptest.NewRecorder() + c, _ := gin.CreateTestContext(rec) + body := []byte(`{"model":"gpt-5.5","service_tier":"priority","input":"hello","stream":false}`) + c.Request = httptest.NewRequest(http.MethodPost, "/v1/responses", bytes.NewReader(body)) + c.Request.Header.Set("Content-Type", "application/json") + + // 管理员配置 priority → filter:字段在出站前被删除。 + settings := &OpenAIFastPolicySettings{Rules: []OpenAIFastPolicyRule{{ + ServiceTier: OpenAIFastTierPriority, + Action: BetaPolicyActionFilter, + Scope: BetaPolicyScopeAll, + }}} + raw, err := json.Marshal(settings) + require.NoError(t, err) + repo := &openAIFastPolicyRepoStub{values: map[string]string{SettingKeyOpenAIFastPolicySettings: string(raw)}} + + upstream := &httpUpstreamRecorder{resp: &http.Response{ + StatusCode: http.StatusOK, + Header: http.Header{"Content-Type": []string{"application/json"}, "x-request-id": []string{"rid-resp-filter"}}, + Body: io.NopCloser(strings.NewReader( + `{"id":"resp_1","object":"response","status":"completed","model":"gpt-5.5","output":[],"usage":{"input_tokens":1,"output_tokens":1}}`, + )), + }} + + svc := &OpenAIGatewayService{ + cfg: &config.Config{Security: config.SecurityConfig{URLAllowlist: config.URLAllowlistConfig{Enabled: false}}}, + httpUpstream: upstream, + settingService: NewSettingService(repo, &config.Config{}), + } + account := &Account{ + ID: 7, + Name: "openai-apikey", + Platform: PlatformOpenAI, + Type: AccountTypeAPIKey, + Concurrency: 1, + Credentials: map[string]any{"api_key": "sk-test"}, + Extra: map[string]any{"openai_responses_supported": true}, + Status: StatusActive, + Schedulable: true, + } + + result, err := svc.Forward(context.Background(), c, account, body) + require.NoError(t, err) + require.NotNil(t, result) + // 出站 body 已剥离 service_tier、上游也未回显 → 无 tier → 按标准价计费。 + require.False(t, gjson.GetBytes(upstream.lastBody, "service_tier").Exists(), + "policy filter must strip service_tier from the outbound body") + require.Nil(t, result.ServiceTier, "filtered request must not bill as fast") +} + +// --------------------------------------------------------------------------- +// 上游回显观察与解析器单测 +// --------------------------------------------------------------------------- + +func TestUpstreamResponseModelObserver_ObservesServiceTier(t *testing.T) { + t.Parallel() + + observer := &upstreamResponseModelObserver{} + observer.ObserveOpenAI([]byte(`{"type":"response.created","response":{"model":"gpt-5.5","service_tier":"flex"}}`), "response.created") + require.Equal(t, "flex", observer.ServiceTier()) + + // terminal 声明优先。 + observer.ObserveOpenAI([]byte(`{"type":"response.completed","response":{"model":"gpt-5.5","service_tier":"default"}}`), "response.completed") + require.Equal(t, "default", observer.ServiceTier()) + + // Chat Completions 顶层 service_tier 同样可观察。 + ccObserver := &upstreamResponseModelObserver{} + ccObserver.ObserveOpenAI([]byte(`{"id":"chatcmpl-1","model":"gpt-5.5","service_tier":"priority","choices":[]}`), "chat.completion") + require.Equal(t, "priority", ccObserver.ServiceTier()) +} + +func TestResolvedOpenAIUpstreamServiceTier(t *testing.T) { + t.Parallel() + + priority := func() *string { v := "priority"; return &v }() + + t.Run("upstream echo wins over outbound tier", func(t *testing.T) { + gin.SetMode(gin.TestMode) + c, _ := gin.CreateTestContext(nil) + observer := beginUpstreamResponseModelObservation(c) + observer.ObserveOpenAI([]byte(`{"type":"response.completed","response":{"service_tier":"default"}}`), "response.completed") + + got := resolvedOpenAIUpstreamServiceTier(c, priority) + require.NotNil(t, got) + require.Equal(t, "default", *got) + }) + + t.Run("no upstream echo falls back to outbound tier", func(t *testing.T) { + gin.SetMode(gin.TestMode) + c, _ := gin.CreateTestContext(nil) + beginUpstreamResponseModelObservation(c) + + got := resolvedOpenAIUpstreamServiceTier(c, priority) + require.NotNil(t, got) + require.Equal(t, "priority", *got) + }) + + t.Run("upstream alias fast normalizes to priority", func(t *testing.T) { + gin.SetMode(gin.TestMode) + c, _ := gin.CreateTestContext(nil) + observer := beginUpstreamResponseModelObservation(c) + observer.ObserveOpenAI([]byte(`{"type":"response.completed","response":{"service_tier":"fast"}}`), "response.completed") + + got := resolvedOpenAIUpstreamServiceTier(c, nil) + require.NotNil(t, got) + require.Equal(t, "priority", *got) + }) + + t.Run("no observer keeps outbound tier", func(t *testing.T) { + got := resolvedOpenAIUpstreamServiceTier(nil, priority) + require.NotNil(t, got) + require.Equal(t, "priority", *got) + }) + + t.Run("no observer and no outbound tier stays nil", func(t *testing.T) { + require.Nil(t, resolvedOpenAIUpstreamServiceTier(nil, nil)) + }) + + t.Run("local observer wins without gin context", func(t *testing.T) { + observer := &upstreamResponseModelObserver{} + observer.ObserveOpenAI([]byte(`{"type":"response.completed","response":{"service_tier":"default"}}`), "response.completed") + + got := resolvedOpenAIUpstreamServiceTierFromObserver(observer, priority) + require.NotNil(t, got) + require.Equal(t, "default", *got) + }) + + t.Run("nil local observer falls back to outbound tier", func(t *testing.T) { + got := resolvedOpenAIUpstreamServiceTierFromObserver(nil, priority) + require.NotNil(t, got) + require.Equal(t, "priority", *got) + }) +} diff --git a/backend/internal/service/openai_gateway_cc_pipeline.go b/backend/internal/service/openai_gateway_cc_pipeline.go index 5115dcfea7..8d45c4ff93 100644 --- a/backend/internal/service/openai_gateway_cc_pipeline.go +++ b/backend/internal/service/openai_gateway_cc_pipeline.go @@ -249,6 +249,7 @@ type ccStreamScanState struct { // emit 回调做各自的协议转换与写出。读错误按既有约定过滤 context 取消类噪声后 // 记入 Warn 日志。 func (s *OpenAIGatewayService) scanCCStream( + c *gin.Context, resp *http.Response, logPrefix string, requestID string, @@ -272,6 +273,10 @@ func (s *OpenAIGatewayService) scanCCStream( st.SawDone = true break } + // 观察上游 CC chunk 回显的 model / service_tier(计费以回显为准)。 + if observer := upstreamResponseModelObserverFromContext(c); observer != nil { + observer.ObserveOpenAI([]byte(payload), "chat.completion.chunk") + } if u := extractCCStreamUsage(payload); u != nil { st.Usage = *u @@ -331,6 +336,10 @@ func (s *OpenAIGatewayService) readCCUpstreamJSONResponse( writeError(c, http.StatusBadGateway, "api_error", "Failed to parse upstream response") return nil, OpenAIUsage{}, fmt.Errorf("parse chat completions response: %w", err) } + // 观察上游 CC JSON 回显的 model / service_tier(计费以回显为准)。 + if observer := upstreamResponseModelObserverFromContext(c); observer != nil { + observer.ObserveOpenAI(respBody, "chat.completion") + } usage := OpenAIUsage{} if parsed, ok := extractOpenAIUsageFromJSONBytes(respBody); ok { diff --git a/backend/internal/service/openai_gateway_chat_completions.go b/backend/internal/service/openai_gateway_chat_completions.go index d5639fbe31..7d9241a7ca 100644 --- a/backend/internal/service/openai_gateway_chat_completions.go +++ b/backend/internal/service/openai_gateway_chat_completions.go @@ -190,7 +190,8 @@ func (s *OpenAIGatewayService) ForwardAsChatCompletions( responsesBody = stripped } } - responsesBody, normalizedServiceTier, err := normalizeResponsesBodyServiceTier(responsesBody) + var normalizedServiceTier string + responsesBody, normalizedServiceTier, err = normalizeResponsesBodyServiceTier(responsesBody) if err != nil { return nil, fmt.Errorf("normalize service_tier in responses-shape body: %w", err) } @@ -371,11 +372,13 @@ func (s *OpenAIGatewayService) ForwardAsChatCompletions( return nil, handleErr } - // Propagate ServiceTier and ReasoningEffort to result for billing + // Propagate ServiceTier and ReasoningEffort to result for billing. + // 计费 tier 优先采用上游回显值;上游未回显时回退到最终出站 body(经过 + // fast policy filter/force 之后)里的 tier,policy filter 删掉字段后不再 + // 按原请求 Fast 计费。 if handleErr == nil && result != nil { - if responsesReq.ServiceTier != "" { - st := responsesReq.ServiceTier - result.ServiceTier = &st + if tier := resolvedOpenAIUpstreamServiceTier(c, extractOpenAIServiceTierFromBody(responsesBody)); tier != nil { + result.ServiceTier = tier } if responsesReq.Reasoning != nil && responsesReq.Reasoning.Effort != "" { re := responsesReq.Reasoning.Effort @@ -475,6 +478,7 @@ func (s *OpenAIGatewayService) handleChatBufferedStreamingResponse( observer = beginUpstreamResponseModelObservation(c) } observer.Observe(finalResponse.Model, true) + observer.ObserveServiceTier(finalResponse.ServiceTier, true) if strings.TrimSpace(finalResponse.Status) == "failed" { payload, _ := json.Marshal(gin.H{"type": "response.failed", "response": finalResponse}) // cyber_policy 致命不可重试:不 failover,以 Chat Completions 错误格式回写(F4), diff --git a/backend/internal/service/openai_gateway_chat_completions_raw.go b/backend/internal/service/openai_gateway_chat_completions_raw.go index f3506d045a..923033c4d4 100644 --- a/backend/internal/service/openai_gateway_chat_completions_raw.go +++ b/backend/internal/service/openai_gateway_chat_completions_raw.go @@ -69,9 +69,6 @@ func (s *OpenAIGatewayService) forwardAsRawChatCompletions( } clientStream := gjson.GetBytes(body, "stream").Bool() - // 1b. Extract service tier from the raw body before any transformation. - serviceTier := extractOpenAIServiceTierFromBody(body) - // 2. Resolve model mapping (same as ForwardAsChatCompletions) billingModel := resolveOpenAIForwardModel(account, originalModel, defaultMappedModel) upstreamModel := normalizeOpenAIModelForUpstream(account, billingModel) @@ -106,6 +103,9 @@ func (s *OpenAIGatewayService) forwardAsRawChatCompletions( return nil, policyErr } upstreamBody = updatedBody + // 计费兜底 tier = 最终出站 body(policy filter/force 后)里的 tier; + // 最终值由 resolvedOpenAIUpstreamServiceTier 决定(上游回显优先)。 + serviceTier := extractOpenAIServiceTierFromBody(upstreamBody) if account.Platform == PlatformGrok { strippedBody, stripErr := stripRedundantGrokChatViewImageTool(upstreamBody) if stripErr != nil { @@ -390,7 +390,7 @@ func (s *OpenAIGatewayService) streamRawChatCompletions( UpstreamResponseModelConflict: observedUpstreamResponseModelConflict(c), UpstreamResponseServiceTier: observedUpstreamResponseServiceTier(c), ReasoningEffort: reasoningEffort, - ServiceTier: serviceTier, + ServiceTier: resolvedOpenAIUpstreamServiceTier(c, serviceTier), Stream: true, Duration: time.Since(startTime), FirstTokenMs: firstTokenMs, @@ -492,7 +492,7 @@ func (s *OpenAIGatewayService) bufferRawChatCompletions( UpstreamResponseModelConflict: observedUpstreamResponseModelConflict(c), UpstreamResponseServiceTier: observedUpstreamResponseServiceTier(c), ReasoningEffort: reasoningEffort, - ServiceTier: serviceTier, + ServiceTier: resolvedOpenAIUpstreamServiceTier(c, serviceTier), Stream: false, Duration: time.Since(startTime), }, nil diff --git a/backend/internal/service/openai_gateway_forward.go b/backend/internal/service/openai_gateway_forward.go index 0a4aa23416..c567a00be7 100644 --- a/backend/internal/service/openai_gateway_forward.go +++ b/backend/internal/service/openai_gateway_forward.go @@ -1180,7 +1180,7 @@ func (s *OpenAIGatewayService) Forward(ctx context.Context, c *gin.Context, acco UpstreamResponseModel: observedUpstreamResponseModel(c), UpstreamResponseModelConflict: observedUpstreamResponseModelConflict(c), UpstreamResponseServiceTier: observedUpstreamResponseServiceTier(c), - ServiceTier: serviceTier, + ServiceTier: resolvedOpenAIUpstreamServiceTier(c, serviceTier), ReasoningEffort: reasoningEffort, Stream: reqStream, OpenAIWSMode: false, diff --git a/backend/internal/service/openai_gateway_messages.go b/backend/internal/service/openai_gateway_messages.go index c9113050e1..75841f1061 100644 --- a/backend/internal/service/openai_gateway_messages.go +++ b/backend/internal/service/openai_gateway_messages.go @@ -492,9 +492,10 @@ func (s *OpenAIGatewayService) ForwardAsAnthropic( if promptCacheKey != "" && anthropicDigestChain != "" { s.bindOpenAICompatAnthropicDigestPromptCacheKey(account, apiKeyID, anthropicDigestChain, promptCacheKey, anthropicMatchedDigestChain) } - if responsesReq.ServiceTier != "" { - st := responsesReq.ServiceTier - result.ServiceTier = &st + // 计费 tier 优先采用上游回显值;上游未回显时回退到最终出站 body(经过 + // fast policy filter/force 之后)里的 tier。 + if tier := resolvedOpenAIUpstreamServiceTier(c, extractOpenAIServiceTierFromBody(responsesBody)); tier != nil { + result.ServiceTier = tier } if responsesReq.Reasoning != nil && responsesReq.Reasoning.Effort != "" { re := responsesReq.Reasoning.Effort @@ -572,6 +573,7 @@ func (s *OpenAIGatewayService) handleAnthropicBufferedStreamingResponse( observer = beginUpstreamResponseModelObservation(c) } observer.Observe(finalResponse.Model, true) + observer.ObserveServiceTier(finalResponse.ServiceTier, true) if strings.TrimSpace(finalResponse.Status) == "failed" { payload, _ := json.Marshal(gin.H{"type": "response.failed", "response": finalResponse}) diff --git a/backend/internal/service/openai_gateway_messages_chat_fallback.go b/backend/internal/service/openai_gateway_messages_chat_fallback.go index e2929be92e..31dccb969b 100644 --- a/backend/internal/service/openai_gateway_messages_chat_fallback.go +++ b/backend/internal/service/openai_gateway_messages_chat_fallback.go @@ -158,7 +158,7 @@ func (s *OpenAIGatewayService) bufferChatCompletionsAsAnthropic( BillingModel: billingModel, UpstreamModel: upstreamModel, ReasoningEffort: reasoningEffort, - ServiceTier: serviceTier, + ServiceTier: resolvedOpenAIUpstreamServiceTier(c, serviceTier), Stream: false, Duration: time.Since(startTime), }, nil @@ -204,7 +204,7 @@ func (s *OpenAIGatewayService) streamChatCompletionsAsAnthropic( } } - scan := s.scanCCStream(resp, "openai messages chat fallback", requestID, startTime, emitChunk) + scan := s.scanCCStream(c, resp, "openai messages chat fallback", requestID, startTime, emitChunk) usage := scan.Usage if scan.Err != nil { @@ -218,7 +218,7 @@ func (s *OpenAIGatewayService) streamChatCompletionsAsAnthropic( BillingModel: billingModel, UpstreamModel: upstreamModel, ReasoningEffort: reasoningEffort, - ServiceTier: serviceTier, + ServiceTier: resolvedOpenAIUpstreamServiceTier(c, serviceTier), Stream: true, Duration: time.Since(startTime), FirstTokenMs: scan.FirstTokenMs, @@ -253,7 +253,7 @@ func (s *OpenAIGatewayService) streamChatCompletionsAsAnthropic( BillingModel: billingModel, UpstreamModel: upstreamModel, ReasoningEffort: reasoningEffort, - ServiceTier: serviceTier, + ServiceTier: resolvedOpenAIUpstreamServiceTier(c, serviceTier), Stream: true, Duration: time.Since(startTime), FirstTokenMs: scan.FirstTokenMs, diff --git a/backend/internal/service/openai_gateway_passthrough.go b/backend/internal/service/openai_gateway_passthrough.go index c8af9a70a1..a4375f681e 100644 --- a/backend/internal/service/openai_gateway_passthrough.go +++ b/backend/internal/service/openai_gateway_passthrough.go @@ -515,7 +515,7 @@ func (s *OpenAIGatewayService) forwardOpenAIPassthrough( UpstreamResponseModel: observedUpstreamResponseModel(c), UpstreamResponseModelConflict: observedUpstreamResponseModelConflict(c), UpstreamResponseServiceTier: observedUpstreamResponseServiceTier(c), - ServiceTier: serviceTier, + ServiceTier: resolvedOpenAIUpstreamServiceTier(c, serviceTier), ReasoningEffort: reasoningEffort, Stream: reqStream, OpenAIWSMode: false, diff --git a/backend/internal/service/openai_gateway_request_body.go b/backend/internal/service/openai_gateway_request_body.go index cbf4e6e9c8..c9a61d7465 100644 --- a/backend/internal/service/openai_gateway_request_body.go +++ b/backend/internal/service/openai_gateway_request_body.go @@ -1240,6 +1240,57 @@ func normalizeOpenAIServiceTier(raw string) *string { } } +// ErrInvalidOpenAIServiceTier indicates a request carried a service_tier value +// that is not a known OpenAI tier. HTTP handlers translate it into a 400 +// invalid_request_error so malformed values are rejected up front instead of +// being silently stripped (which would mask the user's intent to use fast +// mode). +type ErrInvalidOpenAIServiceTier struct { + Value string +} + +func (e *ErrInvalidOpenAIServiceTier) Error() string { + return fmt.Sprintf("invalid service_tier %q: must be one of auto, default, fast, flex, priority, scale", e.Value) +} + +const invalidOpenAIServiceTierValueMaxLen = 64 + +func boundInvalidOpenAIServiceTierValue(raw string) string { + if len(raw) <= invalidOpenAIServiceTierValueMaxLen { + return raw + } + return raw[:invalidOpenAIServiceTierValueMaxLen] + "..." +} + +// ValidateOpenAIServiceTierField validates the service_tier field of a raw +// OpenAI-compatible request body (/v1/responses and /v1/chat/completions). +// +// - absent / null → valid, returns "" (field omitted keeps current behavior) +// - "fast" → normalized to "priority" (the two are equivalent; the canonical +// value is what reaches the OpenAI upstream) +// - "priority" / "flex" / "auto" / "default" / "scale" → valid, returned as-is +// - an explicitly present non-string value, an empty string, or any other +// unknown value → *ErrInvalidOpenAIServiceTier (handler maps to HTTP 400), +// matching OpenAI's enum validation semantics +func ValidateOpenAIServiceTierField(body []byte) (string, error) { + tierResult := gjson.GetBytes(body, "service_tier") + if !tierResult.Exists() || tierResult.Type == gjson.Null { + return "", nil + } + if tierResult.Type != gjson.String { + return "", &ErrInvalidOpenAIServiceTier{Value: ""} + } + raw := strings.TrimSpace(tierResult.String()) + if raw == "" { + return "", &ErrInvalidOpenAIServiceTier{Value: raw} + } + norm := normalizedOpenAIServiceTierValue(raw) + if norm == "" { + return "", &ErrInvalidOpenAIServiceTier{Value: boundInvalidOpenAIServiceTierValue(raw)} + } + return norm, nil +} + // OpenAIFastBlockedError indicates a request was rejected by the OpenAI fast // policy (action=block). Mirrors BetaBlockedError on the Claude side. type OpenAIFastBlockedError struct { diff --git a/backend/internal/service/openai_gateway_responses_chat_fallback.go b/backend/internal/service/openai_gateway_responses_chat_fallback.go index 639d4a6bb3..1b4a00b09e 100644 --- a/backend/internal/service/openai_gateway_responses_chat_fallback.go +++ b/backend/internal/service/openai_gateway_responses_chat_fallback.go @@ -39,7 +39,6 @@ func (s *OpenAIGatewayService) forwardResponsesViaRawChatCompletions( } clientStream := responsesReq.Stream - serviceTier := extractOpenAIServiceTierFromBody(body) // custom 工具(如 codex 的 exec)降级为 function 工具转发,回程需按名字还原为 // custom_tool_call 项,先记下名字集合;tool_search 工具同理,回程还原为 // tool_search_call 项;namespace 子工具(如 MCP 工具)摊平转发,回程按映射还原 @@ -88,9 +87,10 @@ func (s *OpenAIGatewayService) forwardResponsesViaRawChatCompletions( } return nil, err } - if serviceTier == nil { - serviceTier = extractOpenAIServiceTierFromBody(chatBody) - } + // 计费兜底 tier = 最终出站 body(policy filter/force 后)里的 tier;最终值由 + // resolvedOpenAIUpstreamServiceTier 决定(上游回显优先)。filter 删掉字段后 + // 这里取到 nil,不再按原请求 Fast 计费。 + serviceTier := extractOpenAIServiceTierFromBody(chatBody) logger.L().Debug("openai responses: forwarding via raw chat completions", zap.Int64("account_id", account.ID), @@ -160,7 +160,7 @@ func (s *OpenAIGatewayService) bufferChatCompletionsAsResponses( BillingModel: billingModel, UpstreamModel: upstreamModel, ReasoningEffort: reasoningEffort, - ServiceTier: serviceTier, + ServiceTier: resolvedOpenAIUpstreamServiceTier(c, serviceTier), Stream: false, Duration: time.Since(startTime), }, nil @@ -216,7 +216,7 @@ func (s *OpenAIGatewayService) streamChatCompletionsAsResponses( c.Writer.Flush() } - scan := s.scanCCStream(resp, "openai responses chat fallback", requestID, startTime, func(chunk *apicompat.ChatCompletionsChunk) { + scan := s.scanCCStream(c, resp, "openai responses chat fallback", requestID, startTime, func(chunk *apicompat.ChatCompletionsChunk) { events := apicompat.ChatCompletionsChunkToResponsesEvents(chunk, state) s.cacheReasoningItemsFromEvents(events) writeEvents(events) @@ -230,7 +230,7 @@ func (s *OpenAIGatewayService) streamChatCompletionsAsResponses( BillingModel: billingModel, UpstreamModel: upstreamModel, ReasoningEffort: reasoningEffort, - ServiceTier: serviceTier, + ServiceTier: resolvedOpenAIUpstreamServiceTier(c, serviceTier), Stream: true, Duration: time.Since(startTime), FirstTokenMs: scan.FirstTokenMs, @@ -244,7 +244,7 @@ func (s *OpenAIGatewayService) streamChatCompletionsAsResponses( BillingModel: billingModel, UpstreamModel: upstreamModel, ReasoningEffort: reasoningEffort, - ServiceTier: serviceTier, + ServiceTier: resolvedOpenAIUpstreamServiceTier(c, serviceTier), Stream: true, Duration: time.Since(startTime), FirstTokenMs: scan.FirstTokenMs, @@ -274,7 +274,7 @@ func (s *OpenAIGatewayService) streamChatCompletionsAsResponses( BillingModel: billingModel, UpstreamModel: upstreamModel, ReasoningEffort: reasoningEffort, - ServiceTier: serviceTier, + ServiceTier: resolvedOpenAIUpstreamServiceTier(c, serviceTier), Stream: true, Duration: time.Since(startTime), FirstTokenMs: scan.FirstTokenMs, diff --git a/backend/internal/service/openai_gateway_service.go b/backend/internal/service/openai_gateway_service.go index 27d94ea54c..c4d085b024 100644 --- a/backend/internal/service/openai_gateway_service.go +++ b/backend/internal/service/openai_gateway_service.go @@ -253,10 +253,8 @@ type OpenAIForwardResult struct { // UpstreamEndpoint is the actual upstream API path used for this request. // It avoids guessing when one downstream protocol can use multiple upstream endpoints. UpstreamEndpoint string - // ServiceTier records the OpenAI Responses API service tier requested by the - // client, e.g. "priority" / "flex". Nil means the request did not specify a - // recognized tier. Usage recording lowers it to UpstreamResponseServiceTier - // when the upstream reports a cheaper tier (see ResolveBillingServiceTier). + // ServiceTier 优先取上游实际响应回显的 tier;缺失时回退到最终出站 body 的 + // tier。nil 表示两者都无识别 tier。 ServiceTier *string // ReasoningEffort is extracted from request body (reasoning.effort) or derived from model suffix. // Stored for usage records display; nil means not provided / not applicable. diff --git a/backend/internal/service/openai_ws_forwarder_v2.go b/backend/internal/service/openai_ws_forwarder_v2.go index dcd5989c99..06af82c7fb 100644 --- a/backend/internal/service/openai_ws_forwarder_v2.go +++ b/backend/internal/service/openai_ws_forwarder_v2.go @@ -776,7 +776,7 @@ func (s *OpenAIGatewayService) forwardOpenAIWSV2( UpstreamResponseServiceTier: responseModelObserver.ServiceTier(), ImageCount: imageCounter.Count(), ImageOutputSizes: imageCounter.Sizes(), - ServiceTier: extractOpenAIServiceTier(reqBody), + ServiceTier: resolvedOpenAIUpstreamServiceTierFromObserver(responseModelObserver, extractOpenAIServiceTier(reqBody)), ReasoningEffort: extractOpenAIReasoningEffort(reqBody, mappedModel, originalModel), Stream: reqStream, OpenAIWSMode: true, diff --git a/backend/internal/service/openai_ws_forwarder_v2_test.go b/backend/internal/service/openai_ws_forwarder_v2_test.go new file mode 100644 index 0000000000..99bf2004a6 --- /dev/null +++ b/backend/internal/service/openai_ws_forwarder_v2_test.go @@ -0,0 +1,96 @@ +package service + +import ( + "context" + "fmt" + "net/http" + "net/http/httptest" + "testing" + + "github.com/Wei-Shaw/sub2api/internal/config" + "github.com/gin-gonic/gin" + "github.com/stretchr/testify/require" +) + +// HTTP POST /v1/responses → forwardOpenAIWSV2 共用 stream/non-stream 的 +// OpenAIForwardResult:上游 response.completed.service_tier 必须覆盖请求 +// fast/priority,不能只读 reqBody。 +func TestForwardOpenAIWSV2_UpstreamDefaultServiceTierWinsOverRequest(t *testing.T) { + gin.SetMode(gin.TestMode) + + cases := []struct { + name string + requestTier string + stream bool + }{ + {name: "priority_nonstream", requestTier: "priority", stream: false}, + {name: "fast_stream", requestTier: "fast", stream: true}, + } + + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + rec := httptest.NewRecorder() + c, _ := gin.CreateTestContext(rec) + c.Request = httptest.NewRequest(http.MethodPost, "/v1/responses", nil) + c.Request.Header.Set("User-Agent", "unit-test-agent/1.0") + + cfg := &config.Config{} + cfg.Security.URLAllowlist.Enabled = false + cfg.Security.URLAllowlist.AllowInsecureHTTP = true + cfg.Gateway.OpenAIWS.Enabled = true + cfg.Gateway.OpenAIWS.APIKeyEnabled = true + cfg.Gateway.OpenAIWS.ResponsesWebsocketsV2 = true + cfg.Gateway.OpenAIWS.MaxConnsPerAccount = 1 + cfg.Gateway.OpenAIWS.MinIdlePerAccount = 0 + cfg.Gateway.OpenAIWS.MaxIdlePerAccount = 1 + cfg.Gateway.OpenAIWS.QueueLimitPerConn = 8 + cfg.Gateway.OpenAIWS.DialTimeoutSeconds = 3 + cfg.Gateway.OpenAIWS.ReadTimeoutSeconds = 5 + cfg.Gateway.OpenAIWS.WriteTimeoutSeconds = 3 + + captureConn := &openAIWSCaptureConn{ + events: [][]byte{ + []byte(`{"type":"response.completed","response":{"id":"resp_tier_v2","status":"completed","service_tier":"default","usage":{"input_tokens":1,"output_tokens":1}}}`), + }, + } + captureDialer := &openAIWSCaptureDialer{conn: captureConn} + pool := newOpenAIWSConnPool(cfg) + pool.setClientDialerForTest(captureDialer) + + svc := &OpenAIGatewayService{ + cfg: cfg, + httpUpstream: &httpUpstreamRecorder{}, + cache: &stubGatewayCache{}, + openaiWSResolver: NewOpenAIWSProtocolResolver(cfg), + toolCorrector: NewCodexToolCorrector(), + openaiWSPool: pool, + } + account := &Account{ + ID: 5882, + Name: "openai-ws-v2-tier", + Platform: PlatformOpenAI, + Type: AccountTypeAPIKey, + Status: StatusActive, + Schedulable: true, + Concurrency: 1, + Credentials: map[string]any{"api_key": "sk-test"}, + Extra: map[string]any{"responses_websockets_v2_enabled": true}, + } + + body := []byte(fmt.Sprintf( + `{"model":"gpt-5.5","stream":%t,"service_tier":%q,"input":[{"type":"input_text","text":"hi"}]}`, + tc.stream, tc.requestTier, + )) + result, err := svc.Forward(context.Background(), c, account, body) + require.NoError(t, err) + require.NotNil(t, result) + require.True(t, result.OpenAIWSMode, "must take HTTP POST → forwardOpenAIWSV2, not HTTP fallback") + require.Equal(t, tc.stream, result.Stream) + require.Equal(t, "resp_tier_v2", result.RequestID) + require.NotNil(t, result.ServiceTier) + require.Equal(t, "default", *result.ServiceTier) + require.Equal(t, "priority", captureConn.lastWrite["service_tier"], + "outbound WS payload still carries the requested Fast tier") + }) + } +} diff --git a/backend/internal/service/openai_ws_http_bridge.go b/backend/internal/service/openai_ws_http_bridge.go index 962095b407..26a08c1bf1 100644 --- a/backend/internal/service/openai_ws_http_bridge.go +++ b/backend/internal/service/openai_ws_http_bridge.go @@ -514,7 +514,7 @@ func (s *OpenAIGatewayService) proxyOpenAIWSHTTPBridgeTurn( UpstreamResponseModel: responseModelObserver.Model(), UpstreamResponseModelConflict: responseModelObserver.Conflict(), UpstreamResponseServiceTier: responseModelObserver.ServiceTier(), - ServiceTier: extractOpenAIServiceTierFromBody(body), + ServiceTier: resolvedOpenAIUpstreamServiceTierFromObserver(responseModelObserver, extractOpenAIServiceTierFromBody(body)), ReasoningEffort: ApplyThinkingEnabledFallback(extractOpenAIReasoningEffortFromBody(body, mappedModel, originalModel), body, mappedModel), Stream: reqStream, OpenAIWSMode: true, diff --git a/backend/internal/service/openai_ws_http_bridge_test.go b/backend/internal/service/openai_ws_http_bridge_test.go index 7824591e07..884d7faec6 100644 --- a/backend/internal/service/openai_ws_http_bridge_test.go +++ b/backend/internal/service/openai_ws_http_bridge_test.go @@ -44,6 +44,45 @@ func TestPrepareOpenAIWSHTTPBridgeBodyStripsWSFields(t *testing.T) { require.Error(t, err) } +func TestProxyOpenAIWSHTTPBridgeTurn_UpstreamDefaultServiceTierWinsOverRequest(t *testing.T) { + gin.SetMode(gin.TestMode) + + // proxyOpenAIWSHTTPBridgeTurn 是 client WS→HTTP bridge,本身不 canonicalize + // fast→priority;生产入口的归一化在 openai_ws_forwarder_ingress.go 的 fast + // policy。本测试只覆盖局部 observer:canonical 请求 priority 被上游 + // response.completed service_tier=default 覆盖。 + sse := strings.Join([]string{ + `data: {"type":"response.completed","response":{"id":"resp_tier","status":"completed","service_tier":"default","usage":{"input_tokens":1,"output_tokens":1}}}`, + ``, + }, "\n") + upstream := &httpUpstreamRecorder{resp: &http.Response{ + StatusCode: http.StatusOK, + Header: http.Header{"Content-Type": []string{"text/event-stream"}}, + Body: io.NopCloser(strings.NewReader(sse)), + }} + svc := &OpenAIGatewayService{ + cfg: &config.Config{Gateway: config.GatewayConfig{MaxLineSize: defaultMaxLineSize}}, + httpUpstream: upstream, + } + account := &Account{ID: 5881, Platform: PlatformOpenAI, Type: AccountTypeAPIKey, Concurrency: 1} + payload := []byte(`{"type":"response.create","model":"gpt-5.5","stream":true,"service_tier":"priority","input":"hi"}`) + recorder := httptest.NewRecorder() + c, _ := gin.CreateTestContext(recorder) + c.Request = httptest.NewRequest(http.MethodGet, "/v1/responses", nil) + + result, err := svc.proxyOpenAIWSHTTPBridgeTurn( + context.Background(), c, account, "test-token", payload, len(payload), + "gpt-5.5", "", "", "", "", 1, + func([]byte) error { return nil }, + ) + + require.NoError(t, err) + require.NotNil(t, result) + require.Equal(t, "priority", gjson.GetBytes(upstream.lastBody, "service_tier").String()) + require.NotNil(t, result.ServiceTier) + require.Equal(t, "default", *result.ServiceTier) +} + func TestProxyOpenAIWSHTTPBridgeTurnAPIKeyAdaptsClientTools(t *testing.T) { gin.SetMode(gin.TestMode) diff --git a/backend/internal/service/upstream_response_model.go b/backend/internal/service/upstream_response_model.go index eb52a76d1f..64cb048cc0 100644 --- a/backend/internal/service/upstream_response_model.go +++ b/backend/internal/service/upstream_response_model.go @@ -22,8 +22,10 @@ const ( // (see responseModelBillingDeclaration). // // The same observer also records the service tier the upstream reports having -// used (OpenAI service_tier, Anthropic usage.speed). Billing consumes it through -// ResolveBillingServiceTier, which only ever lowers the tier a request asked for. +// used (OpenAI service_tier, Anthropic usage.speed). The billable tier is +// resolved by resolvedOpenAIUpstreamServiceTierFromObserver (upstream echo +// first, outbound body tier as fallback); the upstream ResolveBillingServiceTier +// only-lowers path additionally audits downgrades at usage-record time. type upstreamResponseModelObserver struct { first string terminal string @@ -216,6 +218,33 @@ func observedUpstreamResponseServiceTier(c *gin.Context) string { return upstreamResponseModelObserverFromContext(c).ServiceTier() } +// resolvedOpenAIUpstreamServiceTierFromObserver 返回计费/用量日志实际使用的 +// service tier: +// +// 1. observer 记录到的上游真实回显优先——只有上游实际给了 priority/fast 才按 +// Fast 计费;上游回显 default/flex/auto 等则如实采用并据此计费; +// 2. 上游未回显时,回退到「最终出站 body」里的 tier(经过 fast policy +// filter/force 之后),保证 policy filter 删掉字段后不再按原请求 Fast 计费。 +// +// HTTP→WS 等使用局部 observer 的路径必须把该 observer 传进来,不能只读 +// Gin context——局部 observer 不会自动写入 context。 +func resolvedOpenAIUpstreamServiceTierFromObserver(observer *upstreamResponseModelObserver, outboundBodyTier *string) *string { + if observer != nil { + if tier := strings.TrimSpace(observer.ServiceTier()); tier != "" { + return normalizeOpenAIServiceTier(tier) + } + } + return outboundBodyTier +} + +// resolvedOpenAIUpstreamServiceTier 读取 Gin context 上的 observer 后委托 +// resolvedOpenAIUpstreamServiceTierFromObserver。标准 HTTP 转发路径通过 +// beginUpstreamResponseModelObservation 把 observer 挂到 context;局部 +// observer 路径应直接调用 FromObserver。 +func resolvedOpenAIUpstreamServiceTier(c *gin.Context, outboundBodyTier *string) *string { + return resolvedOpenAIUpstreamServiceTierFromObserver(upstreamResponseModelObserverFromContext(c), outboundBodyTier) +} + func observeOpenAISSEBody(observer *upstreamResponseModelObserver, body string) { if observer == nil || strings.TrimSpace(body) == "" { return diff --git a/backend/resources/model-pricing/model_prices_and_context_window.json b/backend/resources/model-pricing/model_prices_and_context_window.json index 7dc445e3fc..490e768f27 100644 --- a/backend/resources/model-pricing/model_prices_and_context_window.json +++ b/backend/resources/model-pricing/model_prices_and_context_window.json @@ -5162,12 +5162,12 @@ "cache_read_input_token_cost": 5e-07, "cache_read_input_token_cost_above_272k_tokens": 1e-06, "cache_read_input_token_cost_flex": 2.5e-07, - "cache_read_input_token_cost_priority": 1e-06, + "cache_read_input_token_cost_priority": 1.25e-6, "input_cost_per_token": 5e-06, "input_cost_per_token_above_272k_tokens": 1e-05, "input_cost_per_token_batches": 2.5e-06, "input_cost_per_token_flex": 2.5e-06, - "input_cost_per_token_priority": 1e-05, + "input_cost_per_token_priority": 12.5e-6, "litellm_provider": "openai", "max_input_tokens": 1050000, "max_output_tokens": 128000, @@ -5177,7 +5177,7 @@ "output_cost_per_token_above_272k_tokens": 4.5e-05, "output_cost_per_token_batches": 1.5e-05, "output_cost_per_token_flex": 1.5e-05, - "output_cost_per_token_priority": 6e-05, + "output_cost_per_token_priority": 75e-6, "supported_endpoints": [ "/v1/chat/completions", "/v1/batch", @@ -5210,12 +5210,12 @@ "cache_read_input_token_cost": 5e-07, "cache_read_input_token_cost_above_272k_tokens": 1e-06, "cache_read_input_token_cost_flex": 2.5e-07, - "cache_read_input_token_cost_priority": 1e-06, + "cache_read_input_token_cost_priority": 1.25e-6, "input_cost_per_token": 5e-06, "input_cost_per_token_above_272k_tokens": 1e-05, "input_cost_per_token_batches": 2.5e-06, "input_cost_per_token_flex": 2.5e-06, - "input_cost_per_token_priority": 1e-05, + "input_cost_per_token_priority": 12.5e-6, "litellm_provider": "openai", "max_input_tokens": 1050000, "max_output_tokens": 128000, @@ -5225,7 +5225,7 @@ "output_cost_per_token_above_272k_tokens": 4.5e-05, "output_cost_per_token_batches": 1.5e-05, "output_cost_per_token_flex": 1.5e-05, - "output_cost_per_token_priority": 6e-05, + "output_cost_per_token_priority": 75e-6, "supported_endpoints": [ "/v1/chat/completions", "/v1/batch", From c0c3e1cb47318908462adb4695b02b7e12689c31 Mon Sep 17 00:00:00 2001 From: alfadb Date: Mon, 24 Aug 2026 11:18:14 +0800 Subject: [PATCH 140/204] fix(openai): wire local observer service tier in WS ingress; bound handler tests - openai_ws_forwarder_ingress: resolve billing tier from the local upstreamResponseModelObserver (upstream echo first) instead of the raw request payload, matching the HTTP->WS bridge and WS v2 forwarder. - openai_ws_http_bridge_test: add fast-alias + upstream default case proving the local observer's echoed tier wins. - handler tests: keep only invalid service_tier -> 400 (short-circuits at validation); valid/omitted semantics covered by the pure service-level validation tests, avoiding real account selection in tests. --- .../openai_service_tier_validation_test.go | 45 +++---------------- .../service/openai_ws_forwarder_ingress.go | 2 +- .../service/openai_ws_http_bridge_test.go | 37 +++++++++++++++ 3 files changed, 44 insertions(+), 40 deletions(-) diff --git a/backend/internal/handler/openai_service_tier_validation_test.go b/backend/internal/handler/openai_service_tier_validation_test.go index b912f812f8..97da6f682c 100644 --- a/backend/internal/handler/openai_service_tier_validation_test.go +++ b/backend/internal/handler/openai_service_tier_validation_test.go @@ -14,7 +14,12 @@ import ( ) // 非法 service_tier 必须在两个 OpenAI 端点(/v1/responses、/v1/chat/completions) -// 上以 OpenAI 兼容错误结构返回 HTTP 400;合法值(fast/priority)不被拒绝。 +// 上以 OpenAI 兼容错误结构返回 HTTP 400。这些用例在 handler 的 service_tier +// 校验处短路,不会进入账号选择/重试。 +// +// 合法值(fast/priority/flex/auto/default/scale)与省略/null 的接受语义由 +// service 层纯校验函数 TestValidateOpenAIServiceTierField 覆盖,避免 handler +// 测试走入真实账号选择/重试路径。 func newServiceTierHandlerTest(t *testing.T) *OpenAIGatewayHandler { t.Helper() @@ -72,25 +77,6 @@ func TestOpenAIGatewayHandlerResponses_InvalidServiceTierRejected400(t *testing. } } -func TestOpenAIGatewayHandlerResponses_ValidServiceTierNotRejected(t *testing.T) { - for _, tier := range []string{"fast", "priority", "flex"} { - body := `{"model":"gpt-5.5","input":"hi","service_tier":"` + tier + `"}` - rec := runOpenAIHandlerServiceTierTest(t, "/v1/responses", body, func(h *OpenAIGatewayHandler, c *gin.Context) { - h.Responses(c) - }) - require.NotEqual(t, http.StatusBadRequest, rec.Code, "tier=%s must not be rejected as invalid", tier) - require.NotContains(t, rec.Body.String(), "invalid service_tier", "tier=%s", tier) - } -} - -func TestOpenAIGatewayHandlerResponses_ServiceTierOmittedKeepsCurrentBehavior(t *testing.T) { - body := `{"model":"gpt-5.5","input":"hi"}` - rec := runOpenAIHandlerServiceTierTest(t, "/v1/responses", body, func(h *OpenAIGatewayHandler, c *gin.Context) { - h.Responses(c) - }) - require.NotContains(t, rec.Body.String(), "invalid service_tier") -} - func TestOpenAIGatewayHandlerChatCompletions_InvalidServiceTierRejected400(t *testing.T) { for _, body := range []string{ `{"model":"gpt-5.5","messages":[{"role":"user","content":"hi"}],"service_tier":"turbo"}`, @@ -106,22 +92,3 @@ func TestOpenAIGatewayHandlerChatCompletions_InvalidServiceTierRejected400(t *te require.Contains(t, rec.Body.String(), "invalid service_tier", "body=%s", body) } } - -func TestOpenAIGatewayHandlerChatCompletions_ValidServiceTierNotRejected(t *testing.T) { - for _, tier := range []string{"fast", "priority", "auto", "default", "scale", "flex"} { - body := `{"model":"gpt-5.5","messages":[{"role":"user","content":"hi"}],"service_tier":"` + tier + `"}` - rec := runOpenAIHandlerServiceTierTest(t, "/v1/chat/completions", body, func(h *OpenAIGatewayHandler, c *gin.Context) { - h.ChatCompletions(c) - }) - require.NotEqual(t, http.StatusBadRequest, rec.Code, "tier=%q must not be rejected as invalid", tier) - require.NotContains(t, rec.Body.String(), "invalid service_tier", "tier=%q", tier) - } -} - -func TestOpenAIGatewayHandlerChatCompletions_ServiceTierOmittedKeepsCurrentBehavior(t *testing.T) { - body := `{"model":"gpt-5.5","messages":[{"role":"user","content":"hi"}]}` - rec := runOpenAIHandlerServiceTierTest(t, "/v1/chat/completions", body, func(h *OpenAIGatewayHandler, c *gin.Context) { - h.ChatCompletions(c) - }) - require.NotContains(t, rec.Body.String(), "invalid service_tier") -} diff --git a/backend/internal/service/openai_ws_forwarder_ingress.go b/backend/internal/service/openai_ws_forwarder_ingress.go index 124f8d76a7..0265ad6903 100644 --- a/backend/internal/service/openai_ws_forwarder_ingress.go +++ b/backend/internal/service/openai_ws_forwarder_ingress.go @@ -1164,7 +1164,7 @@ func (s *OpenAIGatewayService) ProxyResponsesWebSocketFromClient( UpstreamResponseModel: responseModelObserver.Model(), UpstreamResponseModelConflict: responseModelObserver.Conflict(), UpstreamResponseServiceTier: responseModelObserver.ServiceTier(), - ServiceTier: extractOpenAIServiceTierFromBody(payload), + ServiceTier: resolvedOpenAIUpstreamServiceTierFromObserver(responseModelObserver, extractOpenAIServiceTierFromBody(payload)), ReasoningEffort: ApplyThinkingEnabledFallback(extractOpenAIReasoningEffortFromBody(payload, mappedModel, originalModel), payload, mappedModel), Stream: reqStream, OpenAIWSMode: true, diff --git a/backend/internal/service/openai_ws_http_bridge_test.go b/backend/internal/service/openai_ws_http_bridge_test.go index 884d7faec6..75a93411fe 100644 --- a/backend/internal/service/openai_ws_http_bridge_test.go +++ b/backend/internal/service/openai_ws_http_bridge_test.go @@ -83,6 +83,43 @@ func TestProxyOpenAIWSHTTPBridgeTurn_UpstreamDefaultServiceTierWinsOverRequest(t require.Equal(t, "default", *result.ServiceTier) } +func TestProxyOpenAIWSHTTPBridgeTurn_UpstreamDefaultWinsOverFastAlias(t *testing.T) { + gin.SetMode(gin.TestMode) + + // 客户端别名 fast 同样被上游回显的 default 覆盖:局部 observer 的 + // ServiceTier() 是唯一计费依据,绝不回退到请求侧 fast。 + sse := strings.Join([]string{ + `data: {"type":"response.completed","response":{"id":"resp_tier2","status":"completed","service_tier":"default","usage":{"input_tokens":1,"output_tokens":1}}}`, + ``, + }, "\n") + upstream := &httpUpstreamRecorder{resp: &http.Response{ + StatusCode: http.StatusOK, + Header: http.Header{"Content-Type": []string{"text/event-stream"}}, + Body: io.NopCloser(strings.NewReader(sse)), + }} + svc := &OpenAIGatewayService{ + cfg: &config.Config{Gateway: config.GatewayConfig{MaxLineSize: defaultMaxLineSize}}, + httpUpstream: upstream, + } + account := &Account{ID: 5882, Platform: PlatformOpenAI, Type: AccountTypeAPIKey, Concurrency: 1} + payload := []byte(`{"type":"response.create","model":"gpt-5.5","stream":true,"service_tier":"fast","input":"hi"}`) + recorder := httptest.NewRecorder() + c, _ := gin.CreateTestContext(recorder) + c.Request = httptest.NewRequest(http.MethodGet, "/v1/responses", nil) + + result, err := svc.proxyOpenAIWSHTTPBridgeTurn( + context.Background(), c, account, "test-token", payload, len(payload), + "gpt-5.5", "", "", "", "", 1, + func([]byte) error { return nil }, + ) + + require.NoError(t, err) + require.NotNil(t, result) + require.NotNil(t, result.ServiceTier) + require.Equal(t, "default", *result.ServiceTier, + "local observer's upstream-echoed default must win over the fast alias") +} + func TestProxyOpenAIWSHTTPBridgeTurnAPIKeyAdaptsClientTools(t *testing.T) { gin.SetMode(gin.TestMode) From e457f0fa22f2db3bea19b712ecc904a350141ebb Mon Sep 17 00:00:00 2001 From: alfadb Date: Mon, 24 Aug 2026 11:43:44 +0800 Subject: [PATCH 141/204] fix(openai): adapt service tier observation to upstream constraints - cc_pipeline: observe Chat Completions chunks/bodies as untyped payloads (empty event type) so the upstream-echoed service_tier is trusted, matching the upstream constraint that only terminal events and untyped bodies report the actual processing tier. - tests: add model field to terminal SSE frames (observation only triggers on model-bearing frames) and assert response.created tier echo is ignored. --- .../service/openai_fast_service_tier_test.go | 21 ++++++++++++------- .../service/openai_gateway_cc_pipeline.go | 7 +++++-- .../service/openai_ws_forwarder_v2_test.go | 2 +- .../service/openai_ws_http_bridge_test.go | 4 ++-- 4 files changed, 22 insertions(+), 12 deletions(-) diff --git a/backend/internal/service/openai_fast_service_tier_test.go b/backend/internal/service/openai_fast_service_tier_test.go index 31b500c8ba..57e1b59687 100644 --- a/backend/internal/service/openai_fast_service_tier_test.go +++ b/backend/internal/service/openai_fast_service_tier_test.go @@ -757,17 +757,24 @@ func TestUpstreamResponseModelObserver_ObservesServiceTier(t *testing.T) { t.Parallel() observer := &upstreamResponseModelObserver{} + // 上游约束:非终止且有类型的事件(response.created)回显的是请求档位而非 + // 实际处理档位,忽略。 observer.ObserveOpenAI([]byte(`{"type":"response.created","response":{"model":"gpt-5.5","service_tier":"flex"}}`), "response.created") - require.Equal(t, "flex", observer.ServiceTier()) + require.Empty(t, observer.ServiceTier()) - // terminal 声明优先。 + // terminal 声明(带 model 帧)优先。 observer.ObserveOpenAI([]byte(`{"type":"response.completed","response":{"model":"gpt-5.5","service_tier":"default"}}`), "response.completed") require.Equal(t, "default", observer.ServiceTier()) - // Chat Completions 顶层 service_tier 同样可观察。 + // Chat Completions 顶层 service_tier 按 untyped payload 观察(无 type 字段)。 ccObserver := &upstreamResponseModelObserver{} - ccObserver.ObserveOpenAI([]byte(`{"id":"chatcmpl-1","model":"gpt-5.5","service_tier":"priority","choices":[]}`), "chat.completion") + ccObserver.ObserveOpenAI([]byte(`{"id":"chatcmpl-1","model":"gpt-5.5","service_tier":"priority","choices":[]}`), "") require.Equal(t, "priority", ccObserver.ServiceTier()) + + // 无 model 的帧不触发 tier 观察(上游约束:tier 声明必带 model)。 + modelFree := &upstreamResponseModelObserver{} + modelFree.ObserveOpenAI([]byte(`{"type":"response.completed","response":{"service_tier":"default"}}`), "response.completed") + require.Empty(t, modelFree.ServiceTier()) } func TestResolvedOpenAIUpstreamServiceTier(t *testing.T) { @@ -779,7 +786,7 @@ func TestResolvedOpenAIUpstreamServiceTier(t *testing.T) { gin.SetMode(gin.TestMode) c, _ := gin.CreateTestContext(nil) observer := beginUpstreamResponseModelObservation(c) - observer.ObserveOpenAI([]byte(`{"type":"response.completed","response":{"service_tier":"default"}}`), "response.completed") + observer.ObserveOpenAI([]byte(`{"type":"response.completed","response":{"model":"gpt-5.5","service_tier":"default"}}`), "response.completed") got := resolvedOpenAIUpstreamServiceTier(c, priority) require.NotNil(t, got) @@ -800,7 +807,7 @@ func TestResolvedOpenAIUpstreamServiceTier(t *testing.T) { gin.SetMode(gin.TestMode) c, _ := gin.CreateTestContext(nil) observer := beginUpstreamResponseModelObservation(c) - observer.ObserveOpenAI([]byte(`{"type":"response.completed","response":{"service_tier":"fast"}}`), "response.completed") + observer.ObserveOpenAI([]byte(`{"type":"response.completed","response":{"model":"gpt-5.5","service_tier":"fast"}}`), "response.completed") got := resolvedOpenAIUpstreamServiceTier(c, nil) require.NotNil(t, got) @@ -819,7 +826,7 @@ func TestResolvedOpenAIUpstreamServiceTier(t *testing.T) { t.Run("local observer wins without gin context", func(t *testing.T) { observer := &upstreamResponseModelObserver{} - observer.ObserveOpenAI([]byte(`{"type":"response.completed","response":{"service_tier":"default"}}`), "response.completed") + observer.ObserveOpenAI([]byte(`{"type":"response.completed","response":{"model":"gpt-5.5","service_tier":"default"}}`), "response.completed") got := resolvedOpenAIUpstreamServiceTierFromObserver(observer, priority) require.NotNil(t, got) diff --git a/backend/internal/service/openai_gateway_cc_pipeline.go b/backend/internal/service/openai_gateway_cc_pipeline.go index 8d45c4ff93..b0e98e5926 100644 --- a/backend/internal/service/openai_gateway_cc_pipeline.go +++ b/backend/internal/service/openai_gateway_cc_pipeline.go @@ -274,8 +274,10 @@ func (s *OpenAIGatewayService) scanCCStream( break } // 观察上游 CC chunk 回显的 model / service_tier(计费以回显为准)。 + // CC chunk 无 type 字段,按 untyped payload 观察(上游约束:只有终止 + // 事件与无类型 body 报告实际处理档位)。 if observer := upstreamResponseModelObserverFromContext(c); observer != nil { - observer.ObserveOpenAI([]byte(payload), "chat.completion.chunk") + observer.ObserveOpenAI([]byte(payload), "") } if u := extractCCStreamUsage(payload); u != nil { @@ -337,8 +339,9 @@ func (s *OpenAIGatewayService) readCCUpstreamJSONResponse( return nil, OpenAIUsage{}, fmt.Errorf("parse chat completions response: %w", err) } // 观察上游 CC JSON 回显的 model / service_tier(计费以回显为准)。 + // CC JSON 无 type 字段,按 untyped payload 观察(上游约束)。 if observer := upstreamResponseModelObserverFromContext(c); observer != nil { - observer.ObserveOpenAI(respBody, "chat.completion") + observer.ObserveOpenAI(respBody, "") } usage := OpenAIUsage{} diff --git a/backend/internal/service/openai_ws_forwarder_v2_test.go b/backend/internal/service/openai_ws_forwarder_v2_test.go index 99bf2004a6..7cfd7f9928 100644 --- a/backend/internal/service/openai_ws_forwarder_v2_test.go +++ b/backend/internal/service/openai_ws_forwarder_v2_test.go @@ -50,7 +50,7 @@ func TestForwardOpenAIWSV2_UpstreamDefaultServiceTierWinsOverRequest(t *testing. captureConn := &openAIWSCaptureConn{ events: [][]byte{ - []byte(`{"type":"response.completed","response":{"id":"resp_tier_v2","status":"completed","service_tier":"default","usage":{"input_tokens":1,"output_tokens":1}}}`), + []byte(`{"type":"response.completed","response":{"id":"resp_tier_v2","model":"gpt-5.5","status":"completed","service_tier":"default","usage":{"input_tokens":1,"output_tokens":1}}}`), }, } captureDialer := &openAIWSCaptureDialer{conn: captureConn} diff --git a/backend/internal/service/openai_ws_http_bridge_test.go b/backend/internal/service/openai_ws_http_bridge_test.go index 75a93411fe..59ee0a548e 100644 --- a/backend/internal/service/openai_ws_http_bridge_test.go +++ b/backend/internal/service/openai_ws_http_bridge_test.go @@ -52,7 +52,7 @@ func TestProxyOpenAIWSHTTPBridgeTurn_UpstreamDefaultServiceTierWinsOverRequest(t // policy。本测试只覆盖局部 observer:canonical 请求 priority 被上游 // response.completed service_tier=default 覆盖。 sse := strings.Join([]string{ - `data: {"type":"response.completed","response":{"id":"resp_tier","status":"completed","service_tier":"default","usage":{"input_tokens":1,"output_tokens":1}}}`, + `data: {"type":"response.completed","response":{"id":"resp_tier","model":"gpt-5.5","status":"completed","service_tier":"default","usage":{"input_tokens":1,"output_tokens":1}}}`, ``, }, "\n") upstream := &httpUpstreamRecorder{resp: &http.Response{ @@ -89,7 +89,7 @@ func TestProxyOpenAIWSHTTPBridgeTurn_UpstreamDefaultWinsOverFastAlias(t *testing // 客户端别名 fast 同样被上游回显的 default 覆盖:局部 observer 的 // ServiceTier() 是唯一计费依据,绝不回退到请求侧 fast。 sse := strings.Join([]string{ - `data: {"type":"response.completed","response":{"id":"resp_tier2","status":"completed","service_tier":"default","usage":{"input_tokens":1,"output_tokens":1}}}`, + `data: {"type":"response.completed","response":{"id":"resp_tier2","model":"gpt-5.5","status":"completed","service_tier":"default","usage":{"input_tokens":1,"output_tokens":1}}}`, ``, }, "\n") upstream := &httpUpstreamRecorder{resp: &http.Response{ From 1591477a3e401eb19281099dca9599db4a9cbc27 Mon Sep 17 00:00:00 2001 From: alfadb Date: Mon, 24 Aug 2026 11:58:01 +0800 Subject: [PATCH 142/204] test(apicompat): adapt ChatCompletionsResponseToResponses call to upstream functionTools signature --- .../internal/pkg/apicompat/service_tier_passthrough_test.go | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/backend/internal/pkg/apicompat/service_tier_passthrough_test.go b/backend/internal/pkg/apicompat/service_tier_passthrough_test.go index 58d3c83e07..6c8dd0205c 100644 --- a/backend/internal/pkg/apicompat/service_tier_passthrough_test.go +++ b/backend/internal/pkg/apicompat/service_tier_passthrough_test.go @@ -112,7 +112,7 @@ func TestChatCompletionsResponseToResponses_PreservesServiceTier(t *testing.T) { }}, Usage: &ChatUsage{PromptTokens: 1, CompletionTokens: 1, TotalTokens: 2}, } - resp := ChatCompletionsResponseToResponses(cc, "gpt-5.5", nil, false, nil) + resp := ChatCompletionsResponseToResponses(cc, "gpt-5.5", nil, nil, false, nil) require.Equal(t, "default", resp.ServiceTier) raw, err := json.Marshal(resp) @@ -121,7 +121,7 @@ func TestChatCompletionsResponseToResponses_PreservesServiceTier(t *testing.T) { } func TestChatCompletionsResponseToResponses_NilRespOmitsServiceTier(t *testing.T) { - resp := ChatCompletionsResponseToResponses(nil, "gpt-5.5", nil, false, nil) + resp := ChatCompletionsResponseToResponses(nil, "gpt-5.5", nil, nil, false, nil) require.Empty(t, resp.ServiceTier) } From cbe258fd1284f1286cdc1c3843d9958a6f49dad2 Mon Sep 17 00:00:00 2001 From: feeeei Date: Sun, 23 Aug 2026 20:41:45 +0800 Subject: [PATCH 143/204] =?UTF-8?q?build:=20=E5=8D=87=E7=BA=A7=20Go=201.27?= =?UTF-8?q?.0=EF=BC=8C=E5=90=8C=E6=AD=A5=20CI/Dockerfile=20=E5=B9=B6?= =?UTF-8?q?=E9=80=82=E9=85=8D=20jsonv2=20=E4=B8=8E=20golangci-lint=20v2.13?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - go.mod 1.26.6 → 1.27.0;backend-ci/release/security-scan 的 go version 断言、 三个 Dockerfile 的 golang 镜像、README 徽章与 DEV_GUIDE 同步 - golangci-lint-action v2.9 → v2.13(v2.9 由 go1.26 构建,拒绝 go.mod 1.27 目标); 新规则按最小方式处理:排除 G703/G704 污点分析(网关按配置转发/写文件, 与既有 G304 排除策略一致)、reflect.Ptr → reflect.Pointer、 ResetQuota 恒返回错误的 SA4023 与 OIDC EC JWK 的 SA1019 加 nolint - ent 生成代码按 Go 1.27 默认 jsonv2 引擎重新生成:json.RawMessage 字段 生成为同类型别名 jsontext.Value(group.model_pricing / usage_cleanup_task.filters) - x/net v0.56 在 go1.27 下包装标准库 HTTP/2:ConfigureTransports 经 RegisterProtocol("http/2") 打开 Protocols.HTTP2 而不再写 TLSNextProto, ReadIdleTimeout/PingTimeout 建连时映射为 HTTP2Config.SendPingTimeout/PingTimeout; keepalive 测试改断言 Protocols.HTTP2(),并补真实 HTTP/2 协商用例 --- .github/workflows/backend-ci.yml | 6 +-- .github/workflows/release.yml | 2 +- .github/workflows/security-scan.yml | 2 +- DEV_GUIDE.md | 4 +- Dockerfile | 2 +- README.md | 4 +- README_CN.md | 4 +- README_JA.md | 4 +- backend/.golangci.yml | 4 ++ backend/Dockerfile | 2 +- backend/ent/group.go | 3 +- backend/ent/group_create.go | 10 ++-- backend/ent/group_update.go | 10 ++-- backend/ent/mutation.go | 46 ++++++++--------- backend/ent/usagecleanuptask.go | 3 +- backend/ent/usagecleanuptask_create.go | 10 ++-- backend/ent/usagecleanuptask_update.go | 10 ++-- backend/go.mod | 2 +- .../handler/admin/grok_oauth_handler.go | 4 +- .../handler/admin/setting_handler_update.go | 2 +- backend/internal/handler/auth_oidc_oauth.go | 4 +- .../http_upstream_http2_keepalive_test.go | 49 +++++++++++++++++-- .../usage_log_repo_request_type_test.go | 2 +- deploy/Dockerfile | 2 +- 24 files changed, 120 insertions(+), 71 deletions(-) diff --git a/.github/workflows/backend-ci.yml b/.github/workflows/backend-ci.yml index ece09c5dc1..2bac7259a9 100644 --- a/.github/workflows/backend-ci.yml +++ b/.github/workflows/backend-ci.yml @@ -33,7 +33,7 @@ jobs: cache-dependency-path: backend/go.sum - name: Verify Go version run: | - go version | grep -q 'go1.26.6' + go version | grep -q 'go1.27.0' - name: Unit tests working-directory: backend run: make test-unit @@ -73,10 +73,10 @@ jobs: cache-dependency-path: backend/go.sum - name: Verify Go version run: | - go version | grep -q 'go1.26.6' + go version | grep -q 'go1.27.0' - name: golangci-lint uses: golangci/golangci-lint-action@v9 with: - version: v2.9 + version: v2.13 args: --timeout=30m working-directory: backend diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index 4ecc8a26ba..abdfc9c81d 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -115,7 +115,7 @@ jobs: - name: Verify Go version run: | - go version | grep -q 'go1.26.6' + go version | grep -q 'go1.27.0' # Docker setup for GoReleaser - name: Set up QEMU diff --git a/.github/workflows/security-scan.yml b/.github/workflows/security-scan.yml index 0e68d950ac..97357efde2 100644 --- a/.github/workflows/security-scan.yml +++ b/.github/workflows/security-scan.yml @@ -23,7 +23,7 @@ jobs: cache-dependency-path: backend/go.sum - name: Verify Go version run: | - go version | grep -q 'go1.26.6' + go version | grep -q 'go1.27.0' - name: Run govulncheck working-directory: backend run: | diff --git a/DEV_GUIDE.md b/DEV_GUIDE.md index bf5e8867d6..cb1ffabdb3 100644 --- a/DEV_GUIDE.md +++ b/DEV_GUIDE.md @@ -53,7 +53,7 @@ npm install -g pnpm ### CI 要求 -- Go 版本必须是 **1.26.6**:三个 workflow 都用 `go-version-file: backend/go.mod` 取版本,随后硬断言 `go version | grep -q 'go1.26.6'`。升级 Go 时要同时改 `backend/go.mod`、`backend-ci.yml`(两处)、`release.yml`、`security-scan.yml` 里的这句断言,**以及三个 Dockerfile 里的 Go 构建镜像**(`Dockerfile` / `deploy/Dockerfile` 的 `ARG GOLANG_IMAGE`、`backend/Dockerfile` 的 `FROM golang:`)。前者漏了 CI 会在版本校验步骤直接失败;**后者漏了 CI 不会报,而是等到有人用这些 Dockerfile 构建时才失败**(`go.mod requires go >= X (running Y; GOTOOLCHAIN=local)`)。 +- Go 版本必须是 **1.27.0**:三个 workflow 都用 `go-version-file: backend/go.mod` 取版本,随后硬断言 `go version | grep -q 'go1.27.0'`。升级 Go 时要同时改 `backend/go.mod`、`backend-ci.yml`(两处)、`release.yml`、`security-scan.yml` 里的这句断言,**以及三个 Dockerfile 里的 Go 构建镜像**(`Dockerfile` / `deploy/Dockerfile` 的 `ARG GOLANG_IMAGE`、`backend/Dockerfile` 的 `FROM golang:`)。前者漏了 CI 会在版本校验步骤直接失败;**后者漏了 CI 不会报,而是等到有人用这些 Dockerfile 构建时才失败**(`go.mod requires go >= X (running Y; GOTOOLCHAIN=local)`)。 - 前端使用 `pnpm install --frozen-lockfile`,必须提交 `pnpm-lock.yaml` ### 本地测试命令 @@ -203,7 +203,7 @@ go test -tags=integration ./... **解决**: ```bash cd backend -go generate ./ent # 重新生成 ent 代码 +go generate ./ent # 重新生成 ent 代码(json.RawMessage 字段会生成为同类型的 jsontext.Value,属预期) git add ent/ # 生成的文件也要提交 ``` diff --git a/Dockerfile b/Dockerfile index c7991c5a60..adfa4d4702 100644 --- a/Dockerfile +++ b/Dockerfile @@ -8,7 +8,7 @@ # ============================================================================= ARG NODE_IMAGE=node:24-alpine -ARG GOLANG_IMAGE=golang:1.26.6-alpine +ARG GOLANG_IMAGE=golang:1.27.0-alpine ARG ALPINE_IMAGE=alpine:3.21 ARG POSTGRES_IMAGE=postgres:18-alpine ARG GOPROXY=https://goproxy.cn,direct diff --git a/README.md b/README.md index 50ffe7e430..e5d3221c1c 100644 --- a/README.md +++ b/README.md @@ -4,7 +4,7 @@ # Sub2API -[![Go](https://img.shields.io/badge/Go-1.26.5-00ADD8.svg)](https://golang.org/) +[![Go](https://img.shields.io/badge/Go-1.27.0-00ADD8.svg)](https://golang.org/) [![Vue](https://img.shields.io/badge/Vue-3.4+-4FC08D.svg)](https://vuejs.org/) [![PostgreSQL](https://img.shields.io/badge/PostgreSQL-15+-336791.svg)](https://www.postgresql.org/) [![Redis](https://img.shields.io/badge/Redis-7+-DC382D.svg)](https://redis.io/) @@ -194,7 +194,7 @@ Community projects that extend or integrate with Sub2API: | Component | Technology | |-----------|------------| -| Backend | Go 1.26.5, Gin, Ent | +| Backend | Go 1.27.0, Gin, Ent | | Frontend | Vue 3.4+, Vite 5+, TailwindCSS | | Database | PostgreSQL 15+ | | Cache/Queue | Redis 7+ | diff --git a/README_CN.md b/README_CN.md index 034a3819f5..10329d4d8f 100644 --- a/README_CN.md +++ b/README_CN.md @@ -4,7 +4,7 @@ # Sub2API -[![Go](https://img.shields.io/badge/Go-1.26.5-00ADD8.svg)](https://golang.org/) +[![Go](https://img.shields.io/badge/Go-1.27.0-00ADD8.svg)](https://golang.org/) [![Vue](https://img.shields.io/badge/Vue-3.4+-4FC08D.svg)](https://vuejs.org/) [![PostgreSQL](https://img.shields.io/badge/PostgreSQL-15+-336791.svg)](https://www.postgresql.org/) [![Redis](https://img.shields.io/badge/Redis-7+-DC382D.svg)](https://redis.io/) @@ -196,7 +196,7 @@ Sub2API 是一个 AI API 网关平台,用于分发和管理 AI 产品订阅的 | 组件 | 技术 | |------|------| -| 后端 | Go 1.26.5, Gin, Ent | +| 后端 | Go 1.27.0, Gin, Ent | | 前端 | Vue 3.4+, Vite 5+, TailwindCSS | | 数据库 | PostgreSQL 15+ | | 缓存/队列 | Redis 7+ | diff --git a/README_JA.md b/README_JA.md index 384f9daf67..8727367980 100644 --- a/README_JA.md +++ b/README_JA.md @@ -4,7 +4,7 @@ # Sub2API -[![Go](https://img.shields.io/badge/Go-1.26.5-00ADD8.svg)](https://golang.org/) +[![Go](https://img.shields.io/badge/Go-1.27.0-00ADD8.svg)](https://golang.org/) [![Vue](https://img.shields.io/badge/Vue-3.4+-4FC08D.svg)](https://vuejs.org/) [![PostgreSQL](https://img.shields.io/badge/PostgreSQL-15+-336791.svg)](https://www.postgresql.org/) [![Redis](https://img.shields.io/badge/Redis-7+-DC382D.svg)](https://redis.io/) @@ -195,7 +195,7 @@ Sub2API を拡張・統合するコミュニティプロジェクト: | コンポーネント | 技術 | |-----------|------------| -| バックエンド | Go 1.26.5, Gin, Ent | +| バックエンド | Go 1.27.0, Gin, Ent | | フロントエンド | Vue 3.4+, Vite 5+, TailwindCSS | | データベース | PostgreSQL 15+ | | キャッシュ/キュー | Redis 7+ | diff --git a/backend/.golangci.yml b/backend/.golangci.yml index 92ba391694..a4aed11470 100644 --- a/backend/.golangci.yml +++ b/backend/.golangci.yml @@ -57,6 +57,10 @@ linters: - G304 - G306 - G404 + # G703/G704 是 G304/G107 的污点分析版:网关本职就是按配置转发到上游 URL、按配置写本地文件, + # 污点来源即配置本身,规则不适用。 + - G703 + - G704 severity: high confidence: high errcheck: diff --git a/backend/Dockerfile b/backend/Dockerfile index 1efbd3859d..398d9bdfcf 100644 --- a/backend/Dockerfile +++ b/backend/Dockerfile @@ -1,4 +1,4 @@ -FROM golang:1.26.6-alpine +FROM golang:1.27.0-alpine WORKDIR /app diff --git a/backend/ent/group.go b/backend/ent/group.go index c9795fb58f..8f30c26470 100644 --- a/backend/ent/group.go +++ b/backend/ent/group.go @@ -4,6 +4,7 @@ package ent import ( "encoding/json" + "encoding/json/jsontext" "fmt" "strings" "time" @@ -100,7 +101,7 @@ type Group struct { // 是否按上下文长度应用模型阶梯价格;默认开启以保持官方/渠道长上下文价 LongContextPricingEnabled bool `json:"long_context_pricing_enabled,omitempty"` // 分组逐模型定价;优先级高于渠道和内置定价 - ModelPricing json.RawMessage `json:"model_pricing,omitempty"` + ModelPricing jsontext.Value `json:"model_pricing,omitempty"` // 是否仅允许 Claude Code 客户端 ClaudeCodeOnly bool `json:"claude_code_only,omitempty"` // 非 Claude Code 请求降级使用的分组 ID diff --git a/backend/ent/group_create.go b/backend/ent/group_create.go index 158dca1e40..e5e92ccd3f 100644 --- a/backend/ent/group_create.go +++ b/backend/ent/group_create.go @@ -4,7 +4,7 @@ package ent import ( "context" - "encoding/json" + "encoding/json/jsontext" "errors" "fmt" "time" @@ -575,7 +575,7 @@ func (_c *GroupCreate) SetNillableLongContextPricingEnabled(v *bool) *GroupCreat } // SetModelPricing sets the "model_pricing" field. -func (_c *GroupCreate) SetModelPricing(v json.RawMessage) *GroupCreate { +func (_c *GroupCreate) SetModelPricing(v jsontext.Value) *GroupCreate { _c.mutation.SetModelPricing(v) return _c } @@ -2445,7 +2445,7 @@ func (u *GroupUpsert) UpdateLongContextPricingEnabled() *GroupUpsert { } // SetModelPricing sets the "model_pricing" field. -func (u *GroupUpsert) SetModelPricing(v json.RawMessage) *GroupUpsert { +func (u *GroupUpsert) SetModelPricing(v jsontext.Value) *GroupUpsert { u.Set(group.FieldModelPricing, v) return u } @@ -3615,7 +3615,7 @@ func (u *GroupUpsertOne) UpdateLongContextPricingEnabled() *GroupUpsertOne { } // SetModelPricing sets the "model_pricing" field. -func (u *GroupUpsertOne) SetModelPricing(v json.RawMessage) *GroupUpsertOne { +func (u *GroupUpsertOne) SetModelPricing(v jsontext.Value) *GroupUpsertOne { return u.Update(func(s *GroupUpsert) { s.SetModelPricing(v) }) @@ -5005,7 +5005,7 @@ func (u *GroupUpsertBulk) UpdateLongContextPricingEnabled() *GroupUpsertBulk { } // SetModelPricing sets the "model_pricing" field. -func (u *GroupUpsertBulk) SetModelPricing(v json.RawMessage) *GroupUpsertBulk { +func (u *GroupUpsertBulk) SetModelPricing(v jsontext.Value) *GroupUpsertBulk { return u.Update(func(s *GroupUpsert) { s.SetModelPricing(v) }) diff --git a/backend/ent/group_update.go b/backend/ent/group_update.go index beca0c71f0..41e06b4471 100644 --- a/backend/ent/group_update.go +++ b/backend/ent/group_update.go @@ -4,7 +4,7 @@ package ent import ( "context" - "encoding/json" + "encoding/json/jsontext" "errors" "fmt" "time" @@ -803,13 +803,13 @@ func (_u *GroupUpdate) SetNillableLongContextPricingEnabled(v *bool) *GroupUpdat } // SetModelPricing sets the "model_pricing" field. -func (_u *GroupUpdate) SetModelPricing(v json.RawMessage) *GroupUpdate { +func (_u *GroupUpdate) SetModelPricing(v jsontext.Value) *GroupUpdate { _u.mutation.SetModelPricing(v) return _u } // AppendModelPricing appends value to the "model_pricing" field. -func (_u *GroupUpdate) AppendModelPricing(v json.RawMessage) *GroupUpdate { +func (_u *GroupUpdate) AppendModelPricing(v jsontext.Value) *GroupUpdate { _u.mutation.AppendModelPricing(v) return _u } @@ -2924,13 +2924,13 @@ func (_u *GroupUpdateOne) SetNillableLongContextPricingEnabled(v *bool) *GroupUp } // SetModelPricing sets the "model_pricing" field. -func (_u *GroupUpdateOne) SetModelPricing(v json.RawMessage) *GroupUpdateOne { +func (_u *GroupUpdateOne) SetModelPricing(v jsontext.Value) *GroupUpdateOne { _u.mutation.SetModelPricing(v) return _u } // AppendModelPricing appends value to the "model_pricing" field. -func (_u *GroupUpdateOne) AppendModelPricing(v json.RawMessage) *GroupUpdateOne { +func (_u *GroupUpdateOne) AppendModelPricing(v jsontext.Value) *GroupUpdateOne { _u.mutation.AppendModelPricing(v) return _u } diff --git a/backend/ent/mutation.go b/backend/ent/mutation.go index ddf50a1c42..f777a0a5fb 100644 --- a/backend/ent/mutation.go +++ b/backend/ent/mutation.go @@ -4,7 +4,7 @@ package ent import ( "context" - "encoding/json" + "encoding/json/jsontext" "errors" "fmt" "sync" @@ -22142,8 +22142,8 @@ type GroupMutation struct { audio_stt_price_per_hour *float64 addaudio_stt_price_per_hour *float64 long_context_pricing_enabled *bool - model_pricing *json.RawMessage - appendmodel_pricing json.RawMessage + model_pricing *jsontext.Value + appendmodel_pricing jsontext.Value claude_code_only *bool fallback_group_id *int64 addfallback_group_id *int64 @@ -24404,13 +24404,13 @@ func (m *GroupMutation) ResetLongContextPricingEnabled() { } // SetModelPricing sets the "model_pricing" field. -func (m *GroupMutation) SetModelPricing(jm json.RawMessage) { - m.model_pricing = &jm +func (m *GroupMutation) SetModelPricing(j jsontext.Value) { + m.model_pricing = &j m.appendmodel_pricing = nil } // ModelPricing returns the value of the "model_pricing" field in the mutation. -func (m *GroupMutation) ModelPricing() (r json.RawMessage, exists bool) { +func (m *GroupMutation) ModelPricing() (r jsontext.Value, exists bool) { v := m.model_pricing if v == nil { return @@ -24421,7 +24421,7 @@ func (m *GroupMutation) ModelPricing() (r json.RawMessage, exists bool) { // OldModelPricing returns the old "model_pricing" field's value of the Group entity. // If the Group object wasn't provided to the builder, the object is fetched from the database. // An error is returned if the mutation operation is not UpdateOne, or the database query fails. -func (m *GroupMutation) OldModelPricing(ctx context.Context) (v json.RawMessage, err error) { +func (m *GroupMutation) OldModelPricing(ctx context.Context) (v jsontext.Value, err error) { if !m.op.Is(OpUpdateOne) { return v, errors.New("OldModelPricing is only allowed on UpdateOne operations") } @@ -24435,13 +24435,13 @@ func (m *GroupMutation) OldModelPricing(ctx context.Context) (v json.RawMessage, return oldValue.ModelPricing, nil } -// AppendModelPricing adds jm to the "model_pricing" field. -func (m *GroupMutation) AppendModelPricing(jm json.RawMessage) { - m.appendmodel_pricing = append(m.appendmodel_pricing, jm...) +// AppendModelPricing adds j to the "model_pricing" field. +func (m *GroupMutation) AppendModelPricing(j jsontext.Value) { + m.appendmodel_pricing = append(m.appendmodel_pricing, j...) } // AppendedModelPricing returns the list of values that were appended to the "model_pricing" field in this mutation. -func (m *GroupMutation) AppendedModelPricing() (json.RawMessage, bool) { +func (m *GroupMutation) AppendedModelPricing() (jsontext.Value, bool) { if len(m.appendmodel_pricing) == 0 { return nil, false } @@ -26515,7 +26515,7 @@ func (m *GroupMutation) SetField(name string, value ent.Value) error { m.SetLongContextPricingEnabled(v) return nil case group.FieldModelPricing: - v, ok := value.(json.RawMessage) + v, ok := value.(jsontext.Value) if !ok { return fmt.Errorf("unexpected type %T for field %s", value, name) } @@ -43151,8 +43151,8 @@ type UsageCleanupTaskMutation struct { created_at *time.Time updated_at *time.Time status *string - filters *json.RawMessage - appendfilters json.RawMessage + filters *jsontext.Value + appendfilters jsontext.Value created_by *int64 addcreated_by *int64 deleted_rows *int64 @@ -43376,13 +43376,13 @@ func (m *UsageCleanupTaskMutation) ResetStatus() { } // SetFilters sets the "filters" field. -func (m *UsageCleanupTaskMutation) SetFilters(jm json.RawMessage) { - m.filters = &jm +func (m *UsageCleanupTaskMutation) SetFilters(j jsontext.Value) { + m.filters = &j m.appendfilters = nil } // Filters returns the value of the "filters" field in the mutation. -func (m *UsageCleanupTaskMutation) Filters() (r json.RawMessage, exists bool) { +func (m *UsageCleanupTaskMutation) Filters() (r jsontext.Value, exists bool) { v := m.filters if v == nil { return @@ -43393,7 +43393,7 @@ func (m *UsageCleanupTaskMutation) Filters() (r json.RawMessage, exists bool) { // OldFilters returns the old "filters" field's value of the UsageCleanupTask entity. // If the UsageCleanupTask object wasn't provided to the builder, the object is fetched from the database. // An error is returned if the mutation operation is not UpdateOne, or the database query fails. -func (m *UsageCleanupTaskMutation) OldFilters(ctx context.Context) (v json.RawMessage, err error) { +func (m *UsageCleanupTaskMutation) OldFilters(ctx context.Context) (v jsontext.Value, err error) { if !m.op.Is(OpUpdateOne) { return v, errors.New("OldFilters is only allowed on UpdateOne operations") } @@ -43407,13 +43407,13 @@ func (m *UsageCleanupTaskMutation) OldFilters(ctx context.Context) (v json.RawMe return oldValue.Filters, nil } -// AppendFilters adds jm to the "filters" field. -func (m *UsageCleanupTaskMutation) AppendFilters(jm json.RawMessage) { - m.appendfilters = append(m.appendfilters, jm...) +// AppendFilters adds j to the "filters" field. +func (m *UsageCleanupTaskMutation) AppendFilters(j jsontext.Value) { + m.appendfilters = append(m.appendfilters, j...) } // AppendedFilters returns the list of values that were appended to the "filters" field in this mutation. -func (m *UsageCleanupTaskMutation) AppendedFilters() (json.RawMessage, bool) { +func (m *UsageCleanupTaskMutation) AppendedFilters() (jsontext.Value, bool) { if len(m.appendfilters) == 0 { return nil, false } @@ -43964,7 +43964,7 @@ func (m *UsageCleanupTaskMutation) SetField(name string, value ent.Value) error m.SetStatus(v) return nil case usagecleanuptask.FieldFilters: - v, ok := value.(json.RawMessage) + v, ok := value.(jsontext.Value) if !ok { return fmt.Errorf("unexpected type %T for field %s", value, name) } diff --git a/backend/ent/usagecleanuptask.go b/backend/ent/usagecleanuptask.go index e3a17b5aed..b4dbf0fd34 100644 --- a/backend/ent/usagecleanuptask.go +++ b/backend/ent/usagecleanuptask.go @@ -4,6 +4,7 @@ package ent import ( "encoding/json" + "encoding/json/jsontext" "fmt" "strings" "time" @@ -25,7 +26,7 @@ type UsageCleanupTask struct { // Status holds the value of the "status" field. Status string `json:"status,omitempty"` // Filters holds the value of the "filters" field. - Filters json.RawMessage `json:"filters,omitempty"` + Filters jsontext.Value `json:"filters,omitempty"` // CreatedBy holds the value of the "created_by" field. CreatedBy int64 `json:"created_by,omitempty"` // DeletedRows holds the value of the "deleted_rows" field. diff --git a/backend/ent/usagecleanuptask_create.go b/backend/ent/usagecleanuptask_create.go index 0b1dcff55e..b6dbcb3cc8 100644 --- a/backend/ent/usagecleanuptask_create.go +++ b/backend/ent/usagecleanuptask_create.go @@ -4,7 +4,7 @@ package ent import ( "context" - "encoding/json" + "encoding/json/jsontext" "errors" "fmt" "time" @@ -58,7 +58,7 @@ func (_c *UsageCleanupTaskCreate) SetStatus(v string) *UsageCleanupTaskCreate { } // SetFilters sets the "filters" field. -func (_c *UsageCleanupTaskCreate) SetFilters(v json.RawMessage) *UsageCleanupTaskCreate { +func (_c *UsageCleanupTaskCreate) SetFilters(v jsontext.Value) *UsageCleanupTaskCreate { _c.mutation.SetFilters(v) return _c } @@ -375,7 +375,7 @@ func (u *UsageCleanupTaskUpsert) UpdateStatus() *UsageCleanupTaskUpsert { } // SetFilters sets the "filters" field. -func (u *UsageCleanupTaskUpsert) SetFilters(v json.RawMessage) *UsageCleanupTaskUpsert { +func (u *UsageCleanupTaskUpsert) SetFilters(v jsontext.Value) *UsageCleanupTaskUpsert { u.Set(usagecleanuptask.FieldFilters, v) return u } @@ -592,7 +592,7 @@ func (u *UsageCleanupTaskUpsertOne) UpdateStatus() *UsageCleanupTaskUpsertOne { } // SetFilters sets the "filters" field. -func (u *UsageCleanupTaskUpsertOne) SetFilters(v json.RawMessage) *UsageCleanupTaskUpsertOne { +func (u *UsageCleanupTaskUpsertOne) SetFilters(v jsontext.Value) *UsageCleanupTaskUpsertOne { return u.Update(func(s *UsageCleanupTaskUpsert) { s.SetFilters(v) }) @@ -999,7 +999,7 @@ func (u *UsageCleanupTaskUpsertBulk) UpdateStatus() *UsageCleanupTaskUpsertBulk } // SetFilters sets the "filters" field. -func (u *UsageCleanupTaskUpsertBulk) SetFilters(v json.RawMessage) *UsageCleanupTaskUpsertBulk { +func (u *UsageCleanupTaskUpsertBulk) SetFilters(v jsontext.Value) *UsageCleanupTaskUpsertBulk { return u.Update(func(s *UsageCleanupTaskUpsert) { s.SetFilters(v) }) diff --git a/backend/ent/usagecleanuptask_update.go b/backend/ent/usagecleanuptask_update.go index 604202c679..d233258bbe 100644 --- a/backend/ent/usagecleanuptask_update.go +++ b/backend/ent/usagecleanuptask_update.go @@ -4,7 +4,7 @@ package ent import ( "context" - "encoding/json" + "encoding/json/jsontext" "errors" "fmt" "time" @@ -51,13 +51,13 @@ func (_u *UsageCleanupTaskUpdate) SetNillableStatus(v *string) *UsageCleanupTask } // SetFilters sets the "filters" field. -func (_u *UsageCleanupTaskUpdate) SetFilters(v json.RawMessage) *UsageCleanupTaskUpdate { +func (_u *UsageCleanupTaskUpdate) SetFilters(v jsontext.Value) *UsageCleanupTaskUpdate { _u.mutation.SetFilters(v) return _u } // AppendFilters appends value to the "filters" field. -func (_u *UsageCleanupTaskUpdate) AppendFilters(v json.RawMessage) *UsageCleanupTaskUpdate { +func (_u *UsageCleanupTaskUpdate) AppendFilters(v jsontext.Value) *UsageCleanupTaskUpdate { _u.mutation.AppendFilters(v) return _u } @@ -374,13 +374,13 @@ func (_u *UsageCleanupTaskUpdateOne) SetNillableStatus(v *string) *UsageCleanupT } // SetFilters sets the "filters" field. -func (_u *UsageCleanupTaskUpdateOne) SetFilters(v json.RawMessage) *UsageCleanupTaskUpdateOne { +func (_u *UsageCleanupTaskUpdateOne) SetFilters(v jsontext.Value) *UsageCleanupTaskUpdateOne { _u.mutation.SetFilters(v) return _u } // AppendFilters appends value to the "filters" field. -func (_u *UsageCleanupTaskUpdateOne) AppendFilters(v json.RawMessage) *UsageCleanupTaskUpdateOne { +func (_u *UsageCleanupTaskUpdateOne) AppendFilters(v jsontext.Value) *UsageCleanupTaskUpdateOne { _u.mutation.AppendFilters(v) return _u } diff --git a/backend/go.mod b/backend/go.mod index 2f07042ce5..b86368117f 100644 --- a/backend/go.mod +++ b/backend/go.mod @@ -1,6 +1,6 @@ module github.com/Wei-Shaw/sub2api -go 1.26.6 +go 1.27.0 require ( entgo.io/ent v0.14.5 diff --git a/backend/internal/handler/admin/grok_oauth_handler.go b/backend/internal/handler/admin/grok_oauth_handler.go index 696a24b419..fdab4473de 100644 --- a/backend/internal/handler/admin/grok_oauth_handler.go +++ b/backend/internal/handler/admin/grok_oauth_handler.go @@ -615,8 +615,10 @@ func (h *GrokOAuthHandler) ResetQuota(c *gin.Context) { response.BadRequest(c, "grok quota service is not enabled") return } + // ResetQuota 恒返回 GROK_QUOTA_RESET_UNSUPPORTED(xAI 无 OAuth 配额重置接口),err != nil 恒真为预期。 + //nolint:staticcheck // SA4023 result, err := h.quotaService.ResetQuota(c.Request.Context(), accountID) - if err != nil { + if err != nil { //nolint:staticcheck // SA4023 response.ErrorFrom(c, err) return } diff --git a/backend/internal/handler/admin/setting_handler_update.go b/backend/internal/handler/admin/setting_handler_update.go index 3775c01e11..b2c001fe73 100644 --- a/backend/internal/handler/admin/setting_handler_update.go +++ b/backend/internal/handler/admin/setting_handler_update.go @@ -441,7 +441,7 @@ func buildSettingKeyByJSONName() map[string]string { out := make(map[string]string, t.NumField()) for i := 0; i < t.NumField(); i++ { field := t.Field(i) - if field.Type.Kind() == reflect.Ptr { + if field.Type.Kind() == reflect.Pointer { continue } name, _, _ := strings.Cut(field.Tag.Get("json"), ",") diff --git a/backend/internal/handler/auth_oidc_oauth.go b/backend/internal/handler/auth_oidc_oauth.go index 0367e4cff0..13c26cf18c 100644 --- a/backend/internal/handler/auth_oidc_oauth.go +++ b/backend/internal/handler/auth_oidc_oauth.go @@ -1144,10 +1144,10 @@ func (k oidcJWK) publicKey() (any, error) { if err != nil { return nil, fmt.Errorf("decode ec y: %w", err) } - if !curve.IsOnCurve(x, y) { + if !curve.IsOnCurve(x, y) { //nolint:staticcheck // JWK 以裸坐标给出公钥;替换为 ecdsa.ParseUncompressedPublicKey 需改变点编码,待单独迁移 return nil, errors.New("ec point is not on curve") } - return &ecdsa.PublicKey{Curve: curve, X: x, Y: y}, nil + return &ecdsa.PublicKey{Curve: curve, X: x, Y: y}, nil //nolint:staticcheck // 同上 default: return nil, fmt.Errorf("unsupported jwk kty: %s", k.Kty) } diff --git a/backend/internal/repository/http_upstream_http2_keepalive_test.go b/backend/internal/repository/http_upstream_http2_keepalive_test.go index ead61da3b2..66a30dab0e 100644 --- a/backend/internal/repository/http_upstream_http2_keepalive_test.go +++ b/backend/internal/repository/http_upstream_http2_keepalive_test.go @@ -1,7 +1,10 @@ package repository import ( + "context" + "crypto/x509" "net/http" + "net/http/httptest" "net/url" "testing" "time" @@ -19,6 +22,16 @@ func http2KeepAliveTestPoolSettings() poolSettings { } } +// requireHTTP2Configured 断言 http2 已显式挂到 http.Transport 上。 +// x/net/http2 在 go1.27 && !http2legacy 下是标准库 HTTP/2 的包装:ConfigureTransports 通过 +// Transport.RegisterProtocol("http/2") 注册配置并打开 Protocols.HTTP2(TLSNextProto 不承载 h2 入口), +// ReadIdleTimeout/PingTimeout 在建连时映射为 http.HTTP2Config.SendPingTimeout/PingTimeout。 +func requireHTTP2Configured(t *testing.T, tr *http.Transport, msg string) { + t.Helper() + require.NotNil(t, tr.Protocols, msg) + require.True(t, tr.Protocols.HTTP2(), msg) +} + // Codex/OpenAI 上游改走 HTTP/2 后,池化连接被代理/NAT 静默掐断会成为“死连接”: // 两端都以为连接存活,请求落上去会挂到 TCP 重传超时(分钟级)才失败。Go 的 // http2.Transport 默认 ReadIdleTimeout=0(不发健康 PING),无法检测这种死连接。 @@ -34,7 +47,7 @@ func TestEnableOpenAIHTTP2KeepAlive_EnablesPingHealthCheck(t *testing.T) { require.Positive(t, h2.ReadIdleTimeout, "必须启用空闲 PING 探测以剔除死连接") require.Equal(t, openAIHTTP2ReadIdleTimeout, h2.ReadIdleTimeout) require.Equal(t, openAIHTTP2PingTimeout, h2.PingTimeout, "PING 无响应必须有超时判定") - require.NotNil(t, tr.TLSNextProto["h2"], "http2 必须已挂到底层 http.Transport 上") + requireHTTP2Configured(t, tr, "http2 必须已挂到底层 http.Transport 上") } // openai_h2 模式构建的 Transport 必须带上 H2 PING 健康探测,从源头剔除死连接。 @@ -42,17 +55,45 @@ func TestBuildUpstreamTransport_OpenAIH2_EnablesPingHealthCheck(t *testing.T) { tr, err := buildUpstreamTransport(http2KeepAliveTestPoolSettings(), nil, upstreamProtocolModeOpenAIH2) require.NoError(t, err) require.True(t, tr.ForceAttemptHTTP2, "openai_h2 必须启用 HTTP/2") - require.NotNil(t, tr.TLSNextProto["h2"], "openai_h2 必须显式配置 http2 以启用 ReadIdleTimeout") + requireHTTP2Configured(t, tr, "openai_h2 必须显式配置 http2 以启用 ReadIdleTimeout") } // 非 H2 模式(default/h1)不应因本次改动被误配置:default 走 Go 自动 H2(惰性配置, -// 构建时 TLSNextProto 仍为空),h1 模式显式禁用 H2。避免波及 Claude/Gemini 热路径。 +// 构建时 Protocols/TLSNextProto 仍为空),h1 模式显式禁用 H2。避免波及 Claude/Gemini 热路径。 func TestBuildUpstreamTransport_NonOpenAIH2_NotEagerlyConfigured(t *testing.T) { tr, err := buildUpstreamTransport(http2KeepAliveTestPoolSettings(), nil, upstreamProtocolModeDefault) require.NoError(t, err) + require.Nil(t, tr.Protocols, "default 模式不应在构建期主动配置 http2 keepalive") require.Nil(t, tr.TLSNextProto["h2"], "default 模式不应在构建期主动配置 http2 keepalive") } +// openai_h2 模式构建的 Transport 必须真正以 HTTP/2 与上游通信,PING 健康探测才有载体: +// 自定义 DialContext 下 Go 不会自动启用 H2,全靠 enableOpenAIHTTP2KeepAlive 的显式配置。 +func TestBuildUpstreamTransport_OpenAIH2_NegotiatesHTTP2(t *testing.T) { + srv := httptest.NewUnstartedServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { + w.WriteHeader(http.StatusOK) + })) + srv.EnableHTTP2 = true + srv.StartTLS() + defer srv.Close() + + tr, err := buildUpstreamTransport(http2KeepAliveTestPoolSettings(), nil, upstreamProtocolModeOpenAIH2) + require.NoError(t, err) + defer tr.CloseIdleConnections() + require.NotNil(t, tr.TLSClientConfig) + roots := x509.NewCertPool() + roots.AddCert(srv.Certificate()) + tr.TLSClientConfig.RootCAs = roots + + req, err := http.NewRequestWithContext(context.Background(), http.MethodGet, srv.URL, nil) + require.NoError(t, err) + resp, err := tr.RoundTrip(req) + require.NoError(t, err) + require.NoError(t, resp.Body.Close()) + require.Equal(t, http.StatusOK, resp.StatusCode) + require.Equal(t, 2, resp.ProtoMajor, "openai_h2 必须协商到 HTTP/2") +} + // 死连接在经 HTTP 代理(CONNECT 隧道)时最高发,这是带 proxy 账号的真实生产路径: // 显式 http2 配置须与 Transport.Proxy 同时正确生效,不能相互干扰。 func TestBuildUpstreamTransport_OpenAIH2_WithHTTPProxy_EnablesKeepAlive(t *testing.T) { @@ -62,6 +103,6 @@ func TestBuildUpstreamTransport_OpenAIH2_WithHTTPProxy_EnablesKeepAlive(t *testi tr, err := buildUpstreamTransport(http2KeepAliveTestPoolSettings(), proxyURL, upstreamProtocolModeOpenAIH2) require.NoError(t, err) require.True(t, tr.ForceAttemptHTTP2) - require.NotNil(t, tr.TLSNextProto["h2"], "经代理的 openai_h2 也必须启用 http2 keepalive") + requireHTTP2Configured(t, tr, "经代理的 openai_h2 也必须启用 http2 keepalive") require.NotNil(t, tr.Proxy, "HTTP 代理仍须通过 Transport.Proxy 生效") } diff --git a/backend/internal/repository/usage_log_repo_request_type_test.go b/backend/internal/repository/usage_log_repo_request_type_test.go index c69f374d41..a67c93c345 100644 --- a/backend/internal/repository/usage_log_repo_request_type_test.go +++ b/backend/internal/repository/usage_log_repo_request_type_test.go @@ -780,7 +780,7 @@ func (s usageLogScannerStub) Scan(dest ...any) error { } for i := range dest { dv := reflect.ValueOf(dest[i]) - if dv.Kind() != reflect.Ptr { + if dv.Kind() != reflect.Pointer { return fmt.Errorf("dest[%d] is not pointer", i) } dv.Elem().Set(reflect.ValueOf(s.values[i])) diff --git a/deploy/Dockerfile b/deploy/Dockerfile index 30c7a1a240..ab312c4852 100644 --- a/deploy/Dockerfile +++ b/deploy/Dockerfile @@ -7,7 +7,7 @@ # ============================================================================= ARG NODE_IMAGE=node:24-alpine -ARG GOLANG_IMAGE=golang:1.26.6-alpine +ARG GOLANG_IMAGE=golang:1.27.0-alpine ARG ALPINE_IMAGE=alpine:3.20 ARG GOPROXY=https://goproxy.cn,direct ARG GOSUMDB=sum.golang.google.cn From 3b8177642905323201ddac5ac4e27b1f310ab9b9 Mon Sep 17 00:00:00 2001 From: feeeei Date: Sun, 23 Aug 2026 20:41:45 +0800 Subject: [PATCH 144/204] =?UTF-8?q?fix(test):=20grok=20QueryQuota=20?= =?UTF-8?q?=E7=94=A8=E4=BE=8B=E6=8E=92=E9=99=A4=E5=90=8E=E5=8F=B0=20/v1/mo?= =?UTF-8?q?dels=20=E5=90=8C=E6=AD=A5=E8=AF=B7=E6=B1=82=EF=BC=8C=E6=B6=88?= =?UTF-8?q?=E9=99=A4=E8=AF=B7=E6=B1=82=E8=AE=A1=E6=95=B0=E7=AB=9E=E6=80=81?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit QueryQuota 返回前经 scheduleGrokObservedModelsSync 异步拉取 GET /v1/models, 该请求是否早于 upstream.snapshot() 落到 mock 取决于调度时序,三个精确断言 请求数的用例约 0.5% 偶发多出一条。新增 quotaSnapshot 只返回配额探测链路的 请求,三处断言改用它。 --- .../service/grok_quota_service_test.go | 22 ++++++++++++++++--- 1 file changed, 19 insertions(+), 3 deletions(-) diff --git a/backend/internal/service/grok_quota_service_test.go b/backend/internal/service/grok_quota_service_test.go index 70ee2c8d72..9d94d1b989 100644 --- a/backend/internal/service/grok_quota_service_test.go +++ b/backend/internal/service/grok_quota_service_test.go @@ -301,6 +301,22 @@ func (u *grokHybridUpstream) snapshot() ([]*http.Request, [][]byte) { return requests, bodies } +// quotaSnapshot 返回配额探测链路的请求及请求体,不含 scheduleGrokObservedModelsSync +// 在 QueryQuota 返回后异步发出的 GET /v1/models:该请求是否已落到上游取决于调度时序。 +func (u *grokHybridUpstream) quotaSnapshot() ([]*http.Request, [][]byte) { + requests, bodies := u.snapshot() + quotaRequests := make([]*http.Request, 0, len(requests)) + quotaBodies := make([][]byte, 0, len(bodies)) + for i, req := range requests { + if req.URL.Path == "/v1/models" { + continue + } + quotaRequests = append(quotaRequests, req) + quotaBodies = append(quotaBodies, bodies[i]) + } + return quotaRequests, quotaBodies +} + func (r *grokQuotaProxyRepo) GetByID(_ context.Context, id int64) (*Proxy, error) { r.calls++ return r.proxies[id], nil @@ -741,7 +757,7 @@ func TestGrokQuotaServiceQueryQuotaFreeFallsBackToGrok45(t *testing.T) { require.EqualValues(t, 2_000_000, *result.Snapshot.Tokens.Limit) require.True(t, result.HeadersObserved) - requests, bodies := upstream.snapshot() + requests, bodies := upstream.quotaSnapshot() require.Len(t, requests, 3) responseCalls := 0 for i, req := range requests { @@ -781,7 +797,7 @@ func TestGrokQuotaServiceQueryQuotaPaidBillingSkipsActiveProbe(t *testing.T) { require.Empty(t, result.Model) require.Nil(t, result.LocalUsage24h) - requests, _ := upstream.snapshot() + requests, _ := upstream.quotaSnapshot() require.Len(t, requests, 2) for _, req := range requests { require.Equal(t, "/v1/billing", req.URL.Path) @@ -806,7 +822,7 @@ func TestGrokQuotaServiceQueryQuotaCustomPaidMonthlyLimitSkipsActiveProbe(t *tes require.InDelta(t, monthlyLimit, *result.Billing.MonthlyLimitCents, 1e-9) require.Nil(t, result.Snapshot) - requests, _ := upstream.snapshot() + requests, _ := upstream.quotaSnapshot() require.Len(t, requests, 2) for _, req := range requests { require.Equal(t, "/v1/billing", req.URL.Path) From 73aabc861cacbfc9240bb306ef0aa04511d0164f Mon Sep 17 00:00:00 2001 From: feeeei Date: Mon, 24 Aug 2026 12:19:50 +0800 Subject: [PATCH 145/204] =?UTF-8?q?build:=20=E5=8F=96=E6=B6=88=20gosec=20G?= =?UTF-8?q?703/G704=20=E5=85=A8=E5=B1=80=E6=8E=92=E9=99=A4=EF=BC=8C?= =?UTF-8?q?=E7=94=9F=E4=BA=A7=E4=BB=A3=E7=A0=81=E9=80=90=E7=82=B9=20nolint?= =?UTF-8?q?=E3=80=81=E6=B5=8B=E8=AF=95=E6=96=87=E4=BB=B6=E6=8C=89=E8=B7=AF?= =?UTF-8?q?=E5=BE=84=E8=B1=81=E5=85=8D=EF=BC=9BDEV=5FGUIDE=20=E5=90=8C?= =?UTF-8?q?=E6=AD=A5=20golangci-lint=20v2.13?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- DEV_GUIDE.md | 6 +++--- backend/.golangci.yml | 14 ++++++++++---- backend/internal/pkg/servertiming/http.go | 4 ++-- backend/internal/service/gateway_service.go | 6 +++--- backend/internal/service/pricing_service.go | 2 +- 5 files changed, 19 insertions(+), 13 deletions(-) diff --git a/DEV_GUIDE.md b/DEV_GUIDE.md index cb1ffabdb3..2f440d0f62 100644 --- a/DEV_GUIDE.md +++ b/DEV_GUIDE.md @@ -34,8 +34,8 @@ ### 开发工具 ```bash -# golangci-lint(CI 用 v2.9,本地建议装同一版以免版本差异带来的噪音) -go install github.com/golangci/golangci-lint/v2/cmd/golangci-lint@v2.9 +# golangci-lint(CI 用 v2.13,本地建议装同一版以免版本差异带来的噪音) +go install github.com/golangci/golangci-lint/v2/cmd/golangci-lint@v2.13 # pnpm (前端包管理) npm install -g pnpm @@ -47,7 +47,7 @@ npm install -g pnpm | Workflow | 触发条件 | 检查内容 | |----------|----------|----------| -| **backend-ci.yml** | push, pull_request | 单元测试 + 集成测试 + golangci-lint v2.9 | +| **backend-ci.yml** | push, pull_request | 单元测试 + 集成测试 + golangci-lint v2.13 | | **security-scan.yml** | push, pull_request, 每周一 | govulncheck + gosec + pnpm audit | | **release.yml** | tag `v*` | 构建发布(PR 不触发) | diff --git a/backend/.golangci.yml b/backend/.golangci.yml index a4aed11470..08d1b61f45 100644 --- a/backend/.golangci.yml +++ b/backend/.golangci.yml @@ -57,10 +57,6 @@ linters: - G304 - G306 - G404 - # G703/G704 是 G304/G107 的污点分析版:网关本职就是按配置转发到上游 URL、按配置写本地文件, - # 污点来源即配置本身,规则不适用。 - - G703 - - G704 severity: high confidence: high errcheck: @@ -125,6 +121,16 @@ linters: # Default: true — must be true, ent generates 130K+ lines of code generated-is-used: true + exclusions: + rules: + # G703/G704 污点分析在测试文件中只会命中 httptest mock 与测试者自设的 + # 环境变量路径,不构成攻击面;且该分析跨环境结果不稳定(本地/CI 报告的 + # 位置集合不同),逐点 nolint 无法收敛,故按路径豁免。生产代码不豁免, + # 必须逐点 //nolint:gosec 并写明信任边界。 + - path: '_test\.go$' + linters: [ gosec ] + text: 'G70[34]' + formatters: enable: - gofmt diff --git a/backend/internal/pkg/servertiming/http.go b/backend/internal/pkg/servertiming/http.go index e326e24302..2ad8a04ae1 100644 --- a/backend/internal/pkg/servertiming/http.go +++ b/backend/internal/pkg/servertiming/http.go @@ -53,10 +53,10 @@ func Do(client *http.Client, req *http.Request) (*http.Response, error) { client = http.DefaultClient } if req == nil || !Active(req.Context()) { - return client.Do(req) + return client.Do(req) //nolint:gosec // G704: 通用埋点包装器,不构造 URL;请求由调用方构造,SSRF 信任边界在调用方 } startedAt := time.Now() - response, err := client.Do(req) + response, err := client.Do(req) //nolint:gosec // G704: 同上 RecordDependency(req.Context(), dependencyModule(req), startedAt, time.Now()) return response, err } diff --git a/backend/internal/service/gateway_service.go b/backend/internal/service/gateway_service.go index 0c0140b338..37bab2f97d 100644 --- a/backend/internal/service/gateway_service.go +++ b/backend/internal/service/gateway_service.go @@ -1520,19 +1520,19 @@ func (s *GatewayService) initDebugGatewayBodyFile(path string) { } // 如果 path 指向一个已存在的目录,自动追加默认文件名 - if info, err := os.Stat(path); err == nil && info.IsDir() { + if info, err := os.Stat(path); err == nil && info.IsDir() { //nolint:gosec // G703: path 仅来自启动环境变量 SUB2API_DEBUG_GATEWAY_BODY(运维配置),非请求输入 path = filepath.Join(path, debugGatewayBodyDefaultFilename) } // 确保父目录存在 if dir := filepath.Dir(path); dir != "." { - if err := os.MkdirAll(dir, 0755); err != nil { + if err := os.MkdirAll(dir, 0755); err != nil { //nolint:gosec // G703: 同上 slog.Error("failed to create gateway debug log directory", "dir", dir, "error", err) return } } - f, err := os.OpenFile(path, os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0644) + f, err := os.OpenFile(path, os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0644) //nolint:gosec // G703: 同上 if err != nil { slog.Error("failed to open gateway debug log file", "path", path, "error", err) return diff --git a/backend/internal/service/pricing_service.go b/backend/internal/service/pricing_service.go index f7733ae001..6ae24dd39e 100644 --- a/backend/internal/service/pricing_service.go +++ b/backend/internal/service/pricing_service.go @@ -596,7 +596,7 @@ func (s *PricingService) useFallbackPricing() error { } pricingFile := s.getPricingFilePath() - if err := os.WriteFile(pricingFile, data, 0644); err != nil { + if err := os.WriteFile(pricingFile, data, 0644); err != nil { //nolint:gosec // G703: 路径为配置的数据目录 + 硬编码文件名,非请求输入 logger.LegacyPrintf("service.pricing", "[Pricing] Failed to copy fallback: %v", err) } From 269a4092418b57b36312991fdc35afdc918761eb Mon Sep 17 00:00:00 2001 From: alfadb Date: Mon, 24 Aug 2026 12:37:53 +0800 Subject: [PATCH 146/204] fix(openai): harden flaky alloc guard in tool schema sanitize test --- backend/internal/service/openai_responses_tool_schema_test.go | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/backend/internal/service/openai_responses_tool_schema_test.go b/backend/internal/service/openai_responses_tool_schema_test.go index cf676645e1..faaf9062de 100644 --- a/backend/internal/service/openai_responses_tool_schema_test.go +++ b/backend/internal/service/openai_responses_tool_schema_test.go @@ -587,7 +587,9 @@ func TestSanitizeOpenAIResponsesToolParameterTypes_RewriteCountIndependentOfHits }) // 命中切片扩容是对数级,留出充裕余量;线性写法在这里会是 2000 量级。 - require.Less(t, largeAllocs, smallAllocs+40, + // 干净环境实测 large 约 17 allocs,200 是 10 倍余量,同时容忍 CI 慢 pod 上 + // 包内后台 goroutine(日志/ticker)对进程级 Mallocs 的噪声污染。 + require.Less(t, largeAllocs, 200.0, "分配次数随命中数线性增长,说明退回了逐路径全量重写 (small=%v large=%v)", smallAllocs, largeAllocs) // 同时确认大 body 的结果确实全部修好了。 From 695ebede70e0bed4c8fd4c87b5a426448a08ea4c Mon Sep 17 00:00:00 2001 From: yan9651688 <174289968+yan9651688@users.noreply.github.com> Date: Mon, 24 Aug 2026 13:05:12 +0800 Subject: [PATCH 147/204] fix(billing): normalize CN Anthropic usage tokens --- backend/internal/pkg/apicompat/types.go | 14 + .../service/gateway_anthropic_passthrough.go | 67 +++++ .../service/gateway_forward_as_responses.go | 44 +++- .../service/kimi_anthropic_usage_test.go | 248 ++++++++++++++++++ ...penai_gateway_messages_anthropic_native.go | 6 +- 5 files changed, 369 insertions(+), 10 deletions(-) create mode 100644 backend/internal/service/kimi_anthropic_usage_test.go diff --git a/backend/internal/pkg/apicompat/types.go b/backend/internal/pkg/apicompat/types.go index b96d16b911..ab6df351ef 100644 --- a/backend/internal/pkg/apicompat/types.go +++ b/backend/internal/pkg/apicompat/types.go @@ -155,12 +155,26 @@ func AnthropicStopReasonString(p *string) string { return *p } +// AnthropicPromptTokensDetails holds OpenAI-compatible prompt token details +// occasionally included by Anthropic-compatible providers. +type AnthropicPromptTokensDetails struct { + CachedTokens int `json:"cached_tokens,omitempty"` +} + // AnthropicUsage holds token counts in Anthropic format. type AnthropicUsage struct { InputTokens int `json:"input_tokens"` OutputTokens int `json:"output_tokens"` CacheCreationInputTokens int `json:"cache_creation_input_tokens"` CacheReadInputTokens int `json:"cache_read_input_tokens"` + // Anthropic-compatible providers can also expose their native OpenAI-style + // total/cache fields. Preserve them so callers can normalize provider totals + // into Anthropic's mutually-exclusive billing buckets. + PromptTokens int `json:"prompt_tokens,omitempty"` + CachedTokens int `json:"cached_tokens,omitempty"` + PromptTokensDetails *AnthropicPromptTokensDetails `json:"prompt_tokens_details,omitempty"` + PromptCacheHitTokens *int `json:"prompt_cache_hit_tokens,omitempty"` + PromptCacheMissTokens *int `json:"prompt_cache_miss_tokens,omitempty"` } // --------------------------------------------------------------------------- diff --git a/backend/internal/service/gateway_anthropic_passthrough.go b/backend/internal/service/gateway_anthropic_passthrough.go index 320d800cec..ededd5b830 100644 --- a/backend/internal/service/gateway_anthropic_passthrough.go +++ b/backend/internal/service/gateway_anthropic_passthrough.go @@ -698,6 +698,72 @@ func parseSSEUsagePassthrough(data string, usage *ClaudeUsage) { usage.CacheCreationInputTokens = int(total) } } + + // Kimi's Anthropic-compatible stream uses input_tokens with two meanings: + // message_start reports total prompt input, while message_delta reports only + // uncached input. prompt_tokens remains the total in both events. Normalize + // to ClaudeUsage's mutually-exclusive buckets so downstream billing does not + // subtract cache tokens from an already-uncached value. + usageNode := parsed.Get("usage") + if parsed.Get("type").String() == "message_start" { + usageNode = parsed.Get("message.usage") + } + normalizeAnthropicCompatiblePromptUsage(usageNode, usage) +} + +// normalizeAnthropicCompatiblePromptUsage converts provider-native OpenAI-style +// prompt/cache fields into Claude's mutually-exclusive usage buckets. Native +// Anthropic responses do not expose these aliases and are left alone. +func normalizeAnthropicCompatiblePromptUsage(usageNode gjson.Result, usage *ClaudeUsage) bool { + if usage == nil || !usageNode.Exists() { + return false + } + promptTokens := usageNode.Get("prompt_tokens") + promptCacheHitTokens := usageNode.Get("prompt_cache_hit_tokens") + promptCacheMissTokens := usageNode.Get("prompt_cache_miss_tokens") + if (!promptTokens.Exists() || promptTokens.Int() <= 0) && + !promptCacheHitTokens.Exists() && !promptCacheMissTokens.Exists() { + return false + } + + cacheReadTokens := usage.CacheReadInputTokens + if v := usageNode.Get("cache_read_input_tokens"); v.Exists() { + cacheReadTokens = int(v.Int()) + } + if cacheReadTokens == 0 { + if v := usageNode.Get("cached_tokens"); v.Exists() { + cacheReadTokens = int(v.Int()) + } + } + if cacheReadTokens == 0 { + if v := usageNode.Get("prompt_tokens_details.cached_tokens"); v.Exists() { + cacheReadTokens = int(v.Int()) + } + } + if cacheReadTokens == 0 && promptCacheHitTokens.Exists() { + cacheReadTokens = max(int(promptCacheHitTokens.Int()), 0) + } + + cacheCreationTokens := usage.CacheCreationInputTokens + if v := usageNode.Get("cache_creation_input_tokens"); v.Exists() { + cacheCreationTokens = int(v.Int()) + } + if cacheCreationTokens == 0 { + cc5m := usageNode.Get("cache_creation.ephemeral_5m_input_tokens").Int() + cc1h := usageNode.Get("cache_creation.ephemeral_1h_input_tokens").Int() + if cc5m > 0 || cc1h > 0 { + cacheCreationTokens = int(cc5m + cc1h) + } + } + + if promptCacheMissTokens.Exists() { + usage.InputTokens = max(int(promptCacheMissTokens.Int()), 0) + } else { + usage.InputTokens = max(int(promptTokens.Int())-cacheReadTokens-cacheCreationTokens, 0) + } + usage.CacheReadInputTokens = cacheReadTokens + usage.CacheCreationInputTokens = cacheCreationTokens + return true } func parseClaudeUsageFromResponseBody(body []byte) *ClaudeUsage { @@ -731,6 +797,7 @@ func parseClaudeUsageFromResponseBody(body []byte) *ClaudeUsage { usage.CacheReadInputTokens = int(cached) } } + normalizeAnthropicCompatiblePromptUsage(usageNode, usage) return usage } diff --git a/backend/internal/service/gateway_forward_as_responses.go b/backend/internal/service/gateway_forward_as_responses.go index cdd0197eab..6fcb1b2ed0 100644 --- a/backend/internal/service/gateway_forward_as_responses.go +++ b/backend/internal/service/gateway_forward_as_responses.go @@ -285,18 +285,46 @@ func mergeAnthropicUsage(dst *ClaudeUsage, src apicompat.AnthropicUsage) { if dst == nil { return } - if src.InputTokens > 0 { - dst.InputTokens = src.InputTokens + + // Some Anthropic-compatible providers retain OpenAI-style prompt/cache + // fields. Prefer those authoritative totals or hit/miss buckets over the + // overloaded input_tokens field. This covers Kimi's changing stream + // semantics as well as GLM/DeepSeek cache aliases. + if src.PromptTokens > 0 || src.PromptCacheHitTokens != nil || src.PromptCacheMissTokens != nil { + cacheReadTokens := src.CacheReadInputTokens + if cacheReadTokens == 0 && src.CachedTokens > 0 { + cacheReadTokens = src.CachedTokens + } + if cacheReadTokens == 0 && src.PromptTokensDetails != nil && src.PromptTokensDetails.CachedTokens > 0 { + cacheReadTokens = src.PromptTokensDetails.CachedTokens + } + if cacheReadTokens == 0 && src.PromptCacheHitTokens != nil { + cacheReadTokens = max(*src.PromptCacheHitTokens, 0) + } + + if src.PromptCacheMissTokens != nil { + dst.InputTokens = max(*src.PromptCacheMissTokens, 0) + } else { + dst.InputTokens = max(src.PromptTokens-cacheReadTokens-src.CacheCreationInputTokens, 0) + } + dst.CacheReadInputTokens = cacheReadTokens + dst.CacheCreationInputTokens = src.CacheCreationInputTokens + } else { + if src.InputTokens > 0 { + dst.InputTokens = src.InputTokens + } + if src.CacheReadInputTokens > 0 { + dst.CacheReadInputTokens = src.CacheReadInputTokens + } else if src.CachedTokens > 0 { + dst.CacheReadInputTokens = src.CachedTokens + } + if src.CacheCreationInputTokens > 0 { + dst.CacheCreationInputTokens = src.CacheCreationInputTokens + } } if src.OutputTokens > 0 { dst.OutputTokens = src.OutputTokens } - if src.CacheReadInputTokens > 0 { - dst.CacheReadInputTokens = src.CacheReadInputTokens - } - if src.CacheCreationInputTokens > 0 { - dst.CacheCreationInputTokens = src.CacheCreationInputTokens - } } // parseAnthropicSSEField parses an SSE field line in the form "field:value" or "field: value". diff --git a/backend/internal/service/kimi_anthropic_usage_test.go b/backend/internal/service/kimi_anthropic_usage_test.go new file mode 100644 index 0000000000..458ba9fb39 --- /dev/null +++ b/backend/internal/service/kimi_anthropic_usage_test.go @@ -0,0 +1,248 @@ +package service + +import ( + "encoding/json" + "testing" + + "github.com/Wei-Shaw/sub2api/internal/config" + "github.com/Wei-Shaw/sub2api/internal/pkg/apicompat" + "github.com/stretchr/testify/require" +) + +func TestParseSSEUsagePassthroughNormalizesKimiPromptUsage(t *testing.T) { + usage := &ClaudeUsage{} + + parseSSEUsagePassthrough(`{"type":"message_start","message":{"usage":{"input_tokens":173306,"cache_creation_input_tokens":0,"cache_read_input_tokens":0,"output_tokens":0,"prompt_tokens":173306,"cached_tokens":0}}}`, usage) + require.Equal(t, 173306, usage.InputTokens) + require.Zero(t, usage.CacheReadInputTokens) + + parseSSEUsagePassthrough(`{"type":"message_delta","usage":{"input_tokens":250,"cache_creation_input_tokens":0,"cache_read_input_tokens":173056,"output_tokens":166,"prompt_tokens":173306,"cached_tokens":173056}}`, usage) + require.Equal(t, 250, usage.InputTokens, "Kimi message_delta input_tokens is already the uncached bucket") + require.Equal(t, 173056, usage.CacheReadInputTokens) + require.Equal(t, 166, usage.OutputTokens) +} + +func TestParseSSEUsagePassthroughKimiFullyCachedInputReplacesStartTotal(t *testing.T) { + usage := &ClaudeUsage{} + + parseSSEUsagePassthrough(`{"type":"message_start","message":{"usage":{"input_tokens":173306,"prompt_tokens":173306}}}`, usage) + parseSSEUsagePassthrough(`{"type":"message_delta","usage":{"input_tokens":0,"cache_read_input_tokens":173306,"output_tokens":8,"prompt_tokens":173306,"cached_tokens":173306}}`, usage) + + require.Zero(t, usage.InputTokens, "an explicit zero uncached bucket must not retain message_start's total") + require.Equal(t, 173306, usage.CacheReadInputTokens) +} + +func TestParseClaudeUsageFromResponseBodyNormalizesCNProviderAliases(t *testing.T) { + tests := []struct { + name string + body string + wantInput int + wantCacheRead int + wantOutput int + }{ + { + name: "Kimi top-level cached_tokens", + body: `{"usage":{"input_tokens":173306,"output_tokens":166,"cache_read_input_tokens":173056,"prompt_tokens":173306,"cached_tokens":173056}}`, + wantInput: 250, + wantCacheRead: 173056, + wantOutput: 166, + }, + { + name: "GLM nested prompt cache details", + body: `{"usage":{"input_tokens":1200,"output_tokens":300,"prompt_tokens":1200,"prompt_tokens_details":{"cached_tokens":800}}}`, + wantInput: 400, + wantCacheRead: 800, + wantOutput: 300, + }, + { + name: "DeepSeek prompt cache hit and miss buckets", + body: `{"usage":{"input_tokens":1200,"output_tokens":300,"prompt_cache_hit_tokens":800,"prompt_cache_miss_tokens":400}}`, + wantInput: 400, + wantCacheRead: 800, + wantOutput: 300, + }, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + usage := parseClaudeUsageFromResponseBody([]byte(tt.body)) + require.Equal(t, tt.wantInput, usage.InputTokens) + require.Equal(t, tt.wantCacheRead, usage.CacheReadInputTokens) + require.Equal(t, tt.wantOutput, usage.OutputTokens) + }) + } +} + +func TestParseSSEUsagePassthroughNormalizesGLMAndDeepSeekAliases(t *testing.T) { + tests := []struct { + name string + data string + wantInput int + wantCacheRead int + }{ + { + name: "GLM", + data: `{"type":"message_delta","usage":{"input_tokens":1200,"output_tokens":30,"prompt_tokens":1200,"prompt_tokens_details":{"cached_tokens":800}}}`, + wantInput: 400, + wantCacheRead: 800, + }, + { + name: "DeepSeek", + data: `{"type":"message_delta","usage":{"input_tokens":1200,"output_tokens":30,"prompt_cache_hit_tokens":800,"prompt_cache_miss_tokens":400}}`, + wantInput: 400, + wantCacheRead: 800, + }, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + usage := &ClaudeUsage{} + parseSSEUsagePassthrough(tt.data, usage) + require.Equal(t, tt.wantInput, usage.InputTokens) + require.Equal(t, tt.wantCacheRead, usage.CacheReadInputTokens) + require.Equal(t, 30, usage.OutputTokens) + }) + } +} + +func TestMergeAnthropicUsageNormalizesKimiStreamForOpenAIBilling(t *testing.T) { + var start apicompat.AnthropicStreamEvent + require.NoError(t, json.Unmarshal([]byte(`{"type":"message_start","message":{"usage":{"input_tokens":173306,"prompt_tokens":173306,"cached_tokens":0}}}`), &start)) + var delta apicompat.AnthropicStreamEvent + require.NoError(t, json.Unmarshal([]byte(`{"type":"message_delta","usage":{"input_tokens":250,"cache_read_input_tokens":173056,"output_tokens":166,"prompt_tokens":173306,"cached_tokens":173056}}`), &delta)) + + usage := &ClaudeUsage{} + mergeAnthropicUsage(usage, start.Message.Usage) + mergeAnthropicUsage(usage, *delta.Usage) + require.Equal(t, 250, usage.InputTokens) + require.Equal(t, 173056, usage.CacheReadInputTokens) + + openAIUsage := claudeUsageToOpenAIUsage(usage) + require.Equal(t, 173306, openAIUsage.InputTokens, "OpenAI gateway expects an inclusive input total") + require.Equal(t, 250, openAIUsage.InputTokens-openAIUsage.CacheReadInputTokens-openAIUsage.CacheCreationInputTokens) + require.Equal(t, 166, openAIUsage.OutputTokens) +} + +func TestMergeAnthropicUsageNormalizesGLMAndDeepSeekAliases(t *testing.T) { + tests := []struct { + name string + raw string + }{ + { + name: "GLM", + raw: `{"input_tokens":1200,"output_tokens":30,"prompt_tokens":1200,"prompt_tokens_details":{"cached_tokens":800}}`, + }, + { + name: "DeepSeek", + raw: `{"input_tokens":1200,"output_tokens":30,"prompt_cache_hit_tokens":800,"prompt_cache_miss_tokens":400}`, + }, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + var src apicompat.AnthropicUsage + require.NoError(t, json.Unmarshal([]byte(tt.raw), &src)) + + usage := &ClaudeUsage{} + mergeAnthropicUsage(usage, src) + require.Equal(t, 400, usage.InputTokens) + require.Equal(t, 800, usage.CacheReadInputTokens) + + openAIUsage := claudeUsageToOpenAIUsage(usage) + require.Equal(t, 1200, openAIUsage.InputTokens) + require.Equal(t, 400, openAIUsage.InputTokens-openAIUsage.CacheReadInputTokens-openAIUsage.CacheCreationInputTokens) + }) + } +} + +func TestClaudeUsageToOpenAIUsagePreservesCNProviderNativeAnthropicBuckets(t *testing.T) { + tests := []struct { + name string + usage ClaudeUsage + wantTotal int + wantUncached int + }{ + { + name: "GLM", + usage: ClaudeUsage{ + InputTokens: 2, + OutputTokens: 302, + CacheCreationInputTokens: 733, + CacheReadInputTokens: 376156, + }, + wantTotal: 376891, + wantUncached: 2, + }, + { + name: "DeepSeek", + usage: ClaudeUsage{ + InputTokens: 400, + OutputTokens: 30, + CacheReadInputTokens: 800, + }, + wantTotal: 1200, + wantUncached: 400, + }, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + openAIUsage := claudeUsageToOpenAIUsage(&tt.usage) + require.Equal(t, tt.wantTotal, openAIUsage.InputTokens) + require.Equal(t, tt.wantUncached, openAIUsage.InputTokens-openAIUsage.CacheReadInputTokens-openAIUsage.CacheCreationInputTokens) + require.Equal(t, tt.usage.CacheReadInputTokens, openAIUsage.CacheReadInputTokens) + require.Equal(t, tt.usage.CacheCreationInputTokens, openAIUsage.CacheCreationInputTokens) + }) + } +} + +func TestCNProviderAnthropicUsageBillsUncachedInput(t *testing.T) { + tests := []struct { + name string + model string + body string + wantInput int + }{ + { + name: "Kimi", + model: "k3", + body: `{"usage":{"input_tokens":173306,"output_tokens":166,"prompt_tokens":173306,"cached_tokens":173056}}`, + wantInput: 250, + }, + { + name: "GLM", + model: "glm-5.2", + body: `{"usage":{"input_tokens":1200,"output_tokens":30,"prompt_tokens":1200,"prompt_tokens_details":{"cached_tokens":800}}}`, + wantInput: 400, + }, + { + name: "DeepSeek", + model: "deepseek-v4-flash", + body: `{"usage":{"input_tokens":1200,"output_tokens":30,"prompt_cache_hit_tokens":800,"prompt_cache_miss_tokens":400}}`, + wantInput: 400, + }, + } + + billing := NewBillingService(&config.Config{}, nil) + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + claudeUsage := parseClaudeUsageFromResponseBody([]byte(tt.body)) + openAIUsage := claudeUsageToOpenAIUsage(claudeUsage) + uncachedInput := max(openAIUsage.InputTokens-openAIUsage.CacheReadInputTokens-openAIUsage.CacheCreationInputTokens, 0) + require.Equal(t, tt.wantInput, uncachedInput) + + cost, err := billing.CalculateCost(tt.model, UsageTokens{ + InputTokens: uncachedInput, + OutputTokens: openAIUsage.OutputTokens, + CacheCreationTokens: openAIUsage.CacheCreationInputTokens, + CacheReadTokens: openAIUsage.CacheReadInputTokens, + }, 1) + require.NoError(t, err) + require.Positive(t, cost.InputCost, "uncached input must contribute to the final charge") + + pricing, err := billing.GetModelPricing(tt.model) + require.NoError(t, err) + require.InDelta(t, float64(tt.wantInput)*pricing.InputPricePerToken, cost.InputCost, 1e-12) + }) + } +} diff --git a/backend/internal/service/openai_gateway_messages_anthropic_native.go b/backend/internal/service/openai_gateway_messages_anthropic_native.go index 8f107300b4..a4bc7b9f3a 100644 --- a/backend/internal/service/openai_gateway_messages_anthropic_native.go +++ b/backend/internal/service/openai_gateway_messages_anthropic_native.go @@ -530,13 +530,15 @@ func (s *OpenAIGatewayService) nativeAnthropicStreamResult( } // claudeUsageToOpenAIUsage 把 Anthropic 格式 usage 映射到 OpenAI 网关统一的 -// 用量结构(字段一一对应)。 +// 用量结构。Anthropic 的 input_tokens 不含缓存读写,而 OpenAI 网关内部 +// 约定 InputTokens 是包含缓存明细的总输入;这里必须先合并,RecordUsage +// 才能准确拆回互斥的计费桶。 func claudeUsageToOpenAIUsage(u *ClaudeUsage) OpenAIUsage { if u == nil { return OpenAIUsage{} } return OpenAIUsage{ - InputTokens: u.InputTokens, + InputTokens: u.InputTokens + u.CacheCreationInputTokens + u.CacheReadInputTokens, OutputTokens: u.OutputTokens, CacheCreationInputTokens: u.CacheCreationInputTokens, CacheReadInputTokens: u.CacheReadInputTokens, From 6f972145b72f0631c0ff77aa534df9585dd724e1 Mon Sep 17 00:00:00 2001 From: NellPoi Date: Sun, 23 Aug 2026 23:40:46 +0800 Subject: [PATCH 148/204] =?UTF-8?q?feat:=20=E6=94=AF=E6=8C=81=20OpenAI=20?= =?UTF-8?q?=E9=87=8D=E7=BD=AE=E5=8D=A1=E6=8C=89=E7=94=A8=E9=87=8F=E9=98=88?= =?UTF-8?q?=E5=80=BC=E8=87=AA=E5=8A=A8=E4=BD=BF=E7=94=A8?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- backend/cmd/server/wire.go | 7 + backend/cmd/server/wire_gen.go | 12 +- backend/cmd/server/wire_gen_test.go | 1 + .../handler/admin/openai_oauth_handler.go | 77 +- backend/internal/handler/wire.go | 1 + .../internal/service/account_usage_service.go | 7 +- backend/internal/service/admin_account.go | 15 + .../service/openai_account_scheduler.go | 3 + .../openai_gateway_chat_completions.go | 2 + .../service/openai_gateway_forward.go | 2 + .../service/openai_gateway_messages.go | 2 + .../service/openai_gateway_passthrough.go | 2 + .../service/openai_gateway_scheduling.go | 33 + .../internal/service/openai_gateway_usage.go | 4 +- .../service/openai_quota_auto_reset.go | 809 ++++++++++++++++++ .../service/openai_quota_auto_reset_config.go | 148 ++++ .../service/openai_quota_auto_reset_test.go | 332 +++++++ .../service/openai_quota_reset_credits.go | 24 + .../openai_quota_reset_credits_test.go | 8 +- .../service/openai_quota_reset_workflow.go | 86 ++ .../internal/service/openai_quota_service.go | 40 +- .../service/openai_quota_spark_window_test.go | 26 + backend/internal/service/ratelimit_service.go | 6 + backend/internal/service/wire.go | 24 + .../components/account/EditAccountModal.vue | 82 ++ .../account/OpenAIQuotaResetCell.vue | 62 ++ .../__tests__/EditAccountModal.spec.ts | 72 ++ .../OpenAIQuotaResetCell.spark_shadow.spec.ts | 42 + .../src/i18n/locales/en/admin/accounts.ts | 16 + .../src/i18n/locales/zh/admin/accounts.ts | 16 + frontend/src/types/index.ts | 11 + 31 files changed, 1906 insertions(+), 66 deletions(-) create mode 100644 backend/internal/service/openai_quota_auto_reset.go create mode 100644 backend/internal/service/openai_quota_auto_reset_config.go create mode 100644 backend/internal/service/openai_quota_auto_reset_test.go create mode 100644 backend/internal/service/openai_quota_reset_workflow.go diff --git a/backend/cmd/server/wire.go b/backend/cmd/server/wire.go index a38962ffdb..06720610ba 100644 --- a/backend/cmd/server/wire.go +++ b/backend/cmd/server/wire.go @@ -125,6 +125,7 @@ func provideCleanup( upstreamBillingProbe *service.UpstreamBillingProbeService, ollamaCloudUsage *service.OllamaCloudUsageService, auditLog *service.AuditLogService, + openAIAutoReset *service.OpenAIQuotaAutoResetService, promptAudit *securityaudit.PromptService, pluginManager *service.PluginManager, ) func() { @@ -145,6 +146,12 @@ func provideCleanup( } return nil }}, + {"OpenAIQuotaAutoResetService", func() error { + if openAIAutoReset != nil { + openAIAutoReset.Stop() + } + return nil + }}, {"OpsIngressRejectAggregator", func() error { if opsIngressReject != nil { opsIngressReject.Stop() diff --git a/backend/cmd/server/wire_gen.go b/backend/cmd/server/wire_gen.go index 1300989dc6..9a40b19afc 100644 --- a/backend/cmd/server/wire_gen.go +++ b/backend/cmd/server/wire_gen.go @@ -318,7 +318,8 @@ func initializeApplication(buildInfo handler.BuildInfo) (*Application, error) { batchImageHandler := handler.ProvideBatchImageHandler(batchImagePublicService, batchImageDownloadService, batchImageCleanupService, openAIGatewayHandler) idempotencyCoordinator := service.ProvideIdempotencyCoordinator(idempotencyRepository, configConfig) idempotencyCleanupService := service.ProvideIdempotencyCleanupService(idempotencyRepository, configConfig) - handlers := handler.ProvideHandlers(authHandler, userHandler, apiKeyHandler, usageHandler, redeemHandler, subscriptionHandler, announcementHandler, channelMonitorUserHandler, channelMonitorV2Handler, adminHandlers, gatewayHandler, openAIGatewayHandler, handlerSettingHandler, totpHandler, passkeyHandler, handlerPaymentHandler, paymentWebhookHandler, availableChannelHandler, modelPlazaHandler, asyncImageHandler, batchImageHandler, idempotencyCoordinator, idempotencyCleanupService) + openAIQuotaAutoResetService := service.ProvideOpenAIQuotaAutoResetService(accountRepository, openAIQuotaService, rateLimitService, idempotencyCoordinator, auditLogService, settingService, leaderLockCache) + handlers := handler.ProvideHandlers(authHandler, userHandler, apiKeyHandler, usageHandler, redeemHandler, subscriptionHandler, announcementHandler, channelMonitorUserHandler, channelMonitorV2Handler, adminHandlers, gatewayHandler, openAIGatewayHandler, handlerSettingHandler, totpHandler, passkeyHandler, handlerPaymentHandler, paymentWebhookHandler, availableChannelHandler, modelPlazaHandler, asyncImageHandler, batchImageHandler, idempotencyCoordinator, idempotencyCleanupService, openAIQuotaAutoResetService) jwtAuthMiddleware := middleware.NewJWTAuthMiddleware(authService, userService, settingService, auditLogService) optionalJWTAuthMiddleware := middleware.NewOptionalJWTAuthMiddleware(authService, userService, settingService, auditLogService) adminAuthMiddleware := middleware.NewAdminAuthMiddleware(authService, userService, settingService, auditLogService) @@ -345,7 +346,7 @@ func initializeApplication(buildInfo handler.BuildInfo) (*Application, error) { channelMonitorRunner := service.ProvideChannelMonitorRunner(channelMonitorService, settingService, channelMonitorQuotaFetcher) channelMonitorV2Aggregator := service.ProvideChannelMonitorV2Aggregator(channelMonitorV2Repository, db, settingService) userPlatformQuotaUsageFlusher := service.ProvideUserPlatformQuotaUsageFlusher(configConfig, billingCache, serviceUserPlatformQuotaRepository, timingWheelService) - v := provideCleanup(client, redisClient, opsMetricsCollector, opsAggregationService, opsAlertEvaluatorService, opsCleanupService, opsScheduledReportService, opsSystemLogSink, opsService, opsIngressRejectAggregator, apiKeyService, authCacheInvalidationWorker, schedulerSnapshotService, tokenRefreshService, accountExpiryService, cnProviderBalanceCheckService, openAICodexVersionSyncService, proxyExpiryService, subscriptionExpiryService, usageCleanupService, idempotencyCleanupService, batchImageCleanupService, batchImageWorkerRuntime, pricingService, emailQueueService, billingCacheService, usageRecordWorkerPool, subscriptionService, oAuthService, openAIOAuthService, geminiOAuthService, antigravityOAuthService, grokOAuthService, openAIGatewayService, scheduledTestRunnerService, backupService, paymentOrderExpiryService, channelMonitorRunner, channelMonitorV2Aggregator, userPlatformQuotaUsageFlusher, upstreamBillingProbeService, ollamaCloudUsageService, auditLogService, promptService, pluginManager) + v := provideCleanup(client, redisClient, opsMetricsCollector, opsAggregationService, opsAlertEvaluatorService, opsCleanupService, opsScheduledReportService, opsSystemLogSink, opsService, opsIngressRejectAggregator, apiKeyService, authCacheInvalidationWorker, schedulerSnapshotService, tokenRefreshService, accountExpiryService, cnProviderBalanceCheckService, openAICodexVersionSyncService, proxyExpiryService, subscriptionExpiryService, usageCleanupService, idempotencyCleanupService, batchImageCleanupService, batchImageWorkerRuntime, pricingService, emailQueueService, billingCacheService, usageRecordWorkerPool, subscriptionService, oAuthService, openAIOAuthService, geminiOAuthService, antigravityOAuthService, grokOAuthService, openAIGatewayService, scheduledTestRunnerService, backupService, paymentOrderExpiryService, channelMonitorRunner, channelMonitorV2Aggregator, userPlatformQuotaUsageFlusher, upstreamBillingProbeService, ollamaCloudUsageService, auditLogService, openAIQuotaAutoResetService, promptService, pluginManager) application := &Application{ Server: httpServer, PromptAudit: promptService, @@ -426,6 +427,7 @@ func provideCleanup( upstreamBillingProbe *service.UpstreamBillingProbeService, ollamaCloudUsage *service.OllamaCloudUsageService, auditLog *service.AuditLogService, + openAIAutoReset *service.OpenAIQuotaAutoResetService, promptAudit *securityaudit.PromptService, pluginManager *service.PluginManager, ) func() { @@ -445,6 +447,12 @@ func provideCleanup( } return nil }}, + {"OpenAIQuotaAutoResetService", func() error { + if openAIAutoReset != nil { + openAIAutoReset.Stop() + } + return nil + }}, {"OpsIngressRejectAggregator", func() error { if opsIngressReject != nil { opsIngressReject.Stop() diff --git a/backend/cmd/server/wire_gen_test.go b/backend/cmd/server/wire_gen_test.go index a4858cc363..b3581641ea 100644 --- a/backend/cmd/server/wire_gen_test.go +++ b/backend/cmd/server/wire_gen_test.go @@ -94,6 +94,7 @@ func TestProvideCleanup_WithMinimalDependencies_NoPanic(t *testing.T) { nil, // upstreamBillingProbe nil, // ollamaCloudUsage nil, // auditLog + nil, // openAIAutoReset nil, // promptAudit nil, // pluginManager ) diff --git a/backend/internal/handler/admin/openai_oauth_handler.go b/backend/internal/handler/admin/openai_oauth_handler.go index d7cfc8d2a6..ce83d4bfe8 100644 --- a/backend/internal/handler/admin/openai_oauth_handler.go +++ b/backend/internal/handler/admin/openai_oauth_handler.go @@ -34,12 +34,6 @@ type openAIAccountStateRecoverer interface { RecoverAccountState(ctx context.Context, accountID int64, options service.AccountRecoveryOptions) (*service.SuccessfulTestRecoveryResult, error) } -const ( - openAIQuotaResetWarningCacheRefreshFailed = "reset_credit_cache_refresh_failed" - openAIQuotaResetWarningAccountRecoveryFailed = "account_state_recovery_failed" - openAIQuotaResetWarningAccountRefreshFailed = "account_state_refresh_failed" -) - // openAIQuotaResetPostProcessTimeout bounds the work performed AFTER the // (non-refundable) reset credit has already been consumed upstream. The whole // request must stay comfortably inside the panel HTTP client timeout, otherwise @@ -47,6 +41,14 @@ const ( // it — spending a second credit. const openAIQuotaResetPostProcessTimeout = 8 * time.Second +// 保留 handler 包内的告警码名称,避免共享工作流下沉到 service 后破坏既有测试和包内调用。 +// 实际值统一引用 service 常量,防止手动重置与自动重置的响应码发生漂移。 +const ( + openAIQuotaResetWarningCacheRefreshFailed = service.OpenAIQuotaResetWarningCacheRefreshFailed + openAIQuotaResetWarningAccountRecoveryFailed = service.OpenAIQuotaResetWarningAccountRecoveryFailed + openAIQuotaResetWarningAccountRefreshFailed = service.OpenAIQuotaResetWarningAccountRefreshFailed +) + type openAIQuotaResetResponse struct { service.OpenAIQuotaResetResult Quota *service.OpenAIQuotaUsage `json:"quota,omitempty"` @@ -493,6 +495,7 @@ func (h *OpenAIOAuthHandler) QueryQuota(c *gin.Context) { response.ErrorFrom(c, err) return } + service.NotifyOpenAIAutoResetCredit(accountID) response.Success(c, usage) } @@ -523,6 +526,7 @@ func (h *OpenAIOAuthHandler) RefreshQuota(c *gin.Context) { response.Error(c, http.StatusInternalServerError, "openai quota query returned an empty result") return } + service.NotifyOpenAIAutoResetCredit(accountID) refreshResponse := openAIQuotaRefreshResponse{OpenAIQuotaUsage: *usage} // A failed snapshot write leaves the previous cache intact — report it as a @@ -600,54 +604,19 @@ func (h *OpenAIOAuthHandler) ResetQuota(c *gin.Context) { postCtx, cancelPost := openAIQuotaResetPostProcessContext(c.Request.Context()) defer cancelPost() - // Step 1 — unblocking the account is the whole point of consuming a credit - // (#3672 / #3740), so it runs FIRST and is never gated on the display cache. - // Recovery is DB-only and leaves the manual `schedulable` switch untouched. - if h.rateLimitService == nil { - resetResponse.WarningCode = openAIQuotaResetWarningAccountRecoveryFailed - response.Success(c, resetResponse) - return + postResult := service.RunOpenAIQuotaResetPostProcess( + postCtx, + accountID, + h.quotaService, + h.rateLimitService, + h.adminService.GetAccount, + ) + resetResponse.Quota = postResult.Quota + resetResponse.CacheRefreshed = postResult.CacheRefreshed + resetResponse.AccountStateRecovered = postResult.AccountStateRecovered + resetResponse.WarningCode = postResult.WarningCode + if postResult.Account != nil { + resetResponse.Account = dto.AccountFromService(postResult.Account) } - if _, err := h.rateLimitService.RecoverAccountState(postCtx, accountID, service.AccountRecoveryOptions{ - InvalidateToken: true, - }); err != nil { - // Recovery failures are almost always storage-level; the remaining steps - // share that dependency, so stop here instead of compounding the failure. - slog.Warn("openai_quota_reset_account_recovery_failed", "account_id", accountID, "error", err) - resetResponse.WarningCode = openAIQuotaResetWarningAccountRecoveryFailed - response.Success(c, resetResponse) - return - } - resetResponse.AccountStateRecovered = true - - // Step 2 — refresh the reset-credit display cache. A failure here is reported - // but must not hide the recovered account row produced by step 3. - usage, usageErr := h.quotaService.QueryUsage(postCtx, accountID) - switch { - case usageErr != nil || usage == nil: - slog.Warn("openai_quota_reset_cache_refresh_failed", "account_id", accountID, "error", usageErr) - resetResponse.WarningCode = openAIQuotaResetWarningCacheRefreshFailed - default: - if err := h.quotaService.CacheResetCreditsSnapshot(postCtx, accountID, usage.RateLimitResetCredits); err != nil { - slog.Warn("openai_quota_reset_cache_refresh_failed", "account_id", accountID, "error", err) - resetResponse.WarningCode = openAIQuotaResetWarningCacheRefreshFailed - } else { - resetResponse.Quota = usage - resetResponse.CacheRefreshed = true - } - } - - // Step 3 — hand back the post-recovery account row so the list drops the - // stale rate-limit badge without waiting for the next poll. - account, err := h.adminService.GetAccount(postCtx, accountID) - if err != nil { - slog.Warn("openai_quota_reset_account_refresh_failed", "account_id", accountID, "error", err) - if resetResponse.WarningCode == "" { - resetResponse.WarningCode = openAIQuotaResetWarningAccountRefreshFailed - } - response.Success(c, resetResponse) - return - } - resetResponse.Account = dto.AccountFromService(account) response.Success(c, resetResponse) } diff --git a/backend/internal/handler/wire.go b/backend/internal/handler/wire.go index bd11f72f9a..0e75dc9258 100644 --- a/backend/internal/handler/wire.go +++ b/backend/internal/handler/wire.go @@ -196,6 +196,7 @@ func ProvideHandlers( batchImageHandler *BatchImageHandler, _ *service.IdempotencyCoordinator, _ *service.IdempotencyCleanupService, + _ *service.OpenAIQuotaAutoResetService, ) *Handlers { return &Handlers{ Auth: authHandler, diff --git a/backend/internal/service/account_usage_service.go b/backend/internal/service/account_usage_service.go index 1661eca7c6..f49d3aaa71 100644 --- a/backend/internal/service/account_usage_service.go +++ b/backend/internal/service/account_usage_service.go @@ -729,6 +729,9 @@ func (s *AccountUsageService) getOpenAIUsage(ctx context.Context, account *Accou if updates := buildCodexSparkWindowExtraUpdates(quotaUsage, now); len(updates) > 0 { mergeAccountExtra(account, updates) s.persistOpenAICodexProbeSnapshot(account.ID, updates) + if account.ParentAccountID != nil { + notifyOpenAIAutoReset(*account.ParentAccountID) + } if usage.UpdatedAt == nil { usage.UpdatedAt = &now } @@ -921,7 +924,9 @@ func (s *AccountUsageService) persistOpenAICodexProbeSnapshot(accountID int64, u go func() { updateCtx, updateCancel := context.WithTimeout(context.Background(), 5*time.Second) defer updateCancel() - _ = s.accountRepo.UpdateExtra(updateCtx, accountID, updates) + if err := s.accountRepo.UpdateExtra(updateCtx, accountID, updates); err == nil { + notifyOpenAIAutoReset(accountID) + } }() } diff --git a/backend/internal/service/admin_account.go b/backend/internal/service/admin_account.go index cc09fb808f..ae194f61e1 100644 --- a/backend/internal/service/admin_account.go +++ b/backend/internal/service/admin_account.go @@ -470,6 +470,10 @@ func (s *adminServiceImpl) CreateAccount(ctx context.Context, input *CreateAccou if err != nil { return nil, err } + accountExtra, err = normalizeOpenAIAutoResetCreditExtra(input.Platform, input.Type, false, accountExtra) + if err != nil { + return nil, err + } // 绑定分组 groupIDs := input.GroupIDs @@ -559,6 +563,14 @@ func (s *adminServiceImpl) UpdateAccount(ctx context.Context, id int64, input *U if err != nil { return nil, err } + effectiveType := account.Type + if input.Type != "" { + effectiveType = input.Type + } + normalizedExtra, err = normalizeOpenAIAutoResetCreditExtra(account.Platform, effectiveType, account.IsShadow(), normalizedExtra) + if err != nil { + return nil, err + } } previousProbeIdentity := upstreamBillingProbeIdentity(account) previousOllamaUsageIdentity := ollamaCloudUsageIdentity(account) @@ -649,6 +661,7 @@ func (s *adminServiceImpl) UpdateAccount(ctx context.Context, id int64, input *U OllamaCloudUsageSessionExtraKey, OllamaCloudUsageAutoRefreshExtraKey, OllamaCloudUsageSnapshotExtraKey, + OpenAIAutoResetCreditStateExtraKey, } { if v, ok := account.Extra[key]; ok { normalizedExtra[key] = v @@ -860,6 +873,7 @@ func (s *adminServiceImpl) UpdateAccount(ctx context.Context, id int64, input *U // (如 model_rate_limits / passive_usage_* 等)。 func (s *adminServiceImpl) UpdateAccountExtra(ctx context.Context, id int64, updates map[string]any) error { updates = sanitizedCodexFingerprintExtraUpdates(updates) + updates = stripOpenAIAutoResetCreditManagedExtra(updates, true) delete(updates, UpstreamBillingProbeEnabledExtraKey) delete(updates, UpstreamBillingRateSyncEnabledExtraKey) delete(updates, UpstreamBillingProbeExtraKey) @@ -886,6 +900,7 @@ func (s *adminServiceImpl) UpdateAccountExtra(ctx context.Context, id int64, upd func (s *adminServiceImpl) BulkUpdateAccounts(ctx context.Context, input *BulkUpdateAccountsInput) (*BulkUpdateAccountsResult, error) { // Managed probe/session state may only enter through dedicated typed endpoints. input.Extra = sanitizedCodexFingerprintExtraUpdates(input.Extra) + input.Extra = stripOpenAIAutoResetCreditManagedExtra(input.Extra, true) delete(input.Extra, UpstreamBillingProbeEnabledExtraKey) delete(input.Extra, UpstreamBillingRateSyncEnabledExtraKey) delete(input.Extra, UpstreamBillingProbeExtraKey) diff --git a/backend/internal/service/openai_account_scheduler.go b/backend/internal/service/openai_account_scheduler.go index 2f2fef563b..2986f6abeb 100644 --- a/backend/internal/service/openai_account_scheduler.go +++ b/backend/internal/service/openai_account_scheduler.go @@ -1780,6 +1780,9 @@ func (s *defaultOpenAIAccountScheduler) isAccountRequestCompatibleReason(ctx con // rechecks won't reach healthy accounts that fell outside TopK — manifesting as // "no available accounts" even though healthy ones exist. if paused, decision := shouldAutoPauseOpenAIAccountByQuota(ctx, account); paused { + if decision.reason != "" { + return false, decision.reason + } reason := "quota_auto_pause" if decision.window != "" { reason += "_" + decision.window diff --git a/backend/internal/service/openai_gateway_chat_completions.go b/backend/internal/service/openai_gateway_chat_completions.go index d5639fbe31..e2b947c18b 100644 --- a/backend/internal/service/openai_gateway_chat_completions.go +++ b/backend/internal/service/openai_gateway_chat_completions.go @@ -389,6 +389,8 @@ func (s *OpenAIGatewayService) ForwardAsChatCompletions( if snapshot := ParseCodexRateLimitHeaders(resp.Header); snapshot != nil { s.updateCodexUsageSnapshot(ctx, account.ID, snapshot) } + } else if handleErr == nil && account.IsShadow() && account.ParentAccountID != nil { + notifyOpenAIAutoReset(*account.ParentAccountID) } return result, handleErr diff --git a/backend/internal/service/openai_gateway_forward.go b/backend/internal/service/openai_gateway_forward.go index 0a4aa23416..fda1b2ce21 100644 --- a/backend/internal/service/openai_gateway_forward.go +++ b/backend/internal/service/openai_gateway_forward.go @@ -1164,6 +1164,8 @@ func (s *OpenAIGatewayService) Forward(ctx context.Context, c *gin.Context, acco if snapshot := ParseCodexRateLimitHeaders(resp.Header); snapshot != nil { s.updateCodexUsageSnapshot(ctx, account.ID, snapshot) } + } else if account.IsShadow() && account.ParentAccountID != nil { + notifyOpenAIAutoReset(*account.ParentAccountID) } if usage == nil { diff --git a/backend/internal/service/openai_gateway_messages.go b/backend/internal/service/openai_gateway_messages.go index c9113050e1..71295c9511 100644 --- a/backend/internal/service/openai_gateway_messages.go +++ b/backend/internal/service/openai_gateway_messages.go @@ -508,6 +508,8 @@ func (s *OpenAIGatewayService) ForwardAsAnthropic( if snapshot := ParseCodexRateLimitHeaders(resp.Header); snapshot != nil { s.updateCodexUsageSnapshot(ctx, account.ID, snapshot) } + } else if handleErr == nil && account.IsShadow() && account.ParentAccountID != nil { + notifyOpenAIAutoReset(*account.ParentAccountID) } return result, handleErr diff --git a/backend/internal/service/openai_gateway_passthrough.go b/backend/internal/service/openai_gateway_passthrough.go index c8af9a70a1..8e8039b5b6 100644 --- a/backend/internal/service/openai_gateway_passthrough.go +++ b/backend/internal/service/openai_gateway_passthrough.go @@ -500,6 +500,8 @@ func (s *OpenAIGatewayService) forwardOpenAIPassthrough( if snapshot := ParseCodexRateLimitHeaders(resp.Header); snapshot != nil { s.updateCodexUsageSnapshot(ctx, account.ID, snapshot) } + } else if account.ParentAccountID != nil { + notifyOpenAIAutoReset(*account.ParentAccountID) } if usage == nil { diff --git a/backend/internal/service/openai_gateway_scheduling.go b/backend/internal/service/openai_gateway_scheduling.go index 5a0de5cd65..2a4a4f3d09 100644 --- a/backend/internal/service/openai_gateway_scheduling.go +++ b/backend/internal/service/openai_gateway_scheduling.go @@ -450,6 +450,7 @@ type openAIQuotaAutoPauseDecision struct { window string threshold float64 utilization float64 + reason string } func shouldAutoPauseGrokAccountByQuota(account *Account) (bool, openAIQuotaAutoPauseDecision) { @@ -520,6 +521,38 @@ func shouldAutoPauseOpenAIAccountByQuota(ctx context.Context, account *Account) if account == nil || !account.IsOpenAI() { return false, openAIQuotaAutoPauseDecision{} } + // 自动用卡有独立阈值:达到消费阈值时必须先退出调度;仅达到普通暂停阈值时, + // 只有新鲜状态明确存在可用卡才继续放行到消费阈值。 + if config := ResolveOpenAIAutoResetCreditConfig(account); config.Enabled { + now := time.Now() + utilization5h, has5h := resolveOpenAIQuotaUtilization(account.Extra, "5h", now) + utilization7d, has7d := resolveOpenAIQuotaUtilization(account.Extra, "7d", now) + if has5h && utilization5h >= config.Threshold5h { + notifyOpenAIAutoReset(account.ID) + return true, openAIQuotaAutoPauseDecision{window: "5h", threshold: config.Threshold5h, utilization: utilization5h, reason: "quota_auto_reset_pending_5h"} + } + if has7d && utilization7d >= config.Threshold7d { + notifyOpenAIAutoReset(account.ID) + return true, openAIQuotaAutoPauseDecision{window: "7d", threshold: config.Threshold7d, utilization: utilization7d, reason: "quota_auto_reset_pending_7d"} + } + + disabled5h := resolveAccountExtraBool(account.Extra, "auto_pause_5h_disabled") + disabled7d := resolveAccountExtraBool(account.Extra, "auto_pause_7d_disabled") + pause5h, pause7d := resolveOpenAIQuotaAutoPauseThresholds(ctx, account) + pauseReached5h := !disabled5h && pause5h > 0 && has5h && utilization5h >= pause5h + pauseReached7d := !disabled7d && pause7d > 0 && has7d && utilization7d >= pause7d + if pauseReached5h || pauseReached7d { + state := openAIAutoResetStateFromExtra(account.Extra) + if state != nil && state.Status == OpenAIAutoResetStatusAvailable && state.AvailableCount > 0 && !openAIAutoResetStateStale(state, now) { + return false, openAIQuotaAutoPauseDecision{} + } + notifyOpenAIAutoReset(account.ID) + if pauseReached5h { + return true, openAIQuotaAutoPauseDecision{window: "5h", threshold: pause5h, utilization: utilization5h, reason: "quota_auto_reset_credit_check_5h"} + } + return true, openAIQuotaAutoPauseDecision{window: "7d", threshold: pause7d, utilization: utilization7d, reason: "quota_auto_reset_credit_check_7d"} + } + } // Per-account explicit-disable flags must take precedence over the global default. // Without these, leaving the account threshold blank means "use global default", // so an admin has no way to exempt a single account from auto-pause once a global diff --git a/backend/internal/service/openai_gateway_usage.go b/backend/internal/service/openai_gateway_usage.go index 25af28973a..7489456bb8 100644 --- a/backend/internal/service/openai_gateway_usage.go +++ b/backend/internal/service/openai_gateway_usage.go @@ -1075,7 +1075,9 @@ func (s *OpenAIGatewayService) updateCodexUsageSnapshot(ctx context.Context, acc go func() { updateCtx, cancel := context.WithTimeout(context.Background(), 5*time.Second) defer cancel() - _ = s.accountRepo.UpdateExtra(updateCtx, accountID, updates) + if err := s.accountRepo.UpdateExtra(updateCtx, accountID, updates); err == nil { + notifyOpenAIAutoReset(accountID) + } }() } diff --git a/backend/internal/service/openai_quota_auto_reset.go b/backend/internal/service/openai_quota_auto_reset.go new file mode 100644 index 0000000000..aafc5991d7 --- /dev/null +++ b/backend/internal/service/openai_quota_auto_reset.go @@ -0,0 +1,809 @@ +package service + +import ( + "context" + "crypto/sha256" + "encoding/hex" + "encoding/json" + "errors" + "fmt" + "log/slog" + "net/http" + "sort" + "strings" + "sync" + "time" + + infraerrors "github.com/Wei-Shaw/sub2api/internal/pkg/errors" + "github.com/Wei-Shaw/sub2api/internal/pkg/pagination" + "github.com/google/uuid" +) + +const ( + openAIAutoResetScanInterval = time.Minute + openAIAutoResetSnapshotTTL = openAIProbeCacheTTL + openAIAutoResetBatchSize = 100 + openAIAutoResetWorkerCount = 4 + openAIAutoResetQueueCapacity = 1024 + openAIAutoResetAttemptTTL = 8 * 24 * time.Hour + openAIAutoResetLeaderLockKey = "jobs:openai-auto-reset-credit" +) + +const ( + OpenAIAutoResetStatusChecking = "checking" + OpenAIAutoResetStatusAvailable = "available" + OpenAIAutoResetStatusResetting = "resetting" + OpenAIAutoResetStatusSuccess = "success" + OpenAIAutoResetStatusNoCredit = "no_credit" + OpenAIAutoResetStatusFailed = "failed" +) + +// OpenAIAutoResetCreditState 是可返回管理端的脱敏运行态。Attempt* 仅保存不可逆 +// 指纹,用于重启后拒绝切换到另一张卡;不会保存卡 ID 或兑换 ID。 +type OpenAIAutoResetCreditState struct { + Status string `json:"status"` + TriggerWindow string `json:"trigger_window,omitempty"` + AvailableCount int `json:"available_count"` + CheckedAt string `json:"checked_at,omitempty"` + LastResultAt string `json:"last_result_at,omitempty"` + ErrorCode string `json:"error_code,omitempty"` + AttemptCycleHash string `json:"attempt_cycle_hash,omitempty"` + AttemptCreditHash string `json:"attempt_credit_hash,omitempty"` +} + +type openAIAutoResetQuota interface { + QueryUsage(ctx context.Context, accountID int64) (*OpenAIQuotaUsage, error) + CacheResetCreditsSnapshot(ctx context.Context, accountID int64, credits *OpenAIRateLimitResetCredits) error + ResetCreditTargeted(ctx context.Context, accountID int64, creditID, redeemRequestID string) (*OpenAIQuotaResetResult, error) +} + +type openAIAutoResetContextKey struct{} + +func withOpenAIAutoResetContext(ctx context.Context) context.Context { + if ctx == nil { + ctx = context.Background() + } + return context.WithValue(ctx, openAIAutoResetContextKey{}, true) +} + +func isOpenAIAutoResetContext(ctx context.Context) bool { + if ctx == nil { + return false + } + value, _ := ctx.Value(openAIAutoResetContextKey{}).(bool) + return value +} + +type openAIAutoResetRecovery interface { + RecoverAccountState(ctx context.Context, accountID int64, options AccountRecoveryOptions) (*SuccessfulTestRecoveryResult, error) +} + +// OpenAIQuotaAutoResetService 通过小型去重队列承接实时信号,并用分钟扫描补偿 +// 重启、漏事件和多实例读取;真正消费仍由 PostgreSQL 幂等记录串行化。 +type OpenAIQuotaAutoResetService struct { + accountRepo AccountRepository + quota openAIAutoResetQuota + recoverer openAIAutoResetRecovery + idempotency *IdempotencyCoordinator + audit *AuditLogService + settings *SettingService + leaderLock LeaderLockCache + + ctx context.Context + cancel context.CancelFunc + queue chan int64 + pending sync.Map + owner string + start sync.Once + stop sync.Once + wg sync.WaitGroup +} + +func NewOpenAIQuotaAutoResetService( + accountRepo AccountRepository, + quota openAIAutoResetQuota, + recoverer openAIAutoResetRecovery, + idempotency *IdempotencyCoordinator, + audit *AuditLogService, + settings *SettingService, + leaderLock LeaderLockCache, +) *OpenAIQuotaAutoResetService { + ctx, cancel := context.WithCancel(context.Background()) + return &OpenAIQuotaAutoResetService{ + accountRepo: accountRepo, + quota: quota, + recoverer: recoverer, + idempotency: idempotency, + audit: audit, + settings: settings, + leaderLock: leaderLock, + ctx: ctx, + cancel: cancel, + queue: make(chan int64, openAIAutoResetQueueCapacity), + owner: uuid.NewString(), + } +} + +func (s *OpenAIQuotaAutoResetService) Start() { + if s == nil || s.accountRepo == nil || s.quota == nil || s.idempotency == nil { + return + } + s.start.Do(func() { + setOpenAIAutoResetNotifier(s) + for range openAIAutoResetWorkerCount { + s.wg.Add(1) + go s.runWorker() + } + s.wg.Add(1) + go s.runScanner() + }) +} + +func (s *OpenAIQuotaAutoResetService) Stop() { + if s == nil { + return + } + s.stop.Do(func() { + clearOpenAIAutoResetNotifier(s) + s.cancel() + s.wg.Wait() + }) +} + +// Notify 是请求热路径的非阻塞入口。同一账号尚在队列时只保留一个任务;队列 +// 满时丢弃本次信号,分钟扫描仍会补偿,因此不会反向拖慢网关请求。 +func (s *OpenAIQuotaAutoResetService) Notify(accountID int64) { + if s == nil || accountID <= 0 { + return + } + if _, loaded := s.pending.LoadOrStore(accountID, struct{}{}); loaded { + return + } + select { + case <-s.ctx.Done(): + s.pending.Delete(accountID) + case s.queue <- accountID: + default: + s.pending.Delete(accountID) + slog.Warn("openai_auto_reset_queue_full", "account_id", accountID) + } +} + +func (s *OpenAIQuotaAutoResetService) runWorker() { + defer s.wg.Done() + for { + select { + case <-s.ctx.Done(): + return + case accountID := <-s.queue: + ctx, cancel := context.WithTimeout(s.ctx, 50*time.Second) + if err := s.evaluateAccount(ctx, accountID); err != nil && !errors.Is(err, context.Canceled) { + slog.Warn("openai_auto_reset_evaluate_failed", "account_id", accountID, "error_code", infraerrors.Reason(err)) + } + cancel() + s.pending.Delete(accountID) + } + } +} + +func (s *OpenAIQuotaAutoResetService) runScanner() { + defer s.wg.Done() + timer := time.NewTimer(2 * time.Second) + defer timer.Stop() + select { + case <-s.ctx.Done(): + return + case <-timer.C: + s.scanEnabledAccounts(s.ctx) + } + ticker := time.NewTicker(openAIAutoResetScanInterval) + defer ticker.Stop() + for { + select { + case <-s.ctx.Done(): + return + case <-ticker.C: + s.scanEnabledAccounts(s.ctx) + } + } +} + +func (s *OpenAIQuotaAutoResetService) scanEnabledAccounts(ctx context.Context) { + release, scan := s.tryAcquireScanLock(ctx) + if !scan { + return + } + if release != nil { + defer release() + } + for page := 1; ; page++ { + accounts, pageInfo, err := s.accountRepo.ListWithFilters(ctx, pagination.PaginationParams{ + Page: page, PageSize: openAIAutoResetBatchSize, + }, PlatformOpenAI, AccountTypeOAuth, StatusActive, "", 0, "") + if err != nil { + slog.Warn("openai_auto_reset_scan_failed", "page", page, "error", err) + return + } + for i := range accounts { + account := &accounts[i] + if account.Schedulable && ResolveOpenAIAutoResetCreditConfig(account).Enabled { + s.Notify(account.ID) + } + } + if len(accounts) < openAIAutoResetBatchSize || pageInfo == nil || page >= pageInfo.Pages { + return + } + } +} + +// Redis 锁异常时允许重复扫描,避免协调设施故障导致所有实例同时停止补偿; +// 消费唯一性由数据库幂等记录负责,扫描锁只用于削减重复查询。 +func (s *OpenAIQuotaAutoResetService) tryAcquireScanLock(ctx context.Context) (func(), bool) { + if s.leaderLock == nil { + return func() {}, true + } + ok, err := s.leaderLock.TryAcquireLeaderLock(ctx, openAIAutoResetLeaderLockKey, s.owner, 55*time.Second) + if err != nil { + slog.Warn("openai_auto_reset_leader_lock_unavailable", "error", err) + return func() {}, true + } + if !ok { + return nil, false + } + return func() { + releaseCtx, cancel := context.WithTimeout(context.Background(), 2*time.Second) + defer cancel() + _ = s.leaderLock.ReleaseLeaderLock(releaseCtx, openAIAutoResetLeaderLockKey, s.owner) + }, true +} + +type openAIAutoResetAssessment struct { + triggerWindow string + resetReached bool + pauseReached bool + utilization5h float64 + utilization7d float64 + threshold5h float64 + threshold7d float64 +} + +func (s *OpenAIQuotaAutoResetService) evaluateAccount(ctx context.Context, accountID int64) error { + ctx = withOpenAIAutoResetContext(ctx) + account, err := s.accountRepo.GetByID(ctx, accountID) + if err != nil || account == nil { + return err + } + if account.IsShadow() { + if account.ParentAccountID != nil { + s.Notify(*account.ParentAccountID) + } + return nil + } + config := ResolveOpenAIAutoResetCreditConfig(account) + if !config.Enabled || !account.IsActive() || !account.Schedulable { + return nil + } + + now := time.Now() + assessment := s.assessExtra(account, config, now) + state := openAIAutoResetStateFromExtra(account.Extra) + needsQuery := openAIAutoResetSnapshotStale(account.Extra, now) || assessment.resetReached + if assessment.pauseReached && !assessment.resetReached { + needsQuery = needsQuery || state == nil || state.Status == OpenAIAutoResetStatusChecking || state.Status == OpenAIAutoResetStatusFailed || openAIAutoResetStateStale(state, now) + } + if !needsQuery { + if !assessment.pauseReached && state != nil && state.TriggerWindow != "" { + state.TriggerWindow = "" + state.ErrorCode = "" + state.CheckedAt = now.UTC().Format(time.RFC3339) + if state.AvailableCount > 0 { + state.Status = OpenAIAutoResetStatusAvailable + } else { + state.Status = OpenAIAutoResetStatusNoCredit + } + return s.persistState(ctx, accountID, state) + } + return nil + } + + checking := &OpenAIAutoResetCreditState{ + Status: OpenAIAutoResetStatusChecking, + TriggerWindow: assessment.triggerWindow, + AvailableCount: stateAvailableCount(state), + CheckedAt: now.UTC().Format(time.RFC3339), + } + copyOpenAIAutoResetAttempt(checking, state) + if err := s.persistState(ctx, accountID, checking); err != nil { + return err + } + + usage, err := s.quota.QueryUsage(ctx, accountID) + if err != nil || usage == nil { + return s.failState(ctx, accountID, checking, "RESET_CREDIT_QUERY_FAILED", err) + } + if err := s.persistFreshUsage(ctx, accountID, usage, now); err != nil { + return s.failState(ctx, accountID, checking, "USAGE_SNAPSHOT_WRITE_FAILED", err) + } + if usage.RateLimitResetCredits == nil { + return s.failState(ctx, accountID, checking, "RESET_CREDIT_DETAILS_UNAVAILABLE", nil) + } + + // 查询期间管理员可能关闭开关;消费前重新读取账号,确保尚未发出的任务可取消。 + account, err = s.accountRepo.GetByID(ctx, accountID) + if err != nil || account == nil { + return err + } + config = ResolveOpenAIAutoResetCreditConfig(account) + if !config.Enabled { + return nil + } + assessment = s.assessUsage(usage, account, config, now) + available := usage.RateLimitResetCredits.AvailableCount + if !assessment.resetReached { + status := OpenAIAutoResetStatusNoCredit + if available > 0 { + status = OpenAIAutoResetStatusAvailable + } + return s.persistState(ctx, accountID, &OpenAIAutoResetCreditState{ + Status: status, + TriggerWindow: assessment.triggerWindow, + AvailableCount: available, + CheckedAt: now.UTC().Format(time.RFC3339), + }) + } + if available <= 0 { + return s.persistState(ctx, accountID, &OpenAIAutoResetCreditState{ + Status: OpenAIAutoResetStatusNoCredit, + TriggerWindow: assessment.triggerWindow, + AvailableCount: 0, + CheckedAt: now.UTC().Format(time.RFC3339), + LastResultAt: now.UTC().Format(time.RFC3339), + ErrorCode: "NO_RESET_CREDIT", + }) + } + + cycleSeed := openAIAutoResetCycleSeed(usage) + cycleHash := shortOpenAIAutoResetHash(cycleSeed) + candidate, selectErr := selectOpenAIAutoResetCandidate(usage.autoResetCandidates, available, state, cycleHash) + if selectErr != nil { + failed := checking + failed.AvailableCount = available + failed.TriggerWindow = assessment.triggerWindow + failed.AttemptCycleHash = cycleHash + return s.failState(ctx, accountID, failed, infraerrors.Reason(selectErr), selectErr) + } + creditHash := shortOpenAIAutoResetHash(candidate.ID) + stableKey := fmt.Sprintf("oarc:%d:%s:%s", accountID, creditHash, cycleHash) + redeemRequestID := uuid.NewSHA1(uuid.NameSpaceURL, []byte(stableKey)).String() + resetting := &OpenAIAutoResetCreditState{ + Status: OpenAIAutoResetStatusResetting, + TriggerWindow: assessment.triggerWindow, + AvailableCount: available, + CheckedAt: now.UTC().Format(time.RFC3339), + AttemptCycleHash: cycleHash, + AttemptCreditHash: creditHash, + } + if err := s.persistState(ctx, accountID, resetting); err != nil { + return err + } + + account, err = s.accountRepo.GetByID(ctx, accountID) + if err != nil || account == nil || !ResolveOpenAIAutoResetCreditConfig(account).Enabled { + return err + } + result, err := s.idempotency.Execute(ctx, IdempotencyExecuteOptions{ + Scope: "openai_auto_reset_credit", + ActorScope: fmt.Sprintf("account:%d", accountID), + Method: http.MethodPost, + Route: "/system/openai/reset-credit/auto", + IdempotencyKey: stableKey, + Payload: map[string]any{ + "account_id": accountID, + "credit_hash": creditHash, + "cycle_hash": cycleHash, + }, + TTL: openAIAutoResetAttemptTTL, + RequireKey: true, + }, func(execCtx context.Context) (any, error) { + resetResult, resetErr := s.quota.ResetCreditTargeted(execCtx, accountID, candidate.ID, redeemRequestID) + if resetErr != nil { + return nil, resetErr + } + if resetResult == nil { + return nil, infraerrors.InternalServer("OPENAI_AUTO_RESET_EMPTY_RESULT", "automatic reset returned an empty result") + } + // 幂等表只保存脱敏结果,避免上游返回的卡 ID 被持久化到响应体列。 + return openAIAutoResetConsumeResult{Code: resetResult.Code, WindowsReset: resetResult.WindowsReset}, nil + }) + if err != nil { + // 另一个实例已持有同一周期的兑换时保持 resetting,等待下一轮读取同一 + // 幂等结果;不能把并发冲突误报成上游消费失败,更不能改选下一张卡。 + reason := infraerrors.Reason(err) + if reason == infraerrors.Reason(ErrIdempotencyInProgress) || reason == infraerrors.Reason(ErrIdempotencyRetryBackoff) { + return nil + } + s.recordAudit(accountID, assessment, available, "failed", 0, infraerrors.Reason(err)) + return s.failState(ctx, accountID, resetting, infraerrors.Reason(err), err) + } + + consumeResult := decodeOpenAIAutoResetConsumeResult(result.Data) + if strings.EqualFold(strings.TrimSpace(consumeResult.Code), "no_credit") { + noCreditAt := time.Now().UTC().Format(time.RFC3339) + noCredit := &OpenAIAutoResetCreditState{ + Status: OpenAIAutoResetStatusNoCredit, + TriggerWindow: assessment.triggerWindow, + AvailableCount: 0, + CheckedAt: noCreditAt, + LastResultAt: noCreditAt, + ErrorCode: "NO_RESET_CREDIT", + AttemptCycleHash: cycleHash, + AttemptCreditHash: creditHash, + } + s.recordAudit(accountID, assessment, available, "no_credit", 0, noCredit.ErrorCode) + return s.persistState(ctx, accountID, noCredit) + } + postCtx, cancelPost := context.WithTimeout(context.WithoutCancel(ctx), 8*time.Second) + post := RunOpenAIQuotaResetPostProcess(postCtx, accountID, s.quota, s.recoverer, s.accountRepo.GetByID) + cancelPost() + if !post.AccountStateRecovered || post.WarningCode != "" { + code := post.WarningCode + if code == "" { + code = OpenAIQuotaResetWarningAccountRecoveryFailed + } + s.recordAudit(accountID, assessment, available, "recovery_failed", consumeResult.WindowsReset, code) + return s.failState(ctx, accountID, resetting, code, nil) + } + + successAt := time.Now().UTC().Format(time.RFC3339) + success := &OpenAIAutoResetCreditState{ + Status: OpenAIAutoResetStatusSuccess, + TriggerWindow: assessment.triggerWindow, + AvailableCount: max(0, available-1), + CheckedAt: successAt, + LastResultAt: successAt, + AttemptCycleHash: cycleHash, + AttemptCreditHash: creditHash, + } + if post.Quota != nil && post.Quota.RateLimitResetCredits != nil { + success.AvailableCount = post.Quota.RateLimitResetCredits.AvailableCount + } + if err := s.persistState(ctx, accountID, success); err != nil { + return err + } + s.recordAudit(accountID, assessment, available, "success", consumeResult.WindowsReset, "") + slog.Info("openai_auto_reset_credit_success", + "account_id", accountID, + "trigger_window", assessment.triggerWindow, + "threshold_5h", assessment.threshold5h, + "threshold_7d", assessment.threshold7d, + "utilization_5h", assessment.utilization5h, + "utilization_7d", assessment.utilization7d, + "windows_reset", consumeResult.WindowsReset, + ) + return nil +} + +type openAIAutoResetConsumeResult struct { + Code string `json:"code"` + WindowsReset int `json:"windows_reset"` +} + +func decodeOpenAIAutoResetConsumeResult(value any) openAIAutoResetConsumeResult { + if typed, ok := value.(openAIAutoResetConsumeResult); ok { + return typed + } + raw, _ := json.Marshal(value) + var decoded openAIAutoResetConsumeResult + _ = json.Unmarshal(raw, &decoded) + return decoded +} + +func (s *OpenAIQuotaAutoResetService) assessExtra(account *Account, config OpenAIAutoResetCreditConfig, now time.Time) openAIAutoResetAssessment { + utilization5h, _ := resolveOpenAIQuotaUtilization(account.Extra, "5h", now) + utilization7d, _ := resolveOpenAIQuotaUtilization(account.Extra, "7d", now) + return s.buildAssessment(account, config, utilization5h, utilization7d) +} + +func (s *OpenAIQuotaAutoResetService) assessUsage(usage *OpenAIQuotaUsage, account *Account, config OpenAIAutoResetCreditConfig, now time.Time) openAIAutoResetAssessment { + updates := buildOpenAIAutoResetUsageUpdates(usage, now) + utilization5h := readOpenAIQuotaUsedPercent(updates, "5h") / 100 + utilization7d := readOpenAIQuotaUsedPercent(updates, "7d") / 100 + return s.buildAssessment(account, config, utilization5h, utilization7d) +} + +func (s *OpenAIQuotaAutoResetService) buildAssessment(account *Account, config OpenAIAutoResetCreditConfig, utilization5h, utilization7d float64) openAIAutoResetAssessment { + assessment := openAIAutoResetAssessment{ + utilization5h: utilization5h, + utilization7d: utilization7d, + threshold5h: config.Threshold5h, + threshold7d: config.Threshold7d, + } + reset5h := utilization5h >= config.Threshold5h + reset7d := utilization7d >= config.Threshold7d + assessment.resetReached = reset5h || reset7d + assessment.triggerWindow = joinOpenAIAutoResetWindows(reset5h, reset7d) + + pause5h, pause7d := resolveOpenAIQuotaAutoPauseThresholds(context.Background(), account) + if s.settings != nil { + pause5h, pause7d = resolveOpenAIQuotaAutoPauseThresholds( + withOpenAIQuotaAutoPauseSettings(context.Background(), s.settings.GetOpenAIQuotaAutoPauseSettings(context.Background())), + account, + ) + } + pauseReached5h := !resolveAccountExtraBool(account.Extra, "auto_pause_5h_disabled") && pause5h > 0 && utilization5h >= pause5h + pauseReached7d := !resolveAccountExtraBool(account.Extra, "auto_pause_7d_disabled") && pause7d > 0 && utilization7d >= pause7d + assessment.pauseReached = pauseReached5h || pauseReached7d || assessment.resetReached + if assessment.triggerWindow == "" { + assessment.triggerWindow = joinOpenAIAutoResetWindows(pauseReached5h, pauseReached7d) + } + return assessment +} + +func joinOpenAIAutoResetWindows(fiveHour, sevenDay bool) string { + switch { + case fiveHour && sevenDay: + return "5h+7d" + case fiveHour: + return "5h" + case sevenDay: + return "7d" + default: + return "" + } +} + +func buildOpenAIAutoResetUsageUpdates(usage *OpenAIQuotaUsage, now time.Time) map[string]any { + if usage == nil || usage.RateLimit == nil { + return nil + } + rateLimit := usage.RateLimit + snapshot := &OpenAICodexUsageSnapshot{UpdatedAt: now.UTC().Format(time.RFC3339)} + applyWindow := func(window *OpenAIRateLimitWindow, primary bool) { + if window == nil { + return + } + used := window.UsedPercent + resetAfter := int(window.ResetAfterSeconds) + windowMinutes := int(window.LimitWindowSeconds / 60) + if primary { + snapshot.PrimaryUsedPercent = &used + snapshot.PrimaryResetAfterSeconds = &resetAfter + snapshot.PrimaryWindowMinutes = &windowMinutes + } else { + snapshot.SecondaryUsedPercent = &used + snapshot.SecondaryResetAfterSeconds = &resetAfter + snapshot.SecondaryWindowMinutes = &windowMinutes + } + } + applyWindow(rateLimit.PrimaryWindow, true) + applyWindow(rateLimit.SecondaryWindow, false) + return buildCodexUsageExtraUpdates(snapshot, now) +} + +func (s *OpenAIQuotaAutoResetService) persistFreshUsage(ctx context.Context, accountID int64, usage *OpenAIQuotaUsage, now time.Time) error { + updates := buildOpenAIAutoResetUsageUpdates(usage, now) + if len(updates) > 0 { + if err := s.accountRepo.UpdateExtra(ctx, accountID, updates); err != nil { + return err + } + } + return s.quota.CacheResetCreditsSnapshot(ctx, accountID, usage.RateLimitResetCredits) +} + +func selectOpenAIAutoResetCandidate(candidates []openAIAutoResetCreditCandidate, available int, previous *OpenAIAutoResetCreditState, cycleHash string) (openAIAutoResetCreditCandidate, error) { + if available <= 0 { + return openAIAutoResetCreditCandidate{}, infraerrors.Conflict("OPENAI_AUTO_RESET_NO_CREDIT", "no reset credit is available") + } + if len(candidates) < available { + return openAIAutoResetCreditCandidate{}, infraerrors.Conflict("OPENAI_AUTO_RESET_CREDIT_DETAILS_INCOMPLETE", "reset credit details are incomplete") + } + for _, candidate := range candidates { + if _, err := time.Parse(time.RFC3339, candidate.ExpiresAt); err != nil { + return openAIAutoResetCreditCandidate{}, infraerrors.Conflict("OPENAI_AUTO_RESET_CREDIT_EXPIRY_INVALID", "reset credit expiration is invalid") + } + } + sorted := append([]openAIAutoResetCreditCandidate(nil), candidates...) + sort.SliceStable(sorted, func(i, j int) bool { + left, leftErr := time.Parse(time.RFC3339, sorted[i].ExpiresAt) + right, rightErr := time.Parse(time.RFC3339, sorted[j].ExpiresAt) + if leftErr != nil { + return false + } + if rightErr != nil { + return true + } + return left.Before(right) + }) + if previous != nil && previous.AttemptCycleHash == cycleHash && previous.AttemptCreditHash != "" { + for _, candidate := range sorted { + if shortOpenAIAutoResetHash(candidate.ID) == previous.AttemptCreditHash { + if strings.TrimSpace(candidate.ID) == "" { + break + } + return candidate, nil + } + } + return openAIAutoResetCreditCandidate{}, infraerrors.Conflict("OPENAI_AUTO_RESET_ORIGINAL_CREDIT_UNAVAILABLE", "the original reset credit cannot be confirmed; refusing to switch credits") + } + if len(sorted) == 0 || strings.TrimSpace(sorted[0].ID) == "" { + return openAIAutoResetCreditCandidate{}, infraerrors.Conflict("OPENAI_AUTO_RESET_CREDIT_ID_MISSING", "the earliest reset credit has no official id") + } + return sorted[0], nil +} + +func openAIAutoResetCycleSeed(usage *OpenAIQuotaUsage) string { + if usage == nil || usage.RateLimit == nil { + return "5h:0|7d:0" + } + var fiveHour, sevenDay int64 + for _, window := range []*OpenAIRateLimitWindow{usage.RateLimit.PrimaryWindow, usage.RateLimit.SecondaryWindow} { + if window == nil { + continue + } + resetAt := window.ResetAt + if resetAt <= 0 { + resetAt = usage.FetchedAt + window.ResetAfterSeconds + } + if window.LimitWindowSeconds <= 6*60*60 { + fiveHour = resetAt + } else { + sevenDay = resetAt + } + } + return fmt.Sprintf("5h:%d|7d:%d", fiveHour, sevenDay) +} + +func shortOpenAIAutoResetHash(value string) string { + sum := sha256.Sum256([]byte(value)) + return hex.EncodeToString(sum[:12]) +} + +func openAIAutoResetSnapshotStale(extra map[string]any, now time.Time) bool { + if len(extra) == 0 { + return true + } + raw, ok := extra["codex_usage_updated_at"] + if !ok { + return true + } + updatedAt, err := parseTime(fmt.Sprint(raw)) + return err != nil || now.Sub(updatedAt) >= openAIAutoResetSnapshotTTL +} + +func openAIAutoResetStateFromExtra(extra map[string]any) *OpenAIAutoResetCreditState { + if len(extra) == 0 { + return nil + } + raw, ok := extra[OpenAIAutoResetCreditStateExtraKey] + if !ok || raw == nil { + return nil + } + encoded, err := json.Marshal(raw) + if err != nil { + return nil + } + var state OpenAIAutoResetCreditState + if err := json.Unmarshal(encoded, &state); err != nil || state.Status == "" { + return nil + } + return &state +} + +func openAIAutoResetStateStale(state *OpenAIAutoResetCreditState, now time.Time) bool { + if state == nil || state.CheckedAt == "" { + return true + } + checkedAt, err := time.Parse(time.RFC3339, state.CheckedAt) + return err != nil || now.Sub(checkedAt) >= openAIAutoResetSnapshotTTL +} + +func stateAvailableCount(state *OpenAIAutoResetCreditState) int { + if state == nil { + return 0 + } + return state.AvailableCount +} + +func copyOpenAIAutoResetAttempt(target, source *OpenAIAutoResetCreditState) { + if target == nil || source == nil { + return + } + target.AttemptCycleHash = source.AttemptCycleHash + target.AttemptCreditHash = source.AttemptCreditHash +} + +func (s *OpenAIQuotaAutoResetService) persistState(ctx context.Context, accountID int64, state *OpenAIAutoResetCreditState) error { + if state == nil { + return nil + } + return s.accountRepo.UpdateExtra(ctx, accountID, map[string]any{OpenAIAutoResetCreditStateExtraKey: state}) +} + +func (s *OpenAIQuotaAutoResetService) failState(ctx context.Context, accountID int64, state *OpenAIAutoResetCreditState, code string, cause error) error { + if state == nil { + state = &OpenAIAutoResetCreditState{} + } + if strings.TrimSpace(code) == "" { + code = "OPENAI_AUTO_RESET_FAILED" + } + state.Status = OpenAIAutoResetStatusFailed + state.ErrorCode = code + state.LastResultAt = time.Now().UTC().Format(time.RFC3339) + if err := s.persistState(ctx, accountID, state); err != nil { + return err + } + slog.Warn("openai_auto_reset_credit_failed", + "account_id", accountID, + "trigger_window", state.TriggerWindow, + "available_count", state.AvailableCount, + "error_code", code, + ) + if cause != nil { + return cause + } + return infraerrors.Conflict(code, "automatic reset credit operation failed") +} + +func (s *OpenAIQuotaAutoResetService) recordAudit(accountID int64, assessment openAIAutoResetAssessment, available int, resultCode string, windowsReset int, errorCode string) { + if s.audit == nil { + return + } + statusCode := http.StatusOK + if resultCode != "success" { + statusCode = http.StatusConflict + } + s.audit.Record(&AuditLog{ + ActorEmail: "system", + ActorRole: "system", + AuthMethod: "system", + Action: "system.openai.reset_credit.auto", + Method: "SYSTEM", + Path: fmt.Sprintf("/system/openai/accounts/%d/auto-reset-credit", accountID), + StatusCode: statusCode, + Extra: map[string]any{ + "account_id": accountID, + "trigger_window": assessment.triggerWindow, + "threshold_5h": assessment.threshold5h, + "threshold_7d": assessment.threshold7d, + "utilization_5h": assessment.utilization5h, + "utilization_7d": assessment.utilization7d, + "available_count": available, + "result_code": resultCode, + "windows_reset": windowsReset, + "error_code": errorCode, + }, + }) +} + +var openAIAutoResetNotifierRegistry struct { + sync.RWMutex + service *OpenAIQuotaAutoResetService +} + +func setOpenAIAutoResetNotifier(service *OpenAIQuotaAutoResetService) { + openAIAutoResetNotifierRegistry.Lock() + openAIAutoResetNotifierRegistry.service = service + openAIAutoResetNotifierRegistry.Unlock() +} + +func clearOpenAIAutoResetNotifier(service *OpenAIQuotaAutoResetService) { + openAIAutoResetNotifierRegistry.Lock() + if openAIAutoResetNotifierRegistry.service == service { + openAIAutoResetNotifierRegistry.service = nil + } + openAIAutoResetNotifierRegistry.Unlock() +} + +func notifyOpenAIAutoReset(accountID int64) { + openAIAutoResetNotifierRegistry.RLock() + service := openAIAutoResetNotifierRegistry.service + openAIAutoResetNotifierRegistry.RUnlock() + if service != nil { + service.Notify(accountID) + } +} + +// NotifyOpenAIAutoResetCredit 供额度查询入口发送轻量信号;不执行同步上游请求。 +func NotifyOpenAIAutoResetCredit(accountID int64) { + notifyOpenAIAutoReset(accountID) +} diff --git a/backend/internal/service/openai_quota_auto_reset_config.go b/backend/internal/service/openai_quota_auto_reset_config.go new file mode 100644 index 0000000000..e891049795 --- /dev/null +++ b/backend/internal/service/openai_quota_auto_reset_config.go @@ -0,0 +1,148 @@ +package service + +import ( + "encoding/json" + "math" + "net/http" + "strconv" + "strings" + + infraerrors "github.com/Wei-Shaw/sub2api/internal/pkg/errors" +) + +const ( + OpenAIAutoResetCreditEnabledExtraKey = "auto_reset_credit_enabled" + OpenAIAutoResetCredit5hThresholdExtraKey = "auto_reset_credit_5h_threshold" + OpenAIAutoResetCredit7dThresholdExtraKey = "auto_reset_credit_7d_threshold" + OpenAIAutoResetCreditStateExtraKey = "codex_auto_reset_credit_state" + + openAIAutoResetCreditDefaultThreshold = 1.0 + openAIAutoResetCreditMinimumThreshold = 0.001 +) + +// OpenAIAutoResetCreditConfig 是账号级自动用卡配置。阈值采用 0-1 比例, +// 避免后端调度与前端百分比展示混用同一数值语义。 +type OpenAIAutoResetCreditConfig struct { + Enabled bool + Threshold5h float64 + Threshold7d float64 +} + +// ResolveOpenAIAutoResetCreditConfig 只接受 OpenAI OAuth 母账号;历史账号未配置时 +// 始终保持关闭,防止升级后产生意外消费。 +func ResolveOpenAIAutoResetCreditConfig(account *Account) OpenAIAutoResetCreditConfig { + config := OpenAIAutoResetCreditConfig{ + Threshold5h: openAIAutoResetCreditDefaultThreshold, + Threshold7d: openAIAutoResetCreditDefaultThreshold, + } + if !isOpenAIAutoResetCreditAccount(account) || account.Extra == nil { + return config + } + config.Enabled = resolveAccountExtraBool(account.Extra, OpenAIAutoResetCreditEnabledExtraKey) + if value, ok := resolveAccountExtraNumber(account.Extra, OpenAIAutoResetCredit5hThresholdExtraKey); ok && isValidOpenAIAutoResetThreshold(value) { + config.Threshold5h = value + } + if value, ok := resolveAccountExtraNumber(account.Extra, OpenAIAutoResetCredit7dThresholdExtraKey); ok && isValidOpenAIAutoResetThreshold(value) { + config.Threshold7d = value + } + return config +} + +func isOpenAIAutoResetCreditAccount(account *Account) bool { + return account != nil && account.Platform == PlatformOpenAI && account.Type == AccountTypeOAuth && !account.IsShadow() +} + +// normalizeOpenAIAutoResetCreditExtra 校验管理请求中的配置并剥离服务运行态。 +// enabled=true 时补齐两个 100% 默认阈值;关闭时保留已设置阈值,方便再次开启。 +func normalizeOpenAIAutoResetCreditExtra(platform, accountType string, isShadow bool, extra map[string]any) (map[string]any, error) { + if extra == nil { + return nil, nil + } + normalized := cloneOpenAIAutoResetExtra(extra) + delete(normalized, OpenAIAutoResetCreditStateExtraKey) + + _, hasEnabled := normalized[OpenAIAutoResetCreditEnabledExtraKey] + _, has5h := normalized[OpenAIAutoResetCredit5hThresholdExtraKey] + _, has7d := normalized[OpenAIAutoResetCredit7dThresholdExtraKey] + if !hasEnabled && !has5h && !has7d { + return normalized, nil + } + if platform != PlatformOpenAI || accountType != AccountTypeOAuth || isShadow { + return nil, infraerrors.New(http.StatusBadRequest, "OPENAI_AUTO_RESET_CREDIT_ACCOUNT_INVALID", "automatic reset credits are only supported for OpenAI OAuth parent accounts") + } + + enabled := false + if hasEnabled { + value, ok := normalized[OpenAIAutoResetCreditEnabledExtraKey].(bool) + if !ok { + return nil, infraerrors.New(http.StatusBadRequest, "OPENAI_AUTO_RESET_CREDIT_ENABLED_INVALID", "auto_reset_credit_enabled must be a boolean") + } + enabled = value + } + for key, present := range map[string]bool{ + OpenAIAutoResetCredit5hThresholdExtraKey: has5h, + OpenAIAutoResetCredit7dThresholdExtraKey: has7d, + } { + if !present { + if enabled { + normalized[key] = openAIAutoResetCreditDefaultThreshold + } + continue + } + value, ok := parseOpenAIAutoResetThreshold(normalized[key]) + if !ok || !isValidOpenAIAutoResetThreshold(value) { + return nil, infraerrors.Newf(http.StatusBadRequest, "OPENAI_AUTO_RESET_CREDIT_THRESHOLD_INVALID", "%s must be between 0.001 and 1.0", key) + } + normalized[key] = value + } + return normalized, nil +} + +func stripOpenAIAutoResetCreditManagedExtra(extra map[string]any, stripConfig bool) map[string]any { + if extra == nil { + return nil + } + delete(extra, OpenAIAutoResetCreditStateExtraKey) + if stripConfig { + delete(extra, OpenAIAutoResetCreditEnabledExtraKey) + delete(extra, OpenAIAutoResetCredit5hThresholdExtraKey) + delete(extra, OpenAIAutoResetCredit7dThresholdExtraKey) + } + return extra +} + +func parseOpenAIAutoResetThreshold(value any) (float64, bool) { + switch typed := value.(type) { + case float64: + return typed, true + case float32: + return float64(typed), true + case int: + return float64(typed), true + case int64: + return float64(typed), true + case json.Number: + parsed, err := typed.Float64() + return parsed, err == nil + case string: + parsed, err := strconv.ParseFloat(strings.TrimSpace(typed), 64) + return parsed, err == nil + default: + return 0, false + } +} + +func isValidOpenAIAutoResetThreshold(value float64) bool { + return !math.IsNaN(value) && !math.IsInf(value, 0) && value >= openAIAutoResetCreditMinimumThreshold && value <= 1 +} + +func cloneOpenAIAutoResetExtra(source map[string]any) map[string]any { + if source == nil { + return nil + } + cloned := make(map[string]any, len(source)) + for key, value := range source { + cloned[key] = value + } + return cloned +} diff --git a/backend/internal/service/openai_quota_auto_reset_test.go b/backend/internal/service/openai_quota_auto_reset_test.go new file mode 100644 index 0000000000..ad2dc965aa --- /dev/null +++ b/backend/internal/service/openai_quota_auto_reset_test.go @@ -0,0 +1,332 @@ +package service + +import ( + "context" + "encoding/json" + "sync" + "sync/atomic" + "testing" + "time" + + "github.com/stretchr/testify/require" +) + +func TestNormalizeOpenAIAutoResetCreditExtra(t *testing.T) { + t.Run("历史账号默认关闭", func(t *testing.T) { + account := &Account{Platform: PlatformOpenAI, Type: AccountTypeOAuth} + config := ResolveOpenAIAutoResetCreditConfig(account) + require.False(t, config.Enabled) + require.Equal(t, 1.0, config.Threshold5h) + require.Equal(t, 1.0, config.Threshold7d) + }) + + t.Run("开启时补齐两个百分百阈值并剥离运行态", func(t *testing.T) { + extra, err := normalizeOpenAIAutoResetCreditExtra(PlatformOpenAI, AccountTypeOAuth, false, map[string]any{ + OpenAIAutoResetCreditEnabledExtraKey: true, + OpenAIAutoResetCreditStateExtraKey: map[string]any{"status": "success"}, + }) + require.NoError(t, err) + require.Equal(t, 1.0, extra[OpenAIAutoResetCredit5hThresholdExtraKey]) + require.Equal(t, 1.0, extra[OpenAIAutoResetCredit7dThresholdExtraKey]) + require.NotContains(t, extra, OpenAIAutoResetCreditStateExtraKey) + }) + + t.Run("阈值和账号类型严格校验", func(t *testing.T) { + _, err := normalizeOpenAIAutoResetCreditExtra(PlatformOpenAI, AccountTypeOAuth, false, map[string]any{ + OpenAIAutoResetCreditEnabledExtraKey: true, + OpenAIAutoResetCredit5hThresholdExtraKey: 0.0009, + }) + require.Error(t, err) + + _, err = normalizeOpenAIAutoResetCreditExtra(PlatformOpenAI, AccountTypeOAuth, true, map[string]any{ + OpenAIAutoResetCreditEnabledExtraKey: true, + }) + require.Error(t, err) + }) +} + +func TestShouldAutoPauseOpenAIAccountByQuota_AutoResetCreditStates(t *testing.T) { + now := time.Now().UTC() + baseExtra := map[string]any{ + OpenAIAutoResetCreditEnabledExtraKey: true, + OpenAIAutoResetCredit5hThresholdExtraKey: 1.0, + OpenAIAutoResetCredit7dThresholdExtraKey: 1.0, + "auto_pause_5h_threshold": 0.8, + "auto_pause_7d_disabled": true, + "codex_5h_used_percent": 90.0, + "codex_usage_updated_at": now.Format(time.RFC3339), + "codex_5h_reset_at": now.Add(time.Hour).Format(time.RFC3339), + } + + t.Run("卡状态未知时暂停并触发异步查询", func(t *testing.T) { + account := &Account{ID: 1, Platform: PlatformOpenAI, Type: AccountTypeOAuth, Extra: cloneOpenAIAutoResetExtra(baseExtra)} + paused, decision := shouldAutoPauseOpenAIAccountByQuota(context.Background(), account) + require.True(t, paused) + require.Equal(t, "quota_auto_reset_credit_check_5h", decision.reason) + }) + + t.Run("明确有卡时允许继续到用卡阈值", func(t *testing.T) { + extra := cloneOpenAIAutoResetExtra(baseExtra) + extra[OpenAIAutoResetCreditStateExtraKey] = OpenAIAutoResetCreditState{ + Status: OpenAIAutoResetStatusAvailable, AvailableCount: 1, CheckedAt: now.Format(time.RFC3339), + } + account := &Account{ID: 2, Platform: PlatformOpenAI, Type: AccountTypeOAuth, Extra: extra} + paused, _ := shouldAutoPauseOpenAIAccountByQuota(context.Background(), account) + require.False(t, paused) + }) + + t.Run("达到用卡阈值后即使有卡也退出调度", func(t *testing.T) { + extra := cloneOpenAIAutoResetExtra(baseExtra) + extra["codex_5h_used_percent"] = 100.0 + extra[OpenAIAutoResetCreditStateExtraKey] = OpenAIAutoResetCreditState{ + Status: OpenAIAutoResetStatusAvailable, AvailableCount: 1, CheckedAt: now.Format(time.RFC3339), + } + account := &Account{ID: 3, Platform: PlatformOpenAI, Type: AccountTypeOAuth, Extra: extra} + paused, decision := shouldAutoPauseOpenAIAccountByQuota(context.Background(), account) + require.True(t, paused) + require.Equal(t, "quota_auto_reset_pending_5h", decision.reason) + }) + + t.Run("自然窗口重置后清除动态阻塞", func(t *testing.T) { + extra := cloneOpenAIAutoResetExtra(baseExtra) + extra["codex_5h_used_percent"] = 100.0 + extra["codex_5h_reset_at"] = now.Add(-time.Second).Format(time.RFC3339) + extra[OpenAIAutoResetCreditStateExtraKey] = OpenAIAutoResetCreditState{ + Status: OpenAIAutoResetStatusFailed, TriggerWindow: "5h", ErrorCode: "RESET_FAILED", + } + account := &Account{ID: 4, Platform: PlatformOpenAI, Type: AccountTypeOAuth, Extra: extra} + paused, _ := shouldAutoPauseOpenAIAccountByQuota(context.Background(), account) + require.False(t, paused) + }) +} + +func TestSelectOpenAIAutoResetCandidate_FailsClosed(t *testing.T) { + candidates := []openAIAutoResetCreditCandidate{ + {ID: "later", ExpiresAt: "2026-09-02T00:00:00Z"}, + {ID: "earlier", ExpiresAt: "2026-09-01T00:00:00Z"}, + } + selected, err := selectOpenAIAutoResetCandidate(candidates, 2, nil, "cycle-a") + require.NoError(t, err) + require.Equal(t, "earlier", selected.ID) + + _, err = selectOpenAIAutoResetCandidate([]openAIAutoResetCreditCandidate{ + {ExpiresAt: "2026-09-01T00:00:00Z"}, + }, 1, nil, "cycle-a") + require.Error(t, err) + + _, err = selectOpenAIAutoResetCandidate(candidates, 2, &OpenAIAutoResetCreditState{ + AttemptCycleHash: "cycle-a", AttemptCreditHash: shortOpenAIAutoResetHash("missing"), + }, "cycle-a") + require.Error(t, err, "模糊结果后原卡消失时不得切换下一张卡") +} + +func TestOpenAIQuotaAutoResetService_AssessesIndependentWindows(t *testing.T) { + service := &OpenAIQuotaAutoResetService{} + account := &Account{Extra: map[string]any{ + "auto_pause_5h_disabled": true, + "auto_pause_7d_disabled": true, + }} + config := OpenAIAutoResetCreditConfig{Enabled: true, Threshold5h: 0.8, Threshold7d: 0.9} + tests := []struct { + name string + fiveHour float64 + sevenDay float64 + wantWindow string + }{ + {name: "5h", fiveHour: 0.8, sevenDay: 0.2, wantWindow: "5h"}, + {name: "7d", fiveHour: 0.2, sevenDay: 0.9, wantWindow: "7d"}, + {name: "同时触发", fiveHour: 0.95, sevenDay: 0.95, wantWindow: "5h+7d"}, + } + for _, test := range tests { + t.Run(test.name, func(t *testing.T) { + assessment := service.buildAssessment(account, config, test.fiveHour, test.sevenDay) + require.True(t, assessment.resetReached) + require.Equal(t, test.wantWindow, assessment.triggerWindow) + }) + } +} + +type autoResetTestAccountRepo struct { + AccountRepository + mu sync.Mutex + account *Account +} + +func (r *autoResetTestAccountRepo) GetByID(_ context.Context, id int64) (*Account, error) { + r.mu.Lock() + defer r.mu.Unlock() + copy := *r.account + copy.Extra = cloneOpenAIAutoResetExtra(r.account.Extra) + return ©, nil +} + +func (r *autoResetTestAccountRepo) UpdateExtra(_ context.Context, id int64, updates map[string]any) error { + r.mu.Lock() + defer r.mu.Unlock() + if r.account.Extra == nil { + r.account.Extra = make(map[string]any) + } + for key, value := range updates { + r.account.Extra[key] = value + } + return nil +} + +type autoResetTestQuota struct { + usage *OpenAIQuotaUsage + resetCalls atomic.Int32 + resetEntered chan struct{} + releaseReset chan struct{} + enterOnce sync.Once + mu sync.Mutex + resetArgs [][2]string + failFirst bool +} + +func (q *autoResetTestQuota) QueryUsage(context.Context, int64) (*OpenAIQuotaUsage, error) { + copy := *q.usage + return ©, nil +} + +func (q *autoResetTestQuota) CacheResetCreditsSnapshot(context.Context, int64, *OpenAIRateLimitResetCredits) error { + return nil +} + +func (q *autoResetTestQuota) ResetCreditTargeted(_ context.Context, _ int64, creditID, redeemRequestID string) (*OpenAIQuotaResetResult, error) { + if creditID == "" || redeemRequestID == "" { + panic("targeted reset identifiers must be present") + } + call := q.resetCalls.Add(1) + q.mu.Lock() + q.resetArgs = append(q.resetArgs, [2]string{creditID, redeemRequestID}) + q.mu.Unlock() + if q.failFirst && call == 1 { + return nil, context.DeadlineExceeded + } + if q.resetEntered != nil { + q.enterOnce.Do(func() { close(q.resetEntered) }) + } + if q.releaseReset != nil { + <-q.releaseReset + } + return &OpenAIQuotaResetResult{Code: "ok", WindowsReset: 2}, nil +} + +type autoResetTestRecoverer struct{} + +func (autoResetTestRecoverer) RecoverAccountState(context.Context, int64, AccountRecoveryOptions) (*SuccessfulTestRecoveryResult, error) { + return &SuccessfulTestRecoveryResult{ClearedRateLimit: true}, nil +} + +func TestOpenAIQuotaAutoResetService_ConcurrentInstancesConsumeOnce(t *testing.T) { + now := time.Now().UTC() + account := &Account{ + ID: 99, Platform: PlatformOpenAI, Type: AccountTypeOAuth, + Status: StatusActive, Schedulable: true, + Extra: map[string]any{ + OpenAIAutoResetCreditEnabledExtraKey: true, + OpenAIAutoResetCredit5hThresholdExtraKey: 1.0, + OpenAIAutoResetCredit7dThresholdExtraKey: 1.0, + "codex_5h_used_percent": 100.0, + "codex_7d_used_percent": 10.0, + "codex_usage_updated_at": now.Format(time.RFC3339), + "codex_5h_reset_at": now.Add(time.Hour).Format(time.RFC3339), + "codex_7d_reset_at": now.Add(24 * time.Hour).Format(time.RFC3339), + }, + } + repo := &autoResetTestAccountRepo{account: account} + usage := &OpenAIQuotaUsage{ + FetchedAt: now.Unix(), + RateLimit: &OpenAIRateLimit{ + PrimaryWindow: &OpenAIRateLimitWindow{UsedPercent: 100, LimitWindowSeconds: 5 * 60 * 60, ResetAfterSeconds: 3600, ResetAt: now.Add(time.Hour).Unix()}, + SecondaryWindow: &OpenAIRateLimitWindow{UsedPercent: 10, LimitWindowSeconds: 7 * 24 * 60 * 60, ResetAfterSeconds: 86400, ResetAt: now.Add(24 * time.Hour).Unix()}, + }, + RateLimitResetCredits: &OpenAIRateLimitResetCredits{ + AvailableCount: 1, + Credits: []OpenAIRateLimitResetCreditDetail{{ExpiresAt: now.Add(48 * time.Hour).Format(time.RFC3339)}}, + }, + autoResetCandidates: []openAIAutoResetCreditCandidate{{ID: "credit-sensitive-id", ExpiresAt: now.Add(48 * time.Hour).Format(time.RFC3339)}}, + } + quota := &autoResetTestQuota{usage: usage, resetEntered: make(chan struct{}), releaseReset: make(chan struct{})} + idempotencyRepo := newInMemoryIdempotencyRepo() + config := DefaultIdempotencyConfig() + config.ObserveOnly = false + config.ProcessingTimeout = time.Second + serviceA := NewOpenAIQuotaAutoResetService(repo, quota, autoResetTestRecoverer{}, NewIdempotencyCoordinator(idempotencyRepo, config), nil, nil, nil) + serviceB := NewOpenAIQuotaAutoResetService(repo, quota, autoResetTestRecoverer{}, NewIdempotencyCoordinator(idempotencyRepo, config), nil, nil, nil) + + var wg sync.WaitGroup + wg.Add(2) + go func() { + defer wg.Done() + _ = serviceA.evaluateAccount(context.Background(), account.ID) + }() + <-quota.resetEntered + go func() { + defer wg.Done() + _ = serviceB.evaluateAccount(context.Background(), account.ID) + }() + time.Sleep(50 * time.Millisecond) + close(quota.releaseReset) + wg.Wait() + + require.Equal(t, int32(1), quota.resetCalls.Load()) + repo.mu.Lock() + state := openAIAutoResetStateFromExtra(repo.account.Extra) + repo.mu.Unlock() + require.NotNil(t, state) + require.Equal(t, OpenAIAutoResetStatusSuccess, state.Status) + encodedState, err := json.Marshal(state) + require.NoError(t, err) + require.NotContains(t, string(encodedState), "credit-sensitive-id") +} + +func TestOpenAIQuotaAutoResetService_TimeoutRetryReusesRequestBody(t *testing.T) { + now := time.Now().UTC() + account := &Account{ + ID: 100, Platform: PlatformOpenAI, Type: AccountTypeOAuth, + Status: StatusActive, Schedulable: true, + Extra: map[string]any{ + OpenAIAutoResetCreditEnabledExtraKey: true, + OpenAIAutoResetCredit5hThresholdExtraKey: 1.0, + OpenAIAutoResetCredit7dThresholdExtraKey: 1.0, + "codex_5h_used_percent": 100.0, + "codex_usage_updated_at": now.Format(time.RFC3339), + "codex_5h_reset_at": now.Add(time.Hour).Format(time.RFC3339), + }, + } + repo := &autoResetTestAccountRepo{account: account} + expiresAt := now.Add(48 * time.Hour).Format(time.RFC3339) + quota := &autoResetTestQuota{ + failFirst: true, + usage: &OpenAIQuotaUsage{ + FetchedAt: now.Unix(), + RateLimit: &OpenAIRateLimit{ + PrimaryWindow: &OpenAIRateLimitWindow{UsedPercent: 100, LimitWindowSeconds: 5 * 60 * 60, ResetAfterSeconds: 3600, ResetAt: now.Add(time.Hour).Unix()}, + }, + RateLimitResetCredits: &OpenAIRateLimitResetCredits{ + AvailableCount: 1, + Credits: []OpenAIRateLimitResetCreditDetail{{ExpiresAt: expiresAt}}, + }, + autoResetCandidates: []openAIAutoResetCreditCandidate{{ID: "retry-credit", ExpiresAt: expiresAt}}, + }, + } + idempotencyConfig := DefaultIdempotencyConfig() + idempotencyConfig.ObserveOnly = false + idempotencyConfig.FailedRetryBackoff = 0 + service := NewOpenAIQuotaAutoResetService( + repo, + quota, + autoResetTestRecoverer{}, + NewIdempotencyCoordinator(newInMemoryIdempotencyRepo(), idempotencyConfig), + nil, nil, nil, + ) + + require.Error(t, service.evaluateAccount(context.Background(), account.ID)) + require.NoError(t, service.evaluateAccount(context.Background(), account.ID)) + quota.mu.Lock() + args := append([][2]string(nil), quota.resetArgs...) + quota.mu.Unlock() + require.Len(t, args, 2) + require.Equal(t, args[0], args[1], "超时重试必须复用相同 credit_id 与 redeem_request_id") +} diff --git a/backend/internal/service/openai_quota_reset_credits.go b/backend/internal/service/openai_quota_reset_credits.go index 9ff7e70f16..b87e3fd0d1 100644 --- a/backend/internal/service/openai_quota_reset_credits.go +++ b/backend/internal/service/openai_quota_reset_credits.go @@ -8,6 +8,9 @@ import ( ) type openAIRateLimitResetCreditDetailPayload struct { + ID string `json:"id,omitempty"` + CreditID string `json:"credit_id,omitempty"` + CreditIDCamel string `json:"creditId,omitempty"` ExpiresAt string `json:"expires_at,omitempty"` ExpiresAtCamel string `json:"expiresAt,omitempty"` ResetType string `json:"reset_type,omitempty"` @@ -29,6 +32,14 @@ type openAIRateLimitResetCreditDetails struct { AvailableCreditCount int CreditListPresent bool Credits []OpenAIRateLimitResetCreditDetail + AutoResetCandidates []openAIAutoResetCreditCandidate +} + +// openAIAutoResetCreditCandidate 仅在服务内部流转。上游卡 ID 不进入 API DTO、 +// 账号 extra 或日志,避免管理端响应扩大敏感标识暴露面。 +type openAIAutoResetCreditCandidate struct { + ID string + ExpiresAt string } func parseOpenAIRateLimitResetCreditDetails(body []byte) (openAIRateLimitResetCreditDetails, error) { @@ -64,6 +75,7 @@ func parseOpenAIRateLimitResetCreditDetails(body []byte) (openAIRateLimitResetCr } credits := make([]OpenAIRateLimitResetCreditDetail, 0, len(rawCredits)) + autoResetCandidates := make([]openAIAutoResetCreditCandidate, 0, len(rawCredits)) availableCreditCount := 0 for _, raw := range rawCredits { if raw == nil { @@ -88,12 +100,24 @@ func parseOpenAIRateLimitResetCreditDetails(body []byte) (openAIRateLimitResetCr continue } credits = append(credits, OpenAIRateLimitResetCreditDetail{ExpiresAt: expiresAt}) + creditID := strings.TrimSpace(raw.ID) + if creditID == "" { + creditID = strings.TrimSpace(raw.CreditID) + } + if creditID == "" { + creditID = strings.TrimSpace(raw.CreditIDCamel) + } + autoResetCandidates = append(autoResetCandidates, openAIAutoResetCreditCandidate{ + ID: creditID, + ExpiresAt: expiresAt, + }) } return openAIRateLimitResetCreditDetails{ AvailableCount: availableCount, AvailableCreditCount: availableCreditCount, CreditListPresent: creditListPresent, Credits: credits, + AutoResetCandidates: autoResetCandidates, }, nil } diff --git a/backend/internal/service/openai_quota_reset_credits_test.go b/backend/internal/service/openai_quota_reset_credits_test.go index 34f87f9a2f..2deb01ed89 100644 --- a/backend/internal/service/openai_quota_reset_credits_test.go +++ b/backend/internal/service/openai_quota_reset_credits_test.go @@ -14,8 +14,8 @@ func TestParseOpenAIRateLimitResetCreditDetails_PreservesAvailableCreditOrder(t "availableCount":"2", "credits":[ {"reset_type":"codex_rate_limits","status":"redeemed","expires_at":"2026-07-01T04:05:06Z"}, - {"reset_type":"codex_rate_limits","status":"available","expires_at":"2026-07-04T04:05:06Z"}, - {"resetType":"codex_rate_limits","status":"available","expiresAt":"2026-07-03T04:05:06Z"}, + {"id":"credit-later","reset_type":"codex_rate_limits","status":"available","expires_at":"2026-07-04T04:05:06Z"}, + {"creditId":"credit-earlier","resetType":"codex_rate_limits","status":"available","expiresAt":"2026-07-03T04:05:06Z"}, {"reset_type":"other","status":"available","expires_at":"2026-07-02T04:05:06Z"} ] }`) @@ -28,6 +28,10 @@ func TestParseOpenAIRateLimitResetCreditDetails_PreservesAvailableCreditOrder(t {ExpiresAt: "2026-07-04T04:05:06Z"}, {ExpiresAt: "2026-07-03T04:05:06Z"}, }, details.Credits) + require.Equal(t, []openAIAutoResetCreditCandidate{ + {ID: "credit-later", ExpiresAt: "2026-07-04T04:05:06Z"}, + {ID: "credit-earlier", ExpiresAt: "2026-07-03T04:05:06Z"}, + }, details.AutoResetCandidates) } func TestQueryUsageResetCreditCountPrecedence(t *testing.T) { diff --git a/backend/internal/service/openai_quota_reset_workflow.go b/backend/internal/service/openai_quota_reset_workflow.go new file mode 100644 index 0000000000..430b29618b --- /dev/null +++ b/backend/internal/service/openai_quota_reset_workflow.go @@ -0,0 +1,86 @@ +package service + +import ( + "context" + "log/slog" + + infraerrors "github.com/Wei-Shaw/sub2api/internal/pkg/errors" +) + +const ( + OpenAIQuotaResetWarningCacheRefreshFailed = "reset_credit_cache_refresh_failed" + OpenAIQuotaResetWarningAccountRecoveryFailed = "account_state_recovery_failed" + OpenAIQuotaResetWarningAccountRefreshFailed = "account_state_refresh_failed" +) + +type openAIQuotaResetWorkflowQuota interface { + QueryUsage(ctx context.Context, accountID int64) (*OpenAIQuotaUsage, error) + CacheResetCreditsSnapshot(ctx context.Context, accountID int64, credits *OpenAIRateLimitResetCredits) error +} + +type openAIQuotaResetWorkflowRecoverer interface { + RecoverAccountState(ctx context.Context, accountID int64, options AccountRecoveryOptions) (*SuccessfulTestRecoveryResult, error) +} + +// OpenAIQuotaResetPostProcessResult 汇总手动和自动用卡后的共享恢复结果。 +// WarningCode 允许上游消费成功但本地恢复部分失败时仍然准确呈现状态。 +type OpenAIQuotaResetPostProcessResult struct { + Quota *OpenAIQuotaUsage + Account *Account + CacheRefreshed bool + AccountStateRecovered bool + WarningCode string +} + +// RunOpenAIQuotaResetPostProcess 按“解除限流、刷新额度缓存、刷新账号行”的固定顺序 +// 执行消费后恢复,避免手动和自动入口在失败语义上逐渐分叉。 +func RunOpenAIQuotaResetPostProcess( + ctx context.Context, + accountID int64, + quota openAIQuotaResetWorkflowQuota, + recoverer openAIQuotaResetWorkflowRecoverer, + loadAccount func(context.Context, int64) (*Account, error), +) OpenAIQuotaResetPostProcessResult { + result := OpenAIQuotaResetPostProcessResult{} + if recoverer == nil { + result.WarningCode = OpenAIQuotaResetWarningAccountRecoveryFailed + return result + } + if _, err := recoverer.RecoverAccountState(ctx, accountID, AccountRecoveryOptions{InvalidateToken: true}); err != nil { + slog.Warn("openai_quota_reset_account_recovery_failed", "account_id", accountID, "error_code", infraerrors.Reason(err)) + result.WarningCode = OpenAIQuotaResetWarningAccountRecoveryFailed + return result + } + result.AccountStateRecovered = true + + if quota != nil { + usage, usageErr := quota.QueryUsage(ctx, accountID) + switch { + case usageErr != nil || usage == nil: + slog.Warn("openai_quota_reset_cache_refresh_failed", "account_id", accountID, "error_code", infraerrors.Reason(usageErr)) + result.WarningCode = OpenAIQuotaResetWarningCacheRefreshFailed + default: + if err := quota.CacheResetCreditsSnapshot(ctx, accountID, usage.RateLimitResetCredits); err != nil { + slog.Warn("openai_quota_reset_cache_refresh_failed", "account_id", accountID, "error_code", infraerrors.Reason(err)) + result.WarningCode = OpenAIQuotaResetWarningCacheRefreshFailed + } else { + result.Quota = usage + result.CacheRefreshed = true + } + } + } + + if loadAccount == nil { + return result + } + account, err := loadAccount(ctx, accountID) + if err != nil { + slog.Warn("openai_quota_reset_account_refresh_failed", "account_id", accountID, "error_code", infraerrors.Reason(err)) + if result.WarningCode == "" { + result.WarningCode = OpenAIQuotaResetWarningAccountRefreshFailed + } + return result + } + result.Account = account + return result +} diff --git a/backend/internal/service/openai_quota_service.go b/backend/internal/service/openai_quota_service.go index 58bf4659f5..6e40c497fc 100644 --- a/backend/internal/service/openai_quota_service.go +++ b/backend/internal/service/openai_quota_service.go @@ -87,6 +87,7 @@ type OpenAIQuotaUsage struct { AdditionalRateLimits []OpenAIAdditionalRateLimit `json:"additional_rate_limits,omitempty"` RateLimitResetCredits *OpenAIRateLimitResetCredits `json:"rate_limit_reset_credits,omitempty"` FetchedAt int64 `json:"fetched_at"` + autoResetCandidates []openAIAutoResetCreditCandidate } // OpenAIQuotaResetCredit captures the redeemed credit metadata returned by the @@ -180,6 +181,10 @@ func (s *OpenAIQuotaService) QueryUsage(ctx context.Context, accountID int64) (* continue } status := resp.StatusCode + if isOpenAIAutoResetContext(ctx) { + slog.Warn("openai_quota_query_failed", "account_id", accountID, "status", status, "source", "auto_reset") + return nil, infraerrors.Newf(mapUpstreamStatus(status), "OPENAI_QUOTA_UPSTREAM_ERROR", "upstream returned %d", status) + } body := truncate(s.redactQuotaErrorBody(ctx, accountID, resp.String()), 240) slog.Warn("openai_quota_query_failed", "account_id", accountID, "status", status, "body", body) return nil, infraerrors.Newf(mapUpstreamStatus(status), "OPENAI_QUOTA_UPSTREAM_ERROR", "upstream returned %d: %s", status, body) @@ -190,6 +195,7 @@ func (s *OpenAIQuotaService) QueryUsage(ctx context.Context, accountID int64) (* payload.FetchedAt = time.Now().Unix() details := s.queryResetCreditDetails(callCtx, client, accessToken, chatGPTAccountID, fedRAMP, accountID) if details != nil { + payload.autoResetCandidates = details.AutoResetCandidates hasDetailCount := details.AvailableCount != nil if payload.RateLimitResetCredits == nil { payload.RateLimitResetCredits = &OpenAIRateLimitResetCredits{} @@ -274,6 +280,25 @@ func (s *OpenAIQuotaService) queryResetCreditDetails(ctx context.Context, client // The redeem_request_id is auto-generated (uuid-like) — upstream uses it for // idempotency. Returns the consumed credit metadata so the UI can refresh. func (s *OpenAIQuotaService) ResetCredit(ctx context.Context, accountID int64) (*OpenAIQuotaResetResult, error) { + redeemRequestID, err := generateRedeemRequestID() + if err != nil { + return nil, infraerrors.Newf(http.StatusInternalServerError, "OPENAI_QUOTA_REDEEM_ID_FAILED", "failed to generate redeem id: %v", err) + } + return s.resetCredit(ctx, accountID, "", redeemRequestID, false) +} + +// ResetCreditTargeted 使用固定卡 ID 与兑换 ID执行自动消费。调用方必须在重试时 +// 复用同一组参数;本方法不会回退到不带 credit_id 的旧消费方式。 +func (s *OpenAIQuotaService) ResetCreditTargeted(ctx context.Context, accountID int64, creditID, redeemRequestID string) (*OpenAIQuotaResetResult, error) { + creditID = strings.TrimSpace(creditID) + redeemRequestID = strings.TrimSpace(redeemRequestID) + if creditID == "" || redeemRequestID == "" { + return nil, infraerrors.New(http.StatusBadRequest, "OPENAI_QUOTA_TARGETED_RESET_INVALID", "credit_id and redeem_request_id are required") + } + return s.resetCredit(ctx, accountID, creditID, redeemRequestID, true) +} + +func (s *OpenAIQuotaService) resetCredit(ctx context.Context, accountID int64, creditID, redeemRequestID string, targeted bool) (*OpenAIQuotaResetResult, error) { // Shadow guard: resetting credits via a shadow account would silently // operate on the parent's quota; that is surprising and unwanted. Callers // must reset the parent account directly. @@ -297,11 +322,6 @@ func (s *OpenAIQuotaService) ResetCredit(ctx context.Context, accountID int64) ( return nil, err } - redeemRequestID, err := generateRedeemRequestID() - if err != nil { - return nil, infraerrors.Newf(http.StatusInternalServerError, "OPENAI_QUOTA_REDEEM_ID_FAILED", "failed to generate redeem id: %v", err) - } - client, err := s.privacyClientFactory(proxyURL) if err != nil { return nil, infraerrors.Newf(http.StatusBadGateway, "OPENAI_QUOTA_CLIENT_ERROR", "failed to build upstream client: %v", err) @@ -318,10 +338,14 @@ func (s *OpenAIQuotaService) ResetCredit(ctx context.Context, accountID int64) ( return nil, infraerrors.Newf(http.StatusBadGateway, "OPENAI_QUOTA_AUTH_FAILED", "failed to build upstream authentication: %v", headerErr) } headers["content-type"] = "application/json" + body := map[string]string{"redeem_request_id": redeemRequestID} + if targeted { + body["credit_id"] = creditID + } resp, err := client.R(). SetContext(callCtx). SetHeaders(headers). - SetBody(map[string]string{"redeem_request_id": redeemRequestID}). + SetBody(body). SetSuccessResult(&payload). Post(chatGPTRateLimitResetURL) if err != nil { @@ -336,6 +360,10 @@ func (s *OpenAIQuotaService) ResetCredit(ctx context.Context, accountID int64) ( continue } status := resp.StatusCode + if targeted { + slog.Warn("openai_quota_targeted_reset_failed", "account_id", accountID, "status", status) + return nil, infraerrors.Newf(mapUpstreamStatus(status), "OPENAI_QUOTA_RESET_UPSTREAM_ERROR", "upstream returned %d", status) + } body := truncate(s.redactQuotaErrorBody(callCtx, accountID, resp.String()), 240) slog.Warn("openai_quota_reset_failed", "account_id", accountID, "status", status, "body", body) return nil, infraerrors.Newf(mapUpstreamStatus(status), "OPENAI_QUOTA_RESET_UPSTREAM_ERROR", "upstream returned %d: %s", status, body) diff --git a/backend/internal/service/openai_quota_spark_window_test.go b/backend/internal/service/openai_quota_spark_window_test.go index a351381cb4..cb47a0c0c5 100644 --- a/backend/internal/service/openai_quota_spark_window_test.go +++ b/backend/internal/service/openai_quota_spark_window_test.go @@ -189,6 +189,32 @@ func TestResetCreditShadowRejected(t *testing.T) { "shadow ResetCredit 应映射为 409 Conflict 而非 500") } +func TestResetCreditTargetedSendsStableCreditAndRedeemIDs(t *testing.T) { + account := &Account{ + ID: 203, Platform: PlatformOpenAI, Type: AccountTypeOAuth, + Credentials: map[string]any{"chatgpt_account_id": "account-targeted"}, + } + repo := &stubQuotaAccountRepo{accounts: map[int64]*Account{account.ID: account}} + tokenCache := &stubQuotaTokenCache{tokens: map[string]string{OpenAITokenCacheKey(account): "fake-token"}} + tokenProvider := NewOpenAITokenProvider(repo, tokenCache, nil) + var body map[string]string + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + require.Equal(t, "/backend-api/wham/rate-limit-reset-credits/consume", r.URL.Path) + require.NoError(t, json.NewDecoder(r.Body).Decode(&body)) + w.Header().Set("content-type", "application/json") + _, _ = w.Write([]byte(`{"code":"ok","windows_reset":1}`)) + })) + defer srv.Close() + + svc := NewOpenAIQuotaService(repo, nil, tokenProvider, newQuotaRedirectingFactory(srv)) + result, err := svc.ResetCreditTargeted(context.Background(), account.ID, "credit-123", "redeem-456") + require.NoError(t, err) + require.Equal(t, "ok", result.Code) + require.Equal(t, map[string]string{ + "credit_id": "credit-123", "redeem_request_id": "redeem-456", + }, body) +} + func TestResetCreditAgentIdentityUsesAssertionAndRecoversInvalidTaskOnce(t *testing.T) { _, privateKey, err := ed25519.GenerateKey(rand.Reader) require.NoError(t, err) diff --git a/backend/internal/service/ratelimit_service.go b/backend/internal/service/ratelimit_service.go index 2c42b810b6..f5ded9ccf0 100644 --- a/backend/internal/service/ratelimit_service.go +++ b/backend/internal/service/ratelimit_service.go @@ -1092,6 +1092,9 @@ func (s *RateLimitService) handle429(ctx context.Context, account *Account, head // 单影子场景直接变成无可用账号(外审第8轮 P1)。整段跳过;影子的 codex_* 仅由 account_usage 的 // QueryUsage→persistOpenAICodexProbeSnapshot 维护,枯竭由调度守卫处理。 if account.IsShadow() { + if account.ParentAccountID != nil { + notifyOpenAIAutoReset(*account.ParentAccountID) + } return } // 国产供应商(kimi/zhipu/deepseek)的 429 走专用可恢复路径:余额不足 → 临时停调, @@ -1105,6 +1108,7 @@ func (s *RateLimitService) handle429(ctx context.Context, account *Account, head if account.Platform == PlatformOpenAI { persistOpenAI429PlanType(ctx, s.accountRepo, account, responseBody) s.persistOpenAICodexSnapshot(ctx, account, headers) + notifyOpenAIAutoReset(account.ID) if resetAt := s.calculateOpenAI429ResetTime(headers); resetAt != nil { s.notifyAccountSchedulingBlocked(account, *resetAt, "429") if err := s.accountRepo.SetRateLimited(ctx, account.ID, *resetAt); err != nil { @@ -1620,7 +1624,9 @@ func (s *RateLimitService) persistOpenAICodexSnapshot(ctx context.Context, accou } if err := s.accountRepo.UpdateExtra(ctx, account.ID, updates); err != nil { slog.Warn("openai_codex_snapshot_persist_failed", "account_id", account.ID, "error", err) + return } + notifyOpenAIAutoReset(account.ID) } // parseOpenAIRateLimitResetTime 解析 OpenAI 格式的 429 响应,返回重置时间的 Unix 时间戳 diff --git a/backend/internal/service/wire.go b/backend/internal/service/wire.go index 3e469a95c5..a3e8cb935c 100644 --- a/backend/internal/service/wire.go +++ b/backend/internal/service/wire.go @@ -189,6 +189,29 @@ func ProvideOpenAIQuotaService( return service } +// ProvideOpenAIQuotaAutoResetService 启动账号级自动用卡队列与补偿扫描。 +func ProvideOpenAIQuotaAutoResetService( + accountRepo AccountRepository, + quotaService *OpenAIQuotaService, + rateLimitService *RateLimitService, + idempotency *IdempotencyCoordinator, + audit *AuditLogService, + settingService *SettingService, + leaderLock LeaderLockCache, +) *OpenAIQuotaAutoResetService { + service := NewOpenAIQuotaAutoResetService( + accountRepo, + quotaService, + rateLimitService, + idempotency, + audit, + settingService, + leaderLock, + ) + service.Start() + return service +} + func ProvideAccountUsageService( accountRepo AccountRepository, usageLogRepo UsageLogRepository, @@ -842,6 +865,7 @@ var ProviderSet = wire.NewSet( ProvideGrokTokenProvider, ProvideOpenAITokenProvider, ProvideOpenAIQuotaService, + ProvideOpenAIQuotaAutoResetService, ProvideGrokQuotaService, ProvideCNProviderQuotaService, ProvideCNProviderBalanceService, diff --git a/frontend/src/components/account/EditAccountModal.vue b/frontend/src/components/account/EditAccountModal.vue index d1cb92df59..e93d4726e1 100644 --- a/frontend/src/components/account/EditAccountModal.vue +++ b/frontend/src/components/account/EditAccountModal.vue @@ -2266,6 +2266,66 @@ +
+
+
+ +

+ {{ t('admin.accounts.autoResetCredit.hint') }} +

+
+ +
+
+
+ + +
+
+ + +
+
+

{{ t('admin.accounts.autoResetCredit.thresholdHint') }}

+
+
(null) const autoPause7dThreshold = ref(null) const autoPause5hDisabled = ref(false) const autoPause7dDisabled = ref(false) +const autoResetCreditEnabled = ref(false) +const autoResetCredit5hThreshold = ref(100) +const autoResetCredit7dThreshold = ref(100) const upstreamBillingAutoProbeEnabled = ref(false) const upstreamBillingRateSyncEnabled = ref(false) const mixedScheduling = ref(false) // For antigravity accounts: enable mixed scheduling @@ -3626,6 +3689,11 @@ const syncFormFromAccount = (newAccount: Account | null) => { autoPause7dThreshold.value = typeof extra?.auto_pause_7d_threshold === 'number' ? extra.auto_pause_7d_threshold * 100 : null autoPause5hDisabled.value = extra?.auto_pause_5h_disabled === true autoPause7dDisabled.value = extra?.auto_pause_7d_disabled === true + autoResetCreditEnabled.value = extra?.auto_reset_credit_enabled === true + autoResetCredit5hThreshold.value = + typeof extra?.auto_reset_credit_5h_threshold === 'number' ? extra.auto_reset_credit_5h_threshold * 100 : 100 + autoResetCredit7dThreshold.value = + typeof extra?.auto_reset_credit_7d_threshold === 'number' ? extra.auto_reset_credit_7d_threshold * 100 : 100 upstreamBillingAutoProbeEnabled.value = extra?.upstream_billing_probe_enabled === true upstreamBillingRateSyncEnabled.value = upstreamBillingAutoProbeEnabled.value && extra?.upstream_billing_rate_sync_enabled === true @@ -4518,6 +4586,13 @@ const handleSubmit = async () => { appStore.showError(t('admin.accounts.pleaseSelectStatus')) return } + if (autoResetCreditEnabled.value) { + const thresholds = [autoResetCredit5hThreshold.value, autoResetCredit7dThreshold.value] + if (thresholds.some((value) => !Number.isFinite(value) || value < 0.1 || value > 100)) { + appStore.showError(t('admin.accounts.autoResetCredit.thresholdInvalid')) + return + } + } const updatePayload: Record = { ...form } try { @@ -5082,6 +5157,13 @@ const handleSubmit = async () => { } else { delete newExtra.auto_pause_7d_disabled } + if (props.account.type === 'oauth' && !isSparkShadow.value) { + newExtra.auto_reset_credit_enabled = autoResetCreditEnabled.value + newExtra.auto_reset_credit_5h_threshold = autoResetCredit5hThreshold.value / 100 + newExtra.auto_reset_credit_7d_threshold = autoResetCredit7dThreshold.value / 100 + } + // 运行态只允许后端服务更新,账号编辑不得回写旧状态。 + delete newExtra.codex_auto_reset_credit_state delete newExtra.codex_image_generation_bridge_enabled switch (codexImageToolMode.value) { diff --git a/frontend/src/components/account/OpenAIQuotaResetCell.vue b/frontend/src/components/account/OpenAIQuotaResetCell.vue index cb81bcfd9d..6a3225b8bf 100644 --- a/frontend/src/components/account/OpenAIQuotaResetCell.vue +++ b/frontend/src/components/account/OpenAIQuotaResetCell.vue @@ -63,6 +63,32 @@
+
+ + {{ autoResetStateLabel }} + + {{ autoResetState.trigger_window }} + + + + {{ formatResetCreditExpiry(autoResetState.checked_at, 'short') }} + + + {{ autoResetState.error_code }} + +
+
(null) const showResetConfirm = ref(false) const showResetCreditDetails = ref(false) +type AutoResetCreditState = NonNullable['codex_auto_reset_credit_state']> +const validAutoResetStatuses = new Set(['checking', 'available', 'resetting', 'success', 'no_credit', 'failed']) +const autoResetState = computed(() => { + if (props.account.extra?.auto_reset_credit_enabled !== true) return null + const state = props.account.extra?.codex_auto_reset_credit_state + if (!state || typeof state !== 'object' || !validAutoResetStatuses.has(String(state.status))) return null + return state +}) +const autoResetStateLabel = computed(() => { + if (!autoResetState.value?.status) return '' + const keyByStatus: Record = { + checking: 'checking', + available: 'available', + resetting: 'resetting', + success: 'success', + no_credit: 'noCredit', + failed: 'failed' + } + return t(`admin.accounts.openaiQuotaReset.autoStatus.${keyByStatus[autoResetState.value.status]}`) +}) +const autoResetStateClass = computed(() => { + switch (autoResetState.value?.status) { + case 'available': + return 'bg-blue-50 text-blue-700 dark:bg-blue-900/30 dark:text-blue-300' + case 'success': + return 'bg-emerald-50 text-emerald-700 dark:bg-emerald-900/30 dark:text-emerald-300' + case 'no_credit': + case 'failed': + return 'bg-red-50 text-red-700 dark:bg-red-900/30 dark:text-red-300' + case 'resetting': + return 'bg-orange-50 text-orange-700 dark:bg-orange-900/30 dark:text-orange-300' + default: + return 'bg-gray-100 text-gray-600 dark:bg-dark-800 dark:text-gray-300' + } +}) + // Rehydrate the card from the persisted snapshot. Credits that already expired // are dropped and the count is clamped to what remains: the snapshot has no // freshness signal, so an unfiltered read would offer to consume credits that no diff --git a/frontend/src/components/account/__tests__/EditAccountModal.spec.ts b/frontend/src/components/account/__tests__/EditAccountModal.spec.ts index acd0436f6a..eceb670c92 100644 --- a/frontend/src/components/account/__tests__/EditAccountModal.spec.ts +++ b/frontend/src/components/account/__tests__/EditAccountModal.spec.ts @@ -290,6 +290,18 @@ function buildOpenAISetupTokenAccount() { } as any } +function buildOpenAIOAuthParentAccount() { + return { + ...buildAccount(), + id: 7, + name: 'OpenAI OAuth Parent', + type: 'oauth', + parent_account_id: null, + credentials: { access_token: 'oauth-token' }, + extra: {} + } as any +} + function mountModal(account = buildAccount()) { return mount(EditAccountModal, { props: { @@ -1351,3 +1363,63 @@ describe('EditAccountModal', () => { ) }) }) + +describe('EditAccountModal OpenAI 自动使用重置卡', () => { + beforeEach(() => { + authIsSimpleMode.value = true + updateAccountMock.mockReset() + checkMixedChannelRiskMock.mockReset().mockResolvedValue({ has_risk: false }) + }) + + it('仅对 OpenAI OAuth 母账号显示,默认关闭且阈值为 100/100', () => { + const parent = mountModal(buildOpenAIOAuthParentAccount()) + expect(parent.find('[data-testid="auto-reset-credit-settings"]').exists()).toBe(true) + expect((parent.get('[data-testid="auto-reset-credit-5h-threshold"]').element as HTMLInputElement).value).toBe('100') + expect((parent.get('[data-testid="auto-reset-credit-7d-threshold"]').element as HTMLInputElement).value).toBe('100') + expect(parent.get('[data-testid="auto-reset-credit-5h-threshold"]').attributes('disabled')).toBeDefined() + parent.unmount() + + for (const account of [buildAccount(), buildOpenAISetupTokenAccount(), buildOpenAISparkShadowAccount()]) { + const wrapper = mountModal(account) + expect(wrapper.find('[data-testid="auto-reset-credit-settings"]').exists()).toBe(false) + wrapper.unmount() + } + }) + + it('独立保存两个阈值,并禁止把运行态回写到管理请求', async () => { + const account = buildOpenAIOAuthParentAccount() + account.extra = { + codex_auto_reset_credit_state: { + status: 'success', + trigger_window: '5h', + available_count: 1 + } + } + updateAccountMock.mockResolvedValue(account) + const wrapper = mountModal(account) + + await wrapper.get('[data-testid="auto-reset-credit-enabled"]').trigger('click') + await wrapper.get('[data-testid="auto-reset-credit-5h-threshold"]').setValue('75.5') + await wrapper.get('[data-testid="auto-reset-credit-7d-threshold"]').setValue('92') + await wrapper.get('form#edit-account-form').trigger('submit.prevent') + + expect(updateAccountMock).toHaveBeenCalledTimes(1) + const extra = updateAccountMock.mock.calls[0]?.[1]?.extra + expect(extra).toMatchObject({ + auto_reset_credit_enabled: true, + auto_reset_credit_5h_threshold: 0.755, + auto_reset_credit_7d_threshold: 0.92 + }) + expect(extra).not.toHaveProperty('codex_auto_reset_credit_state') + wrapper.unmount() + }) + + it('开启后拒绝超出 0.1–100 范围的任一阈值', async () => { + const wrapper = mountModal(buildOpenAIOAuthParentAccount()) + await wrapper.get('[data-testid="auto-reset-credit-enabled"]').trigger('click') + await wrapper.get('[data-testid="auto-reset-credit-5h-threshold"]').setValue('0') + await wrapper.get('form#edit-account-form').trigger('submit.prevent') + expect(updateAccountMock).not.toHaveBeenCalled() + wrapper.unmount() + }) +}) diff --git a/frontend/src/components/account/__tests__/OpenAIQuotaResetCell.spark_shadow.spec.ts b/frontend/src/components/account/__tests__/OpenAIQuotaResetCell.spark_shadow.spec.ts index f888cbee44..280725bc5b 100644 --- a/frontend/src/components/account/__tests__/OpenAIQuotaResetCell.spark_shadow.spec.ts +++ b/frontend/src/components/account/__tests__/OpenAIQuotaResetCell.spark_shadow.spec.ts @@ -344,3 +344,45 @@ describe('OpenAIQuotaResetCell — 外审 F6:影子禁用重置', () => { wrapper.unmount() }) }) + +describe('OpenAIQuotaResetCell 自动用卡运行态', () => { + it.each([ + ['checking', 'checking'], + ['available', 'available'], + ['resetting', 'resetting'], + ['success', 'success'], + ['no_credit', 'noCredit'], + ['failed', 'failed'], + ] as const)('展示 %s 状态且不需要暴露卡标识', (status, labelKey) => { + const account = makeAccount({ + extra: { + auto_reset_credit_enabled: true, + codex_auto_reset_credit_state: { + status, + trigger_window: '5h', + available_count: 1, + checked_at: '2099-07-03T04:05:06Z', + error_code: status === 'failed' ? 'RESET_FAILED' : undefined, + }, + }, + }) + const wrapper = mount(OpenAIQuotaResetCell, { props: { account } }) + const state = wrapper.get('[data-testid="auto-reset-credit-state"]') + expect(state.text()).toContain(`admin.accounts.openaiQuotaReset.autoStatus.${labelKey}`) + expect(state.text()).toContain('5h') + expect(state.text()).not.toContain('credit_id') + wrapper.unmount() + }) + + it('开关关闭时不显示历史运行态', () => { + const account = makeAccount({ + extra: { + auto_reset_credit_enabled: false, + codex_auto_reset_credit_state: { status: 'success', available_count: 1 }, + }, + }) + const wrapper = mount(OpenAIQuotaResetCell, { props: { account } }) + expect(wrapper.find('[data-testid="auto-reset-credit-state"]').exists()).toBe(false) + wrapper.unmount() + }) +}) diff --git a/frontend/src/i18n/locales/en/admin/accounts.ts b/frontend/src/i18n/locales/en/admin/accounts.ts index 3c126b78b0..9a2b1739b0 100644 --- a/frontend/src/i18n/locales/en/admin/accounts.ts +++ b/frontend/src/i18n/locales/en/admin/accounts.ts @@ -821,6 +821,14 @@ export default { autoPause5hDisabled: 'Disable 5h auto-pause', autoPause7dDisabled: 'Disable 7d auto-pause', autoPauseDisabledHint: 'When enabled, this account is never auto-paused (even if a global default threshold is configured).', + autoResetCredit: { + title: 'Automatically use reset credits', + hint: 'Uses the earliest-expiring available credit only when actual usage reaches a threshold. Off by default; the account remains paused if no credit is available or reset fails.', + threshold5h: '5h auto-reset threshold (%)', + threshold7d: '7d auto-reset threshold (%)', + thresholdHint: 'Each window is evaluated independently. Enter 0.1–100; both default to 100.', + thresholdInvalid: 'Automatic reset-credit thresholds must be between 0.1% and 100%.' + }, // Quota control (Anthropic OAuth/SetupToken only) quotaControl: { title: 'Quota Control', @@ -1515,6 +1523,14 @@ export default { resetAccountRecoveryFailed: 'The window was reset, but account state recovery failed. Recover the account state manually.', resetAccountRefreshFailed: 'The window, account state, and reset-credit cache were updated, but the latest account display could not be loaded.', refreshCachePersistFailed: 'Showing the live count, but its expiration details were unavailable, so the cached details were kept.', + autoStatus: { + checking: 'Checking', + available: 'Credit available', + resetting: 'Auto-resetting', + success: 'Auto-reset succeeded', + noCredit: 'No credit', + failed: 'Auto-reset failed' + }, confirmTitle: 'Confirm Weekly Limit Reset', confirmMessage: 'This will consume 1 reset credit to immediately restore the current window ({count} remaining). This action cannot be undone. Continue?' }, diff --git a/frontend/src/i18n/locales/zh/admin/accounts.ts b/frontend/src/i18n/locales/zh/admin/accounts.ts index 923776d259..4c44d93392 100644 --- a/frontend/src/i18n/locales/zh/admin/accounts.ts +++ b/frontend/src/i18n/locales/zh/admin/accounts.ts @@ -486,6 +486,14 @@ export default { resetAccountRecoveryFailed: '窗口已重置,但账号状态恢复失败,请手动恢复账号状态。', resetAccountRefreshFailed: '窗口、账号状态和重置次数缓存已更新,但无法加载最新账号显示。', refreshCachePersistFailed: '已显示实时次数,但到期明细获取失败,仍保留原有缓存明细。', + autoStatus: { + checking: '检测中', + available: '卡可用', + resetting: '自动重置中', + success: '自动重置成功', + noCredit: '无卡', + failed: '自动重置失败' + }, confirmTitle: '确认重置周限', confirmMessage: '将消耗 1 次重置次数立即恢复当前窗口,剩余 {count} 次。此操作不可撤销,确定继续吗?' }, @@ -885,6 +893,14 @@ export default { autoPause5hDisabled: '禁用 5h 自动暂停', autoPause7dDisabled: '禁用 7d 自动暂停', autoPauseDisabledHint: '开启后该账号永不进入自动暂停(即使全局默认阈值已配置)。', + autoResetCredit: { + title: '自动使用重置卡', + hint: '仅在实际用量达到阈值时使用最早到期的可用卡;默认关闭。无卡或失败时账号保持暂停。', + threshold5h: '5h 自动用卡阈值(%)', + threshold7d: '7d 自动用卡阈值(%)', + thresholdHint: '两个窗口独立判断,任一达到自身阈值即触发。可填写 0.1–100,默认均为 100。', + thresholdInvalid: '自动使用重置卡阈值必须在 0.1% 到 100% 之间。' + }, // Quota control (Anthropic OAuth/SetupToken only) quotaControl: { title: '配额控制', diff --git a/frontend/src/types/index.ts b/frontend/src/types/index.ts index df6075c5c9..10a72a0a17 100644 --- a/frontend/src/types/index.ts +++ b/frontend/src/types/index.ts @@ -1134,6 +1134,17 @@ export interface Account { available_count?: number credits?: { expires_at?: string }[] } + auto_reset_credit_enabled?: boolean + auto_reset_credit_5h_threshold?: number + auto_reset_credit_7d_threshold?: number + codex_auto_reset_credit_state?: { + status?: 'checking' | 'available' | 'resetting' | 'success' | 'no_credit' | 'failed' + trigger_window?: string + available_count?: number + checked_at?: string + last_result_at?: string + error_code?: string + } } & Record) proxy_id: number | null proxy_fallback_origin_id?: number | null From 96b160d9a0c07121f87ebce4a313374c0ad711c6 Mon Sep 17 00:00:00 2001 From: NellPoi Date: Mon, 24 Aug 2026 13:46:19 +0800 Subject: [PATCH 149/204] =?UTF-8?q?fix:=20=E4=BF=AE=E5=A4=8D=E9=87=8D?= =?UTF-8?q?=E7=BD=AE=E5=B7=A5=E4=BD=9C=E6=B5=81=E5=85=B1=E4=BA=AB=E5=91=8A?= =?UTF-8?q?=E8=AD=A6=E7=A0=81=E6=A3=80=E6=9F=A5?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../internal/handler/admin/openai_oauth_handler.go | 8 -------- .../admin/openai_oauth_handler_reset_quota_test.go | 14 +++++++------- 2 files changed, 7 insertions(+), 15 deletions(-) diff --git a/backend/internal/handler/admin/openai_oauth_handler.go b/backend/internal/handler/admin/openai_oauth_handler.go index ce83d4bfe8..779e4455cd 100644 --- a/backend/internal/handler/admin/openai_oauth_handler.go +++ b/backend/internal/handler/admin/openai_oauth_handler.go @@ -41,14 +41,6 @@ type openAIAccountStateRecoverer interface { // it — spending a second credit. const openAIQuotaResetPostProcessTimeout = 8 * time.Second -// 保留 handler 包内的告警码名称,避免共享工作流下沉到 service 后破坏既有测试和包内调用。 -// 实际值统一引用 service 常量,防止手动重置与自动重置的响应码发生漂移。 -const ( - openAIQuotaResetWarningCacheRefreshFailed = service.OpenAIQuotaResetWarningCacheRefreshFailed - openAIQuotaResetWarningAccountRecoveryFailed = service.OpenAIQuotaResetWarningAccountRecoveryFailed - openAIQuotaResetWarningAccountRefreshFailed = service.OpenAIQuotaResetWarningAccountRefreshFailed -) - type openAIQuotaResetResponse struct { service.OpenAIQuotaResetResult Quota *service.OpenAIQuotaUsage `json:"quota,omitempty"` diff --git a/backend/internal/handler/admin/openai_oauth_handler_reset_quota_test.go b/backend/internal/handler/admin/openai_oauth_handler_reset_quota_test.go index c0e3ca161d..b9e8dac679 100644 --- a/backend/internal/handler/admin/openai_oauth_handler_reset_quota_test.go +++ b/backend/internal/handler/admin/openai_oauth_handler_reset_quota_test.go @@ -215,7 +215,7 @@ func TestOpenAIResetQuota_RecoveryFailureStopsWorkflow(t *testing.T) { status, envelope := performOpenAIQuotaResetRequest(t, handler) require.Equal(t, http.StatusOK, status) - require.Equal(t, openAIQuotaResetWarningAccountRecoveryFailed, envelope.Data.WarningCode) + require.Equal(t, service.OpenAIQuotaResetWarningAccountRecoveryFailed, envelope.Data.WarningCode) require.False(t, envelope.Data.AccountStateRecovered) require.False(t, envelope.Data.CacheRefreshed) require.Nil(t, envelope.Data.Quota) @@ -237,7 +237,7 @@ func TestOpenAIResetQuota_MissingRecovererReportsRecoveryFailure(t *testing.T) { status, envelope := performOpenAIQuotaResetRequest(t, handler) require.Equal(t, http.StatusOK, status) - require.Equal(t, openAIQuotaResetWarningAccountRecoveryFailed, envelope.Data.WarningCode) + require.Equal(t, service.OpenAIQuotaResetWarningAccountRecoveryFailed, envelope.Data.WarningCode) require.False(t, envelope.Data.AccountStateRecovered) require.Zero(t, quota.queryCalls) require.Zero(t, adminService.calls) @@ -260,7 +260,7 @@ func TestOpenAIResetQuota_QueryFailureStillRecoversAndReturnsAccount(t *testing. status, envelope := performOpenAIQuotaResetRequest(t, handler) require.Equal(t, http.StatusOK, status) - require.Equal(t, openAIQuotaResetWarningCacheRefreshFailed, envelope.Data.WarningCode) + require.Equal(t, service.OpenAIQuotaResetWarningCacheRefreshFailed, envelope.Data.WarningCode) require.True(t, envelope.Data.AccountStateRecovered) require.False(t, envelope.Data.CacheRefreshed) require.Nil(t, envelope.Data.Quota) @@ -285,7 +285,7 @@ func TestOpenAIResetQuota_CacheFailureStillRecoversAndReturnsAccount(t *testing. status, envelope := performOpenAIQuotaResetRequest(t, handler) require.Equal(t, http.StatusOK, status) - require.Equal(t, openAIQuotaResetWarningCacheRefreshFailed, envelope.Data.WarningCode) + require.Equal(t, service.OpenAIQuotaResetWarningCacheRefreshFailed, envelope.Data.WarningCode) require.True(t, envelope.Data.AccountStateRecovered) require.False(t, envelope.Data.CacheRefreshed) require.Nil(t, envelope.Data.Quota) @@ -307,7 +307,7 @@ func TestOpenAIResetQuota_AccountRefreshFailureReportsRecoveredState(t *testing. status, envelope := performOpenAIQuotaResetRequest(t, handler) require.Equal(t, http.StatusOK, status) - require.Equal(t, openAIQuotaResetWarningAccountRefreshFailed, envelope.Data.WarningCode) + require.Equal(t, service.OpenAIQuotaResetWarningAccountRefreshFailed, envelope.Data.WarningCode) require.True(t, envelope.Data.CacheRefreshed) require.True(t, envelope.Data.AccountStateRecovered) require.NotNil(t, envelope.Data.Quota) @@ -331,7 +331,7 @@ func TestOpenAIResetQuota_CacheAndAccountFailureKeepsFirstWarning(t *testing.T) status, envelope := performOpenAIQuotaResetRequest(t, handler) require.Equal(t, http.StatusOK, status) - require.Equal(t, openAIQuotaResetWarningCacheRefreshFailed, envelope.Data.WarningCode) + require.Equal(t, service.OpenAIQuotaResetWarningCacheRefreshFailed, envelope.Data.WarningCode) require.True(t, envelope.Data.AccountStateRecovered) require.Nil(t, envelope.Data.Account) } @@ -435,7 +435,7 @@ func TestOpenAIQuotaEmptyUsageIsHandledWithoutPanic(t *testing.T) { status, envelope := performOpenAIQuotaResetRequest(t, handler) require.Equal(t, http.StatusOK, status) - require.Equal(t, openAIQuotaResetWarningCacheRefreshFailed, envelope.Data.WarningCode) + require.Equal(t, service.OpenAIQuotaResetWarningCacheRefreshFailed, envelope.Data.WarningCode) require.True(t, envelope.Data.AccountStateRecovered) require.NotNil(t, envelope.Data.Account) require.Zero(t, quota.cacheCalls) From 847c0c45263b8823b32c0f8c34387e1f7a6c1f3b Mon Sep 17 00:00:00 2001 From: Xiangzhe Date: Mon, 24 Aug 2026 14:20:00 +0800 Subject: [PATCH 150/204] feat(gateway): configure model list read limit Add gateway.models_list_read_max_bytes with the existing 8 MiB behavior as its default, and apply it consistently to generic, Codex, and Antigravity model-list reads. Read one sentinel byte for Codex manifests so oversized responses return an explicit bounded upstream error instead of malformed JSON. --- backend/cmd/server/wire_gen.go | 2 +- backend/internal/config/config.go | 10 ++++ backend/internal/config/config_test.go | 12 +++++ backend/internal/pkg/antigravity/client.go | 13 +++--- .../internal/pkg/antigravity/client_test.go | 46 +++++++++++++++---- .../service/antigravity_quota_fetcher.go | 8 ++-- .../service/antigravity_quota_fetcher_test.go | 35 ++++++++++++++ .../service/models_list_response_limit.go | 10 ++++ .../models_list_response_limit_test.go | 25 ++++++++++ .../service/openai_codex_models_service.go | 20 +++++--- .../openai_codex_models_service_test.go | 46 +++++++++++++++++++ backend/internal/service/upstream_models.go | 16 ++++--- .../internal/service/upstream_models_test.go | 25 ++++++++++ deploy/config.example.yaml | 3 ++ 14 files changed, 240 insertions(+), 31 deletions(-) create mode 100644 backend/internal/service/models_list_response_limit.go create mode 100644 backend/internal/service/models_list_response_limit_test.go diff --git a/backend/cmd/server/wire_gen.go b/backend/cmd/server/wire_gen.go index 1300989dc6..5ac2ba5823 100644 --- a/backend/cmd/server/wire_gen.go +++ b/backend/cmd/server/wire_gen.go @@ -194,7 +194,7 @@ func initializeApplication(buildInfo handler.BuildInfo) (*Application, error) { groupCapacityService := service.NewGroupCapacityService(accountRepository, groupRepository, concurrencyService, sessionLimitCache, rpmCache) groupHandler := admin.NewGroupHandler(adminService, dashboardService, groupCapacityService) claudeUsageFetcher := repository.NewClaudeUsageFetcher(httpUpstream) - antigravityQuotaFetcher := service.NewAntigravityQuotaFetcher(proxyRepository) + antigravityQuotaFetcher := service.NewAntigravityQuotaFetcher(proxyRepository, configConfig) grokQuotaFetcher := service.NewGrokQuotaFetcher() grokQuotaService := service.ProvideGrokQuotaService(accountRepository, proxyRepository, grokTokenProvider, httpUpstream, configConfig, usageLogRepository, settingService) openAIQuotaService := service.ProvideOpenAIQuotaService(accountRepository, proxyRepository, openAITokenProvider, privacyClientFactory, openAIGatewayService) diff --git a/backend/internal/config/config.go b/backend/internal/config/config.go index b8218d1824..8c856cbf61 100644 --- a/backend/internal/config/config.go +++ b/backend/internal/config/config.go @@ -61,6 +61,10 @@ const ( // 可通过 gateway.upstream_response_read_max_bytes 配置项覆盖。 const DefaultUpstreamResponseReadMaxBytes int64 = 128 * 1024 * 1024 +// DefaultModelsListReadMaxBytes 上游模型列表响应体的默认读取上限。 +// 可通过 gateway.models_list_read_max_bytes 配置项覆盖。 +const DefaultModelsListReadMaxBytes int64 = 8 * 1024 * 1024 + type Config struct { Server ServerConfig `mapstructure:"server"` Log LogConfig `mapstructure:"log"` @@ -960,6 +964,8 @@ type GatewayConfig struct { TextMaxBodySize int64 `mapstructure:"text_max_body_size"` // 非流式上游响应体读取上限(字节),用于防止无界读取导致内存放大 UpstreamResponseReadMaxBytes int64 `mapstructure:"upstream_response_read_max_bytes"` + // 上游模型列表响应体读取上限(字节) + ModelsListReadMaxBytes int64 `mapstructure:"models_list_read_max_bytes"` // 代理探测响应体读取上限(字节) ProxyProbeResponseReadMaxBytes int64 `mapstructure:"proxy_probe_response_read_max_bytes"` // Gemini 上游响应头调试日志开关(默认关闭,避免高频日志开销) @@ -2456,6 +2462,7 @@ func setDefaults() { viper.SetDefault("gateway.max_body_size", int64(256*1024*1024)) viper.SetDefault("gateway.text_max_body_size", int64(32*1024*1024)) viper.SetDefault("gateway.upstream_response_read_max_bytes", DefaultUpstreamResponseReadMaxBytes) + viper.SetDefault("gateway.models_list_read_max_bytes", DefaultModelsListReadMaxBytes) viper.SetDefault("gateway.proxy_probe_response_read_max_bytes", int64(1024*1024)) viper.SetDefault("gateway.gemini_debug_response_headers", false) viper.SetDefault("gateway.connection_pool_isolation", ConnectionPoolIsolationAccountProxy) @@ -3265,6 +3272,9 @@ func (c *Config) Validate() error { if c.Gateway.UpstreamResponseReadMaxBytes <= 0 { return fmt.Errorf("gateway.upstream_response_read_max_bytes must be positive") } + if c.Gateway.ModelsListReadMaxBytes <= 0 { + return fmt.Errorf("gateway.models_list_read_max_bytes must be positive") + } if c.Gateway.ProxyProbeResponseReadMaxBytes <= 0 { return fmt.Errorf("gateway.proxy_probe_response_read_max_bytes must be positive") } diff --git a/backend/internal/config/config_test.go b/backend/internal/config/config_test.go index 7cef4dfc1f..a8fbba0977 100644 --- a/backend/internal/config/config_test.go +++ b/backend/internal/config/config_test.go @@ -23,6 +23,13 @@ func resetViperWithJWTSecret(t *testing.T) { t.Setenv("JWT_SECRET", strings.Repeat("x", 32)) } +func TestLoadDefaultModelsListReadMaxBytes(t *testing.T) { + resetViperWithJWTSecret(t) + cfg, err := Load() + require.NoError(t, err) + require.Equal(t, DefaultModelsListReadMaxBytes, cfg.Gateway.ModelsListReadMaxBytes) +} + func TestLoadTimezonePrecedence(t *testing.T) { tests := []struct { name string @@ -1803,6 +1810,11 @@ func TestValidateConfigErrors(t *testing.T) { mutate: func(c *Config) { c.Gateway.TextMaxBodySize = c.Gateway.MaxBodySize + 1 }, wantErr: "gateway.text_max_body_size", }, + { + name: "gateway models list read limit", + mutate: func(c *Config) { c.Gateway.ModelsListReadMaxBytes = 0 }, + wantErr: "gateway.models_list_read_max_bytes", + }, { name: "gateway response header timeout", mutate: func(c *Config) { c.Gateway.ResponseHeaderTimeout = -1 }, diff --git a/backend/internal/pkg/antigravity/client.go b/backend/internal/pkg/antigravity/client.go index 785c8af3c4..a3ea6709f7 100644 --- a/backend/internal/pkg/antigravity/client.go +++ b/backend/internal/pkg/antigravity/client.go @@ -255,8 +255,6 @@ const ( proxyTLSHandshakeTimeout = 5 * time.Second // clientTimeout 整体请求超时(含连接、发送、等待响应、读取 body) clientTimeout = 10 * time.Second - // fetchAvailableModelsBodyLimit limits model-list responses to avoid unbounded memory use. - fetchAvailableModelsBodyLimit int64 = 8 << 20 ) func NewClient(proxyURL string) (*Client, error) { @@ -656,10 +654,13 @@ type FetchAvailableModelsResponse struct { // FetchAvailableModels 获取可用模型和配额信息,返回解析后的结构体和原始 JSON // 支持 URL fallback:sandbox → daily → prod -func (c *Client) FetchAvailableModels(ctx context.Context, accessToken, projectID string) (*FetchAvailableModelsResponse, map[string]any, error) { +func (c *Client) FetchAvailableModels(ctx context.Context, accessToken, projectID string, bodyLimit int64) (*FetchAvailableModelsResponse, map[string]any, error) { if c == nil || c.httpClient == nil { return nil, nil, errors.New("antigravity client is not configured") } + if bodyLimit <= 0 { + return nil, nil, errors.New("fetchAvailableModels body limit must be positive") + } reqBody := FetchAvailableModelsRequest{Project: projectID} bodyBytes, err := json.Marshal(reqBody) @@ -693,13 +694,13 @@ func (c *Client) FetchAvailableModels(ctx context.Context, accessToken, projectI return nil, nil, lastErr } - respBodyBytes, err := io.ReadAll(io.LimitReader(resp.Body, fetchAvailableModelsBodyLimit+1)) + respBodyBytes, err := io.ReadAll(io.LimitReader(resp.Body, bodyLimit+1)) _ = resp.Body.Close() // 立即关闭,避免循环内 defer 导致的资源泄漏 if err != nil { return nil, nil, fmt.Errorf("读取响应失败: %w", err) } - if int64(len(respBodyBytes)) > fetchAvailableModelsBodyLimit { - return nil, nil, fmt.Errorf("响应超过 %d 字节", fetchAvailableModelsBodyLimit) + if int64(len(respBodyBytes)) > bodyLimit { + return nil, nil, fmt.Errorf("响应超过 %d 字节", bodyLimit) } // 检查是否需要 URL 降级 diff --git a/backend/internal/pkg/antigravity/client_test.go b/backend/internal/pkg/antigravity/client_test.go index b6c2e6a502..7a525879fa 100644 --- a/backend/internal/pkg/antigravity/client_test.go +++ b/backend/internal/pkg/antigravity/client_test.go @@ -15,6 +15,8 @@ import ( "time" ) +const defaultFetchAvailableModelsBodyLimit int64 = 8 << 20 + // --------------------------------------------------------------------------- // NewAPIRequestWithURL // --------------------------------------------------------------------------- @@ -1517,7 +1519,7 @@ func TestClient_FetchAvailableModels_Success_RealCall(t *testing.T) { withMockBaseURLs(t, []string{server.URL}) client := mustNewClient(t, "") - resp, rawResp, err := client.FetchAvailableModels(context.Background(), "test-token", "project-abc") + resp, rawResp, err := client.FetchAvailableModels(context.Background(), "test-token", "project-abc", defaultFetchAvailableModelsBodyLimit) if err != nil { t.Fatalf("FetchAvailableModels 失败: %v", err) } @@ -1562,6 +1564,34 @@ func TestClient_FetchAvailableModels_Success_RealCall(t *testing.T) { } } +func TestClient_FetchAvailableModels_RejectsNonPositiveBodyLimit(t *testing.T) { + client := mustNewClient(t, "") + _, _, err := client.FetchAvailableModels(context.Background(), "token", "proj", 0) + if err == nil || !strings.Contains(err.Error(), "body limit must be positive") { + t.Fatalf("非正读取上限应返回调用错误: %v", err) + } +} + +func TestClient_FetchAvailableModels_UsesConfiguredBodyLimit(t *testing.T) { + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + w.Header().Set("Content-Type", "application/json") + w.WriteHeader(http.StatusOK) + _, _ = w.Write([]byte(`{"models":{"model-a":{}}}`)) + })) + defer server.Close() + + withMockBaseURLs(t, []string{server.URL}) + + client := mustNewClient(t, "") + _, _, err := client.FetchAvailableModels(context.Background(), "token", "proj", 8) + if err == nil { + t.Fatal("响应超过配置上限时应返回错误") + } + if !strings.Contains(err.Error(), "响应超过 8 字节") { + t.Fatalf("错误应包含配置上限: %v", err) + } +} + func TestClient_FetchAvailableModels_HTTPError_RealCall(t *testing.T) { server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { w.WriteHeader(http.StatusForbidden) @@ -1572,7 +1602,7 @@ func TestClient_FetchAvailableModels_HTTPError_RealCall(t *testing.T) { withMockBaseURLs(t, []string{server.URL}) client := mustNewClient(t, "") - _, _, err := client.FetchAvailableModels(context.Background(), "bad-token", "proj") + _, _, err := client.FetchAvailableModels(context.Background(), "bad-token", "proj", defaultFetchAvailableModelsBodyLimit) if err == nil { t.Fatal("服务器返回 403 时应返回错误") } @@ -1592,7 +1622,7 @@ func TestClient_FetchAvailableModels_InvalidJSON_RealCall(t *testing.T) { withMockBaseURLs(t, []string{server.URL}) client := mustNewClient(t, "") - _, _, err := client.FetchAvailableModels(context.Background(), "token", "proj") + _, _, err := client.FetchAvailableModels(context.Background(), "token", "proj", defaultFetchAvailableModelsBodyLimit) if err == nil { t.Fatal("无效 JSON 响应应返回错误") } @@ -1622,7 +1652,7 @@ func TestClient_FetchAvailableModels_URLFallback_RealCall(t *testing.T) { withMockBaseURLs(t, []string{server1.URL, server2.URL}) client := mustNewClient(t, "") - resp, _, err := client.FetchAvailableModels(context.Background(), "token", "proj") + resp, _, err := client.FetchAvailableModels(context.Background(), "token", "proj", defaultFetchAvailableModelsBodyLimit) if err != nil { t.Fatalf("FetchAvailableModels 应在 fallback 后成功: %v", err) } @@ -1650,7 +1680,7 @@ func TestClient_FetchAvailableModels_AllURLsFail_RealCall(t *testing.T) { withMockBaseURLs(t, []string{server1.URL, server2.URL}) client := mustNewClient(t, "") - _, _, err := client.FetchAvailableModels(context.Background(), "token", "proj") + _, _, err := client.FetchAvailableModels(context.Background(), "token", "proj", defaultFetchAvailableModelsBodyLimit) if err == nil { t.Fatal("所有 URL 都失败时应返回错误") } @@ -1669,7 +1699,7 @@ func TestClient_FetchAvailableModels_ContextCanceled_RealCall(t *testing.T) { ctx, cancel := context.WithCancel(context.Background()) cancel() - _, _, err := client.FetchAvailableModels(ctx, "token", "proj") + _, _, err := client.FetchAvailableModels(ctx, "token", "proj", defaultFetchAvailableModelsBodyLimit) if err == nil { t.Fatal("context 取消时应返回错误") } @@ -1686,7 +1716,7 @@ func TestClient_FetchAvailableModels_EmptyModels_RealCall(t *testing.T) { withMockBaseURLs(t, []string{server.URL}) client := mustNewClient(t, "") - resp, rawResp, err := client.FetchAvailableModels(context.Background(), "token", "proj") + resp, rawResp, err := client.FetchAvailableModels(context.Background(), "token", "proj", defaultFetchAvailableModelsBodyLimit) if err != nil { t.Fatalf("FetchAvailableModels 失败: %v", err) } @@ -1748,7 +1778,7 @@ func TestClient_FetchAvailableModels_404Fallback_RealCall(t *testing.T) { withMockBaseURLs(t, []string{server1.URL, server2.URL}) client := mustNewClient(t, "") - resp, _, err := client.FetchAvailableModels(context.Background(), "token", "proj") + resp, _, err := client.FetchAvailableModels(context.Background(), "token", "proj", defaultFetchAvailableModelsBodyLimit) if err != nil { t.Fatalf("FetchAvailableModels 应在 404 fallback 后成功: %v", err) } diff --git a/backend/internal/service/antigravity_quota_fetcher.go b/backend/internal/service/antigravity_quota_fetcher.go index 9e09c90443..e296654e6d 100644 --- a/backend/internal/service/antigravity_quota_fetcher.go +++ b/backend/internal/service/antigravity_quota_fetcher.go @@ -10,6 +10,7 @@ import ( "strings" "time" + "github.com/Wei-Shaw/sub2api/internal/config" "github.com/Wei-Shaw/sub2api/internal/pkg/antigravity" ) @@ -28,11 +29,12 @@ const ( // AntigravityQuotaFetcher 从 Antigravity API 获取额度 type AntigravityQuotaFetcher struct { proxyRepo ProxyRepository + cfg *config.Config } // NewAntigravityQuotaFetcher 创建 AntigravityQuotaFetcher -func NewAntigravityQuotaFetcher(proxyRepo ProxyRepository) *AntigravityQuotaFetcher { - return &AntigravityQuotaFetcher{proxyRepo: proxyRepo} +func NewAntigravityQuotaFetcher(proxyRepo ProxyRepository, cfg *config.Config) *AntigravityQuotaFetcher { + return &AntigravityQuotaFetcher{proxyRepo: proxyRepo, cfg: cfg} } // CanFetch 检查是否可以获取此账户的额度 @@ -55,7 +57,7 @@ func (f *AntigravityQuotaFetcher) FetchQuota(ctx context.Context, account *Accou } // 调用 API 获取配额 - modelsResp, modelsRaw, err := client.FetchAvailableModels(ctx, accessToken, projectID) + modelsResp, modelsRaw, err := client.FetchAvailableModels(ctx, accessToken, projectID, resolveModelsListReadLimit(f.cfg)) if err != nil { // 403 Forbidden: 不报错,返回 is_forbidden 标记 var forbiddenErr *antigravity.ForbiddenError diff --git a/backend/internal/service/antigravity_quota_fetcher_test.go b/backend/internal/service/antigravity_quota_fetcher_test.go index e0f5705141..a5463ec007 100644 --- a/backend/internal/service/antigravity_quota_fetcher_test.go +++ b/backend/internal/service/antigravity_quota_fetcher_test.go @@ -3,11 +3,16 @@ package service import ( + "context" "errors" + "net/http" + "net/http/httptest" "testing" + "time" "github.com/stretchr/testify/require" + "github.com/Wei-Shaw/sub2api/internal/config" "github.com/Wei-Shaw/sub2api/internal/pkg/antigravity" ) @@ -390,6 +395,36 @@ func TestBuildUsageInfo_AICredits(t *testing.T) { require.Equal(t, 5.0, info.AICredits[0].MinimumBalance) } +func TestFetchQuotaUsesConfiguredModelsListBodyLimit(t *testing.T) { + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { + w.Header().Set("Content-Type", "application/json") + _, _ = w.Write([]byte(`{"models":{"model-a":{}}}`)) + })) + defer server.Close() + + oldBaseURLs := append([]string(nil), antigravity.BaseURLs...) + oldAvailability := antigravity.DefaultURLAvailability + t.Cleanup(func() { + antigravity.BaseURLs = oldBaseURLs + antigravity.DefaultURLAvailability = oldAvailability + }) + antigravity.BaseURLs = []string{server.URL} + antigravity.DefaultURLAvailability = antigravity.NewURLAvailability(time.Minute) + + cfg := &config.Config{} + cfg.Gateway.ModelsListReadMaxBytes = 8 + fetcher := NewAntigravityQuotaFetcher(nil, cfg) + _, err := fetcher.FetchQuota(context.Background(), &Account{ + Platform: PlatformAntigravity, + Type: AccountTypeOAuth, + Credentials: map[string]any{ + "access_token": "token", + "project_id": "project", + }, + }, "") + require.ErrorContains(t, err, "响应超过 8 字节") +} + func TestFetchQuota_ForbiddenReturnsIsForbidden(t *testing.T) { // 模拟 FetchQuota 遇到 403 时的行为: // FetchAvailableModels 返回 ForbiddenError → FetchQuota 应返回 is_forbidden=true diff --git a/backend/internal/service/models_list_response_limit.go b/backend/internal/service/models_list_response_limit.go new file mode 100644 index 0000000000..b10260fd98 --- /dev/null +++ b/backend/internal/service/models_list_response_limit.go @@ -0,0 +1,10 @@ +package service + +import "github.com/Wei-Shaw/sub2api/internal/config" + +func resolveModelsListReadLimit(cfg *config.Config) int64 { + if cfg != nil && cfg.Gateway.ModelsListReadMaxBytes > 0 { + return cfg.Gateway.ModelsListReadMaxBytes + } + return config.DefaultModelsListReadMaxBytes +} diff --git a/backend/internal/service/models_list_response_limit_test.go b/backend/internal/service/models_list_response_limit_test.go new file mode 100644 index 0000000000..d697351510 --- /dev/null +++ b/backend/internal/service/models_list_response_limit_test.go @@ -0,0 +1,25 @@ +package service + +import ( + "testing" + + "github.com/Wei-Shaw/sub2api/internal/config" + "github.com/stretchr/testify/require" +) + +func TestResolveModelsListReadLimit(t *testing.T) { + t.Run("nil config uses default", func(t *testing.T) { + require.Equal(t, config.DefaultModelsListReadMaxBytes, resolveModelsListReadLimit(nil)) + }) + + t.Run("configured limit wins", func(t *testing.T) { + cfg := &config.Config{} + cfg.Gateway.ModelsListReadMaxBytes = 16 << 20 + require.Equal(t, int64(16<<20), resolveModelsListReadLimit(cfg)) + }) + + t.Run("non-positive limit uses default", func(t *testing.T) { + cfg := &config.Config{} + require.Equal(t, config.DefaultModelsListReadMaxBytes, resolveModelsListReadLimit(cfg)) + }) +} diff --git a/backend/internal/service/openai_codex_models_service.go b/backend/internal/service/openai_codex_models_service.go index 02279b5c0c..7c06dc99bd 100644 --- a/backend/internal/service/openai_codex_models_service.go +++ b/backend/internal/service/openai_codex_models_service.go @@ -27,12 +27,11 @@ import ( var chatgptCodexModelsURL = "https://chatgpt.com/backend-api/codex/models" const ( - codexModelsManifestBodyLimit int64 = 8 << 20 - codexModelsManifestCacheBodyLimit = 1 << 20 - codexModelsManifestCacheMaxEntries = 64 - codexModelsManifestCacheTTL = 30 * time.Second - codexModelsManifestCacheStaleTTL = 5 * time.Minute - codexModelsManifestRequestTimeout = 15 * time.Second + codexModelsManifestCacheBodyLimit = 1 << 20 + codexModelsManifestCacheMaxEntries = 64 + codexModelsManifestCacheTTL = 30 * time.Second + codexModelsManifestCacheStaleTTL = 5 * time.Minute + codexModelsManifestRequestTimeout = 15 * time.Second ) // CodexModelsManifest carries the client representation plus caching metadata. @@ -515,13 +514,20 @@ func (s *OpenAIGatewayService) fetchCodexModelsManifestUpstream(ctx context.Cont } } - body, err := io.ReadAll(io.LimitReader(resp.Body, codexModelsManifestBodyLimit)) + bodyLimit := resolveModelsListReadLimit(s.cfg) + body, err := io.ReadAll(io.LimitReader(resp.Body, bodyLimit+1)) if err != nil { return nil, &codexModelsManifestUpstreamError{ err: infraerrors.Newf(http.StatusBadGateway, "OPENAI_CODEX_MODELS_UPSTREAM_FAILED", "read codex models manifest response: %v", err), retryable: isRetryableCodexModelsManifestTransportError(err), } } + if int64(len(body)) > bodyLimit { + return nil, &codexModelsManifestUpstreamError{ + err: infraerrors.Newf(http.StatusBadGateway, "OPENAI_CODEX_MODELS_UPSTREAM_FAILED", "codex models manifest response exceeds %d bytes", bodyLimit), + retryable: true, + } + } upstreamBody := body if request.useAPIKeyUpstream { body = convertOpenAIModelListToCodexManifest(body) diff --git a/backend/internal/service/openai_codex_models_service_test.go b/backend/internal/service/openai_codex_models_service_test.go index 8f4c495755..503d494857 100644 --- a/backend/internal/service/openai_codex_models_service_test.go +++ b/backend/internal/service/openai_codex_models_service_test.go @@ -1,6 +1,7 @@ package service import ( + "bytes" "context" "errors" "fmt" @@ -623,6 +624,51 @@ func TestConvertOpenAIModelListToCodexManifest(t *testing.T) { } } +func TestFetchCodexModelsManifestUsesConfiguredBodyLimit(t *testing.T) { + upstream := &codexModelsHTTPUpstreamStub{do: func(_ *http.Request, _ string, _ int64, _ int) (*http.Response, error) { + return &http.Response{ + StatusCode: http.StatusOK, + Header: make(http.Header), + Body: io.NopCloser(strings.NewReader(`{"models":[{"slug":"gpt-5.6"}]}`)), + }, nil + }} + + s := newCodexModelsAPIKeyTestService(upstream) + s.cfg.Gateway.ModelsListReadMaxBytes = 8 + _, err := s.FetchCodexModelsManifest( + context.Background(), + newCodexModelsAPIKeyTestAccount("https://upstream.example"), + "0.144.0", + "", + ) + require.Error(t, err) + require.Equal(t, "OPENAI_CODEX_MODELS_UPSTREAM_FAILED", infraerrors.Reason(err)) + require.Contains(t, err.Error(), "response exceeds 8 bytes") + require.True(t, IsRetryableCodexModelsManifestError(err)) +} + +func TestFetchCodexModelsManifestAcceptsConfiguredLimitAboveLegacyBoundary(t *testing.T) { + manifestBody := `{"models":[{"slug":"gpt-5.6","display_name":"` + strings.Repeat("x", (8<<20)+1024) + `"}]}` + require.Greater(t, len(manifestBody), 8<<20) + require.Less(t, len(manifestBody), 16<<20) + + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { + w.Header().Set("Content-Type", "application/json") + _, _ = io.WriteString(w, manifestBody) + })) + defer server.Close() + + original := chatgptCodexModelsURL + chatgptCodexModelsURL = server.URL + defer func() { chatgptCodexModelsURL = original }() + + s := &OpenAIGatewayService{cfg: &config.Config{}} + s.cfg.Gateway.ModelsListReadMaxBytes = 16 << 20 + manifest, err := s.FetchCodexModelsManifest(context.Background(), newCodexModelsTestAccount(), "0.144.0", "") + require.NoError(t, err) + require.True(t, bytes.Equal([]byte(manifestBody), manifest.Body), "manifest body must be returned intact") +} + func TestFetchCodexModelsManifestRejectsInvalidEnvelope(t *testing.T) { tests := []struct { name string diff --git a/backend/internal/service/upstream_models.go b/backend/internal/service/upstream_models.go index 3941794860..790b2243d2 100644 --- a/backend/internal/service/upstream_models.go +++ b/backend/internal/service/upstream_models.go @@ -14,8 +14,6 @@ import ( "github.com/Wei-Shaw/sub2api/internal/pkg/geminicli" ) -const upstreamModelsBodyLimit int64 = 8 << 20 - // UpstreamModelSyncErrorKind classifies model sync failures for safe HTTP mapping. type UpstreamModelSyncErrorKind string @@ -101,12 +99,13 @@ func (s *AccountTestService) FetchUpstreamSupportedModels(ctx context.Context, a } defer func() { _ = resp.Body.Close() }() - body, err := io.ReadAll(io.LimitReader(resp.Body, upstreamModelsBodyLimit+1)) + bodyLimit := resolveModelsListReadLimit(s.cfg) + body, err := io.ReadAll(io.LimitReader(resp.Body, bodyLimit+1)) if err != nil { return nil, newUpstreamModelSyncUpstreamError("Failed to read upstream model list", err) } - if int64(len(body)) > upstreamModelsBodyLimit { - return nil, newUpstreamModelSyncUpstreamError("Upstream model list response is too large", fmt.Errorf("response exceeds %d bytes", upstreamModelsBodyLimit)) + if int64(len(body)) > bodyLimit { + return nil, newUpstreamModelSyncUpstreamError("Upstream model list response is too large", fmt.Errorf("response exceeds %d bytes", bodyLimit)) } if resp.StatusCode < http.StatusOK || resp.StatusCode >= http.StatusMultipleChoices { @@ -506,7 +505,12 @@ func (s *AccountTestService) fetchAntigravityOAuthUpstreamModels(ctx context.Con if err != nil { return nil, newUpstreamModelSyncConfigError("Failed to configure Antigravity client", err) } - modelsResp, _, err := client.FetchAvailableModels(ctx, accessToken, strings.TrimSpace(account.GetCredential("project_id"))) + modelsResp, _, err := client.FetchAvailableModels( + ctx, + accessToken, + strings.TrimSpace(account.GetCredential("project_id")), + resolveModelsListReadLimit(s.cfg), + ) if err != nil { return nil, newUpstreamModelSyncUpstreamError("Failed to fetch Antigravity available models", err) } diff --git a/backend/internal/service/upstream_models_test.go b/backend/internal/service/upstream_models_test.go index b6f3cb3f95..114c647d45 100644 --- a/backend/internal/service/upstream_models_test.go +++ b/backend/internal/service/upstream_models_test.go @@ -394,6 +394,31 @@ func TestFetchUpstreamSupportedModelsParsesOpenAIResponse(t *testing.T) { require.Equal(t, "Bearer openai-key", upstream.lastReq.Header.Get("Authorization")) } +func TestFetchUpstreamSupportedModelsUsesConfiguredBodyLimit(t *testing.T) { + t.Parallel() + + upstream := &httpUpstreamRecorder{resp: &http.Response{ + StatusCode: http.StatusOK, + Header: http.Header{"Content-Type": []string{"application/json"}}, + Body: io.NopCloser(strings.NewReader(`{"data":[{"id":"gpt-5"}]}`)), + }} + cfg := upstreamModelSyncTestConfig() + cfg.Gateway.ModelsListReadMaxBytes = 8 + svc := &AccountTestService{httpUpstream: upstream, cfg: cfg} + + _, err := svc.FetchUpstreamSupportedModels(context.Background(), &Account{ + ID: 7, + Platform: PlatformOpenAI, + Type: AccountTypeAPIKey, + Credentials: map[string]any{ + "api_key": "openai-key", + "base_url": "https://openai.example.com/v1", + }, + }) + require.Error(t, err) + require.Contains(t, err.Error(), "response exceeds 8 bytes") +} + func TestFetchUpstreamSupportedModelsParsesGrokAPIKeyResponse(t *testing.T) { t.Parallel() diff --git a/deploy/config.example.yaml b/deploy/config.example.yaml index a0dbfbf973..033cb29908 100644 --- a/deploy/config.example.yaml +++ b/deploy/config.example.yaml @@ -235,6 +235,9 @@ gateway: # Max bytes to read for non-stream upstream responses (default: 8MB) # 非流式上游响应体读取上限(默认 8MB) upstream_response_read_max_bytes: 8388608 + # Max bytes to read for upstream model-list responses (default: 8MB) + # 上游模型列表响应体读取上限(默认 8MB) + models_list_read_max_bytes: 8388608 # Max bytes to read for proxy probe responses (default: 1MB) # 代理探测响应体读取上限(默认 1MB) proxy_probe_response_read_max_bytes: 1048576 From 03e8ab41346b42de9ece4e3e5bfcb6ca2b8cb57e Mon Sep 17 00:00:00 2001 From: "github-actions[bot]" <41898282+github-actions[bot]@users.noreply.github.com> Date: Mon, 24 Aug 2026 07:30:34 +0000 Subject: [PATCH 151/204] chore: sync VERSION to 0.1.180 [skip ci] --- backend/cmd/server/VERSION | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/backend/cmd/server/VERSION b/backend/cmd/server/VERSION index f4fdeb66be..2005625e83 100644 --- a/backend/cmd/server/VERSION +++ b/backend/cmd/server/VERSION @@ -1 +1 @@ -0.1.179 +0.1.180 From 99ec347eaff944d255032565717053ad02d5f5f3 Mon Sep 17 00:00:00 2001 From: wucm667 Date: Thu, 20 Aug 2026 22:45:35 +0800 Subject: [PATCH 152/204] fix(antigravity): migrate legacy Sonnet tests to 4.6 --- backend/internal/domain/constants.go | 6 +-- backend/internal/domain/constants_test.go | 14 ++++++ .../internal/service/account_test_service.go | 18 ++++--- .../account_test_service_antigravity_test.go | 16 ++++++ .../antigravity_credits_overages_test.go | 6 +-- .../service/antigravity_model_mapping_test.go | 12 ++--- .../service/antigravity_rate_limit_test.go | 50 ++++++++++++++++--- .../antigravity_single_account_retry_test.go | 4 +- .../internal/service/model_rate_limit_test.go | 8 +-- 9 files changed, 103 insertions(+), 31 deletions(-) create mode 100644 backend/internal/service/account_test_service_antigravity_test.go diff --git a/backend/internal/domain/constants.go b/backend/internal/domain/constants.go index cd821165a4..6500502014 100644 --- a/backend/internal/domain/constants.go +++ b/backend/internal/domain/constants.go @@ -105,11 +105,11 @@ var DefaultAntigravityModelMapping = map[string]string{ "claude-opus-4-6": "claude-opus-4-6-thinking", // 简称映射 "claude-opus-4-5-thinking": "claude-opus-4-6-thinking", // 迁移旧模型 "claude-sonnet-4-6": "claude-sonnet-4-6", - "claude-sonnet-4-5": "claude-sonnet-4-5", - "claude-sonnet-4-5-thinking": "claude-sonnet-4-5-thinking", + "claude-sonnet-4-5": "claude-sonnet-4-6", // 迁移旧模型 + "claude-sonnet-4-5-thinking": "claude-sonnet-4-6", // 迁移旧模型 // Claude 详细版本 ID 映射 "claude-opus-4-5-20251101": "claude-opus-4-6-thinking", // 迁移旧模型 - "claude-sonnet-4-5-20250929": "claude-sonnet-4-5", + "claude-sonnet-4-5-20250929": "claude-sonnet-4-6", // 迁移旧模型 // Claude Haiku → Sonnet(无 Haiku 支持) "claude-haiku-4-5": "claude-sonnet-4-6", "claude-haiku-4-5-20251001": "claude-sonnet-4-6", diff --git a/backend/internal/domain/constants_test.go b/backend/internal/domain/constants_test.go index e847e22f30..7cfcd7fa51 100644 --- a/backend/internal/domain/constants_test.go +++ b/backend/internal/domain/constants_test.go @@ -43,6 +43,20 @@ func TestDefaultAntigravityModelMapping_ContainsNewClaudeModels(t *testing.T) { } } +func TestDefaultAntigravityModelMapping_MigratesLegacySonnet45(t *testing.T) { + t.Parallel() + + for _, model := range []string{ + "claude-sonnet-4-5", + "claude-sonnet-4-5-thinking", + "claude-sonnet-4-5-20250929", + } { + if got := DefaultAntigravityModelMapping[model]; got != "claude-sonnet-4-6" { + t.Fatalf("expected legacy model %q to map to claude-sonnet-4-6, got %q", model, got) + } + } +} + func TestDefaultAntigravityModelMapping_Gemini31ProAliases(t *testing.T) { t.Parallel() diff --git a/backend/internal/service/account_test_service.go b/backend/internal/service/account_test_service.go index 451f90db16..e7ce083ff5 100644 --- a/backend/internal/service/account_test_service.go +++ b/backend/internal/service/account_test_service.go @@ -43,8 +43,9 @@ import ( var sseDataPrefix = regexp.MustCompile(`^data:\s*`) const ( - testClaudeAPIURL = "https://api.anthropic.com/v1/messages?beta=true" - chatgptCodexAPIURL = "https://chatgpt.com/backend-api/codex/responses" + testClaudeAPIURL = "https://api.anthropic.com/v1/messages?beta=true" + chatgptCodexAPIURL = "https://chatgpt.com/backend-api/codex/responses" + defaultAntigravityTestModel = "claude-sonnet-4-6" ) // TestEvent represents a SSE event for account testing @@ -2311,11 +2312,7 @@ func (s *AccountTestService) routeAntigravityTest(c *gin.Context, account *Accou func (s *AccountTestService) testAntigravityAccountConnection(c *gin.Context, account *Account, modelID string) error { ctx := c.Request.Context() - // 默认模型:Claude 使用 claude-sonnet-4-5,Gemini 使用 gemini-3-pro-preview - testModelID := modelID - if testModelID == "" { - testModelID = "claude-sonnet-4-5" - } + testModelID := antigravityConnectionTestModel(modelID) if s.antigravityGatewayService == nil { return s.sendErrorAndEnd(c, "Antigravity gateway service not configured") @@ -2346,6 +2343,13 @@ func (s *AccountTestService) testAntigravityAccountConnection(c *gin.Context, ac return nil } +func antigravityConnectionTestModel(modelID string) string { + if modelID == "" { + return defaultAntigravityTestModel + } + return modelID +} + // buildGeminiAPIKeyRequest builds request for Gemini API Key accounts func (s *AccountTestService) buildGeminiAPIKeyRequest(ctx context.Context, account *Account, modelID string, payload []byte) (*http.Request, error) { apiKey := account.GetCredential("api_key") diff --git a/backend/internal/service/account_test_service_antigravity_test.go b/backend/internal/service/account_test_service_antigravity_test.go new file mode 100644 index 0000000000..b3362f3f69 --- /dev/null +++ b/backend/internal/service/account_test_service_antigravity_test.go @@ -0,0 +1,16 @@ +//go:build unit + +package service + +import ( + "testing" + + "github.com/stretchr/testify/require" +) + +func TestAntigravityConnectionTestModel(t *testing.T) { + t.Parallel() + + require.Equal(t, "claude-sonnet-4-6", antigravityConnectionTestModel("")) + require.Equal(t, "gemini-3.1-pro-preview", antigravityConnectionTestModel("gemini-3.1-pro-preview")) +} diff --git a/backend/internal/service/antigravity_credits_overages_test.go b/backend/internal/service/antigravity_credits_overages_test.go index 7a5224daf3..bdba5cec7b 100644 --- a/backend/internal/service/antigravity_credits_overages_test.go +++ b/backend/internal/service/antigravity_credits_overages_test.go @@ -239,7 +239,7 @@ func TestAntigravityRetryLoop_ModelRateLimited_InjectsCredits(t *testing.T) { Extra: map[string]any{ "allow_overages": true, modelRateLimitsKey: map[string]any{ - "claude-sonnet-4-5": map[string]any{ + "claude-sonnet-4-6": map[string]any{ "rate_limited_at": time.Now().UTC().Format(time.RFC3339), "rate_limit_reset_at": time.Now().Add(30 * time.Minute).UTC().Format(time.RFC3339), }, @@ -290,7 +290,7 @@ func TestAntigravityRetryLoop_CreditsExhausted_DoesNotInject(t *testing.T) { Extra: map[string]any{ "allow_overages": true, modelRateLimitsKey: map[string]any{ - "claude-sonnet-4-5": map[string]any{ + "claude-sonnet-4-6": map[string]any{ "rate_limited_at": time.Now().UTC().Format(time.RFC3339), "rate_limit_reset_at": time.Now().Add(30 * time.Minute).UTC().Format(time.RFC3339), }, @@ -355,7 +355,7 @@ func TestAntigravityRetryLoop_CreditErrorMarksExhausted(t *testing.T) { Extra: map[string]any{ "allow_overages": true, modelRateLimitsKey: map[string]any{ - "claude-sonnet-4-5": map[string]any{ + "claude-sonnet-4-6": map[string]any{ "rate_limited_at": time.Now().UTC().Format(time.RFC3339), "rate_limit_reset_at": time.Now().Add(30 * time.Minute).UTC().Format(time.RFC3339), }, diff --git a/backend/internal/service/antigravity_model_mapping_test.go b/backend/internal/service/antigravity_model_mapping_test.go index 62ff2e295d..0f86aa4a9c 100644 --- a/backend/internal/service/antigravity_model_mapping_test.go +++ b/backend/internal/service/antigravity_model_mapping_test.go @@ -69,10 +69,10 @@ func TestAntigravityGatewayService_GetMappedModel(t *testing.T) { expected: "claude-sonnet-4-6", }, { - name: "默认映射 - claude-sonnet-4-5-20250929 → claude-sonnet-4-5", + name: "默认映射 - claude-sonnet-4-5-20250929 → claude-sonnet-4-6", requestedModel: "claude-sonnet-4-5-20250929", accountMapping: nil, - expected: "claude-sonnet-4-5", + expected: "claude-sonnet-4-6", }, // 3. 默认映射中的透传(映射到自己) @@ -89,10 +89,10 @@ func TestAntigravityGatewayService_GetMappedModel(t *testing.T) { expected: "claude-sonnet-4-6", }, { - name: "默认映射透传 - claude-sonnet-4-5", + name: "默认映射 - claude-sonnet-4-5 → claude-sonnet-4-6", requestedModel: "claude-sonnet-4-5", accountMapping: nil, - expected: "claude-sonnet-4-5", + expected: "claude-sonnet-4-6", }, { name: "默认映射透传 - claude-opus-4-8", @@ -113,10 +113,10 @@ func TestAntigravityGatewayService_GetMappedModel(t *testing.T) { expected: "claude-opus-4-6-thinking", }, { - name: "默认映射透传 - claude-sonnet-4-5-thinking", + name: "默认映射 - claude-sonnet-4-5-thinking → claude-sonnet-4-6", requestedModel: "claude-sonnet-4-5-thinking", accountMapping: nil, - expected: "claude-sonnet-4-5-thinking", + expected: "claude-sonnet-4-6", }, { name: "默认映射透传 - gemini-2.5-flash", diff --git a/backend/internal/service/antigravity_rate_limit_test.go b/backend/internal/service/antigravity_rate_limit_test.go index c9b4298291..7a06a4e49e 100644 --- a/backend/internal/service/antigravity_rate_limit_test.go +++ b/backend/internal/service/antigravity_rate_limit_test.go @@ -206,7 +206,7 @@ func TestHandleUpstreamError_429_NonModelRateLimit(t *testing.T) { // 但 429 兜底逻辑会使用 requestedModel 设置模型级限流 require.Nil(t, result) require.Len(t, repo.modelRateLimitCalls, 1) - require.Equal(t, "claude-sonnet-4-5", repo.modelRateLimitCalls[0].modelKey) + require.Equal(t, "claude-sonnet-4-6", repo.modelRateLimitCalls[0].modelKey) } // TestHandleUpstreamError_429_NonModelRateLimit_UsesMappedModelKey 测试 429 非模型限流场景 @@ -844,17 +844,28 @@ func TestSetAntigravityModelRateLimits_GeminiWritesFamilyScope(t *testing.T) { require.Equal(t, antigravityGeminiModelRateLimitKey, repo.modelRateLimitCalls[1].modelKey) } -func TestSetAntigravityModelRateLimits_ClaudeDoesNotWriteGeminiScope(t *testing.T) { +func TestSetAntigravityModelRateLimits_DoesNotDoubleMapCustomChain(t *testing.T) { repo := &stubAntigravityAccountRepo{} svc := &AntigravityGatewayService{} - account := &Account{ID: 790, Platform: PlatformAntigravity} + account := &Account{ + ID: 790, + Platform: PlatformAntigravity, + Credentials: map[string]any{ + "model_mapping": map[string]any{ + "custom-sonnet": "claude-sonnet-4-5", + "claude-sonnet-4-5": "claude-sonnet-4-6", + }, + }, + } resetAt := time.Now().Add(30 * time.Second) + canonicalModel := resolveFinalAntigravityModelKey(context.Background(), account, "custom-sonnet") + require.Equal(t, "claude-sonnet-4-5", canonicalModel) success := svc.setAntigravityModelRateLimits( context.Background(), repo, account, - "claude-sonnet-4-5", + canonicalModel, "[test]", 429, resetAt, @@ -866,6 +877,33 @@ func TestSetAntigravityModelRateLimits_ClaudeDoesNotWriteGeminiScope(t *testing. require.Equal(t, "claude-sonnet-4-5", repo.modelRateLimitCalls[0].modelKey) } +func TestSetModelRateLimitAndClearSession_UsesUpstreamReportedModelMetadata(t *testing.T) { + repo := &stubAntigravityAccountRepo{} + svc := &AntigravityGatewayService{accountRepo: repo} + account := &Account{ + ID: 791, + Platform: PlatformAntigravity, + Credentials: map[string]any{ + "model_mapping": map[string]any{ + "claude-sonnet-4-5": "claude-sonnet-4-6", + }, + }, + } + + svc.setModelRateLimitAndClearSession(&handleModelRateLimitParams{ + ctx: context.Background(), + prefix: "[test]", + account: account, + statusCode: 429, + }, &antigravitySmartRetryInfo{ + RetryDelay: 30 * time.Second, + ModelName: "claude-sonnet-4-5", + }) + + require.Len(t, repo.modelRateLimitCalls, 1) + require.Equal(t, "claude-sonnet-4-5", repo.modelRateLimitCalls[0].modelKey) +} + func TestAntigravityRetryLoop_PreCheck_SwitchesWhenRateLimited(t *testing.T) { upstream := &recordingOKUpstream{} account := &Account{ @@ -877,7 +915,7 @@ func TestAntigravityRetryLoop_PreCheck_SwitchesWhenRateLimited(t *testing.T) { Concurrency: 1, Extra: map[string]any{ modelRateLimitsKey: map[string]any{ - "claude-sonnet-4-5": map[string]any{ + "claude-sonnet-4-6": map[string]any{ "rate_limit_reset_at": time.Now().Add(2 * time.Second).Format(time.RFC3339), }, }, @@ -920,7 +958,7 @@ func TestAntigravityRetryLoop_PreCheck_SwitchesWhenRemainingLong(t *testing.T) { Concurrency: 1, Extra: map[string]any{ modelRateLimitsKey: map[string]any{ - "claude-sonnet-4-5": map[string]any{ + "claude-sonnet-4-6": map[string]any{ "rate_limit_reset_at": time.Now().Add(11 * time.Second).Format(time.RFC3339), }, }, diff --git a/backend/internal/service/antigravity_single_account_retry_test.go b/backend/internal/service/antigravity_single_account_retry_test.go index 6e58ab75d2..85677e59c4 100644 --- a/backend/internal/service/antigravity_single_account_retry_test.go +++ b/backend/internal/service/antigravity_single_account_retry_test.go @@ -693,7 +693,7 @@ func TestAntigravityRetryLoop_PreCheck_SingleAccountRetry_SkipsRateLimit(t *test Concurrency: 1, Extra: map[string]any{ modelRateLimitsKey: map[string]any{ - "claude-sonnet-4-5": map[string]any{ + "claude-sonnet-4-6": map[string]any{ "rate_limit_reset_at": time.Now().Add(30 * time.Second).Format(time.RFC3339), }, }, @@ -737,7 +737,7 @@ func TestAntigravityRetryLoop_PreCheck_NoSingleAccountRetry_SwitchesOnRateLimit( Concurrency: 1, Extra: map[string]any{ modelRateLimitsKey: map[string]any{ - "claude-sonnet-4-5": map[string]any{ + "claude-sonnet-4-6": map[string]any{ "rate_limit_reset_at": time.Now().Add(30 * time.Second).Format(time.RFC3339), }, }, diff --git a/backend/internal/service/model_rate_limit_test.go b/backend/internal/service/model_rate_limit_test.go index 430d91baf6..3293853d74 100644 --- a/backend/internal/service/model_rate_limit_test.go +++ b/backend/internal/service/model_rate_limit_test.go @@ -255,7 +255,7 @@ func TestIsModelRateLimited_OpenAIImageGenerationIntentBlocksTextModelImageTool( require.True(t, account.isModelRateLimitedWithContext(WithOpenAIImageGenerationIntent(context.Background()), "gpt-5.4")) } -func TestIsModelRateLimited_Antigravity_ThinkingAffectsModelKey(t *testing.T) { +func TestIsModelRateLimited_Antigravity_LegacySonnetUsesCanonicalModelKey(t *testing.T) { now := time.Now() future := now.Add(10 * time.Minute).Format(time.RFC3339) @@ -263,7 +263,7 @@ func TestIsModelRateLimited_Antigravity_ThinkingAffectsModelKey(t *testing.T) { Platform: PlatformAntigravity, Extra: map[string]any{ modelRateLimitsKey: map[string]any{ - "claude-sonnet-4-5-thinking": map[string]any{ + "claude-sonnet-4-6": map[string]any{ "rate_limit_reset_at": future, }, }, @@ -453,7 +453,7 @@ func TestGetRateLimitRemainingTime(t *testing.T) { Platform: PlatformAntigravity, Extra: map[string]any{ modelRateLimitsKey: map[string]any{ - "claude-sonnet-4-5": map[string]any{ + "claude-sonnet-4-6": map[string]any{ "rate_limit_reset_at": future15m, }, }, @@ -469,7 +469,7 @@ func TestGetRateLimitRemainingTime(t *testing.T) { Platform: PlatformAntigravity, Extra: map[string]any{ modelRateLimitsKey: map[string]any{ - "claude-sonnet-4-5": map[string]any{ + "claude-sonnet-4-6": map[string]any{ "rate_limit_reset_at": future5m, }, }, From 71aa6e357448736105f24f4032836bb6e570ed65 Mon Sep 17 00:00:00 2001 From: wucm667 Date: Mon, 24 Aug 2026 16:07:27 +0800 Subject: [PATCH 153/204] fix(antigravity): preserve explicit Sonnet 4.5 routing --- backend/internal/domain/constants.go | 4 ++-- backend/internal/domain/constants_test.go | 17 +++++++++-------- .../antigravity_credits_overages_test.go | 6 +++--- .../service/antigravity_model_mapping_test.go | 13 +++++++++++-- .../service/antigravity_rate_limit_test.go | 6 +++--- .../antigravity_single_account_retry_test.go | 4 ++-- .../internal/service/model_rate_limit_test.go | 8 ++++---- 7 files changed, 34 insertions(+), 24 deletions(-) diff --git a/backend/internal/domain/constants.go b/backend/internal/domain/constants.go index 6500502014..1ed90ee940 100644 --- a/backend/internal/domain/constants.go +++ b/backend/internal/domain/constants.go @@ -105,8 +105,8 @@ var DefaultAntigravityModelMapping = map[string]string{ "claude-opus-4-6": "claude-opus-4-6-thinking", // 简称映射 "claude-opus-4-5-thinking": "claude-opus-4-6-thinking", // 迁移旧模型 "claude-sonnet-4-6": "claude-sonnet-4-6", - "claude-sonnet-4-5": "claude-sonnet-4-6", // 迁移旧模型 - "claude-sonnet-4-5-thinking": "claude-sonnet-4-6", // 迁移旧模型 + "claude-sonnet-4-5": "claude-sonnet-4-5", // 显式 canonical 选择透传 + "claude-sonnet-4-5-thinking": "claude-sonnet-4-6", // 迁移旧兼容别名 // Claude 详细版本 ID 映射 "claude-opus-4-5-20251101": "claude-opus-4-6-thinking", // 迁移旧模型 "claude-sonnet-4-5-20250929": "claude-sonnet-4-6", // 迁移旧模型 diff --git a/backend/internal/domain/constants_test.go b/backend/internal/domain/constants_test.go index 7cfcd7fa51..acac038ef2 100644 --- a/backend/internal/domain/constants_test.go +++ b/backend/internal/domain/constants_test.go @@ -43,16 +43,17 @@ func TestDefaultAntigravityModelMapping_ContainsNewClaudeModels(t *testing.T) { } } -func TestDefaultAntigravityModelMapping_MigratesLegacySonnet45(t *testing.T) { +func TestDefaultAntigravityModelMapping_PreservesExplicitSonnet45AndMigratesLegacyAliases(t *testing.T) { t.Parallel() - for _, model := range []string{ - "claude-sonnet-4-5", - "claude-sonnet-4-5-thinking", - "claude-sonnet-4-5-20250929", - } { - if got := DefaultAntigravityModelMapping[model]; got != "claude-sonnet-4-6" { - t.Fatalf("expected legacy model %q to map to claude-sonnet-4-6, got %q", model, got) + cases := map[string]string{ + "claude-sonnet-4-5": "claude-sonnet-4-5", + "claude-sonnet-4-5-thinking": "claude-sonnet-4-6", + "claude-sonnet-4-5-20250929": "claude-sonnet-4-6", + } + for model, want := range cases { + if got := DefaultAntigravityModelMapping[model]; got != want { + t.Fatalf("expected model %q to map to %q, got %q", model, want, got) } } } diff --git a/backend/internal/service/antigravity_credits_overages_test.go b/backend/internal/service/antigravity_credits_overages_test.go index bdba5cec7b..7a5224daf3 100644 --- a/backend/internal/service/antigravity_credits_overages_test.go +++ b/backend/internal/service/antigravity_credits_overages_test.go @@ -239,7 +239,7 @@ func TestAntigravityRetryLoop_ModelRateLimited_InjectsCredits(t *testing.T) { Extra: map[string]any{ "allow_overages": true, modelRateLimitsKey: map[string]any{ - "claude-sonnet-4-6": map[string]any{ + "claude-sonnet-4-5": map[string]any{ "rate_limited_at": time.Now().UTC().Format(time.RFC3339), "rate_limit_reset_at": time.Now().Add(30 * time.Minute).UTC().Format(time.RFC3339), }, @@ -290,7 +290,7 @@ func TestAntigravityRetryLoop_CreditsExhausted_DoesNotInject(t *testing.T) { Extra: map[string]any{ "allow_overages": true, modelRateLimitsKey: map[string]any{ - "claude-sonnet-4-6": map[string]any{ + "claude-sonnet-4-5": map[string]any{ "rate_limited_at": time.Now().UTC().Format(time.RFC3339), "rate_limit_reset_at": time.Now().Add(30 * time.Minute).UTC().Format(time.RFC3339), }, @@ -355,7 +355,7 @@ func TestAntigravityRetryLoop_CreditErrorMarksExhausted(t *testing.T) { Extra: map[string]any{ "allow_overages": true, modelRateLimitsKey: map[string]any{ - "claude-sonnet-4-6": map[string]any{ + "claude-sonnet-4-5": map[string]any{ "rate_limited_at": time.Now().UTC().Format(time.RFC3339), "rate_limit_reset_at": time.Now().Add(30 * time.Minute).UTC().Format(time.RFC3339), }, diff --git a/backend/internal/service/antigravity_model_mapping_test.go b/backend/internal/service/antigravity_model_mapping_test.go index 0f86aa4a9c..61cc7e31d6 100644 --- a/backend/internal/service/antigravity_model_mapping_test.go +++ b/backend/internal/service/antigravity_model_mapping_test.go @@ -89,10 +89,10 @@ func TestAntigravityGatewayService_GetMappedModel(t *testing.T) { expected: "claude-sonnet-4-6", }, { - name: "默认映射 - claude-sonnet-4-5 → claude-sonnet-4-6", + name: "显式 canonical 选择 - claude-sonnet-4-5 透传", requestedModel: "claude-sonnet-4-5", accountMapping: nil, - expected: "claude-sonnet-4-6", + expected: "claude-sonnet-4-5", }, { name: "默认映射透传 - claude-opus-4-8", @@ -118,6 +118,15 @@ func TestAntigravityGatewayService_GetMappedModel(t *testing.T) { accountMapping: nil, expected: "claude-sonnet-4-6", }, + { + name: "账户显式目标只映射一步 - custom-sonnet → claude-sonnet-4-5", + requestedModel: "custom-sonnet", + accountMapping: map[string]string{ + "custom-sonnet": "claude-sonnet-4-5", + "claude-sonnet-4-5": "claude-sonnet-4-6", + }, + expected: "claude-sonnet-4-5", + }, { name: "默认映射透传 - gemini-2.5-flash", requestedModel: "gemini-2.5-flash", diff --git a/backend/internal/service/antigravity_rate_limit_test.go b/backend/internal/service/antigravity_rate_limit_test.go index 7a06a4e49e..d632f14bda 100644 --- a/backend/internal/service/antigravity_rate_limit_test.go +++ b/backend/internal/service/antigravity_rate_limit_test.go @@ -206,7 +206,7 @@ func TestHandleUpstreamError_429_NonModelRateLimit(t *testing.T) { // 但 429 兜底逻辑会使用 requestedModel 设置模型级限流 require.Nil(t, result) require.Len(t, repo.modelRateLimitCalls, 1) - require.Equal(t, "claude-sonnet-4-6", repo.modelRateLimitCalls[0].modelKey) + require.Equal(t, "claude-sonnet-4-5", repo.modelRateLimitCalls[0].modelKey) } // TestHandleUpstreamError_429_NonModelRateLimit_UsesMappedModelKey 测试 429 非模型限流场景 @@ -915,7 +915,7 @@ func TestAntigravityRetryLoop_PreCheck_SwitchesWhenRateLimited(t *testing.T) { Concurrency: 1, Extra: map[string]any{ modelRateLimitsKey: map[string]any{ - "claude-sonnet-4-6": map[string]any{ + "claude-sonnet-4-5": map[string]any{ "rate_limit_reset_at": time.Now().Add(2 * time.Second).Format(time.RFC3339), }, }, @@ -958,7 +958,7 @@ func TestAntigravityRetryLoop_PreCheck_SwitchesWhenRemainingLong(t *testing.T) { Concurrency: 1, Extra: map[string]any{ modelRateLimitsKey: map[string]any{ - "claude-sonnet-4-6": map[string]any{ + "claude-sonnet-4-5": map[string]any{ "rate_limit_reset_at": time.Now().Add(11 * time.Second).Format(time.RFC3339), }, }, diff --git a/backend/internal/service/antigravity_single_account_retry_test.go b/backend/internal/service/antigravity_single_account_retry_test.go index 85677e59c4..6e58ab75d2 100644 --- a/backend/internal/service/antigravity_single_account_retry_test.go +++ b/backend/internal/service/antigravity_single_account_retry_test.go @@ -693,7 +693,7 @@ func TestAntigravityRetryLoop_PreCheck_SingleAccountRetry_SkipsRateLimit(t *test Concurrency: 1, Extra: map[string]any{ modelRateLimitsKey: map[string]any{ - "claude-sonnet-4-6": map[string]any{ + "claude-sonnet-4-5": map[string]any{ "rate_limit_reset_at": time.Now().Add(30 * time.Second).Format(time.RFC3339), }, }, @@ -737,7 +737,7 @@ func TestAntigravityRetryLoop_PreCheck_NoSingleAccountRetry_SwitchesOnRateLimit( Concurrency: 1, Extra: map[string]any{ modelRateLimitsKey: map[string]any{ - "claude-sonnet-4-6": map[string]any{ + "claude-sonnet-4-5": map[string]any{ "rate_limit_reset_at": time.Now().Add(30 * time.Second).Format(time.RFC3339), }, }, diff --git a/backend/internal/service/model_rate_limit_test.go b/backend/internal/service/model_rate_limit_test.go index 3293853d74..430d91baf6 100644 --- a/backend/internal/service/model_rate_limit_test.go +++ b/backend/internal/service/model_rate_limit_test.go @@ -255,7 +255,7 @@ func TestIsModelRateLimited_OpenAIImageGenerationIntentBlocksTextModelImageTool( require.True(t, account.isModelRateLimitedWithContext(WithOpenAIImageGenerationIntent(context.Background()), "gpt-5.4")) } -func TestIsModelRateLimited_Antigravity_LegacySonnetUsesCanonicalModelKey(t *testing.T) { +func TestIsModelRateLimited_Antigravity_ThinkingAffectsModelKey(t *testing.T) { now := time.Now() future := now.Add(10 * time.Minute).Format(time.RFC3339) @@ -263,7 +263,7 @@ func TestIsModelRateLimited_Antigravity_LegacySonnetUsesCanonicalModelKey(t *tes Platform: PlatformAntigravity, Extra: map[string]any{ modelRateLimitsKey: map[string]any{ - "claude-sonnet-4-6": map[string]any{ + "claude-sonnet-4-5-thinking": map[string]any{ "rate_limit_reset_at": future, }, }, @@ -453,7 +453,7 @@ func TestGetRateLimitRemainingTime(t *testing.T) { Platform: PlatformAntigravity, Extra: map[string]any{ modelRateLimitsKey: map[string]any{ - "claude-sonnet-4-6": map[string]any{ + "claude-sonnet-4-5": map[string]any{ "rate_limit_reset_at": future15m, }, }, @@ -469,7 +469,7 @@ func TestGetRateLimitRemainingTime(t *testing.T) { Platform: PlatformAntigravity, Extra: map[string]any{ modelRateLimitsKey: map[string]any{ - "claude-sonnet-4-6": map[string]any{ + "claude-sonnet-4-5": map[string]any{ "rate_limit_reset_at": future5m, }, }, From e440ac48c7d7e2649bf3f1e062d2a3793f50b021 Mon Sep 17 00:00:00 2001 From: akihitohyh <79531840+akihitohyh@users.noreply.github.com> Date: Mon, 24 Aug 2026 17:03:44 +0800 Subject: [PATCH 154/204] fix(openai): clear the rejected input status for the whole item type The upstream names one offending index per response, but a replayed conversation routinely carries dozens of items of the same type, each with a status the upstream schema does not accept. Clearing a single index per round trip needs one retry per item, so a conversation with more than maxOpenAIResponsesRejectedFieldRetries such items exhausts the bounded budget and the 400 reaches the client. Reported against tool_search_output items, where the rejection surfaced as "Unknown parameter: 'input[60].status'". Clear the status of every input item sharing the rejected item's type in the same pass. Items of other types keep theirs: the rejection only proves that the rejected item's type has no status field. When the rejected item carries no type to match on, fall back to clearing the named index alone. Co-Authored-By: Claude Opus 5 --- .../openai_responses_rejected_field_retry.go | 50 ++++++++++++++++--- ...nai_responses_rejected_field_retry_test.go | 40 +++++++++++++++ 2 files changed, 84 insertions(+), 6 deletions(-) diff --git a/backend/internal/service/openai_responses_rejected_field_retry.go b/backend/internal/service/openai_responses_rejected_field_retry.go index 20affff9cf..f70bdd89ac 100644 --- a/backend/internal/service/openai_responses_rejected_field_retry.go +++ b/backend/internal/service/openai_responses_rejected_field_retry.go @@ -271,18 +271,56 @@ func openAIResponsesRejectedInputIndex(pattern *regexp.Regexp, param string) (in return 0, false } +// removeOpenAIResponsesRejectedStatusAtIndex drops the status field the +// upstream rejected, and the status of every other input item sharing the +// rejected item's type. +// +// The upstream names one offending index per response, but a replayed +// conversation routinely carries dozens of items of the same type, each with a +// status its schema does not accept. Clearing one index per round trip would +// need one retry per item and exhaust the bounded retry budget long before the +// request could succeed. Items of other types keep their status: the rejection +// only proves that this type has no status field. func removeOpenAIResponsesRejectedStatusAtIndex(body []byte, index int) ([]byte, string, bool, error) { itemPath := fmt.Sprintf("input.%d", index) - if !gjson.GetBytes(body, itemPath).IsObject() { + rejected := gjson.GetBytes(body, itemPath) + if !rejected.IsObject() { return nil, "", false, nil } - statusPath := itemPath + ".status" - if !gjson.GetBytes(body, statusPath).Exists() { + if !gjson.GetBytes(body, itemPath+".status").Exists() { return nil, "", false, nil } - retryBody, err := sjson.DeleteBytes(body, statusPath) - if err != nil { - return nil, "", false, fmt.Errorf("delete rejected status at input[%d]: %w", index, err) + + retryBody := body + cleared := 0 + rejectedType := strings.TrimSpace(rejected.Get("type").String()) + if input := gjson.GetBytes(body, "input"); rejectedType != "" && input.IsArray() { + // Deleting a field never shifts array indexes, so positions read from + // the original body stay valid against the rewritten one. + for itemIndex, item := range input.Array() { + if !item.IsObject() || strings.TrimSpace(item.Get("type").String()) != rejectedType { + continue + } + statusPath := fmt.Sprintf("input.%d.status", itemIndex) + if !gjson.GetBytes(retryBody, statusPath).Exists() { + continue + } + next, err := sjson.DeleteBytes(retryBody, statusPath) + if err != nil { + return nil, "", false, fmt.Errorf("delete rejected status at input[%d]: %w", itemIndex, err) + } + retryBody = next + cleared++ + } + } + if cleared == 0 { + // The rejected item carries no type to match on; fall back to clearing + // just the index the upstream named. + next, err := sjson.DeleteBytes(retryBody, itemPath+".status") + if err != nil { + return nil, "", false, fmt.Errorf("delete rejected status at input[%d]: %w", index, err) + } + retryBody = next } return retryBody, "indexed status parameter rejection", true, nil } diff --git a/backend/internal/service/openai_responses_rejected_field_retry_test.go b/backend/internal/service/openai_responses_rejected_field_retry_test.go index 96b118050c..9f794b1e57 100644 --- a/backend/internal/service/openai_responses_rejected_field_retry_test.go +++ b/backend/internal/service/openai_responses_rejected_field_retry_test.go @@ -7,6 +7,7 @@ import ( "io" "net/http" "net/http/httptest" + "strconv" "strings" "testing" @@ -681,3 +682,42 @@ func newOpenAIRejectedFieldTestResponse(status int, body string) *http.Response Body: io.NopCloser(strings.NewReader(body)), } } + +// A replayed conversation carries many items of the same type, each with a +// status the upstream schema rejects. One rejection must clear all of them: +// clearing one index per round trip exhausts the bounded retry budget. +func TestNormalizeOpenAIResponsesRejectedFieldRetryBodyClearsStatusForWholeType(t *testing.T) { + input := make([]string, 0, 12) + for i := 0; i < 10; i++ { + input = append(input, `{"type":"tool_search_output","status":"completed","call_id":"call_`+strconv.Itoa(i)+`","tools":[]}`) + } + input = append(input, `{"type":"message","role":"user","status":"completed","content":"hi"}`) + body := []byte(`{"input":[` + strings.Join(input, ",") + `]}`) + + responseBody := []byte(`{"error":{"code":"unknown_parameter","message":"Unknown parameter: 'input[7].status'.","param":"input[7].status"}}`) + retryBody, reason, changed, err := normalizeOpenAIResponsesRejectedFieldRetryBody(http.StatusBadRequest, body, responseBody) + require.NoError(t, err) + require.True(t, changed) + require.NotEmpty(t, reason) + + for i := 0; i < 10; i++ { + require.False(t, gjson.GetBytes(retryBody, "input."+strconv.Itoa(i)+".status").Exists(), + "every tool_search_output must lose its status in a single retry, index %d did not", i) + require.Equal(t, "call_"+strconv.Itoa(i), gjson.GetBytes(retryBody, "input."+strconv.Itoa(i)+".call_id").String(), + "unrelated fields must survive") + } + require.Equal(t, "completed", gjson.GetBytes(retryBody, "input.10.status").String(), + "a different item type keeps its status: the rejection only proves this type has none") +} + +// The rejected item may carry no type to match on. +func TestNormalizeOpenAIResponsesRejectedFieldRetryBodyClearsUntypedStatusAtIndexOnly(t *testing.T) { + body := []byte(`{"input":[{"status":"keep_a"},{"status":"remove"}]}`) + responseBody := []byte(`{"error":{"code":"unknown_parameter","message":"Unknown parameter: 'input[1].status'.","param":"input[1].status"}}`) + + retryBody, _, changed, err := normalizeOpenAIResponsesRejectedFieldRetryBody(http.StatusBadRequest, body, responseBody) + require.NoError(t, err) + require.True(t, changed) + require.Equal(t, "keep_a", gjson.GetBytes(retryBody, "input.0.status").String()) + require.False(t, gjson.GetBytes(retryBody, "input.1.status").Exists()) +} From 1563db3f82a4f44a576898c4662e8f1f4b022307 Mon Sep 17 00:00:00 2001 From: 759502416 <38681911+759502416@users.noreply.github.com> Date: Mon, 24 Aug 2026 21:15:39 +0800 Subject: [PATCH 155/204] fix(openai): keep parallel_tool_calls for Responses Lite additional_tools normalizeOpenAIParallelToolCallsWithoutTools only looked at the top-level "tools" array, but normalizeOpenAIResponsesLiteTools moves namespace tools into an input item of type "additional_tools" and deletes the top-level key. A Responses Lite request that carries tools therefore looks like it has none, and the parallel_tool_calls:false that ensureOpenAIResponsesLiteParallelToolCalls had just pinned gets deleted on the way out. OpenAI then applies its default of true and rejects the request: 400 unsupported_value: "X-OpenAI-Internal-Codex-Responses-Lite requires `parallel_tool_calls` to be false." Note the field cannot simply be pinned to false unconditionally: without tools OpenAI rejects it with "'parallel_tool_calls' is only allowed when 'tools' are specified", so the two constraints have to be honoured together. Reuse the same tool-detection standard the Lite path already uses by adding openAIRequestBodyHasTools, the []byte counterpart of openAIResponsesLiteHasTools, so both sides of the repo agree on what "has tools" means. Co-Authored-By: Claude Opus 5 --- .../service/openai_gateway_request_body.go | 28 +++++++++++++++++-- ...nai_gateway_request_body_reasoning_test.go | 20 +++++++++++++ 2 files changed, 46 insertions(+), 2 deletions(-) diff --git a/backend/internal/service/openai_gateway_request_body.go b/backend/internal/service/openai_gateway_request_body.go index c9a61d7465..8aa4364777 100644 --- a/backend/internal/service/openai_gateway_request_body.go +++ b/backend/internal/service/openai_gateway_request_body.go @@ -366,8 +366,7 @@ func normalizeOpenAIParallelToolCallsWithoutTools(body []byte) ([]byte, bool, er if !parallel.Exists() { return body, false, nil } - tools := gjson.GetBytes(body, "tools") - if tools.IsArray() && len(tools.Array()) > 0 { + if openAIRequestBodyHasTools(body) { return body, false, nil } normalized, err := sjson.DeleteBytes(body, "parallel_tool_calls") @@ -377,6 +376,31 @@ func normalizeOpenAIParallelToolCallsWithoutTools(body []byte) ([]byte, bool, er return normalized, true, nil } +// openAIRequestBodyHasTools is the []byte counterpart of openAIResponsesLiteHasTools: +// besides the top-level "tools" array it also recognizes the Responses Lite carrier. +// normalizeOpenAIResponsesLiteTools moves namespace tools into an input item of type +// "additional_tools" and drops the top-level "tools" key; the request still carries +// tools at that point. Looking only at the top level therefore misreads such a body as +// "no tools" and deletes the parallel_tool_calls:false that +// ensureOpenAIResponsesLiteParallelToolCalls had just pinned, and OpenAI falls back to +// its default of true and rejects the request with +// 400 unsupported_value: "X-OpenAI-Internal-Codex-Responses-Lite requires +// `parallel_tool_calls` to be false." +func openAIRequestBodyHasTools(body []byte) bool { + if tools := gjson.GetBytes(body, "tools"); tools.IsArray() && len(tools.Array()) > 0 { + return true + } + for _, item := range gjson.GetBytes(body, "input").Array() { + if strings.TrimSpace(item.Get("type").String()) != "additional_tools" { + continue + } + if tools := item.Get("tools"); tools.IsArray() && len(tools.Array()) > 0 { + return true + } + } + return false +} + func normalizeOpenAIAPIKeyStoreFalseReasoningReplay(body []byte, knownStoreFalse bool) ([]byte, bool, error) { if !knownStoreFalse && gjson.GetBytes(body, "store").Type != gjson.False { return body, false, nil diff --git a/backend/internal/service/openai_gateway_request_body_reasoning_test.go b/backend/internal/service/openai_gateway_request_body_reasoning_test.go index f14a75018b..03397e751f 100644 --- a/backend/internal/service/openai_gateway_request_body_reasoning_test.go +++ b/backend/internal/service/openai_gateway_request_body_reasoning_test.go @@ -270,3 +270,23 @@ func TestNormalizeOpenAIParallelToolCallsWithoutTools(t *testing.T) { require.True(t, changed) require.False(t, gjson.GetBytes(normalized, "parallel_tool_calls").Exists()) } + +// A Responses Lite body that has already been through normalizeOpenAIResponsesLiteTools +// carries its tools in an input item of type "additional_tools" and no longer has a +// top-level "tools" key. It still has tools, so the parallel_tool_calls:false that +// ensureOpenAIResponsesLiteParallelToolCalls pinned must survive this normalization — +// otherwise OpenAI applies its default of true and rejects the request. +func TestNormalizeOpenAIParallelToolCallsWithoutTools_KeepsResponsesLiteAdditionalTools(t *testing.T) { + liteBody := []byte(`{"input":[{"type":"message","role":"user","content":"hi"},{"type":"additional_tools","tools":[{"type":"function","name":"spawn_agent"}]}],"parallel_tool_calls":false}`) + normalized, changed, err := normalizeOpenAIParallelToolCallsWithoutTools(liteBody) + require.NoError(t, err) + require.False(t, changed) + require.Equal(t, gjson.False, gjson.GetBytes(normalized, "parallel_tool_calls").Type) + + // An empty additional_tools item carries no tools, so the field is still dropped. + emptyLiteBody := []byte(`{"input":[{"type":"additional_tools","tools":[]}],"parallel_tool_calls":true}`) + normalized, changed, err = normalizeOpenAIParallelToolCallsWithoutTools(emptyLiteBody) + require.NoError(t, err) + require.True(t, changed) + require.False(t, gjson.GetBytes(normalized, "parallel_tool_calls").Exists()) +} From 9fb260439f7591de1f538d38074c101aa3703fd2 Mon Sep 17 00:00:00 2001 From: shaw Date: Mon, 24 Aug 2026 22:14:45 +0800 Subject: [PATCH 156/204] fix(grok): use official CLI user agent --- backend/internal/pkg/xai/billing.go | 2 +- backend/internal/pkg/xai/cli_identity_test.go | 6 +-- .../internal/repository/http_upstream_test.go | 49 ++++++++++--------- .../internal/service/grok_observed_models.go | 2 +- .../service/grok_quota_service_test.go | 3 +- .../internal/service/grok_upstream_headers.go | 4 -- .../openai_gateway_chat_completions_raw.go | 2 +- .../internal/service/openai_gateway_grok.go | 15 +++--- .../service/openai_gateway_grok_test.go | 10 ++-- 9 files changed, 45 insertions(+), 48 deletions(-) diff --git a/backend/internal/pkg/xai/billing.go b/backend/internal/pkg/xai/billing.go index 44e4772d44..39e1a2c8b7 100644 --- a/backend/internal/pkg/xai/billing.go +++ b/backend/internal/pkg/xai/billing.go @@ -19,7 +19,7 @@ const ( // repository and service layers build their own client identity from it, so // one bump here covers OAuth traffic and billing probes together. // Keep in sync with https://x.ai/cli/stable. - CLIClientVersion = "0.2.114" + CLIClientVersion = "0.2.120" // billingCLIUserAgent is the legacy pager/shell UA used by billing probes. // Distinct from CLIUserAgent() in cli_identity.go (workspace-style UA). billingCLIUserAgent = "grok-pager/" + CLIClientVersion + " grok-shell/" + CLIClientVersion + " (macos; aarch64)" diff --git a/backend/internal/pkg/xai/cli_identity_test.go b/backend/internal/pkg/xai/cli_identity_test.go index 521df7483d..2057b9effd 100644 --- a/backend/internal/pkg/xai/cli_identity_test.go +++ b/backend/internal/pkg/xai/cli_identity_test.go @@ -41,7 +41,7 @@ func TestApplyCLIProxyHeaders(t *testing.T) { req, err := http.NewRequest(http.MethodPost, "https://cli-chat-proxy.grok.com/v1/responses", nil) require.NoError(t, err) - req.Header.Set("User-Agent", "sub2api-grok/1.0") + req.Header.Set("User-Agent", "legacy-client/1.0") ApplyCLIProxyHeaders(req) @@ -56,12 +56,12 @@ func TestApplyCLIProxyHeadersLeavesAPIHostUnchanged(t *testing.T) { req, err := http.NewRequest(http.MethodPost, "https://api.x.ai/v1/responses", nil) require.NoError(t, err) - req.Header.Set("User-Agent", "sub2api-grok/1.0") + req.Header.Set("User-Agent", "direct-api-client/1.0") ApplyCLIProxyHeaders(req) require.Empty(t, req.Header.Get("x-grok-client-version")) require.Empty(t, req.Header.Get("x-grok-client-identifier")) require.Empty(t, req.Header.Get("X-XAI-Token-Auth")) - require.Equal(t, "sub2api-grok/1.0", req.Header.Get("User-Agent")) + require.Equal(t, "direct-api-client/1.0", req.Header.Get("User-Agent")) } diff --git a/backend/internal/repository/http_upstream_test.go b/backend/internal/repository/http_upstream_test.go index ac0c064b20..3c7840dc47 100644 --- a/backend/internal/repository/http_upstream_test.go +++ b/backend/internal/repository/http_upstream_test.go @@ -17,6 +17,7 @@ import ( "github.com/Wei-Shaw/sub2api/internal/config" "github.com/Wei-Shaw/sub2api/internal/pkg/tlsfingerprint" + "github.com/Wei-Shaw/sub2api/internal/pkg/xai" "github.com/Wei-Shaw/sub2api/internal/service" "github.com/stretchr/testify/require" "github.com/stretchr/testify/suite" @@ -228,16 +229,16 @@ func TestHTTPUpstreamDoAppliesGrokCLIIdentityBeforeOAuthRoundTrip(t *testing.T) req, err := http.NewRequest(http.MethodPost, "https://cli-chat-proxy.grok.com/v1/"+endpoint, nil) require.NoError(t, err) - req.Header.Set("User-Agent", "sub2api-grok/1.0") + req.Header.Set("User-Agent", "legacy-client/1.0") resp, err := svc.Do(req, "", accountID, 1) require.NoError(t, err) require.Equal(t, http.StatusOK, resp.StatusCode) require.NoError(t, resp.Body.Close()) - require.Equal(t, "0.2.114", capturedHeaders.Get("x-grok-client-version")) + require.Equal(t, xai.CLIClientVersion, capturedHeaders.Get("x-grok-client-version")) require.Equal(t, "xai-grok-cli", capturedHeaders.Get("X-XAI-Token-Auth")) - require.Equal(t, "xai-grok-workspace/0.2.114", capturedHeaders.Get("User-Agent")) + require.Equal(t, xai.CLIUserAgent(xai.CLIClientVersion), capturedHeaders.Get("User-Agent")) }) } } @@ -454,67 +455,67 @@ func TestApplyGrokCLIProxyHeaders(t *testing.T) { t.Setenv("XAI_GROK_CLI_VERSION", "") req, err := http.NewRequest(http.MethodPost, "https://cli-chat-proxy.grok.com/v1/responses", nil) require.NoError(t, err) - req.Header.Set("User-Agent", "sub2api-grok/1.0") + req.Header.Set("User-Agent", "legacy-client/1.0") applyGrokCLIProxyHeaders(req) - require.Equal(t, "0.2.114", req.Header.Get("x-grok-client-version")) + require.Equal(t, xai.CLIClientVersion, req.Header.Get("x-grok-client-version")) require.Equal(t, "xai-grok-cli", req.Header.Get("X-XAI-Token-Auth")) - require.Equal(t, "xai-grok-workspace/0.2.114", req.Header.Get("User-Agent")) + require.Equal(t, xai.CLIUserAgent(xai.CLIClientVersion), req.Header.Get("User-Agent")) }) t.Run("accepts a valid operator override", func(t *testing.T) { - t.Setenv("XAI_GROK_CLI_VERSION", "0.2.115-alpha.1") + t.Setenv("XAI_GROK_CLI_VERSION", "0.2.121-alpha.1") req, err := http.NewRequest(http.MethodPost, "https://cli-chat-proxy.grok.com/v1/chat/completions", nil) require.NoError(t, err) applyGrokCLIProxyHeaders(req) - require.Equal(t, "0.2.115-alpha.1", req.Header.Get("x-grok-client-version")) - require.Equal(t, "xai-grok-workspace/0.2.115-alpha.1", req.Header.Get("User-Agent")) + require.Equal(t, "0.2.121-alpha.1", req.Header.Get("x-grok-client-version")) + require.Equal(t, xai.CLIUserAgent("0.2.121-alpha.1"), req.Header.Get("User-Agent")) }) t.Run("rejects an unsafe override", func(t *testing.T) { - t.Setenv("XAI_GROK_CLI_VERSION", "0.2.115\r\nX-Injected: true") + t.Setenv("XAI_GROK_CLI_VERSION", "0.2.121\r\nX-Injected: true") req, err := http.NewRequest(http.MethodPost, "https://cli-chat-proxy.grok.com/v1/responses", nil) require.NoError(t, err) applyGrokCLIProxyHeaders(req) - require.Equal(t, "0.2.114", req.Header.Get("x-grok-client-version")) + require.Equal(t, xai.CLIClientVersion, req.Header.Get("x-grok-client-version")) require.Empty(t, req.Header.Get("X-Injected")) }) t.Run("rejects an override below the supported minimum", func(t *testing.T) { - t.Setenv("XAI_GROK_CLI_VERSION", "0.2.113") + t.Setenv("XAI_GROK_CLI_VERSION", "0.2.119") req, err := http.NewRequest(http.MethodPost, "https://cli-chat-proxy.grok.com/v1/responses", nil) require.NoError(t, err) applyGrokCLIProxyHeaders(req) - require.Equal(t, "0.2.114", req.Header.Get("x-grok-client-version")) - require.Equal(t, "xai-grok-workspace/0.2.114", req.Header.Get("User-Agent")) + require.Equal(t, xai.CLIClientVersion, req.Header.Get("x-grok-client-version")) + require.Equal(t, xai.CLIUserAgent(xai.CLIClientVersion), req.Header.Get("User-Agent")) }) t.Run("rejects a prerelease override at the minimum version", func(t *testing.T) { - t.Setenv("XAI_GROK_CLI_VERSION", "0.2.114-beta.1") + t.Setenv("XAI_GROK_CLI_VERSION", "0.2.120-beta.1") req, err := http.NewRequest(http.MethodPost, "https://cli-chat-proxy.grok.com/v1/responses", nil) require.NoError(t, err) applyGrokCLIProxyHeaders(req) - require.Equal(t, "0.2.114", req.Header.Get("x-grok-client-version")) - require.Equal(t, "xai-grok-workspace/0.2.114", req.Header.Get("User-Agent")) + require.Equal(t, xai.CLIClientVersion, req.Header.Get("x-grok-client-version")) + require.Equal(t, xai.CLIUserAgent(xai.CLIClientVersion), req.Header.Get("User-Agent")) }) // Every entry sits above the pinned minimum, so a rejection here can only be // caused by the malformed semver and never by the version being too old. for _, version := range []string{ - "0.2.0115", - "0.2.115-alpha..1", + "0.2.0121", + "0.2.121-alpha..1", "0.3", "1", - "0.2.115+build.1", + "0.2.121+build.1", } { t.Run("rejects invalid semver "+version, func(t *testing.T) { t.Setenv("XAI_GROK_CLI_VERSION", version) @@ -523,8 +524,8 @@ func TestApplyGrokCLIProxyHeaders(t *testing.T) { applyGrokCLIProxyHeaders(req) - require.Equal(t, "0.2.114", req.Header.Get("x-grok-client-version")) - require.Equal(t, "xai-grok-workspace/0.2.114", req.Header.Get("User-Agent")) + require.Equal(t, xai.CLIClientVersion, req.Header.Get("x-grok-client-version")) + require.Equal(t, xai.CLIUserAgent(xai.CLIClientVersion), req.Header.Get("User-Agent")) }) } @@ -532,13 +533,13 @@ func TestApplyGrokCLIProxyHeaders(t *testing.T) { t.Setenv("XAI_GROK_CLI_VERSION", "0.2.95") req, err := http.NewRequest(http.MethodPost, "https://api.x.ai/v1/responses", nil) require.NoError(t, err) - req.Header.Set("User-Agent", "sub2api-grok/1.0") + req.Header.Set("User-Agent", "direct-api-client/1.0") applyGrokCLIProxyHeaders(req) require.Empty(t, req.Header.Get("x-grok-client-version")) require.Empty(t, req.Header.Get("X-XAI-Token-Auth")) - require.Equal(t, "sub2api-grok/1.0", req.Header.Get("User-Agent")) + require.Equal(t, "direct-api-client/1.0", req.Header.Get("User-Agent")) }) } diff --git a/backend/internal/service/grok_observed_models.go b/backend/internal/service/grok_observed_models.go index 480ba457bd..3dba5f0013 100644 --- a/backend/internal/service/grok_observed_models.go +++ b/backend/internal/service/grok_observed_models.go @@ -92,7 +92,7 @@ func (s *GrokQuotaService) syncGrokObservedModels(ctx context.Context, account * } req.Header.Set("Authorization", "Bearer "+token) req.Header.Set("Accept", "application/json") - req.Header.Set("User-Agent", grokUpstreamUserAgent) + req.Header.Set("User-Agent", defaultGrokUpstreamUserAgent()) if account.IsGrokOAuth() { applyGrokCLIHeaders(req.Header) if isGrokCLIProxyTarget(req.URL.String()) { diff --git a/backend/internal/service/grok_quota_service_test.go b/backend/internal/service/grok_quota_service_test.go index 9d94d1b989..af27b67f12 100644 --- a/backend/internal/service/grok_quota_service_test.go +++ b/backend/internal/service/grok_quota_service_test.go @@ -133,8 +133,9 @@ func TestSyncGrokObservedModelsUsesCLIIdentityAndAccountHeaders(t *testing.T) { require.NoError(t, svc.syncGrokObservedModels(context.Background(), account)) require.Equal(t, xai.DefaultCLIBaseURL+"/models", upstream.lastReq.URL.String()) - require.NotEmpty(t, upstream.lastReq.Header.Get("x-grok-client-version")) + require.Equal(t, xai.CLIClientVersion, upstream.lastReq.Header.Get("x-grok-client-version")) require.Equal(t, xai.CLIClientIdentifier, upstream.lastReq.Header.Get("x-grok-client-identifier")) + require.Equal(t, xai.CLIUserAgent(xai.CLIClientVersion), upstream.lastReq.Header.Get("User-Agent")) require.Equal(t, "interactive", upstream.lastReq.Header.Get("X-Grok-Client-Mode")) require.Equal(t, "user-902", upstream.lastReq.Header.Get("X-UserID")) require.Equal(t, "user902@example.test", upstream.lastReq.Header.Get("X-Email")) diff --git a/backend/internal/service/grok_upstream_headers.go b/backend/internal/service/grok_upstream_headers.go index cdfb54bcbf..4b24e4c13b 100644 --- a/backend/internal/service/grok_upstream_headers.go +++ b/backend/internal/service/grok_upstream_headers.go @@ -10,10 +10,6 @@ import ( "github.com/Wei-Shaw/sub2api/internal/pkg/xai" ) -// grokUpstreamUserAgent is kept for compatibility with older Grok request -// tests. Current requests use the pinned default UA from this package. -const grokUpstreamUserAgent = "sub2api-grok/1.0" - // Fixed CLI identity aliases — single source of truth is internal/pkg/xai. const ( grokClientVersionHeader = xai.CLIStableVersion diff --git a/backend/internal/service/openai_gateway_chat_completions_raw.go b/backend/internal/service/openai_gateway_chat_completions_raw.go index 923033c4d4..7427c6fc9c 100644 --- a/backend/internal/service/openai_gateway_chat_completions_raw.go +++ b/backend/internal/service/openai_gateway_chat_completions_raw.go @@ -175,7 +175,7 @@ func (s *OpenAIGatewayService) forwardAsRawChatCompletions( SetActualOpenAIUpstreamEndpoint(c, grokChatRawEndpoint) customUA := account.GetOpenAIUserAgent() if customUA == "" && account.IsGrokOAuth() { - customUA = "sub2api-grok/1.0" + customUA = defaultGrokUpstreamUserAgent() } resp, err := s.sendCCUpstreamRequest(ctx, c, account, targetURL, upstreamBody, clientStream, token, customUA, grokCacheIdentity) if err != nil { diff --git a/backend/internal/service/openai_gateway_grok.go b/backend/internal/service/openai_gateway_grok.go index 10a2731fbb..21c7342356 100644 --- a/backend/internal/service/openai_gateway_grok.go +++ b/backend/internal/service/openai_gateway_grok.go @@ -22,14 +22,13 @@ import ( const ( grokComposerImageBridgeVisionModel = "grok-build-0.1" grokComposerImageBridgeMaxOutputTokens = 512 - // grokUpstreamUserAgent lives in grok_upstream_headers.go (shared with TLS header helpers). - grokCLIVersion = xai.CLIClientVersion - grokDefaultResponsesModel = "grok-4.5" - grokRateLimitFallbackCooldown = 2 * time.Minute - grokRateLimitRepeatCooldown = 10 * time.Minute - grokRateLimitSustainedCooldown = 30 * time.Minute - grokRateLimitMaxAdaptiveCooldown = time.Hour - grokRateLimitBackoffQuietPeriod = time.Hour + grokCLIVersion = xai.CLIClientVersion + grokDefaultResponsesModel = "grok-4.5" + grokRateLimitFallbackCooldown = 2 * time.Minute + grokRateLimitRepeatCooldown = 10 * time.Minute + grokRateLimitSustainedCooldown = 30 * time.Minute + grokRateLimitMaxAdaptiveCooldown = time.Hour + grokRateLimitBackoffQuietPeriod = time.Hour ) func (s *OpenAIGatewayService) forwardGrokResponses( diff --git a/backend/internal/service/openai_gateway_grok_test.go b/backend/internal/service/openai_gateway_grok_test.go index e11954a4bc..d1c966ac07 100644 --- a/backend/internal/service/openai_gateway_grok_test.go +++ b/backend/internal/service/openai_gateway_grok_test.go @@ -828,7 +828,7 @@ func TestBuildGrokResponsesRequestAllowsPublicAPIKeyBaseURLByDefault(t *testing. require.Equal(t, "https://grok.example.test/v1/responses", req.URL.String()) require.Equal(t, "Bearer api-key", req.Header.Get("Authorization")) require.Empty(t, req.Header.Get("X-Grok-Client-Version")) - require.NotEqual(t, grokUpstreamUserAgent, req.Header.Get("User-Agent")) + require.NotEqual(t, defaultGrokUpstreamUserAgent(), req.Header.Get("User-Agent")) } func TestBuildGrokResponsesRequestHonorsOAuthOfficialEndpointSwitch(t *testing.T) { @@ -1132,7 +1132,7 @@ func TestForwardGrokMediaImagesGenerationNormalizesImagineAlias(t *testing.T) { require.Equal(t, "Bearer api-key", upstream.lastReq.Header.Get("Authorization")) require.Equal(t, "application/json", upstream.lastReq.Header.Get("Content-Type")) require.Empty(t, upstream.lastReq.Header.Get("X-Grok-Client-Version")) - require.NotEqual(t, grokUpstreamUserAgent, upstream.lastReq.Header.Get("User-Agent")) + require.NotEqual(t, defaultGrokUpstreamUserAgent(), upstream.lastReq.Header.Get("User-Agent")) require.JSONEq(t, `{"model":"grok-imagine-image-quality","prompt":"draw a cat"}`, string(upstream.lastBody)) require.Equal(t, http.StatusOK, recorder.Code) require.JSONEq(t, `{"data":[{"url":"https://images.test/cat.png"}]}`, recorder.Body.String()) @@ -1646,7 +1646,7 @@ func TestForwardGrokMediaVideoStatusUsesGETWithoutBody(t *testing.T) { require.Equal(t, http.MethodGet, upstream.lastReq.Method) require.Equal(t, "Bearer api-key", upstream.lastReq.Header.Get("Authorization")) require.Empty(t, upstream.lastReq.Header.Get("X-Grok-Client-Version")) - require.NotEqual(t, grokUpstreamUserAgent, upstream.lastReq.Header.Get("User-Agent")) + require.NotEqual(t, defaultGrokUpstreamUserAgent(), upstream.lastReq.Header.Get("User-Agent")) require.Empty(t, upstream.lastReq.Header.Get("Content-Type")) require.Empty(t, upstream.lastBody) require.Equal(t, http.StatusOK, recorder.Code) @@ -1982,7 +1982,7 @@ func TestForwardGrokResponsesAPIKeyUsesXAIResponses(t *testing.T) { require.Equal(t, "https://api.x.ai/v1/responses", upstream.lastReq.URL.String()) require.Equal(t, "Bearer xai-test-key", upstream.lastReq.Header.Get("Authorization")) require.Empty(t, upstream.lastReq.Header.Get("X-Grok-Client-Version")) - require.NotEqual(t, grokUpstreamUserAgent, upstream.lastReq.Header.Get("User-Agent")) + require.NotEqual(t, defaultGrokUpstreamUserAgent(), upstream.lastReq.Header.Get("User-Agent")) require.Equal(t, "grok-4.6", gjson.GetBytes(upstream.lastBody, "model").String()) require.Equal(t, "resp_grok_api_key", result.ResponseID) require.Equal(t, 2, result.Usage.InputTokens) @@ -2259,7 +2259,7 @@ func TestForwardAsChatCompletionsForGrokAPIKeyUsesConfiguredRawEndpointWithoutOA require.Equal(t, "https://grok.example.test/v1/chat/completions", upstream.lastReq.URL.String()) require.Equal(t, "Bearer third-party-key", upstream.lastReq.Header.Get("Authorization")) require.Empty(t, upstream.lastReq.Header.Get("X-Grok-Client-Version")) - require.NotEqual(t, grokUpstreamUserAgent, upstream.lastReq.Header.Get("User-Agent")) + require.NotEqual(t, defaultGrokUpstreamUserAgent(), upstream.lastReq.Header.Get("User-Agent")) } func TestForwardAsChatCompletionsForGrokAPIKeyRejectsNonStreamingResponseWithoutUsage(t *testing.T) { From eb594eefc952e53ffc8b3494d9023ecd3df03e8c Mon Sep 17 00:00:00 2001 From: ranxi2001 Date: Mon, 24 Aug 2026 22:29:02 +0800 Subject: [PATCH 157/204] fix(payment): refresh balance after fulfillment --- frontend/src/views/user/PaymentResultView.vue | 18 ++++++++ .../user/__tests__/PaymentResultView.spec.ts | 42 +++++++++++++++++-- 2 files changed, 57 insertions(+), 3 deletions(-) diff --git a/frontend/src/views/user/PaymentResultView.vue b/frontend/src/views/user/PaymentResultView.vue index a5f32f0a8d..981377ce97 100644 --- a/frontend/src/views/user/PaymentResultView.vue +++ b/frontend/src/views/user/PaymentResultView.vue @@ -107,6 +107,7 @@ import { readPaymentRecoverySnapshot, } from '@/components/payment/paymentFlow' import { usePaymentStore } from '@/stores/payment' +import { useAuthStore } from '@/stores/auth' import { paymentAPI } from '@/api/payment' import type { PublicOrderVerifyResult } from '@/api/payment' import type { OrderStatus, PaymentOrder } from '@/types/payment' @@ -118,6 +119,7 @@ const { t } = i18n const route = useRoute() const router = useRouter() const paymentStore = usePaymentStore() +const authStore = useAuthStore() type ResolvedOrder = PaymentOrder | PublicOrderVerifyResult @@ -139,6 +141,7 @@ const STATUS_REFRESH_INTERVAL_MS = 2000 const STATUS_REFRESH_MAX_ATTEMPTS = 15 let statusRefreshTimer: ReturnType | null = null +let userBalanceRefreshStarted = false const refreshAttempts = ref(0) /** 充值金额 = pay_amount / (1 + fee_rate/100),fee_rate=0 时等于 pay_amount */ @@ -197,6 +200,21 @@ function setResolvedOrder(nextOrder: ResolvedOrder | null): void { if (nextOrder && 'currency' in nextOrder && nextOrder.currency) { currency.value = normalizePaymentCurrency(nextOrder.currency) } + refreshUserBalanceForSuccessfulOrder(nextOrder) +} + +function refreshUserBalanceForSuccessfulOrder(nextOrder: ResolvedOrder | null): void { + if (!nextOrder || userBalanceRefreshStarted || normalizeOrderStatus(nextOrder.status) !== 'COMPLETED') { + return + } + if ('order_type' in nextOrder && nextOrder.order_type !== 'balance') { + return + } + + userBalanceRefreshStarted = true + void authStore.refreshUser().catch(() => { + // The order result remains authoritative even if refreshing profile data fails. + }) } function hasOrderId(nextOrder: ResolvedOrder | null): nextOrder is PaymentOrder { diff --git a/frontend/src/views/user/__tests__/PaymentResultView.spec.ts b/frontend/src/views/user/__tests__/PaymentResultView.spec.ts index 5edae835c0..751e7d83c4 100644 --- a/frontend/src/views/user/__tests__/PaymentResultView.spec.ts +++ b/frontend/src/views/user/__tests__/PaymentResultView.spec.ts @@ -10,6 +10,7 @@ const pollOrderStatus = vi.hoisted(() => vi.fn()) const verifyOrder = vi.hoisted(() => vi.fn()) const verifyOrderPublic = vi.hoisted(() => vi.fn()) const resolveOrderPublicByResumeToken = vi.hoisted(() => vi.fn()) +const refreshUser = vi.hoisted(() => vi.fn()) vi.mock('vue-router', async () => { const actual = await vi.importActual('vue-router') @@ -36,6 +37,12 @@ vi.mock('@/stores/payment', () => ({ }), })) +vi.mock('@/stores/auth', () => ({ + useAuthStore: () => ({ + refreshUser, + }), +})) + vi.mock('@/api/payment', () => ({ paymentAPI: { verifyOrder, @@ -91,6 +98,8 @@ describe('PaymentResultView', () => { verifyOrder.mockReset() verifyOrderPublic.mockReset() resolveOrderPublicByResumeToken.mockReset() + refreshUser.mockReset() + refreshUser.mockResolvedValue({}) window.localStorage.clear() }) @@ -171,7 +180,7 @@ describe('PaymentResultView', () => { })) resolveOrderPublicByResumeToken.mockResolvedValue({ data: { - ...orderFactory('PAID'), + ...orderFactory('COMPLETED'), amount: 100, pay_amount: 103, fee_rate: 3, @@ -190,13 +199,14 @@ describe('PaymentResultView', () => { expect(pollOrderStatus).not.toHaveBeenCalled() expect(resolveOrderPublicByResumeToken).toHaveBeenCalledWith('resume-authoritative') + expect(refreshUser).toHaveBeenCalledTimes(1) expect(wrapper.text()).toContain('payment.result.success') expect(wrapper.text()).toContain('103.00') expect(wrapper.text()).toContain('100.00') expect(window.localStorage.getItem(PAYMENT_RECOVERY_STORAGE_KEY)).toBeNull() }) - it('refreshes a pending resume-token result until the order becomes paid', async () => { + it('waits for completed fulfillment before refreshing the user balance', async () => { vi.useFakeTimers() routeState.query = { resume_token: 'resume-77', @@ -210,7 +220,7 @@ describe('PaymentResultView', () => { data: orderFactory('PENDING'), }) .mockResolvedValueOnce({ - data: orderFactory('PAID'), + data: orderFactory('COMPLETED'), }) const wrapper = mount(PaymentResultView, { @@ -224,6 +234,7 @@ describe('PaymentResultView', () => { await flushPromises() expect(resolveOrderPublicByResumeToken).toHaveBeenCalledTimes(1) + expect(refreshUser).not.toHaveBeenCalled() expect(wrapper.text()).toContain('payment.result.processing') expect(window.localStorage.getItem(PAYMENT_RECOVERY_STORAGE_KEY)).not.toBeNull() @@ -231,11 +242,36 @@ describe('PaymentResultView', () => { await flushPromises() expect(resolveOrderPublicByResumeToken).toHaveBeenCalledTimes(2) + expect(refreshUser).toHaveBeenCalledTimes(1) expect(wrapper.text()).toContain('payment.result.success') expect(wrapper.text()).not.toContain('payment.result.failed') expect(window.localStorage.getItem(PAYMENT_RECOVERY_STORAGE_KEY)).toBeNull() }) + it('keeps the successful result when refreshing the user balance fails', async () => { + routeState.query = { + resume_token: 'resume-refresh-failure', + } + resolveOrderPublicByResumeToken.mockResolvedValue({ + data: orderFactory('COMPLETED'), + }) + refreshUser.mockRejectedValueOnce(new Error('profile refresh failed')) + + const wrapper = mount(PaymentResultView, { + global: { + stubs: { + OrderStatusBadge: true, + }, + }, + }) + + await flushPromises() + + expect(refreshUser).toHaveBeenCalledTimes(1) + expect(wrapper.text()).toContain('payment.result.success') + expect(wrapper.text()).not.toContain('payment.result.failed') + }) + it('falls back to order_id polling when resume-token recovery fails', async () => { routeState.query = { resume_token: 'resume-fail', From e2d9b823f63dc4e8f4014be3fd24a0a73e339867 Mon Sep 17 00:00:00 2001 From: "github-actions[bot]" <41898282+github-actions[bot]@users.noreply.github.com> Date: Mon, 24 Aug 2026 14:35:57 +0000 Subject: [PATCH 158/204] chore: sync VERSION to 0.1.181 [skip ci] --- backend/cmd/server/VERSION | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/backend/cmd/server/VERSION b/backend/cmd/server/VERSION index 2005625e83..7fcea722aa 100644 --- a/backend/cmd/server/VERSION +++ b/backend/cmd/server/VERSION @@ -1 +1 @@ -0.1.180 +0.1.181 From 329b92ef045fd24b49b33e719e42facc7b26e1b2 Mon Sep 17 00:00:00 2001 From: SipengXie2024 <184713193+SipengXie2024@users.noreply.github.com> Date: Mon, 24 Aug 2026 13:27:24 +0000 Subject: [PATCH 159/204] fix(openai): preserve OAuth image prompts verbatim --- backend/internal/service/openai_images.go | 13 +++++++------ .../internal/service/openai_images_responses.go | 1 + backend/internal/service/openai_images_test.go | 15 +++++++++++++++ 3 files changed, 23 insertions(+), 6 deletions(-) diff --git a/backend/internal/service/openai_images.go b/backend/internal/service/openai_images.go index bc6b6b807f..c661aade36 100644 --- a/backend/internal/service/openai_images.go +++ b/backend/internal/service/openai_images.go @@ -34,12 +34,13 @@ const ( openAIImagesGenerationsURL = "https://api.openai.com/v1/images/generations" openAIImagesEditsURL = "https://api.openai.com/v1/images/edits" - openAIChatGPTStartURL = "https://chatgpt.com/" - openAIChatGPTFilesURL = "https://chatgpt.com/backend-api/files" - openAIImageBackendUserAgent = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/131.0.0.0 Safari/537.36" - openAIImageMaxDownloadBytes = 20 << 20 // 20MB per image download - openAIImageMaxUploadPartSize = 20 << 20 // 20MB per multipart upload part - openAIImagesResponsesMainModel = "gpt-5.4-mini" + openAIChatGPTStartURL = "https://chatgpt.com/" + openAIChatGPTFilesURL = "https://chatgpt.com/backend-api/files" + openAIImageBackendUserAgent = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/131.0.0.0 Safari/537.36" + openAIImageMaxDownloadBytes = 20 << 20 // 20MB per image download + openAIImageMaxUploadPartSize = 20 << 20 // 20MB per multipart upload part + openAIImagesResponsesMainModel = "gpt-5.4-mini" + openAIImagesVerbatimPromptInstructions = "When invoking the image_generation tool, use the user's image prompt verbatim. Do not rewrite, expand, summarize, embellish, translate, normalize punctuation, or add or remove visual details or constraints. Preserve the original language, wording, capitalization, quotes, and punctuation exactly." ) type OpenAIImagesCapability string diff --git a/backend/internal/service/openai_images_responses.go b/backend/internal/service/openai_images_responses.go index 9e72aaecc4..9374a6f7c7 100644 --- a/backend/internal/service/openai_images_responses.go +++ b/backend/internal/service/openai_images_responses.go @@ -356,6 +356,7 @@ func buildOpenAIImagesResponsesRequest(parsed *OpenAIImagesRequest, toolModel st req := []byte(`{"instructions":"","stream":true,"reasoning":{"effort":"medium","summary":"auto"},"parallel_tool_calls":true,"include":["reasoning.encrypted_content"],"model":"","store":false,"tool_choice":{"type":"image_generation"}}`) req, _ = sjson.SetBytes(req, "model", openAIImagesResponsesMainModel) + req, _ = sjson.SetBytes(req, "instructions", openAIImagesVerbatimPromptInstructions) input := []byte(`[{"type":"message","role":"user","content":[{"type":"input_text","text":""}]}]`) input, _ = sjson.SetBytes(input, "0.content.0.text", prompt) diff --git a/backend/internal/service/openai_images_test.go b/backend/internal/service/openai_images_test.go index 6761c55131..f06c213f46 100644 --- a/backend/internal/service/openai_images_test.go +++ b/backend/internal/service/openai_images_test.go @@ -2011,6 +2011,21 @@ func TestBuildOpenAIImagesResponsesRequest_StripsInputFidelity(t *testing.T) { require.Equal(t, "edit", gjson.GetBytes(body, "tools.0.action").String()) } +func TestBuildOpenAIImagesResponsesRequest_RequiresVerbatimUserPrompt(t *testing.T) { + prompt := "画一个蓝色马克杯,杯身只写“SkelOT”,保持大小写;白色背景,不要增加其他文字。" + parsed := &OpenAIImagesRequest{ + Endpoint: openAIImagesGenerationsEndpoint, + Model: "gpt-image-2", + Prompt: prompt, + N: 1, + } + + body, err := buildOpenAIImagesResponsesRequest(parsed, "gpt-image-2") + require.NoError(t, err) + require.Equal(t, openAIImagesVerbatimPromptInstructions, gjson.GetBytes(body, "instructions").String()) + require.Equal(t, prompt, gjson.GetBytes(body, "input.0.content.0.text").String()) +} + func TestCollectOpenAIImagesFromResponsesBody_FallsBackToOutputItemDone(t *testing.T) { body := []byte( "data: {\"type\":\"response.created\",\"response\":{\"created_at\":1710000004}}\n\n" + From 4347e5555b674bc5cd0a09fc733ad2afc6976b11 Mon Sep 17 00:00:00 2001 From: HypoxanthineOvO Date: Mon, 24 Aug 2026 23:09:30 +0800 Subject: [PATCH 160/204] fix(composite): route Kimi Code K3 model IDs --- .../internal/handler/composite_platform_test.go | 1 + backend/internal/service/composite_platform.go | 4 +++- .../internal/service/composite_platform_test.go | 4 ++++ .../service/composite_route_resolver_test.go | 16 ++++++++++++++++ 4 files changed, 24 insertions(+), 1 deletion(-) diff --git a/backend/internal/handler/composite_platform_test.go b/backend/internal/handler/composite_platform_test.go index be1706fba3..6e068a4614 100644 --- a/backend/internal/handler/composite_platform_test.go +++ b/backend/internal/handler/composite_platform_test.go @@ -31,6 +31,7 @@ func TestOpenAICompatibleTextTargetAllowsCompositeProviders(t *testing.T) { }{ {model: "grok-4.3", platform: service.PlatformGrok}, {model: "kimi-k2-thinking", platform: service.PlatformKimi}, + {model: "k3", platform: service.PlatformKimi}, {model: "glm-5.2", platform: service.PlatformZhipu}, {model: "deepseek-v3.2", platform: service.PlatformDeepseek}, } diff --git a/backend/internal/service/composite_platform.go b/backend/internal/service/composite_platform.go index e4d836febe..c7736f9582 100644 --- a/backend/internal/service/composite_platform.go +++ b/backend/internal/service/composite_platform.go @@ -139,7 +139,9 @@ func DetectModelPlatform(model string) (string, bool) { return PlatformGemini, true case normalized == "grok" || strings.HasPrefix(normalized, "grok-"): return PlatformGrok, true - case strings.HasPrefix(normalized, "kimi-"), + case normalized == "k3", + normalized == "k3-256k", + strings.HasPrefix(normalized, "kimi-"), strings.HasPrefix(normalized, "moonshot-"): return PlatformKimi, true case strings.HasPrefix(normalized, "glm-"): diff --git a/backend/internal/service/composite_platform_test.go b/backend/internal/service/composite_platform_test.go index e145634889..5373a7fc6f 100644 --- a/backend/internal/service/composite_platform_test.go +++ b/backend/internal/service/composite_platform_test.go @@ -26,9 +26,13 @@ func TestDetectModelPlatform(t *testing.T) { {name: "grok", model: "grok-4", platform: PlatformGrok, ok: true}, {name: "xai prefix", model: "xai/grok-4", platform: PlatformGrok, ok: true}, {name: "kimi", model: "kimi-k2-thinking", platform: PlatformKimi, ok: true}, + {name: "kimi code bare k3", model: "K3", platform: PlatformKimi, ok: true}, + {name: "kimi code bare k3 256k", model: "k3-256k", platform: PlatformKimi, ok: true}, + {name: "kimi code provider prefix", model: "kimi-code/k3", platform: PlatformKimi, ok: true}, {name: "moonshot prefix", model: "moonshot/moonshot-v1-32k", platform: PlatformKimi, ok: true}, {name: "zhipu", model: "glm-5.2", platform: PlatformZhipu, ok: true}, {name: "deepseek", model: "deepseek-v4-pro", platform: PlatformDeepseek, ok: true}, + {name: "unknown k3 alias", model: "k3-preview", ok: false}, {name: "unknown", model: "llama-4-maverick", ok: false}, } diff --git a/backend/internal/service/composite_route_resolver_test.go b/backend/internal/service/composite_route_resolver_test.go index 35028934dd..60e4bd0b82 100644 --- a/backend/internal/service/composite_route_resolver_test.go +++ b/backend/internal/service/composite_route_resolver_test.go @@ -191,6 +191,22 @@ func TestCompositeRouteResolverIgnoresDisabledRoutesAndFallsBackToDetector(t *te require.Nil(t, decision.Route) } +func TestCompositeRouteResolverDetectsKimiCodeBareModels(t *testing.T) { + resolver := NewCompositeRouteResolver(nil) + + for _, model := range []string{"k3", "k3-256k", "kimi-code/k3"} { + t.Run(model, func(t *testing.T) { + decision, err := resolver.Resolve(context.Background(), 7, model, CompositeRouteEndpointMessages) + + require.NoError(t, err) + require.True(t, decision.Matched) + require.Equal(t, CompositeRouteSourceDetector, decision.Source) + require.Equal(t, PlatformKimi, decision.TargetPlatform) + require.Equal(t, model, decision.UpstreamModel) + }) + } +} + func TestCompositeRouteResolverExplicitRoutesCoverBucketTwoProviders(t *testing.T) { resolver := NewCompositeRouteResolver(compositeRouteRepoStub{ routes: []CompositeModelRoute{ From 53d76ad80020b5846580ce2d44b77769f44bd1c6 Mon Sep 17 00:00:00 2001 From: Jiao Ziang <2720649216@qq.com> Date: Tue, 25 Aug 2026 00:21:29 +0800 Subject: [PATCH 161/204] fix(openai): enforce Responses Lite tool call mode --- .../service/openai_gateway_forward.go | 5 +- .../service/openai_responses_lite_tools.go | 37 +++++- .../openai_responses_lite_tools_test.go | 114 +++++++++++++++++- .../service/openai_ws_forwarder_ingress.go | 4 +- ...penai_ws_forwarder_ingress_session_test.go | 10 +- .../openai_ws_v2_passthrough_adapter.go | 8 +- 6 files changed, 162 insertions(+), 16 deletions(-) diff --git a/backend/internal/service/openai_gateway_forward.go b/backend/internal/service/openai_gateway_forward.go index ef53b6732d..38d747ca33 100644 --- a/backend/internal/service/openai_gateway_forward.go +++ b/backend/internal/service/openai_gateway_forward.go @@ -76,8 +76,9 @@ func (s *OpenAIGatewayService) Forward(ctx context.Context, c *gin.Context, acco body = reasoningBody } } - if account.IsOpenAIOAuthLike() && isOpenAIResponsesLiteHeader(c.GetHeader(responsesLiteHeader)) { - liteBody, changed, liteErr := normalizeOpenAIResponsesLiteToolsPayload(body) + responsesLite := account.IsOpenAI() && isOpenAIResponsesLiteHeader(c.GetHeader(responsesLiteHeader)) + if responsesLite { + liteBody, changed, liteErr := normalizeOpenAIResponsesLitePayloadForAccount(body, account) if liteErr != nil { param := "tools" var validationErr *openAIResponsesLiteValidationError diff --git a/backend/internal/service/openai_responses_lite_tools.go b/backend/internal/service/openai_responses_lite_tools.go index f374b59bbf..b13e1443d0 100644 --- a/backend/internal/service/openai_responses_lite_tools.go +++ b/backend/internal/service/openai_responses_lite_tools.go @@ -101,8 +101,17 @@ func normalizeOpenAIResponsesLiteTools(reqBody map[string]any) (bool, error) { } func ensureOpenAIResponsesLiteParallelToolCalls(reqBody map[string]any, changed bool) (bool, error) { - parallel := reqBody["parallel_tool_calls"] + parallel, exists := reqBody["parallel_tool_calls"] + if exists { + if _, ok := parallel.(bool); !ok { + return false, newOpenAIResponsesLiteValidationError("parallel_tool_calls", "responses Lite requires parallel_tool_calls to be a boolean") + } + } if !openAIResponsesLiteHasTools(reqBody) { + if exists { + delete(reqBody, "parallel_tool_calls") + return true, nil + } return changed, nil } if parallel == false { @@ -267,3 +276,29 @@ func normalizeOpenAIResponsesLiteToolsPayload(body []byte) ([]byte, bool, error) } return rebuilt, true, nil } + +func normalizeOpenAIResponsesLiteParallelToolCallsPayload(body []byte) ([]byte, bool, error) { + var requestBody map[string]any + if err := json.Unmarshal(body, &requestBody); err != nil { + return body, false, fmt.Errorf("decode responses Lite request body: %w", err) + } + changed, err := ensureOpenAIResponsesLiteParallelToolCalls(requestBody, false) + if err != nil || !changed { + return body, false, err + } + rebuilt, err := marshalOpenAIUpstreamJSON(requestBody) + if err != nil { + return body, false, fmt.Errorf("encode responses Lite request body: %w", err) + } + return rebuilt, true, nil +} + +func normalizeOpenAIResponsesLitePayloadForAccount(body []byte, account *Account) ([]byte, bool, error) { + if account == nil || !account.IsOpenAI() { + return body, false, nil + } + if account.IsOpenAIOAuthLike() { + return normalizeOpenAIResponsesLiteToolsPayload(body) + } + return normalizeOpenAIResponsesLiteParallelToolCallsPayload(body) +} diff --git a/backend/internal/service/openai_responses_lite_tools_test.go b/backend/internal/service/openai_responses_lite_tools_test.go index 145ddf95b2..e1166ef4e9 100644 --- a/backend/internal/service/openai_responses_lite_tools_test.go +++ b/backend/internal/service/openai_responses_lite_tools_test.go @@ -201,17 +201,25 @@ func TestNormalizeOpenAIResponsesLiteTools_ForcesParallelToolCallsFalse(t *testi } } -func TestNormalizeOpenAIResponsesLiteTools_DoesNotAddParallelToolCallsWithoutTools(t *testing.T) { - reqBody := map[string]any{ - "reasoning": map[string]any{"context": "all_turns"}, - "parallel_tool_calls": true, +func TestNormalizeOpenAIResponsesLiteTools_RemovesParallelToolCallsWithoutTools(t *testing.T) { + for _, value := range []bool{true, false} { + reqBody := map[string]any{ + "reasoning": map[string]any{"context": "all_turns"}, + "parallel_tool_calls": value, + } + + changed, err := normalizeOpenAIResponsesLiteTools(reqBody) + + require.NoError(t, err) + require.True(t, changed) + require.NotContains(t, reqBody, "parallel_tool_calls") } + reqBody := map[string]any{"reasoning": map[string]any{"context": "all_turns"}} changed, err := normalizeOpenAIResponsesLiteTools(reqBody) - require.NoError(t, err) require.False(t, changed) - require.Equal(t, true, reqBody["parallel_tool_calls"]) + require.NotContains(t, reqBody, "parallel_tool_calls") } func TestNormalizeOpenAIResponsesLiteTools_RejectsNonBooleanParallelToolCalls(t *testing.T) { @@ -453,3 +461,97 @@ func TestOpenAIGatewayServiceForward_NormalizesResponsesLiteToolsForOAuth(t *tes }) } } + +func TestOpenAIGatewayServiceForward_RemovesParallelToolCallsForToollessResponsesLite(t *testing.T) { + gin.SetMode(gin.TestMode) + + for _, passthrough := range []bool{false, true} { + name := "managed" + if passthrough { + name = "passthrough" + } + t.Run(name, func(t *testing.T) { + rec := httptest.NewRecorder() + c, _ := gin.CreateTestContext(rec) + c.Request = httptest.NewRequest(http.MethodPost, "/v1/responses", bytes.NewReader(nil)) + c.Request.Header.Set("User-Agent", "codex_cli_rs/0.144.1") + c.Request.Header.Set(responsesLiteHeader, "true") + upstream := &httpUpstreamRecorder{resp: &http.Response{ + StatusCode: http.StatusOK, + Header: http.Header{"Content-Type": []string{"text/event-stream"}}, + Body: io.NopCloser(strings.NewReader( + "data: {\"type\":\"response.completed\",\"response\":{\"id\":\"resp_lite\",\"usage\":{\"input_tokens\":1,\"output_tokens\":1}}}\n\n" + + "data: [DONE]\n\n", + )), + }} + svc := &OpenAIGatewayService{cfg: &config.Config{}, httpUpstream: upstream} + account := &Account{ + ID: 502, Name: "responses-lite-no-tools", Platform: PlatformOpenAI, Type: AccountTypeOAuth, + Concurrency: 1, Status: StatusActive, Schedulable: true, RateMultiplier: f64p(1), + Credentials: map[string]any{"access_token": "oauth-token", "chatgpt_account_id": "chatgpt-account"}, + Extra: map[string]any{"openai_passthrough": passthrough}, + } + body := []byte(`{ + "model":"gpt-5.6-terra","stream":true,"instructions":"test", + "reasoning":{"effort":"high","context":"current_turn"}, + "parallel_tool_calls":true, + "input":[{"type":"message","role":"user","content":"hello"}] + }`) + + result, err := svc.Forward(context.Background(), c, account, body) + + require.NoError(t, err) + require.NotNil(t, result) + require.Equal(t, "true", upstream.lastReq.Header.Get(responsesLiteHeader)) + require.False(t, gjson.GetBytes(upstream.lastBody, "parallel_tool_calls").Exists(), string(upstream.lastBody)) + }) + } +} + +func TestOpenAIGatewayServiceForward_DisablesParallelToolCallsForResponsesLiteAPIKey(t *testing.T) { + gin.SetMode(gin.TestMode) + + for _, passthrough := range []bool{false, true} { + name := "managed" + if passthrough { + name = "passthrough" + } + t.Run(name, func(t *testing.T) { + rec := httptest.NewRecorder() + c, _ := gin.CreateTestContext(rec) + c.Request = httptest.NewRequest(http.MethodPost, "/v1/responses", bytes.NewReader(nil)) + c.Request.Header.Set("User-Agent", "codex_cli_rs/0.144.1") + c.Request.Header.Set(responsesLiteHeader, "true") + upstream := &httpUpstreamRecorder{resp: &http.Response{ + StatusCode: http.StatusOK, + Header: http.Header{"Content-Type": []string{"text/event-stream"}}, + Body: io.NopCloser(strings.NewReader( + "data: {\"type\":\"response.completed\",\"response\":{\"id\":\"resp_lite\",\"usage\":{\"input_tokens\":1,\"output_tokens\":1}}}\n\n" + + "data: [DONE]\n\n", + )), + }} + svc := &OpenAIGatewayService{cfg: &config.Config{}, httpUpstream: upstream} + account := &Account{ + ID: 503, Name: "responses-lite-api-key", Platform: PlatformOpenAI, Type: AccountTypeAPIKey, + Concurrency: 1, Status: StatusActive, Schedulable: true, RateMultiplier: f64p(1), + Credentials: map[string]any{"api_key": "sk-test"}, + Extra: map[string]any{"openai_passthrough": passthrough}, + } + body := []byte(`{ + "model":"gpt-5.6-terra","stream":true,"instructions":"test", + "tools":[{"type":"function","name":"lookup","parameters":{"type":"object"}}], + "parallel_tool_calls":true, + "input":[{"type":"message","role":"user","content":"hello"}] + }`) + + result, err := svc.Forward(context.Background(), c, account, body) + + require.NoError(t, err) + require.NotNil(t, result) + require.Equal(t, "true", upstream.lastReq.Header.Get(responsesLiteHeader)) + require.True(t, gjson.GetBytes(upstream.lastBody, "tools").IsArray()) + require.True(t, gjson.GetBytes(upstream.lastBody, "parallel_tool_calls").Exists()) + require.False(t, gjson.GetBytes(upstream.lastBody, "parallel_tool_calls").Bool()) + }) + } +} diff --git a/backend/internal/service/openai_ws_forwarder_ingress.go b/backend/internal/service/openai_ws_forwarder_ingress.go index 5eff93fc2e..5f9aed1f61 100644 --- a/backend/internal/service/openai_ws_forwarder_ingress.go +++ b/backend/internal/service/openai_ws_forwarder_ingress.go @@ -320,8 +320,8 @@ func (s *OpenAIGatewayService) ProxyResponsesWebSocketFromClient( if accountScoped { normalized = accountScopedPayload } - if account.IsOpenAIOAuthLike() && isOpenAIResponsesLiteWebSocketPayload(normalized) { - litePayload, _, liteErr := normalizeOpenAIResponsesLiteToolsPayload(normalized) + if isOpenAIResponsesLiteWebSocketPayload(normalized) { + litePayload, _, liteErr := normalizeOpenAIResponsesLitePayloadForAccount(normalized, account) if liteErr != nil { return openAIWSClientPayload{}, NewOpenAIWSClientCloseError( coderws.StatusPolicyViolation, diff --git a/backend/internal/service/openai_ws_forwarder_ingress_session_test.go b/backend/internal/service/openai_ws_forwarder_ingress_session_test.go index 097d845037..2e09082d6e 100644 --- a/backend/internal/service/openai_ws_forwarder_ingress_session_test.go +++ b/backend/internal/service/openai_ws_forwarder_ingress_session_test.go @@ -1361,7 +1361,12 @@ func TestOpenAIGatewayService_ProxyResponsesWebSocketFromClient_HTTPBridgeModeRe }() writeCtx, cancelWrite := context.WithTimeout(context.Background(), 3*time.Second) - err = clientConn.Write(writeCtx, coderws.MessageText, []byte(`{"type":"response.create","model":"gpt-5.1","stream":false}`)) + err = clientConn.Write(writeCtx, coderws.MessageText, []byte(`{ + "type":"response.create","model":"gpt-5.1","stream":false, + "parallel_tool_calls":true, + "client_metadata":{"ws_request_header_x_openai_internal_codex_responses_lite":"true"}, + "tools":[{"type":"function","name":"lookup","parameters":{"type":"object"}}] + }`)) cancelWrite() require.NoError(t, err) @@ -1402,6 +1407,9 @@ func TestOpenAIGatewayService_ProxyResponsesWebSocketFromClient_HTTPBridgeModeRe } require.NotNil(t, upstream.lastReq, "http_bridge 模式应调用 HTTP 上游") + require.Equal(t, "true", upstream.lastReq.Header.Get(responsesLiteHeader)) + require.True(t, gjson.GetBytes(upstream.lastBody, "parallel_tool_calls").Exists()) + require.False(t, gjson.GetBytes(upstream.lastBody, "parallel_tool_calls").Bool()) } func TestOpenAIGatewayService_ProxyResponsesWebSocketFromClient_ModeOffReturnsPolicyViolation(t *testing.T) { diff --git a/backend/internal/service/openai_ws_v2_passthrough_adapter.go b/backend/internal/service/openai_ws_v2_passthrough_adapter.go index 96e1c859bb..d22e386e11 100644 --- a/backend/internal/service/openai_ws_v2_passthrough_adapter.go +++ b/backend/internal/service/openai_ws_v2_passthrough_adapter.go @@ -679,8 +679,8 @@ func (s *OpenAIGatewayService) proxyResponsesWebSocketV2Passthrough( if err := validateOpenAIWSBearerToken(account, token); err != nil { return err } - if account.IsOpenAIOAuthLike() && isOpenAIResponsesLiteWebSocketPayload(firstClientMessage) { - liteFirstMessage, _, liteErr := normalizeOpenAIResponsesLiteToolsPayload(firstClientMessage) + if isOpenAIResponsesLiteWebSocketPayload(firstClientMessage) { + liteFirstMessage, _, liteErr := normalizeOpenAIResponsesLitePayloadForAccount(firstClientMessage, account) if liteErr != nil { return NewOpenAIWSClientCloseError(coderws.StatusPolicyViolation, liteErr.Error(), liteErr) } @@ -1011,8 +1011,8 @@ func (s *OpenAIGatewayService) proxyResponsesWebSocketV2Passthrough( } } if isResponseCreate { - if account.IsOpenAIOAuthLike() && isOpenAIResponsesLiteWebSocketPayload(payload) { - litePayload, _, liteErr := normalizeOpenAIResponsesLiteToolsPayload(payload) + if isOpenAIResponsesLiteWebSocketPayload(payload) { + litePayload, _, liteErr := normalizeOpenAIResponsesLitePayloadForAccount(payload, account) if liteErr != nil { return payload, nil, NewOpenAIWSClientCloseError(coderws.StatusPolicyViolation, liteErr.Error(), liteErr) } From d6012b0b351b43d5170a63ae1d562c81f7a5d53b Mon Sep 17 00:00:00 2001 From: Jiao Ziang <2720649216@qq.com> Date: Tue, 25 Aug 2026 01:05:28 +0800 Subject: [PATCH 162/204] fix(openai): preserve numeric precision in Lite payloads --- .../service/openai_responses_lite_tools.go | 5 ++-- .../openai_responses_lite_tools_test.go | 28 +++++++++++++++++++ 2 files changed, 30 insertions(+), 3 deletions(-) diff --git a/backend/internal/service/openai_responses_lite_tools.go b/backend/internal/service/openai_responses_lite_tools.go index b13e1443d0..752ed00561 100644 --- a/backend/internal/service/openai_responses_lite_tools.go +++ b/backend/internal/service/openai_responses_lite_tools.go @@ -1,7 +1,6 @@ package service import ( - "encoding/json" "fmt" "reflect" "strings" @@ -263,7 +262,7 @@ func openAIResponsesLiteToolIdentityForError(rawTool any) string { func normalizeOpenAIResponsesLiteToolsPayload(body []byte) ([]byte, bool, error) { var requestBody map[string]any - if err := json.Unmarshal(body, &requestBody); err != nil { + if err := decodeOpenAIJSONUseNumber(body, &requestBody); err != nil { return body, false, fmt.Errorf("decode responses Lite request body: %w", err) } changed, err := normalizeOpenAIResponsesLiteTools(requestBody) @@ -279,7 +278,7 @@ func normalizeOpenAIResponsesLiteToolsPayload(body []byte) ([]byte, bool, error) func normalizeOpenAIResponsesLiteParallelToolCallsPayload(body []byte) ([]byte, bool, error) { var requestBody map[string]any - if err := json.Unmarshal(body, &requestBody); err != nil { + if err := decodeOpenAIJSONUseNumber(body, &requestBody); err != nil { return body, false, fmt.Errorf("decode responses Lite request body: %w", err) } changed, err := ensureOpenAIResponsesLiteParallelToolCalls(requestBody, false) diff --git a/backend/internal/service/openai_responses_lite_tools_test.go b/backend/internal/service/openai_responses_lite_tools_test.go index e1166ef4e9..3edff5c2da 100644 --- a/backend/internal/service/openai_responses_lite_tools_test.go +++ b/backend/internal/service/openai_responses_lite_tools_test.go @@ -344,6 +344,34 @@ func TestNormalizeOpenAIResponsesLiteToolsPayload_PreservesResponseCreateShape(t require.False(t, gjson.GetBytes(updated, "parallel_tool_calls").Bool()) } +func TestNormalizeOpenAIResponsesLitePayloads_PreserveLargeSequence(t *testing.T) { + body := []byte(`{ + "type":"response.create", + "sequence":900719925474099312345, + "tools":[{"type":"function","name":"lookup"}], + "parallel_tool_calls":true + }`) + tests := []struct { + name string + normalize func([]byte) ([]byte, bool, error) + }{ + {name: "OAuth-like tools normalization", normalize: normalizeOpenAIResponsesLiteToolsPayload}, + {name: "API key parallel normalization", normalize: normalizeOpenAIResponsesLiteParallelToolCallsPayload}, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + updated, changed, err := tt.normalize(body) + + require.NoError(t, err) + require.True(t, changed) + require.Equal(t, "900719925474099312345", gjson.GetBytes(updated, "sequence").Raw) + require.True(t, gjson.GetBytes(updated, "parallel_tool_calls").Exists()) + require.False(t, gjson.GetBytes(updated, "parallel_tool_calls").Bool()) + }) + } +} + func TestApplyCodexOAuthTransform_PreservesLiteNamespaceToolChoice(t *testing.T) { reqBody := map[string]any{ "model": "gpt-5.6-terra", From d5e43ef7d13e76b551cdd19ef38e1f1fb9866a7c Mon Sep 17 00:00:00 2001 From: Jiao Ziang <2720649216@qq.com> Date: Tue, 25 Aug 2026 03:46:46 +0800 Subject: [PATCH 163/204] fix(openai): normalize Lite requests in WS HTTP bridge --- backend/internal/service/openai_ws_http_bridge.go | 9 +++++++++ backend/internal/service/openai_ws_http_bridge_test.go | 4 +++- 2 files changed, 12 insertions(+), 1 deletion(-) diff --git a/backend/internal/service/openai_ws_http_bridge.go b/backend/internal/service/openai_ws_http_bridge.go index 26a08c1bf1..2bb0c200b5 100644 --- a/backend/internal/service/openai_ws_http_bridge.go +++ b/backend/internal/service/openai_ws_http_bridge.go @@ -349,6 +349,15 @@ func (s *OpenAIGatewayService) proxyOpenAIWSHTTPBridgeTurn( LoweredTools: loweredTools, }) } + if account.Platform != PlatformGrok && isOpenAIResponsesLiteWebSocketPayload(payload) { + liteBody, liteChanged, liteErr := normalizeOpenAIResponsesLitePayloadForAccount(body, account) + if liteErr != nil { + return nil, fmt.Errorf("normalize responses Lite payload: %w", liteErr) + } + if liteChanged { + body = liteBody + } + } buildUpstreamRequest := func(requestBody []byte) (*http.Request, error) { upstreamCtx, releaseUpstreamCtx := detachUpstreamContext(ctx) diff --git a/backend/internal/service/openai_ws_http_bridge_test.go b/backend/internal/service/openai_ws_http_bridge_test.go index 59ee0a548e..752fdcca19 100644 --- a/backend/internal/service/openai_ws_http_bridge_test.go +++ b/backend/internal/service/openai_ws_http_bridge_test.go @@ -1239,7 +1239,7 @@ func TestOpenAIWSHTTPBridgeRelaysSSEFramesAsWebSocketMessages(t *testing.T) { Concurrency: 1, Status: StatusActive, } - payload := []byte(`{"type":"response.create","generate":true,"model":"gpt-5","stream":true,"client_metadata":{"ws_request_header_x_openai_internal_codex_responses_lite":"true"},"input":"hi"}`) + payload := []byte(`{"type":"response.create","generate":true,"model":"gpt-5","stream":true,"client_metadata":{"ws_request_header_x_openai_internal_codex_responses_lite":"true"},"input":"hi","tools":[{"type":"function","name":"lookup","parameters":{"type":"object"}}],"parallel_tool_calls":true}`) type bridgeResult struct { result *OpenAIForwardResult @@ -1325,6 +1325,8 @@ func TestOpenAIWSHTTPBridgeRelaysSSEFramesAsWebSocketMessages(t *testing.T) { require.False(t, gjson.GetBytes(upstream.lastBody, "type").Exists()) require.False(t, gjson.GetBytes(upstream.lastBody, "generate").Exists()) require.True(t, gjson.GetBytes(upstream.lastBody, "stream").Bool()) + require.True(t, gjson.GetBytes(upstream.lastBody, "parallel_tool_calls").Exists()) + require.False(t, gjson.GetBytes(upstream.lastBody, "parallel_tool_calls").Bool()) } func TestProxyOpenAIWSHTTPBridgeTurnForGrokDefaultsEmptyModelTo45(t *testing.T) { From 3b7753a8e4a72791001ef558eebbd6e05bee8d9d Mon Sep 17 00:00:00 2001 From: shaw Date: Tue, 25 Aug 2026 08:51:58 +0800 Subject: [PATCH 164/204] chore: update sponsors --- README.md | 5 +++++ README_CN.md | 5 +++++ README_JA.md | 5 +++++ assets/partners/logos/apimart.jpg | Bin 0 -> 60980 bytes 4 files changed, 15 insertions(+) create mode 100644 assets/partners/logos/apimart.jpg diff --git a/README.md b/README.md index e5d3221c1c..16ebab0a32 100644 --- a/README.md +++ b/README.md @@ -162,6 +162,11 @@ Please read the following carefully before using this project: DuckIP - 90M+ global residential network resources across 195+ countries and regions, with rotation and sticky sessions for public data collection, RAG updates, model evaluation, and multi-region data workloads. 🟢Residential Proxy - 20% Off; 🟢Static Residential Proxy - Starting at ¥50.00/IP; 🟢Unlimited Residential Proxy - Starting at ¥19.8/Hour. ✅Get 500M Free Trial. + +APIMart +Thanks to APIMart for sponsoring this project! APIMart is a low-cost API platform for AI image and video generation — GPT-Image-2 from $0.006 per image, with 160+ images per dollar. One async API covers both image and video: submit a task, get an ID, and retrieve results via polling or callback. Batch tens of thousands of images without timeouts, and switch models without changing code. Pay as you go with no monthly fee — sign up here to get started. + + ## Overview diff --git a/README_CN.md b/README_CN.md index 10329d4d8f..e879045374 100644 --- a/README_CN.md +++ b/README_CN.md @@ -165,6 +165,11 @@ DuckIP - 9000 万+ 全球住宅网络资源,覆盖 195+ 国家和地区,支持轮换和粘性会话,适用于公共数据采集、RAG 更新、模型评估和多区域数据工作负载。🟢住宅代理 - 8 折优惠;🟢静态住宅代理 - ¥50.00/IP 起;🟢无限住宅代理 - ¥19.8/小时 起。✅免费领取 500M 试用流量。 + +APIMart +感谢 APIMart 赞助了本项目!APIMart 是专注于 AI 图片/视频生成的低价 API 平台,GPT-Image-2 低至 $0.006/张,1 美元可生成 160+ 张图片。图片、视频一套异步 API 通吃:提交任务获取 ID,通过轮询或回调获取结果;批量生成上万张图片也不会超时,切换模型无需修改代码。按量付费、无月费,通过此注册链接注册即可开始使用。 + + ## 项目概述 diff --git a/README_JA.md b/README_JA.md index 8727367980..17890e4557 100644 --- a/README_JA.md +++ b/README_JA.md @@ -164,6 +164,11 @@ DuckIP - 195 以上の国と地域にわたる 9,000 万以上のグローバルレジデンシャルネットワークリソース。ローテーションとスティッキーセッションに対応し、パブリックデータ収集、RAG 更新、モデル評価、マルチリージョンデータワークロードに最適。🟢レジデンシャルプロキシ - 20% オフ;🟢スタティックレジデンシャルプロキシ - ¥50.00/IP から;🟢無制限レジデンシャルプロキシ - ¥19.8/時間 から。✅500M 無料トライアルを取得。 + +APIMart +APIMart のご支援に感謝します!APIMart は AI 画像・動画生成に特化した低価格 API プラットフォームです。GPT-Image-2 は 1 枚 $0.006 から、1 ドルで 160 枚以上の画像を生成できます。画像と動画の両方に対応する非同期 API を 1 つで利用でき、タスクを送信して ID を取得し、ポーリングまたはコールバックで結果を取得できます。数万枚規模のバッチ処理でもタイムアウトせず、モデルを変更してもコードの変更は不要です。月額料金なしの従量課金制で、こちらの登録リンクからすぐに利用を開始できます。 + + ## 概要 diff --git a/assets/partners/logos/apimart.jpg b/assets/partners/logos/apimart.jpg new file mode 100644 index 0000000000000000000000000000000000000000..e670cea236e5e95ebcba111f98da0178d1e490df GIT binary patch literal 60980 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 literal 0 HcmV?d00001 From b7ec3cdadf0f935da3569d5f16aa81c7b3d12b75 Mon Sep 17 00:00:00 2001 From: William Drake Date: Sun, 16 Aug 2026 08:07:45 -0700 Subject: [PATCH 165/204] fix(openai): fail raw CC streams truncated before any terminal chunk MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The raw Chat Completions passthrough returned a nil error whenever the upstream body ended, so an upstream that cut the SSE stream mid-generation surfaced as HTTP 200 with usage 0/0: the client kept a half-finished answer, the request was not counted as an SLA failure, and ops saw nothing. Observed against opencode.ai/zen/go (deepseek-v4-pro): 11 of 1346 streams in 24h recorded a first token but no final usage, alongside a concurrent `connection reset by peer` against the upstream edge. Track whether the upstream ever emitted a terminal signal — [DONE], a usage chunk, or a finish_reason — and treat a stream that ends without one as an upstream failure. Matching only [DONE] would misfire on compatible upstreams that EOF right after their last chunk and would drop billing for tokens that were actually delivered, so all three count. - nothing written to the client yet: UpstreamFailoverError, retried on another account with no client-visible half stream - bytes already on the wire: typed openAIUpstreamStreamReadError, so the handler appends an SSE error frame and marks the request an SLA failure Client cancel/disconnect keeps the previous semantics — there the upstream read error is indistinguishable from a truncation, so partial usage is still billed rather than blamed on the account. Co-Authored-By: Claude Opus 5 (1M context) --- .../openai_gateway_chat_completions_raw.go | 83 +++-- ...penai_gateway_chat_completions_raw_test.go | 320 ++++++++++++++++++ .../service/openai_raw_stream_truncation.go | 161 +++++++++ .../service/openai_stream_read_error.go | 12 + 4 files changed, 554 insertions(+), 22 deletions(-) create mode 100644 backend/internal/service/openai_raw_stream_truncation.go diff --git a/backend/internal/service/openai_gateway_chat_completions_raw.go b/backend/internal/service/openai_gateway_chat_completions_raw.go index 7427c6fc9c..00bbda0e51 100644 --- a/backend/internal/service/openai_gateway_chat_completions_raw.go +++ b/backend/internal/service/openai_gateway_chat_completions_raw.go @@ -285,6 +285,7 @@ func (s *OpenAIGatewayService) streamRawChatCompletions( clientOutputStarted := false pendingLines := make([]string, 0, 8) refusalDetector := newOpenAIChatSilentRefusalDetector(requestBodyLen) + var terminal openAIRawStreamTerminalState writeLine := func(line string) { if clientDisconnected { @@ -323,6 +324,7 @@ func (s *OpenAIGatewayService) streamRawChatCompletions( refusalDetector.ObserveSSELine(line) if payload, ok := extractOpenAISSEDataLine(line); ok { trimmedPayload := strings.TrimSpace(payload) + terminal.ObserveDataLine(trimmedPayload) if trimmedPayload != "[DONE]" { observer.ObserveOpenAI([]byte(payload), strings.TrimSpace(gjson.Get(payload, "type").String())) usageOnlyChunk := isOpenAIChatUsageOnlyStreamChunk(payload) @@ -350,14 +352,65 @@ func (s *OpenAIGatewayService) streamRawChatCompletions( } } - if err := scanner.Err(); err != nil { - if !errors.Is(err, context.Canceled) && !errors.Is(err, context.DeadlineExceeded) { - logger.L().Warn("openai chat_completions raw: stream read error", - zap.Error(err), - zap.String("request_id", requestID), - ) + resultWithUsage := func() *OpenAIForwardResult { + return &OpenAIForwardResult{ + RequestID: requestID, + Usage: usage, + Model: originalModel, + BillingModel: billingModel, + UpstreamModel: upstreamModel, + UpstreamResponseModel: observedUpstreamResponseModel(c), + UpstreamResponseModelConflict: observedUpstreamResponseModelConflict(c), + UpstreamResponseServiceTier: observedUpstreamResponseServiceTier(c), + ReasoningEffort: reasoningEffort, + ServiceTier: resolvedOpenAIUpstreamServiceTier(c, serviceTier), + Stream: true, + Duration: time.Since(startTime), + FirstTokenMs: firstTokenMs, } - } else if !clientDisconnected && !clientOutputStarted { + } + + scanErr := scanner.Err() + if scanErr != nil && !errors.Is(scanErr, context.Canceled) && !errors.Is(scanErr, context.DeadlineExceeded) { + logger.L().Warn("openai chat_completions raw: stream read error", + zap.Error(scanErr), + zap.String("request_id", requestID), + ) + } + + // 客户端取消/断开后上游读失败与上游截断不可区分(取消会连带取消上游请求), + // 沿用既有语义:按已收到的用量正常收尾计费,不判为上游故障。 + clientAborted := clientDisconnected || + errors.Is(scanErr, context.Canceled) || + errors.Is(scanErr, context.DeadlineExceeded) + + // 上游在任何终止信号之前结束:连接被 reset(scanErr != nil)或干净 EOF。 + // 两者都不能再记成功——此前统一返回 nil error,把上游截断伪装成 + // `HTTP 200 + usage 0/0`,客户端收到半截回答且 Ops 侧完全无感。 + if !clientAborted && terminal.IsTruncated(clientOutputStarted) { + cause := scanErr + if cause == nil { + cause = ErrOpenAIUpstreamStreamTruncated + } + logger.L().Warn("openai chat_completions raw: upstream stream truncated before terminal chunk", + zap.Error(cause), + zap.String("request_id", requestID), + zap.Int64("account_id", account.ID), + zap.String("upstream_model", upstreamModel), + zap.Bool("saw_sse_data", terminal.sawDataLine), + zap.Bool("client_output_started", clientOutputStarted), + ) + if !clientOutputStarted { + // 响应头尚未提交:可以透明换号重试,客户端不会看到半截流。 + return nil, newOpenAIRawStreamTruncatedFailoverError(c, account, requestID, cause) + } + // 已写出语义字节:无法再 failover,改为带类型的上游错误。handler 会据此 + // 补发 SSE error 帧并把本次请求计入 SLA 失败。 + recordOpenAIRawStreamTruncation(c, account, requestID, cause, "http_error") + return resultWithUsage(), newOpenAIUpstreamStreamReadError(cause) + } + + if scanErr == nil && !clientDisconnected && !clientOutputStarted { if refusalDetector.IsSilentRefusal() { return nil, newOpenAISilentRefusalFailoverError(c, account, requestID) } @@ -380,21 +433,7 @@ func (s *OpenAIGatewayService) streamRawChatCompletions( } } - return &OpenAIForwardResult{ - RequestID: requestID, - Usage: usage, - Model: originalModel, - BillingModel: billingModel, - UpstreamModel: upstreamModel, - UpstreamResponseModel: observedUpstreamResponseModel(c), - UpstreamResponseModelConflict: observedUpstreamResponseModelConflict(c), - UpstreamResponseServiceTier: observedUpstreamResponseServiceTier(c), - ReasoningEffort: reasoningEffort, - ServiceTier: resolvedOpenAIUpstreamServiceTier(c, serviceTier), - Stream: true, - Duration: time.Since(startTime), - FirstTokenMs: firstTokenMs, - }, nil + return resultWithUsage(), nil } // ensureOpenAIChatStreamUsage 确保 raw Chat Completions 流式请求会让上游返回 usage。 diff --git a/backend/internal/service/openai_gateway_chat_completions_raw_test.go b/backend/internal/service/openai_gateway_chat_completions_raw_test.go index 8a83bbc7ea..2f0b8dcc08 100644 --- a/backend/internal/service/openai_gateway_chat_completions_raw_test.go +++ b/backend/internal/service/openai_gateway_chat_completions_raw_test.go @@ -687,6 +687,326 @@ func TestForwardAsRawChatCompletions_StripsEmptyToolCallIdentity(t *testing.T) { require.True(t, followUpSeen) } +// 上游在生成中途干净 EOF(无 [DONE]/usage/finish_reason)且已向客户端写出内容: +// 不能再记成 HTTP 200 成功,必须回带类型化的上游截断错误,由 handler 补 SSE error +// 帧并计入 SLA 失败。 +func TestForwardAsRawChatCompletions_TruncatedStreamAfterOutputFailsRequest(t *testing.T) { + gin.SetMode(gin.TestMode) + + body := []byte(`{"model":"deepseek-v4-pro","messages":[{"role":"user","content":"hello"}],"stream":true}`) + rec := httptest.NewRecorder() + c, _ := gin.CreateTestContext(rec) + c.Request = httptest.NewRequest(http.MethodPost, "/v1/chat/completions", bytes.NewReader(body)) + c.Request.Header.Set("Content-Type", "application/json") + + upstreamBody := strings.Join([]string{ + `data: {"id":"chatcmpl_cut","object":"chat.completion.chunk","model":"deepseek-v4-pro","choices":[{"index":0,"delta":{"content":"half an ans"},"finish_reason":null}]}`, + "", + }, "\n") + upstream := &httpUpstreamRecorder{resp: &http.Response{ + StatusCode: http.StatusOK, + Header: http.Header{"Content-Type": []string{"text/event-stream"}, "x-request-id": []string{"rid_truncated"}}, + Body: io.NopCloser(strings.NewReader(upstreamBody)), + }} + + svc := &OpenAIGatewayService{ + cfg: rawChatCompletionsTestConfig(), + httpUpstream: upstream, + } + + result, err := svc.forwardAsRawChatCompletions(context.Background(), c, rawChatCompletionsTestAccount(), body, "") + require.Error(t, err) + require.NotNil(t, result, "已收字节的用量仍需带回,供 ops 记录首 token 时延") + var failoverErr *UpstreamFailoverError + require.False(t, errors.As(err, &failoverErr), "已写出语义字节后不得再 failover") + + code, message, ok := OpenAIUpstreamStreamReadErrorDetails(err) + require.True(t, ok) + require.Equal(t, OpenAIUpstreamStreamTruncatedCode, code) + require.NotEmpty(t, message) + // 已写出的内容保持原样透传,客户端拿到的仍是它已经收到的那部分。 + require.Contains(t, rec.Body.String(), `"content":"half an ans"`) + require.NotContains(t, rec.Body.String(), "data: [DONE]") +} + +// 上游 200 但一个 SSE 字节都没发:响应头尚未提交,应换号重试而不是回 200 空流。 +func TestForwardAsRawChatCompletions_EmptyStreamBeforeOutputTriggersFailover(t *testing.T) { + gin.SetMode(gin.TestMode) + + body := []byte(`{"model":"deepseek-v4-pro","messages":[{"role":"user","content":"hello"}],"stream":true}`) + rec := httptest.NewRecorder() + c, _ := gin.CreateTestContext(rec) + c.Request = httptest.NewRequest(http.MethodPost, "/v1/chat/completions", bytes.NewReader(body)) + c.Request.Header.Set("Content-Type", "application/json") + + upstream := &httpUpstreamRecorder{resp: &http.Response{ + StatusCode: http.StatusOK, + Header: http.Header{"Content-Type": []string{"text/event-stream"}, "x-request-id": []string{"rid_empty"}}, + Body: io.NopCloser(strings.NewReader("")), + }} + + svc := &OpenAIGatewayService{ + cfg: rawChatCompletionsTestConfig(), + httpUpstream: upstream, + } + + result, err := svc.forwardAsRawChatCompletions(context.Background(), c, rawChatCompletionsTestAccount(), body, "") + require.Nil(t, result) + var failoverErr *UpstreamFailoverError + require.True(t, errors.As(err, &failoverErr)) + require.Equal(t, http.StatusBadGateway, failoverErr.StatusCode) + require.Equal(t, OpenAIUpstreamStreamTruncatedCode, + gjson.GetBytes(failoverErr.ResponseBody, "error.code").String()) + require.True(t, failoverErr.ShouldRetryNextAccount()) + require.False(t, c.Writer.Written(), "换号重试前不得提交 200 响应头") + require.Empty(t, rec.Body.String()) +} + +// 传输层错误(Cloudflare edge reset 等)在写出后同样不能记成功,且分类要区别于 +// 干净 EOF,便于 ops 分辨 reset 与静默截断。 +func TestForwardAsRawChatCompletions_StreamReadErrorAfterOutputFailsRequest(t *testing.T) { + gin.SetMode(gin.TestMode) + + body := []byte(`{"model":"deepseek-v4-pro","messages":[{"role":"user","content":"hello"}],"stream":true}`) + rec := httptest.NewRecorder() + c, _ := gin.CreateTestContext(rec) + c.Request = httptest.NewRequest(http.MethodPost, "/v1/chat/completions", bytes.NewReader(body)) + c.Request.Header.Set("Content-Type", "application/json") + + upstream := &httpUpstreamRecorder{resp: &http.Response{ + StatusCode: http.StatusOK, + Header: http.Header{"Content-Type": []string{"text/event-stream"}, "x-request-id": []string{"rid_reset"}}, + Body: &openAIChatStreamReadErrorCloser{ + payload: []byte(`data: {"id":"chatcmpl_reset","object":"chat.completion.chunk","model":"deepseek-v4-pro","choices":[{"index":0,"delta":{"content":"partial"}}]}` + "\n\n"), + err: errors.New("read tcp 172.18.0.4->172.65.90.23:443: read: connection reset by peer"), + }, + }} + + svc := &OpenAIGatewayService{ + cfg: rawChatCompletionsTestConfig(), + httpUpstream: upstream, + } + + result, err := svc.forwardAsRawChatCompletions(context.Background(), c, rawChatCompletionsTestAccount(), body, "") + require.Error(t, err) + require.NotNil(t, result) + + code, _, ok := OpenAIUpstreamStreamReadErrorDetails(err) + require.True(t, ok) + require.Equal(t, OpenAIUpstreamStreamReadErrorCode, code) + require.Contains(t, rec.Body.String(), `"content":"partial"`) +} + +// 边界:缺 [DONE] 但收到了 usage 帧 —— 生成已完整,只是尾巴丢失。必须继续按成功 +// 计费,否则会误伤那些跑完就直接 EOF 的兼容上游并白送 token。 +func TestForwardAsRawChatCompletions_MissingDoneWithUsageStillSucceeds(t *testing.T) { + gin.SetMode(gin.TestMode) + + body := []byte(`{"model":"deepseek-v4-pro","messages":[{"role":"user","content":"hello"}],"stream":true}`) + rec := httptest.NewRecorder() + c, _ := gin.CreateTestContext(rec) + c.Request = httptest.NewRequest(http.MethodPost, "/v1/chat/completions", bytes.NewReader(body)) + c.Request.Header.Set("Content-Type", "application/json") + + upstreamBody := strings.Join([]string{ + `data: {"id":"chatcmpl_nodone","object":"chat.completion.chunk","model":"deepseek-v4-pro","choices":[{"index":0,"delta":{"content":"ok"}}]}`, + "", + `data: {"id":"chatcmpl_nodone","object":"chat.completion.chunk","model":"deepseek-v4-pro","choices":[],"usage":{"prompt_tokens":11,"completion_tokens":6,"total_tokens":17}}`, + "", + }, "\n") + upstream := &httpUpstreamRecorder{resp: &http.Response{ + StatusCode: http.StatusOK, + Header: http.Header{"Content-Type": []string{"text/event-stream"}, "x-request-id": []string{"rid_nodone_usage"}}, + Body: io.NopCloser(strings.NewReader(upstreamBody)), + }} + + svc := &OpenAIGatewayService{ + cfg: rawChatCompletionsTestConfig(), + httpUpstream: upstream, + } + + result, err := svc.forwardAsRawChatCompletions(context.Background(), c, rawChatCompletionsTestAccount(), body, "") + require.NoError(t, err) + require.NotNil(t, result) + require.Equal(t, 11, result.Usage.InputTokens) + require.Equal(t, 6, result.Usage.OutputTokens) +} + +// 边界:缺 [DONE] 与 usage,但末帧带 finish_reason —— 生成正常结束,同样不判截断。 +func TestForwardAsRawChatCompletions_MissingDoneWithFinishReasonStillSucceeds(t *testing.T) { + gin.SetMode(gin.TestMode) + + body := []byte(`{"model":"deepseek-v4-pro","messages":[{"role":"user","content":"hello"}],"stream":true}`) + rec := httptest.NewRecorder() + c, _ := gin.CreateTestContext(rec) + c.Request = httptest.NewRequest(http.MethodPost, "/v1/chat/completions", bytes.NewReader(body)) + c.Request.Header.Set("Content-Type", "application/json") + + upstreamBody := strings.Join([]string{ + `data: {"id":"chatcmpl_finish","object":"chat.completion.chunk","model":"deepseek-v4-pro","choices":[{"index":0,"delta":{"content":"done"},"finish_reason":null}]}`, + "", + `data: {"id":"chatcmpl_finish","object":"chat.completion.chunk","model":"deepseek-v4-pro","choices":[{"index":0,"delta":{},"finish_reason":"stop"}]}`, + "", + }, "\n") + upstream := &httpUpstreamRecorder{resp: &http.Response{ + StatusCode: http.StatusOK, + Header: http.Header{"Content-Type": []string{"text/event-stream"}, "x-request-id": []string{"rid_nodone_finish"}}, + Body: io.NopCloser(strings.NewReader(upstreamBody)), + }} + + svc := &OpenAIGatewayService{ + cfg: rawChatCompletionsTestConfig(), + httpUpstream: upstream, + } + + result, err := svc.forwardAsRawChatCompletions(context.Background(), c, rawChatCompletionsTestAccount(), body, "") + require.NoError(t, err) + require.NotNil(t, result) + require.Contains(t, rec.Body.String(), `"finish_reason":"stop"`) +} + +// openAIRawStreamDisconnectedWriter 模拟客户端已断开:raw 直转路径经 +// WriteString 写出,故两个方法都必须失败(只覆盖 Write 会被内嵌 writer 绕过)。 +type openAIRawStreamDisconnectedWriter struct { + gin.ResponseWriter +} + +func (w *openAIRawStreamDisconnectedWriter) Write([]byte) (int, error) { + return 0, errors.New("write failed: client disconnected") +} + +func (w *openAIRawStreamDisconnectedWriter) WriteString(string) (int, error) { + return 0, errors.New("write failed: client disconnected") +} + +// 客户端已断开时上游随后截断:两者不可区分,沿用既有语义按已收用量正常收尾计费, +// 不得把客户端离场记成上游故障。 +func TestForwardAsRawChatCompletions_ClientDisconnectTruncationStillBills(t *testing.T) { + gin.SetMode(gin.TestMode) + + body := []byte(`{"model":"deepseek-v4-pro","messages":[{"role":"user","content":"hello"}],"stream":true}`) + rec := httptest.NewRecorder() + c, _ := gin.CreateTestContext(rec) + c.Writer = &openAIRawStreamDisconnectedWriter{ResponseWriter: c.Writer} + c.Request = httptest.NewRequest(http.MethodPost, "/v1/chat/completions", bytes.NewReader(body)) + c.Request.Header.Set("Content-Type", "application/json") + + upstreamBody := strings.Join([]string{ + `data: {"id":"chatcmpl_gone","object":"chat.completion.chunk","model":"deepseek-v4-pro","choices":[{"index":0,"delta":{"content":"ok"}}]}`, + "", + }, "\n") + upstream := &httpUpstreamRecorder{resp: &http.Response{ + StatusCode: http.StatusOK, + Header: http.Header{"Content-Type": []string{"text/event-stream"}, "x-request-id": []string{"rid_gone"}}, + Body: io.NopCloser(strings.NewReader(upstreamBody)), + }} + + svc := &OpenAIGatewayService{ + cfg: rawChatCompletionsTestConfig(), + httpUpstream: upstream, + } + + result, err := svc.forwardAsRawChatCompletions(context.Background(), c, rawChatCompletionsTestAccount(), body, "") + require.NoError(t, err) + require.NotNil(t, result) +} + +// 客户端取消会连带取消上游请求,上游读因此报 context.Canceled:同样不判为上游截断。 +func TestForwardAsRawChatCompletions_ClientCancelTruncationStillBills(t *testing.T) { + gin.SetMode(gin.TestMode) + + body := []byte(`{"model":"deepseek-v4-pro","messages":[{"role":"user","content":"hello"}],"stream":true}`) + rec := httptest.NewRecorder() + c, _ := gin.CreateTestContext(rec) + c.Request = httptest.NewRequest(http.MethodPost, "/v1/chat/completions", bytes.NewReader(body)) + c.Request.Header.Set("Content-Type", "application/json") + + upstream := &httpUpstreamRecorder{resp: &http.Response{ + StatusCode: http.StatusOK, + Header: http.Header{"Content-Type": []string{"text/event-stream"}, "x-request-id": []string{"rid_cancel"}}, + Body: &openAIChatStreamReadErrorCloser{ + payload: []byte(`data: {"id":"chatcmpl_cancel","object":"chat.completion.chunk","model":"deepseek-v4-pro","choices":[{"index":0,"delta":{"content":"ok"}}]}` + "\n\n"), + err: context.Canceled, + }, + }} + + svc := &OpenAIGatewayService{ + cfg: rawChatCompletionsTestConfig(), + httpUpstream: upstream, + } + + result, err := svc.forwardAsRawChatCompletions(context.Background(), c, rawChatCompletionsTestAccount(), body, "") + require.NoError(t, err) + require.NotNil(t, result) +} + +func TestOpenAIRawStreamTerminalState(t *testing.T) { + t.Parallel() + + tests := []struct { + name string + payloads []string + clientStarted bool + wantTerminated bool + wantTruncated bool + }{ + { + name: "done sentinel", + payloads: []string{`{"choices":[{"delta":{"content":"a"}}]}`, "[DONE]"}, + clientStarted: true, + wantTerminated: true, + }, + { + name: "usage chunk", + payloads: []string{`{"choices":[],"usage":{"prompt_tokens":1,"completion_tokens":1}}`}, + clientStarted: true, + wantTerminated: true, + }, + { + name: "finish reason", + payloads: []string{`{"choices":[{"delta":{},"finish_reason":"length"}]}`}, + clientStarted: true, + wantTerminated: true, + }, + { + name: "null finish reason is not terminal", + payloads: []string{`{"choices":[{"delta":{"content":"a"},"finish_reason":null}]}`}, + clientStarted: true, + wantTruncated: true, + }, + { + name: "usage null is not terminal", + payloads: []string{`{"choices":[{"delta":{"content":"a"}}],"usage":null}`}, + clientStarted: true, + wantTruncated: true, + }, + { + // 上游对 stream 请求回了裸 JSON:无 data: 行,既有行为是原样透传。 + name: "non-sse body already forwarded", + payloads: nil, + clientStarted: true, + }, + { + name: "no bytes at all", + payloads: nil, + clientStarted: false, + wantTruncated: true, + }, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + t.Parallel() + var state openAIRawStreamTerminalState + for _, payload := range tt.payloads { + state.ObserveDataLine(payload) + } + require.Equal(t, tt.wantTerminated, state.Terminated()) + require.Equal(t, tt.wantTruncated, state.IsTruncated(tt.clientStarted)) + }) + } +} + func TestForwardAsRawChatCompletions_ClientDisconnectDrainsUsage(t *testing.T) { gin.SetMode(gin.TestMode) diff --git a/backend/internal/service/openai_raw_stream_truncation.go b/backend/internal/service/openai_raw_stream_truncation.go new file mode 100644 index 0000000000..678d5125b7 --- /dev/null +++ b/backend/internal/service/openai_raw_stream_truncation.go @@ -0,0 +1,161 @@ +package service + +import ( + "encoding/json" + "errors" + "net/http" + "strings" + + "github.com/gin-gonic/gin" + "github.com/tidwall/gjson" +) + +// openAIRawStreamTruncatedUpstreamMessage 是 raw CC 直转路径上游截断的 ops 消息。 +const openAIRawStreamTruncatedUpstreamMessage = "Upstream Chat Completions stream ended before any terminal chunk" + +// openAIRawStreamTerminalState 记录 raw Chat Completions SSE 流是否收到过 +// **终止信号**。 +// +// 背景:CC 直转路径把上游 SSE 原样透传,此前只要 HTTP 状态是 200 就按成功收尾—— +// 上游中途断流(Cloudflare edge reset、后端 worker 掉线)会被伪装成 +// `HTTP 200 + usage 0/0`:客户端拿到半截回答,网关既不报错也不计入 SLA, +// Ops 侧完全不可见。 +// +// 三种终止信号任一出现即认为上游"讲完了",只是尾巴可能丢失,不作截断处理: +// +// - [DONE] —— OpenAI CC 协议标准哨兵 +// - usage chunk —— include_usage 生效时的末尾用量帧(网关强制打开) +// - finish_reason —— 生成正常结束(stop/length/tool_calls/...) +// +// 只认 [DONE] 会误伤那些跑完最后一帧就直接 EOF 的兼容上游;只认 usage 会误伤 +// 不支持 include_usage 的上游。三者取并集,把误判压到"上游确实在生成中途被切断"。 +type openAIRawStreamTerminalState struct { + // sawDataLine 表示上游至少发过一行 `data:`,即响应确实是 SSE 语义流。 + // 非 SSE 响应体(上游对 stream 请求返回裸 JSON)不参与截断判定,保持既有透传行为。 + sawDataLine bool + sawDone bool + sawUsage bool + sawFinishReason bool +} + +// ObserveDataLine 从单行 SSE `data:` 载荷中提取终止信号。payload 需已 TrimSpace。 +func (t *openAIRawStreamTerminalState) ObserveDataLine(payload string) { + if t == nil { + return + } + t.sawDataLine = true + if payload == "[DONE]" { + t.sawDone = true + return + } + if usage := gjson.Get(payload, "usage"); usage.Exists() && usage.IsObject() { + t.sawUsage = true + } + if t.sawFinishReason { + return + } + for _, choice := range gjson.Get(payload, "choices").Array() { + // finish_reason 为 null 时 String() 返回空串,不算终止。 + if strings.TrimSpace(choice.Get("finish_reason").String()) != "" { + t.sawFinishReason = true + return + } + } +} + +// Terminated 表示上游给出过终止信号。 +func (t *openAIRawStreamTerminalState) Terminated() bool { + return t != nil && (t.sawDone || t.sawUsage || t.sawFinishReason) +} + +// IsTruncated 判定上游是否在任何终止信号之前结束。clientOutputStarted 用于放行 +// 非 SSE 响应体:那类响应本就没有 data: 行,既有行为是原样透传,不在本次判定范围内; +// 但"一个字节都没收到"的空 200 依然算截断。 +func (t *openAIRawStreamTerminalState) IsTruncated(clientOutputStarted bool) bool { + if t == nil || t.Terminated() { + return false + } + return t.sawDataLine || !clientOutputStarted +} + +// newOpenAIRawStreamTruncatedFailoverError 处理"上游截断且尚未向客户端写出任何 +// 字节"的情况:响应头还没提交,可以透明换号重试,客户端不会看到半截流。 +func newOpenAIRawStreamTruncatedFailoverError( + c *gin.Context, + account *Account, + upstreamRequestID string, + cause error, +) *UpstreamFailoverError { + recordOpenAIRawStreamTruncation(c, account, upstreamRequestID, cause, "failover") + + headers := http.Header{} + if id := strings.TrimSpace(upstreamRequestID); id != "" { + headers.Set("x-request-id", id) + } + return &UpstreamFailoverError{ + StatusCode: http.StatusBadGateway, + ResponseBody: openAIRawStreamTruncatedErrorBody(cause), + ResponseHeaders: headers, + } +} + +// recordOpenAIRawStreamTruncation 把上游截断记入 ops 上下文,使其在错误日志与 +// 账号健康度中可见——这正是此前"HTTP 200 假成功"丢掉的信息。 +func recordOpenAIRawStreamTruncation( + c *gin.Context, + account *Account, + upstreamRequestID string, + cause error, + kind string, +) { + if c == nil { + return + } + message := openAIRawStreamTruncatedMessage(cause) + platform := PlatformOpenAI + accountID := int64(0) + accountName := "" + if account != nil { + platform = account.Platform + accountID = account.ID + accountName = account.Name + } + + setOpsUpstreamError(c, http.StatusBadGateway, message, "") + appendOpsUpstreamError(c, OpsUpstreamErrorEvent{ + Platform: platform, + AccountID: accountID, + AccountName: accountName, + UpstreamStatusCode: http.StatusBadGateway, + UpstreamRequestID: strings.TrimSpace(upstreamRequestID), + Kind: kind, + Message: message, + }) +} + +// openAIRawStreamTruncatedMessage 拼出 ops 消息:干净 EOF 没有底层错误可带, +// 传输层错误(connection reset / http2 stream error)则保留原因以便定位。 +func openAIRawStreamTruncatedMessage(cause error) string { + if cause == nil || errors.Is(cause, ErrOpenAIUpstreamStreamTruncated) { + return openAIRawStreamTruncatedUpstreamMessage + } + return openAIRawStreamTruncatedUpstreamMessage + ": " + cause.Error() +} + +// openAIRawStreamTruncatedErrorBody 构造 failover 错误体,code/message 与 +// 写出后走 openAIUpstreamStreamReadError 的客户端分类保持一致。 +func openAIRawStreamTruncatedErrorBody(cause error) []byte { + code, message := classifyOpenAIUpstreamStreamReadError(cause) + body, err := json.Marshal(map[string]any{ + "error": map[string]any{ + "type": "upstream_error", + "code": code, + "message": message, + }, + }) + if err != nil { + return []byte(`{"error":{"type":"upstream_error","code":"` + OpenAIUpstreamStreamTruncatedCode + + `","message":"Upstream response stream ended before completion"}}`) + } + return body +} diff --git a/backend/internal/service/openai_stream_read_error.go b/backend/internal/service/openai_stream_read_error.go index 9a008d8e05..9fda5708ee 100644 --- a/backend/internal/service/openai_stream_read_error.go +++ b/backend/internal/service/openai_stream_read_error.go @@ -12,8 +12,17 @@ const ( // when an upstream HTTP/2 response stream is reset after the request started. OpenAIUpstreamHTTP2StreamErrorCode = "upstream_http2_stream_error" OpenAIUpstreamStreamReadErrorCode = "upstream_stream_read_error" + // OpenAIUpstreamStreamTruncatedCode is returned when an upstream SSE stream + // closes *cleanly* before delivering any terminal signal. A clean EOF carries + // no transport error, so without this classification a truncated generation is + // indistinguishable from a successful one. + OpenAIUpstreamStreamTruncatedCode = "upstream_stream_truncated" ) +// ErrOpenAIUpstreamStreamTruncated marks an upstream SSE stream that ended at +// EOF — without a read error — before any terminal signal arrived. +var ErrOpenAIUpstreamStreamTruncated = errors.New("upstream stream ended before any terminal chunk") + type openAIUpstreamStreamReadError struct { cause error clientCode string @@ -61,6 +70,9 @@ func OpenAIUpstreamStreamReadErrorDetails(err error) (code, message string, ok b func classifyOpenAIUpstreamStreamReadError(err error) (code, message string) { if err != nil { + if errors.Is(err, ErrOpenAIUpstreamStreamTruncated) { + return OpenAIUpstreamStreamTruncatedCode, "Upstream response stream ended before completion" + } lower := strings.ToLower(err.Error()) // net/http's HTTP/2 stream error is unexported. Its stable text contains // "stream error: stream ID ..."; match only the transport signature and From e55727d4c882a1545ba4db10581e41fafea56d07 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E8=B6=85=E7=BA=A7=E8=8B=B1=E9=9B=84=E5=90=89=E5=A7=86?= <303600370@qq.com> Date: Tue, 25 Aug 2026 10:27:48 +0800 Subject: [PATCH 166/204] fix(openai): preserve sticky binding on capacity spillover --- .../service/openai_gateway_scheduling.go | 10 ++++- .../service/openai_gateway_service_test.go | 43 +++++++++++++++++++ 2 files changed, 51 insertions(+), 2 deletions(-) diff --git a/backend/internal/service/openai_gateway_scheduling.go b/backend/internal/service/openai_gateway_scheduling.go index 2a4a4f3d09..a37b3935f7 100644 --- a/backend/internal/service/openai_gateway_scheduling.go +++ b/backend/internal/service/openai_gateway_scheduling.go @@ -1173,6 +1173,11 @@ func (s *OpenAIGatewayService) selectAccountWithLoadAwareness(ctx context.Contex } // ============ Layer 1: Sticky session ============ + // A healthy sticky account whose bounded wait queue is full may be used as a + // one-request capacity spillover in Layer 2. Keep that spillover temporary: + // rewriting the durable binding here would make a short burst migrate the + // whole conversation to a cache-cold account. + stickySpillover := false if sessionHash != "" { accountID := stickyAccountID if accountID > 0 && !isExcluded(accountID) { @@ -1214,6 +1219,7 @@ func (s *OpenAIGatewayService) selectAccountWithLoadAwareness(ctx context.Contex MaxWaiting: cfg.StickySessionMaxWaiting, }) } + stickySpillover = true } } } @@ -1365,7 +1371,7 @@ func (s *OpenAIGatewayService) selectAccountWithLoadAwareness(ctx context.Contex if selectErr != nil { return nil, true, selectErr } - if sessionHash != "" && !gatewayProfitControlGateActive(ctx) { + if sessionHash != "" && !stickySpillover && !gatewayProfitControlGateActive(ctx) { _ = s.setStickySessionAccountID(ctx, groupID, sessionHash, fresh.ID, openaiStickySessionTTL) } return selection, true, nil @@ -1404,7 +1410,7 @@ func (s *OpenAIGatewayService) selectAccountWithLoadAwareness(ctx context.Contex if selectErr != nil { return nil, selectErr } - if sessionHash != "" && !gatewayProfitControlGateActive(ctx) { + if sessionHash != "" && !stickySpillover && !gatewayProfitControlGateActive(ctx) { _ = s.setStickySessionAccountID(ctx, groupID, sessionHash, fresh.ID, openaiStickySessionTTL) } return selection, nil diff --git a/backend/internal/service/openai_gateway_service_test.go b/backend/internal/service/openai_gateway_service_test.go index 1e41298cc1..ff97f26828 100644 --- a/backend/internal/service/openai_gateway_service_test.go +++ b/backend/internal/service/openai_gateway_service_test.go @@ -1181,6 +1181,49 @@ func TestOpenAISelectAccountWithLoadAwareness_StickyWaitPlan(t *testing.T) { } } +func TestOpenAISelectAccountWithLoadAwareness_StickyCapacitySpilloverKeepsBinding(t *testing.T) { + sessionHash := "sticky-spillover" + groupID := int64(1) + repo := stubOpenAIAccountRepo{ + accounts: []Account{ + {ID: 1, Platform: PlatformOpenAI, Status: StatusActive, Schedulable: true, Concurrency: 6, Priority: 1, GroupIDs: []int64{groupID}}, + {ID: 2, Platform: PlatformOpenAI, Status: StatusActive, Schedulable: true, Concurrency: 6, Priority: 1, GroupIDs: []int64{groupID}}, + }, + } + cache := &stubGatewayCache{ + sessionBindings: map[string]int64{"openai:" + sessionHash: 1}, + } + concurrencyCache := stubConcurrencyCache{ + acquireResults: map[int64]bool{1: false, 2: true}, + waitCounts: map[int64]int{1: 1}, + loadMap: map[int64]*AccountLoadInfo{ + 1: {AccountID: 1, LoadRate: 100}, + 2: {AccountID: 2, LoadRate: 10}, + }, + } + cfg := &config.Config{RunMode: config.RunModeStandard} + cfg.Gateway.Scheduling.LoadBatchEnabled = true + cfg.Gateway.Scheduling.StickySessionMaxWaiting = 1 + + svc := &OpenAIGatewayService{ + accountRepo: repo, + cache: cache, + cfg: cfg, + concurrencyService: NewConcurrencyService(concurrencyCache), + } + + selection, err := svc.SelectAccountWithLoadAwareness(context.Background(), &groupID, sessionHash, "gpt-4", nil) + require.NoError(t, err) + require.NotNil(t, selection) + require.NotNil(t, selection.Account) + require.Equal(t, int64(2), selection.Account.ID, "capacity spillover should use the other account for this request") + require.True(t, selection.Acquired) + require.Equal(t, int64(1), cache.sessionBindings["openai:"+sessionHash], "capacity spillover must not migrate the durable sticky binding") + if selection.ReleaseFunc != nil { + selection.ReleaseFunc() + } +} + func TestOpenAISelectAccountWithLoadAwareness_PrefersLowerLoad(t *testing.T) { groupID := int64(1) repo := stubOpenAIAccountRepo{ From 4ca86c52e3edbcc5d38247842f045f6975329263 Mon Sep 17 00:00:00 2001 From: jyking Date: Tue, 25 Aug 2026 10:40:02 +0800 Subject: [PATCH 167/204] =?UTF-8?q?fix(auth):=20=E9=82=AE=E7=AE=B1?= =?UTF-8?q?=E6=8D=A2=E7=BB=91=E5=A2=9E=E5=8A=A0=E5=88=AB=E5=90=8D=E4=B8=8E?= =?UTF-8?q?=E5=B9=B6=E5=8F=91=E5=AE=88=E5=8D=AB?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- backend/internal/repository/user_repo.go | 83 +++++++++- .../internal/service/auth_email_binding.go | 79 +++++++--- .../service/auth_service_email_bind_test.go | 142 +++++++++++++++++- 3 files changed, 274 insertions(+), 30 deletions(-) diff --git a/backend/internal/repository/user_repo.go b/backend/internal/repository/user_repo.go index c072f09b27..3d02d6fbff 100644 --- a/backend/internal/repository/user_repo.go +++ b/backend/internal/repository/user_repo.go @@ -1145,12 +1145,17 @@ func (r *userRepository) ExistsByEmailAlias(ctx context.Context, email string) ( } func existsByEmailAliasWithClient(ctx context.Context, client *dbent.Client, email string) (bool, error) { + _, exists, err := emailAliasOwnerIDWithClient(ctx, client, email, 0) + return exists, err +} + +func emailAliasOwnerIDWithClient(ctx context.Context, client *dbent.Client, email string, currentUserID int64) (int64, bool, error) { if client == nil { - return false, nil + return 0, false, nil } probes := service.EmailAliasDedupProbes(email) if len(probes) == 0 { - return false, nil + return 0, false, nil } preds := make([]predicate.User, 0, 2*len(probes)) @@ -1164,20 +1169,82 @@ func existsByEmailAliasWithClient(ctx context.Context, client *dbent.Client, ema candidates, err := client.User.Query(). Where(dbuser.Or(preds...)). Limit(emailAliasCandidateLimit). - Select(dbuser.FieldEmail). - Strings(ctx) + Select(dbuser.FieldID, dbuser.FieldEmail). + All(ctx) if err != nil { - return false, err + return 0, false, err } // 探针会有过度匹配(点号只在 Gmail 家族无意义),最终判定必须回到完整归一化规则。 + // 返回“其他用户”优先于当前用户,避免历史重复数据让调用方误判为仅当前用户占用。 identity := service.NormalizeEmailForAliasDedup(email) + var selfID int64 + selfExists := false for _, candidate := range candidates { - if service.NormalizeEmailForAliasDedup(candidate) == identity { - return true, nil + if service.NormalizeEmailForAliasDedup(candidate.Email) != identity { + continue + } + if candidate.ID != 0 && candidate.ID != currentUserID { + return candidate.ID, true, nil + } + if candidate.ID == currentUserID { + selfID = candidate.ID + selfExists = true } } - return false, nil + return selfID, selfExists, nil +} + +// UpdateEmailWithAliasGuard 在调用方事务内更新主邮箱与密码哈希。 +// +// 邮箱换绑不能只依赖服务层前置查重:两个并发请求可能同时看到同一收件箱未被占用。 +// 这里先按“字面邮箱 + 收件箱身份”加锁,复查是否已被其他用户占用,再执行写入; +// PostgreSQL 使用事务级 advisory lock 跨实例互斥,测试内存库则由进程内锁兜底。 +func (r *userRepository) UpdateEmailWithAliasGuard( + ctx context.Context, + userID int64, + email string, + passwordHash string, +) error { + if userID <= 0 { + return service.ErrUserNotFound + } + if strings.TrimSpace(email) == "" || passwordHash == "" { + return fmt.Errorf("email identity update requires email and password hash") + } + tx := dbent.TxFromContext(ctx) + if tx == nil { + return fmt.Errorf("email identity update requires a transaction") + } + client := tx.Client() + + releaseEmailLock, err := lockRepositoryScopedKeys( + ctx, + client, + txAwareSQLExecutor(ctx, r.sql, r.client), + normalizedEmailUniquenessLockKey(email), + emailAliasUniquenessLockKey(email), + ) + if err != nil { + return err + } + defer releaseEmailLock() + + ownerID, exists, err := emailAliasOwnerIDWithClient(ctx, client, email, userID) + if err != nil { + return err + } + if exists && ownerID != userID { + return service.ErrEmailExists + } + + if _, err := client.User.UpdateOneID(userID). + SetEmail(email). + SetPasswordHash(passwordHash). + Save(ctx); err != nil { + return translatePersistenceError(err, service.ErrUserNotFound, service.ErrEmailExists) + } + return nil } // dotStrippedEmailExpr 渲染下面的表达式:去掉存量邮箱的大小写、首尾空白(与 diff --git a/backend/internal/service/auth_email_binding.go b/backend/internal/service/auth_email_binding.go index 4fe3c4e85b..733e76b7fd 100644 --- a/backend/internal/service/auth_email_binding.go +++ b/backend/internal/service/auth_email_binding.go @@ -56,12 +56,8 @@ func (s *AuthService) BindEmailIdentity( return nil, ErrPasswordIncorrect } - existingUser, err := s.userRepo.GetByEmail(ctx, normalizedEmail) - switch { - case err == nil && existingUser != nil && existingUser.ID != userID: - return nil, ErrEmailExists - case err != nil && !errors.Is(err, ErrUserNotFound): - return nil, ErrServiceUnavailable + if err := s.ensureEmailIdentityAvailableForUser(ctx, currentUser, normalizedEmail); err != nil { + return nil, err } hashedPassword, err := s.HashPassword(password) @@ -115,19 +111,16 @@ func (s *AuthService) SendEmailIdentityBindCode(ctx context.Context, userID int6 if s.emailService == nil { return ErrServiceUnavailable } - if _, err := s.userRepo.GetByID(ctx, userID); err != nil { + currentUser, err := s.userRepo.GetByID(ctx, userID) + if err != nil { if errors.Is(err, ErrUserNotFound) { return ErrUserNotFound } return ErrServiceUnavailable } - existingUser, err := s.userRepo.GetByEmail(ctx, normalizedEmail) - switch { - case err == nil && existingUser != nil && existingUser.ID != userID: - return ErrEmailExists - case err != nil && !errors.Is(err, ErrUserNotFound): - return ErrServiceUnavailable + if err := s.ensureEmailIdentityAvailableForUser(ctx, currentUser, normalizedEmail); err != nil { + return err } siteName := "Sub2API" @@ -137,6 +130,45 @@ func (s *AuthService) SendEmailIdentityBindCode(ctx context.Context, userID int6 return s.emailService.SendVerifyCode(ctx, normalizedEmail, siteName, firstEmailLocale(locale)) } +// ensureEmailIdentityAvailableForUser 在发码 / 提交换绑前做快速查重。 +// 精确地址或 provider alias 若已指向其他用户的收件箱则直接拒绝; +// 当前用户自己的收件箱允许继续,便于其更换自身的 alias 变体。 +func (s *AuthService) ensureEmailIdentityAvailableForUser( + ctx context.Context, + currentUser *User, + email string, +) error { + if currentUser == nil { + return ErrUserNotFound + } + + existingUser, err := s.userRepo.GetByEmail(ctx, email) + switch { + case err == nil: + if existingUser == nil || existingUser.ID == currentUser.ID { + break + } + return ErrEmailExists + case errors.Is(err, ErrUserNotFound): + // Continue to alias lookup below. + default: + return ErrServiceUnavailable + } + + if NormalizeEmailForAliasDedup(currentUser.Email) == NormalizeEmailForAliasDedup(email) { + return nil + } + + aliasExists, err := s.userRepo.ExistsByEmailAlias(ctx, email) + if err != nil { + return ErrServiceUnavailable + } + if aliasExists { + return ErrEmailExists + } + return nil +} + func normalizeEmailForIdentityBinding(email string) (string, error) { normalized := strings.ToLower(strings.TrimSpace(email)) if normalized == "" || len(normalized) > 255 { @@ -153,6 +185,12 @@ func hasBindableEmailIdentitySubject(email string) bool { return normalized != "" && !isReservedEmail(normalized) } +// emailIdentityAliasGuardRepository 是主邮箱替换所需的事务内原子仓储能力, +// 用于关闭服务层前置查重与实际写入之间的并发窗口。 +type emailIdentityAliasGuardRepository interface { + UpdateEmailWithAliasGuard(ctx context.Context, userID int64, email string, passwordHash string) error +} + func (s *AuthService) updateBoundEmailIdentityTx( ctx context.Context, currentUser *User, @@ -192,16 +230,15 @@ func (s *AuthService) updateBoundEmailIdentityWithClient( return ErrServiceUnavailable } - oldEmail := currentUser.Email - if _, err := client.User.UpdateOneID(currentUser.ID). - SetEmail(email). - SetPasswordHash(hashedPassword). - Save(ctx); err != nil { - if dbent.IsConstraintError(err) { - return ErrEmailExists - } + guard, ok := s.userRepo.(emailIdentityAliasGuardRepository) + if !ok { return ErrServiceUnavailable } + if err := guard.UpdateEmailWithAliasGuard(ctx, currentUser.ID, email, hashedPassword); err != nil { + return err + } + + oldEmail := currentUser.Email if err := replaceBoundEmailAuthIdentityWithClient(ctx, client, currentUser.ID, oldEmail, email, "auth_service_email_bind"); err != nil { if errors.Is(err, ErrEmailExists) { diff --git a/backend/internal/service/auth_service_email_bind_test.go b/backend/internal/service/auth_service_email_bind_test.go index 2d78862ef3..9bdca02f2d 100644 --- a/backend/internal/service/auth_service_email_bind_test.go +++ b/backend/internal/service/auth_service_email_bind_test.go @@ -6,6 +6,7 @@ import ( "context" "database/sql" "errors" + "fmt" "sync" "testing" "time" @@ -13,6 +14,7 @@ import ( dbent "github.com/Wei-Shaw/sub2api/ent" "github.com/Wei-Shaw/sub2api/ent/authidentity" "github.com/Wei-Shaw/sub2api/ent/enttest" + dbuser "github.com/Wei-Shaw/sub2api/ent/user" "github.com/Wei-Shaw/sub2api/internal/config" "github.com/Wei-Shaw/sub2api/internal/pkg/pagination" "github.com/Wei-Shaw/sub2api/internal/repository" @@ -69,7 +71,8 @@ func newAuthServiceForEmailBindWithRefreshCache( ) (*service.AuthService, service.UserRepository, *dbent.Client) { t.Helper() - db, err := sql.Open("sqlite", "file:auth_service_email_bind?mode=memory&cache=shared") + dbName := fmt.Sprintf("file:auth_service_email_bind_%d?mode=memory&cache=shared", time.Now().UnixNano()) + db, err := sql.Open("sqlite", dbName) require.NoError(t, err) t.Cleanup(func() { _ = db.Close() }) @@ -214,6 +217,143 @@ func TestAuthServiceBindEmailIdentity_RejectsExistingEmailOnAnotherUser(t *testi require.Equal(t, 0, countProviderGrantRecords(t, client, sourceUser.ID, "email", "first_bind")) } +func TestAuthServiceBindEmailIdentity_RejectsAliasOfExistingEmailOnAnotherUser(t *testing.T) { + cache := &emailBindCacheStub{ + data: &service.VerificationCodeData{ + Code: "123456", + CreatedAt: time.Now().UTC().Add(-10 * time.Minute), + ExpiresAt: time.Now().UTC().Add(10 * time.Minute), + }, + } + svc, _, client := newAuthServiceForEmailBind(t, nil, cache, nil) + + ctx := context.Background() + sourceUser := createEmailBindTestUser( + t, + client, + "source-user"+service.OIDCConnectSyntheticEmailDomain, + "source-user", + "old-hash", + ) + createEmailBindTestUser(t, client, "zck.ioio123@gmail.com", "inbox-owner", "hash") + + err := svc.SendEmailIdentityBindCode(ctx, sourceUser.ID, "zckioio123+new@gmail.com") + require.ErrorIs(t, err, service.ErrEmailExists) + require.Empty(t, cache.setEmails) + + updatedUser, err := svc.BindEmailIdentity( + ctx, + sourceUser.ID, + "zckioio123+new@gmail.com", + "123456", + "new-password", + ) + require.ErrorIs(t, err, service.ErrEmailExists) + require.Nil(t, updatedUser) + + storedUser, err := client.User.Get(ctx, sourceUser.ID) + require.NoError(t, err) + require.Equal(t, "source-user"+service.OIDCConnectSyntheticEmailDomain, storedUser.Email) + require.Equal(t, "old-hash", storedUser.PasswordHash) +} + +func TestAuthServiceBindEmailIdentity_AllowsOnlyOneConcurrentAliasVariant(t *testing.T) { + cache := &emailBindCacheStub{ + data: &service.VerificationCodeData{ + Code: "123456", + CreatedAt: time.Now().UTC(), + ExpiresAt: time.Now().UTC().Add(10 * time.Minute), + }, + } + svc, _, client := newAuthServiceForEmailBind(t, nil, cache, nil) + + ctx := context.Background() + unique := fmt.Sprintf("%d", time.Now().UnixNano()) + first := createEmailBindTestUser( + t, + client, + "first-"+unique+service.OIDCConnectSyntheticEmailDomain, + "first-"+unique, + "old-hash", + ) + second := createEmailBindTestUser( + t, + client, + "second-"+unique+service.OIDCConnectSyntheticEmailDomain, + "second-"+unique, + "old-hash", + ) + + start := make(chan struct{}) + results := make(chan error, 2) + go func() { + <-start + _, err := svc.BindEmailIdentity(ctx, first.ID, "inbox-"+unique+"+one@gmail.com", "123456", "new-password") + results <- err + }() + go func() { + <-start + _, err := svc.BindEmailIdentity(ctx, second.ID, "inbox-"+unique+"+two@gmail.com", "123456", "new-password") + results <- err + }() + close(start) + + var successes, conflicts int + for range 2 { + err := <-results + switch { + case err == nil: + successes++ + case errors.Is(err, service.ErrEmailExists): + conflicts++ + default: + t.Fatalf("unexpected bind error: %v", err) + } + } + require.Equal(t, 1, successes) + require.Equal(t, 1, conflicts) + + boundCount, err := client.User.Query(). + Where(dbuser.EmailIn( + "inbox-"+unique+"+one@gmail.com", + "inbox-"+unique+"+two@gmail.com", + )). + Count(ctx) + require.NoError(t, err) + require.Equal(t, 1, boundCount) +} + +func TestAuthServiceBindEmailIdentity_RejectsNewAliasWhenAnotherUserSharesCurrentUserInbox(t *testing.T) { + cache := &emailBindCacheStub{ + data: &service.VerificationCodeData{ + Code: "123456", + CreatedAt: time.Now().UTC(), + ExpiresAt: time.Now().UTC().Add(10 * time.Minute), + }, + } + svc, _, client := newAuthServiceForEmailBind(t, nil, cache, nil) + + ctx := context.Background() + hashedPassword, err := svc.HashPassword("current-password") + require.NoError(t, err) + currentUser := createEmailBindTestUser(t, client, "inbox+own@gmail.com", "current", hashedPassword) + createEmailBindTestUser(t, client, "inbox+legacy@gmail.com", "legacy", "hash") + + updatedUser, err := svc.BindEmailIdentity( + ctx, + currentUser.ID, + "inbox+new@gmail.com", + "123456", + "current-password", + ) + require.ErrorIs(t, err, service.ErrEmailExists) + require.Nil(t, updatedUser) + + storedUser, err := client.User.Get(ctx, currentUser.ID) + require.NoError(t, err) + require.Equal(t, "inbox+own@gmail.com", storedUser.Email) +} + func TestAuthServiceBindEmailIdentity_RollsBackWhenFirstBindDefaultsFail(t *testing.T) { assigner := &flakyEmailBindDefaultSubAssignerStub{err: errors.New("temporary assign failure")} cache := &emailBindCacheStub{ From 095b525360fc597e8af55e0ddd61bca76f474ddf Mon Sep 17 00:00:00 2001 From: shaw Date: Tue, 25 Aug 2026 12:14:52 +0800 Subject: [PATCH 168/204] fix(openai): pin Responses Lite parallel tool calls --- .../service/openai_codex_tool_names_test.go | 2 +- .../openai_compact_body_signal_test.go | 2 +- .../openai_gateway_apikey_item_id_test.go | 4 +- .../service/openai_gateway_forward.go | 2 +- .../service/openai_gateway_passthrough.go | 3 +- .../service/openai_gateway_request_body.go | 22 +-- ...nai_gateway_request_body_reasoning_test.go | 23 +-- .../openai_passthrough_normalization_test.go | 14 +- .../service/openai_responses_lite_tools.go | 24 --- .../openai_responses_lite_tools_test.go | 139 +++++++++++------- .../openai_responses_tool_schema_test.go | 4 +- .../service/openai_ws_forwarder_ingress.go | 5 +- ...penai_ws_forwarder_ingress_session_test.go | 3 +- .../service/openai_ws_http_bridge_test.go | 2 +- .../openai_ws_v2_passthrough_adapter.go | 8 +- ...openai_ws_v2_passthrough_lifecycle_test.go | 36 ++++- 16 files changed, 166 insertions(+), 127 deletions(-) diff --git a/backend/internal/service/openai_codex_tool_names_test.go b/backend/internal/service/openai_codex_tool_names_test.go index d6cb9eafa1..73b7164deb 100644 --- a/backend/internal/service/openai_codex_tool_names_test.go +++ b/backend/internal/service/openai_codex_tool_names_test.go @@ -91,7 +91,7 @@ func TestApplyCodexOAuthTransform_ReservedPythonNameIsOAuthOnly(t *testing.T) { require.Equal(t, codexPythonToolAlias, tool["name"]) apiKeyBody := []byte(`{"type":"response.create","tools":[{"type":"function","name":"python"}]}`) - normalized, changed, err := normalizeOpenAIResponsesWebSocketCompatibilityBody(apiKeyBody, &Account{Platform: PlatformOpenAI, Type: AccountTypeAPIKey}) + normalized, changed, err := normalizeOpenAIResponsesWebSocketCompatibilityBody(apiKeyBody, &Account{Platform: PlatformOpenAI, Type: AccountTypeAPIKey}, false) require.NoError(t, err) require.False(t, changed) require.JSONEq(t, string(apiKeyBody), string(normalized)) diff --git a/backend/internal/service/openai_compact_body_signal_test.go b/backend/internal/service/openai_compact_body_signal_test.go index db8b6b404b..16587df0fd 100644 --- a/backend/internal/service/openai_compact_body_signal_test.go +++ b/backend/internal/service/openai_compact_body_signal_test.go @@ -96,7 +96,7 @@ func TestWebSocketCompatibilityNormalizesTriggerAfterPairedOutputCleanup(t *test body := []byte(`{"type":"response.create","model":"gpt-5.4","input":[{"type":"compaction_trigger"},{"type":"function_call","call_id":"call_1","name":"lookup","arguments":"{}"},{"type":"function_call_output","call_id":"call_1","output":"ok"},{"type":"message","role":"user","content":"visible"}]}`) account := &Account{Platform: PlatformOpenAI, Type: AccountTypeOAuth} - normalized, changed, err := normalizeOpenAIResponsesWebSocketCompatibilityBody(body, account) + normalized, changed, err := normalizeOpenAIResponsesWebSocketCompatibilityBody(body, account, false) require.NoError(t, err) require.True(t, changed) items := gjson.GetBytes(normalized, "input").Array() diff --git a/backend/internal/service/openai_gateway_apikey_item_id_test.go b/backend/internal/service/openai_gateway_apikey_item_id_test.go index e3a93bebb3..d5be3cec49 100644 --- a/backend/internal/service/openai_gateway_apikey_item_id_test.go +++ b/backend/internal/service/openai_gateway_apikey_item_id_test.go @@ -271,7 +271,7 @@ func TestNormalizeOpenAIResponsesWebSocketCompatibilityBodyPreservesOpaqueRefere normalized, changed, err := normalizeOpenAIResponsesWebSocketCompatibilityBody(body, &Account{ Platform: PlatformOpenAI, Type: accountType, - }) + }, false) require.NoError(t, err) require.True(t, changed) @@ -285,7 +285,7 @@ func TestNormalizeOpenAIResponsesWebSocketCompatibilityBodyPreservesOpaqueRefere second, changedAgain, err := normalizeOpenAIResponsesWebSocketCompatibilityBody(normalized, &Account{ Platform: PlatformOpenAI, Type: accountType, - }) + }, false) require.NoError(t, err) require.False(t, changedAgain) require.JSONEq(t, string(normalized), string(second)) diff --git a/backend/internal/service/openai_gateway_forward.go b/backend/internal/service/openai_gateway_forward.go index 38d747ca33..6487385000 100644 --- a/backend/internal/service/openai_gateway_forward.go +++ b/backend/internal/service/openai_gateway_forward.go @@ -152,7 +152,7 @@ func (s *OpenAIGatewayService) Forward(ctx context.Context, c *gin.Context, acco return s.forwardResponsesViaNativeAnthropic(ctx, c, account, body, reqModel) } if account.IsOpenAIApiKey() { - if normalized, changed, normalizeErr := normalizeOpenAIParallelToolCallsWithoutTools(body); normalizeErr != nil { + if normalized, changed, normalizeErr := normalizeOpenAIParallelToolCallsWithoutTools(body, responsesLite); normalizeErr != nil { return nil, normalizeErr } else if changed { body = normalized diff --git a/backend/internal/service/openai_gateway_passthrough.go b/backend/internal/service/openai_gateway_passthrough.go index d5d0c75408..b87ce9df87 100644 --- a/backend/internal/service/openai_gateway_passthrough.go +++ b/backend/internal/service/openai_gateway_passthrough.go @@ -212,7 +212,8 @@ func (s *OpenAIGatewayService) forwardOpenAIPassthrough( } } if account != nil && account.IsOpenAI() { - normalizedBody, normalized, normalizeErr := normalizeOpenAIResponsesWebSocketCompatibilityBody(body, account) + responsesLite := isOpenAIResponsesLiteHeader(c.GetHeader(responsesLiteHeader)) || isOpenAIResponsesLiteWebSocketPayload(body) + normalizedBody, normalized, normalizeErr := normalizeOpenAIResponsesWebSocketCompatibilityBody(body, account, responsesLite) if normalizeErr != nil { return nil, fmt.Errorf("normalize passthrough Responses compatibility: %w", normalizeErr) } diff --git a/backend/internal/service/openai_gateway_request_body.go b/backend/internal/service/openai_gateway_request_body.go index 8aa4364777..6272875cc5 100644 --- a/backend/internal/service/openai_gateway_request_body.go +++ b/backend/internal/service/openai_gateway_request_body.go @@ -349,7 +349,7 @@ func normalizeOpenAICompactRequestBody(body []byte) ([]byte, bool, error) { } normalized = next } - if next, removed, err := normalizeOpenAIParallelToolCallsWithoutTools(normalized); err != nil { + if next, removed, err := normalizeOpenAIParallelToolCallsWithoutTools(normalized, false); err != nil { return body, false, err } else if removed { normalized = next @@ -361,7 +361,10 @@ func normalizeOpenAICompactRequestBody(body []byte) ([]byte, bool, error) { return normalized, true, nil } -func normalizeOpenAIParallelToolCallsWithoutTools(body []byte) ([]byte, bool, error) { +func normalizeOpenAIParallelToolCallsWithoutTools(body []byte, responsesLite bool) ([]byte, bool, error) { + if responsesLite { + return body, false, nil + } parallel := gjson.GetBytes(body, "parallel_tool_calls") if !parallel.Exists() { return body, false, nil @@ -376,16 +379,7 @@ func normalizeOpenAIParallelToolCallsWithoutTools(body []byte) ([]byte, bool, er return normalized, true, nil } -// openAIRequestBodyHasTools is the []byte counterpart of openAIResponsesLiteHasTools: -// besides the top-level "tools" array it also recognizes the Responses Lite carrier. -// normalizeOpenAIResponsesLiteTools moves namespace tools into an input item of type -// "additional_tools" and drops the top-level "tools" key; the request still carries -// tools at that point. Looking only at the top level therefore misreads such a body as -// "no tools" and deletes the parallel_tool_calls:false that -// ensureOpenAIResponsesLiteParallelToolCalls had just pinned, and OpenAI falls back to -// its default of true and rejects the request with -// 400 unsupported_value: "X-OpenAI-Internal-Codex-Responses-Lite requires -// `parallel_tool_calls` to be false." +// openAIRequestBodyHasTools 同时识别顶层 tools 和 input[].additional_tools。 func openAIRequestBodyHasTools(body []byte) bool { if tools := gjson.GetBytes(body, "tools"); tools.IsArray() && len(tools.Array()) > 0 { return true @@ -948,7 +942,7 @@ func normalizeOpenAIResponseFormatSchemasBody(body []byte) ([]byte, bool, error) return normalized, true, nil } -func normalizeOpenAIResponsesWebSocketCompatibilityBody(body []byte, account *Account) ([]byte, bool, error) { +func normalizeOpenAIResponsesWebSocketCompatibilityBody(body []byte, account *Account, responsesLite bool) ([]byte, bool, error) { if account == nil || !account.IsOpenAI() { return body, false, nil } @@ -962,7 +956,7 @@ func normalizeOpenAIResponsesWebSocketCompatibilityBody(body []byte, account *Ac } } if account.IsOpenAIApiKey() { - if next, normalizedParallel, err := normalizeOpenAIParallelToolCallsWithoutTools(normalized); err != nil { + if next, normalizedParallel, err := normalizeOpenAIParallelToolCallsWithoutTools(normalized, responsesLite); err != nil { return body, false, err } else if normalizedParallel { normalized = next diff --git a/backend/internal/service/openai_gateway_request_body_reasoning_test.go b/backend/internal/service/openai_gateway_request_body_reasoning_test.go index 03397e751f..543d294880 100644 --- a/backend/internal/service/openai_gateway_request_body_reasoning_test.go +++ b/backend/internal/service/openai_gateway_request_body_reasoning_test.go @@ -259,34 +259,37 @@ func TestNormalizeOpenAIAPIKeyStoreFalseReasoningReplayRejectsEmptyEncryptedCont func TestNormalizeOpenAIParallelToolCallsWithoutTools(t *testing.T) { withTools := []byte(`{"tools":[{"type":"function","name":"lookup"}],"parallel_tool_calls":false}`) - normalized, changed, err := normalizeOpenAIParallelToolCallsWithoutTools(withTools) + normalized, changed, err := normalizeOpenAIParallelToolCallsWithoutTools(withTools, false) require.NoError(t, err) require.False(t, changed) require.Equal(t, string(withTools), string(normalized)) withoutTools := []byte(`{"input":"hi","parallel_tool_calls":true}`) - normalized, changed, err = normalizeOpenAIParallelToolCallsWithoutTools(withoutTools) + normalized, changed, err = normalizeOpenAIParallelToolCallsWithoutTools(withoutTools, false) require.NoError(t, err) require.True(t, changed) require.False(t, gjson.GetBytes(normalized, "parallel_tool_calls").Exists()) } -// A Responses Lite body that has already been through normalizeOpenAIResponsesLiteTools -// carries its tools in an input item of type "additional_tools" and no longer has a -// top-level "tools" key. It still has tools, so the parallel_tool_calls:false that -// ensureOpenAIResponsesLiteParallelToolCalls pinned must survive this normalization — -// otherwise OpenAI applies its default of true and rejects the request. +// Lite 工具迁移到 input[].additional_tools 后,仍应按有工具请求处理。 func TestNormalizeOpenAIParallelToolCallsWithoutTools_KeepsResponsesLiteAdditionalTools(t *testing.T) { liteBody := []byte(`{"input":[{"type":"message","role":"user","content":"hi"},{"type":"additional_tools","tools":[{"type":"function","name":"spawn_agent"}]}],"parallel_tool_calls":false}`) - normalized, changed, err := normalizeOpenAIParallelToolCallsWithoutTools(liteBody) + normalized, changed, err := normalizeOpenAIParallelToolCallsWithoutTools(liteBody, false) require.NoError(t, err) require.False(t, changed) require.Equal(t, gjson.False, gjson.GetBytes(normalized, "parallel_tool_calls").Type) - // An empty additional_tools item carries no tools, so the field is still dropped. + // 非 Lite 请求的空 additional_tools 不构成有效工具声明,字段仍需删除。 emptyLiteBody := []byte(`{"input":[{"type":"additional_tools","tools":[]}],"parallel_tool_calls":true}`) - normalized, changed, err = normalizeOpenAIParallelToolCallsWithoutTools(emptyLiteBody) + normalized, changed, err = normalizeOpenAIParallelToolCallsWithoutTools(emptyLiteBody, false) require.NoError(t, err) require.True(t, changed) require.False(t, gjson.GetBytes(normalized, "parallel_tool_calls").Exists()) + + // Lite 请求即使没有工具,也必须保留已经固定的 false。 + toolLessLiteBody := []byte(`{"input":"hi","parallel_tool_calls":false}`) + normalized, changed, err = normalizeOpenAIParallelToolCallsWithoutTools(toolLessLiteBody, true) + require.NoError(t, err) + require.False(t, changed) + require.Equal(t, gjson.False, gjson.GetBytes(normalized, "parallel_tool_calls").Type) } diff --git a/backend/internal/service/openai_passthrough_normalization_test.go b/backend/internal/service/openai_passthrough_normalization_test.go index ac5cb87c71..f86ecc6927 100644 --- a/backend/internal/service/openai_passthrough_normalization_test.go +++ b/backend/internal/service/openai_passthrough_normalization_test.go @@ -55,7 +55,7 @@ func TestNormalizeOpenAIOAuthResponsesCompatibilityBody_PreservesExplicitInput(t func TestNormalizeOpenAIResponsesWebSocketCompatibilityBody_OnlyStripsOAuthFields(t *testing.T) { body := []byte(`{"type":"response.create","prompt":"hello","commands":{},"truncation":"auto","stop_sequences":["END"],"chat_template_kwargs":{"enable_thinking":true}}`) - oauthBody, changed, err := normalizeOpenAIResponsesWebSocketCompatibilityBody(body, &Account{Platform: PlatformOpenAI, Type: AccountTypeOAuth}) + oauthBody, changed, err := normalizeOpenAIResponsesWebSocketCompatibilityBody(body, &Account{Platform: PlatformOpenAI, Type: AccountTypeOAuth}, false) require.NoError(t, err) require.True(t, changed) require.Equal(t, "hello", gjson.GetBytes(oauthBody, "input").String()) @@ -63,7 +63,7 @@ func TestNormalizeOpenAIResponsesWebSocketCompatibilityBody_OnlyStripsOAuthField require.False(t, gjson.GetBytes(oauthBody, field).Exists(), field) } - apiKeyBody, changed, err := normalizeOpenAIResponsesWebSocketCompatibilityBody(body, &Account{Platform: PlatformOpenAI, Type: AccountTypeAPIKey}) + apiKeyBody, changed, err := normalizeOpenAIResponsesWebSocketCompatibilityBody(body, &Account{Platform: PlatformOpenAI, Type: AccountTypeAPIKey}, false) require.NoError(t, err) require.False(t, changed) require.JSONEq(t, string(body), string(apiKeyBody)) @@ -81,7 +81,7 @@ func TestNormalizeOpenAIResponsesWebSocketCompatibilityBody_SanitizesNativeItemI if oauth { accountType = AccountTypeOAuth } - normalized, changed, err := normalizeOpenAIResponsesWebSocketCompatibilityBody(body, &Account{Platform: PlatformOpenAI, Type: accountType}) + normalized, changed, err := normalizeOpenAIResponsesWebSocketCompatibilityBody(body, &Account{Platform: PlatformOpenAI, Type: accountType}, false) require.NoError(t, err) require.True(t, changed) require.Equal(t, "response.create", gjson.GetBytes(normalized, "type").String()) @@ -105,7 +105,7 @@ func TestNormalizeOpenAIResponsesWebSocketCompatibilityBody_APIKeyStoreFalseRepl normalized, changed, err := normalizeOpenAIResponsesWebSocketCompatibilityBody(body, &Account{ Platform: PlatformOpenAI, Type: AccountTypeAPIKey, - }) + }, false) require.NoError(t, err) require.True(t, changed) @@ -141,13 +141,13 @@ func TestNormalizeOpenAIResponsesReasoningMode(t *testing.T) { func TestNormalizeOpenAIResponsesWebSocketCompatibilityBody_ReasoningModeAccountScope(t *testing.T) { body := []byte(`{"type":"response.create","reasoning":{"mode":"pro"}}`) for _, accountType := range []string{AccountTypeOAuth, AccountTypeSetupToken} { - normalized, changed, err := normalizeOpenAIResponsesWebSocketCompatibilityBody(body, &Account{Platform: PlatformOpenAI, Type: accountType}) + normalized, changed, err := normalizeOpenAIResponsesWebSocketCompatibilityBody(body, &Account{Platform: PlatformOpenAI, Type: accountType}, false) require.NoError(t, err) require.True(t, changed) require.Equal(t, "max", gjson.GetBytes(normalized, "reasoning.effort").String()) require.False(t, gjson.GetBytes(normalized, "reasoning.mode").Exists()) } - apiKeyBody, changed, err := normalizeOpenAIResponsesWebSocketCompatibilityBody(body, &Account{Platform: PlatformOpenAI, Type: AccountTypeAPIKey}) + apiKeyBody, changed, err := normalizeOpenAIResponsesWebSocketCompatibilityBody(body, &Account{Platform: PlatformOpenAI, Type: AccountTypeAPIKey}, false) require.NoError(t, err) require.False(t, changed) require.JSONEq(t, string(body), string(apiKeyBody)) @@ -156,7 +156,7 @@ func TestNormalizeOpenAIResponsesWebSocketCompatibilityBody_ReasoningModeAccount func TestNormalizeOpenAIResponsesWebSocketCompatibilityBody_SanitizesToolSchemas(t *testing.T) { body := []byte(`{"type":"response.create","tools":[{"type":"function","name":"search","parameters":{"type":null,"properties":{"q":{"type":"string","pattern":"^(?=.*foo).+$"}}}}]}`) for _, accountType := range []string{AccountTypeAPIKey, AccountTypeOAuth} { - normalized, changed, err := normalizeOpenAIResponsesWebSocketCompatibilityBody(body, &Account{Platform: PlatformOpenAI, Type: accountType}) + normalized, changed, err := normalizeOpenAIResponsesWebSocketCompatibilityBody(body, &Account{Platform: PlatformOpenAI, Type: accountType}, false) require.NoError(t, err) require.True(t, changed) require.Equal(t, "object", gjson.GetBytes(normalized, "tools.0.parameters.type").String()) diff --git a/backend/internal/service/openai_responses_lite_tools.go b/backend/internal/service/openai_responses_lite_tools.go index 752ed00561..7f6c7f58e5 100644 --- a/backend/internal/service/openai_responses_lite_tools.go +++ b/backend/internal/service/openai_responses_lite_tools.go @@ -106,13 +106,6 @@ func ensureOpenAIResponsesLiteParallelToolCalls(reqBody map[string]any, changed return false, newOpenAIResponsesLiteValidationError("parallel_tool_calls", "responses Lite requires parallel_tool_calls to be a boolean") } } - if !openAIResponsesLiteHasTools(reqBody) { - if exists { - delete(reqBody, "parallel_tool_calls") - return true, nil - } - return changed, nil - } if parallel == false { return changed, nil } @@ -120,23 +113,6 @@ func ensureOpenAIResponsesLiteParallelToolCalls(reqBody map[string]any, changed return true, nil } -func openAIResponsesLiteHasTools(reqBody map[string]any) bool { - if tools, ok := reqBody["tools"].([]any); ok && len(tools) > 0 { - return true - } - input, _ := reqBody["input"].([]any) - for _, rawItem := range input { - item, ok := rawItem.(map[string]any) - if !ok || strings.TrimSpace(firstNonEmptyString(item["type"])) != "additional_tools" { - continue - } - if tools, ok := item["tools"].([]any); ok && len(tools) > 0 { - return true - } - } - return false -} - func ensureOpenAIResponsesLiteReasoningContext(reqBody map[string]any) (bool, error) { rawReasoning, exists := reqBody["reasoning"] if !exists || rawReasoning == nil { diff --git a/backend/internal/service/openai_responses_lite_tools_test.go b/backend/internal/service/openai_responses_lite_tools_test.go index 3edff5c2da..4088882d24 100644 --- a/backend/internal/service/openai_responses_lite_tools_test.go +++ b/backend/internal/service/openai_responses_lite_tools_test.go @@ -201,25 +201,33 @@ func TestNormalizeOpenAIResponsesLiteTools_ForcesParallelToolCallsFalse(t *testi } } -func TestNormalizeOpenAIResponsesLiteTools_RemovesParallelToolCallsWithoutTools(t *testing.T) { - for _, value := range []bool{true, false} { - reqBody := map[string]any{ - "reasoning": map[string]any{"context": "all_turns"}, - "parallel_tool_calls": value, - } - - changed, err := normalizeOpenAIResponsesLiteTools(reqBody) - - require.NoError(t, err) - require.True(t, changed) - require.NotContains(t, reqBody, "parallel_tool_calls") +func TestNormalizeOpenAIResponsesLiteTools_PinsParallelToolCallsWithoutTools(t *testing.T) { + tests := []struct { + name string + parallel any + include bool + wantChanged bool + }{ + {name: "字段缺失", wantChanged: true}, + {name: "值为 true", parallel: true, include: true, wantChanged: true}, + {name: "值为 false", parallel: false, include: true, wantChanged: false}, } - reqBody := map[string]any{"reasoning": map[string]any{"context": "all_turns"}} - changed, err := normalizeOpenAIResponsesLiteTools(reqBody) - require.NoError(t, err) - require.False(t, changed) - require.NotContains(t, reqBody, "parallel_tool_calls") + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + reqBody := map[string]any{"reasoning": map[string]any{"context": "all_turns"}} + if tt.include { + reqBody["parallel_tool_calls"] = tt.parallel + } + + changed, err := normalizeOpenAIResponsesLiteTools(reqBody) + + require.NoError(t, err) + require.Equal(t, tt.wantChanged, changed) + require.Contains(t, reqBody, "parallel_tool_calls") + require.Equal(t, false, reqBody["parallel_tool_calls"]) + }) + } } func TestNormalizeOpenAIResponsesLiteTools_RejectsNonBooleanParallelToolCalls(t *testing.T) { @@ -490,49 +498,70 @@ func TestOpenAIGatewayServiceForward_NormalizesResponsesLiteToolsForOAuth(t *tes } } -func TestOpenAIGatewayServiceForward_RemovesParallelToolCallsForToollessResponsesLite(t *testing.T) { +func TestOpenAIGatewayServiceForward_PinsParallelToolCallsForToollessResponsesLite(t *testing.T) { gin.SetMode(gin.TestMode) - for _, passthrough := range []bool{false, true} { - name := "managed" - if passthrough { - name = "passthrough" - } - t.Run(name, func(t *testing.T) { - rec := httptest.NewRecorder() - c, _ := gin.CreateTestContext(rec) - c.Request = httptest.NewRequest(http.MethodPost, "/v1/responses", bytes.NewReader(nil)) - c.Request.Header.Set("User-Agent", "codex_cli_rs/0.144.1") - c.Request.Header.Set(responsesLiteHeader, "true") - upstream := &httpUpstreamRecorder{resp: &http.Response{ - StatusCode: http.StatusOK, - Header: http.Header{"Content-Type": []string{"text/event-stream"}}, - Body: io.NopCloser(strings.NewReader( - "data: {\"type\":\"response.completed\",\"response\":{\"id\":\"resp_lite\",\"usage\":{\"input_tokens\":1,\"output_tokens\":1}}}\n\n" + - "data: [DONE]\n\n", - )), - }} - svc := &OpenAIGatewayService{cfg: &config.Config{}, httpUpstream: upstream} - account := &Account{ - ID: 502, Name: "responses-lite-no-tools", Platform: PlatformOpenAI, Type: AccountTypeOAuth, - Concurrency: 1, Status: StatusActive, Schedulable: true, RateMultiplier: f64p(1), - Credentials: map[string]any{"access_token": "oauth-token", "chatgpt_account_id": "chatgpt-account"}, - Extra: map[string]any{"openai_passthrough": passthrough}, + accountCases := []struct { + name string + accountType string + credentials map[string]any + }{ + {name: "oauth", accountType: AccountTypeOAuth, credentials: map[string]any{"access_token": "oauth-token", "chatgpt_account_id": "chatgpt-account"}}, + {name: "apikey", accountType: AccountTypeAPIKey, credentials: map[string]any{"api_key": "sk-test"}}, + } + parallelCases := []struct { + name string + field string + }{ + {name: "字段缺失"}, + {name: "值为 true", field: `,"parallel_tool_calls":true`}, + {name: "值为 false", field: `,"parallel_tool_calls":false`}, + } + + for _, accountCase := range accountCases { + for _, passthrough := range []bool{false, true} { + mode := "managed" + if passthrough { + mode = "passthrough" } - body := []byte(`{ - "model":"gpt-5.6-terra","stream":true,"instructions":"test", - "reasoning":{"effort":"high","context":"current_turn"}, - "parallel_tool_calls":true, - "input":[{"type":"message","role":"user","content":"hello"}] - }`) + for _, parallelCase := range parallelCases { + name := accountCase.name + "/" + mode + "/" + parallelCase.name + t.Run(name, func(t *testing.T) { + rec := httptest.NewRecorder() + c, _ := gin.CreateTestContext(rec) + c.Request = httptest.NewRequest(http.MethodPost, "/v1/responses", bytes.NewReader(nil)) + c.Request.Header.Set("User-Agent", "codex_cli_rs/0.144.1") + c.Request.Header.Set(responsesLiteHeader, "true") + upstream := &httpUpstreamRecorder{resp: &http.Response{ + StatusCode: http.StatusOK, + Header: http.Header{"Content-Type": []string{"text/event-stream"}}, + Body: io.NopCloser(strings.NewReader( + "data: {\"type\":\"response.completed\",\"response\":{\"id\":\"resp_lite\",\"usage\":{\"input_tokens\":1,\"output_tokens\":1}}}\n\n" + + "data: [DONE]\n\n", + )), + }} + svc := &OpenAIGatewayService{cfg: &config.Config{}, httpUpstream: upstream} + account := &Account{ + ID: 502, Name: "responses-lite-no-tools", Platform: PlatformOpenAI, Type: accountCase.accountType, + Concurrency: 1, Status: StatusActive, Schedulable: true, RateMultiplier: f64p(1), + Credentials: accountCase.credentials, + Extra: map[string]any{"openai_passthrough": passthrough}, + } + body := []byte(`{ + "model":"gpt-5.6-terra","stream":true,"instructions":"test", + "reasoning":{"effort":"high","context":"current_turn"}, + "input":[{"type":"message","role":"user","content":"hello"}]` + parallelCase.field + ` + }`) - result, err := svc.Forward(context.Background(), c, account, body) + result, err := svc.Forward(context.Background(), c, account, body) - require.NoError(t, err) - require.NotNil(t, result) - require.Equal(t, "true", upstream.lastReq.Header.Get(responsesLiteHeader)) - require.False(t, gjson.GetBytes(upstream.lastBody, "parallel_tool_calls").Exists(), string(upstream.lastBody)) - }) + require.NoError(t, err) + require.NotNil(t, result) + require.Equal(t, "true", upstream.lastReq.Header.Get(responsesLiteHeader)) + require.Equal(t, gjson.False, gjson.GetBytes(upstream.lastBody, "parallel_tool_calls").Type, string(upstream.lastBody)) + }) + } + } } } diff --git a/backend/internal/service/openai_responses_tool_schema_test.go b/backend/internal/service/openai_responses_tool_schema_test.go index faaf9062de..e899e17098 100644 --- a/backend/internal/service/openai_responses_tool_schema_test.go +++ b/backend/internal/service/openai_responses_tool_schema_test.go @@ -497,7 +497,7 @@ func TestOpenAIResponsesToolSchemaPlatformGate_APIKeyAndOAuth(t *testing.T) { normalized, changed, err := normalizeOpenAIResponsesWebSocketCompatibilityBody(body, &Account{ Platform: PlatformOpenAI, Type: accountType, - }) + }, false) require.NoError(t, err) require.True(t, changed) require.Equal(t, "object", gjson.GetBytes(normalized, "tools.0.parameters.type").String()) @@ -508,7 +508,7 @@ func TestOpenAIResponsesToolSchemaPlatformGate_APIKeyAndOAuth(t *testing.T) { normalized, changed, err := normalizeOpenAIResponsesWebSocketCompatibilityBody(body, &Account{ Platform: PlatformGrok, Type: AccountTypeAPIKey, - }) + }, false) require.NoError(t, err) require.False(t, changed) require.Equal(t, string(body), string(normalized)) diff --git a/backend/internal/service/openai_ws_forwarder_ingress.go b/backend/internal/service/openai_ws_forwarder_ingress.go index 5f9aed1f61..8dbb5b1abb 100644 --- a/backend/internal/service/openai_ws_forwarder_ingress.go +++ b/backend/internal/service/openai_ws_forwarder_ingress.go @@ -262,7 +262,8 @@ func (s *OpenAIGatewayService) ProxyResponsesWebSocketFromClient( normalized = capped } } - if compatibilityBody, compatibilityChanged, compatibilityErr := normalizeOpenAIResponsesWebSocketCompatibilityBody(normalized, account); compatibilityErr != nil { + responsesLite := isOpenAIResponsesLiteWebSocketPayload(normalized) + if compatibilityBody, compatibilityChanged, compatibilityErr := normalizeOpenAIResponsesWebSocketCompatibilityBody(normalized, account, responsesLite); compatibilityErr != nil { return openAIWSClientPayload{}, NewOpenAIWSClientCloseError(coderws.StatusPolicyViolation, "invalid websocket request payload", compatibilityErr) } else if compatibilityChanged { normalized = compatibilityBody @@ -320,7 +321,7 @@ func (s *OpenAIGatewayService) ProxyResponsesWebSocketFromClient( if accountScoped { normalized = accountScopedPayload } - if isOpenAIResponsesLiteWebSocketPayload(normalized) { + if responsesLite { litePayload, _, liteErr := normalizeOpenAIResponsesLitePayloadForAccount(normalized, account) if liteErr != nil { return openAIWSClientPayload{}, NewOpenAIWSClientCloseError( diff --git a/backend/internal/service/openai_ws_forwarder_ingress_session_test.go b/backend/internal/service/openai_ws_forwarder_ingress_session_test.go index 2e09082d6e..b05a2efd10 100644 --- a/backend/internal/service/openai_ws_forwarder_ingress_session_test.go +++ b/backend/internal/service/openai_ws_forwarder_ingress_session_test.go @@ -1364,8 +1364,7 @@ func TestOpenAIGatewayService_ProxyResponsesWebSocketFromClient_HTTPBridgeModeRe err = clientConn.Write(writeCtx, coderws.MessageText, []byte(`{ "type":"response.create","model":"gpt-5.1","stream":false, "parallel_tool_calls":true, - "client_metadata":{"ws_request_header_x_openai_internal_codex_responses_lite":"true"}, - "tools":[{"type":"function","name":"lookup","parameters":{"type":"object"}}] + "client_metadata":{"ws_request_header_x_openai_internal_codex_responses_lite":"true"} }`)) cancelWrite() require.NoError(t, err) diff --git a/backend/internal/service/openai_ws_http_bridge_test.go b/backend/internal/service/openai_ws_http_bridge_test.go index 752fdcca19..13752a55ef 100644 --- a/backend/internal/service/openai_ws_http_bridge_test.go +++ b/backend/internal/service/openai_ws_http_bridge_test.go @@ -1239,7 +1239,7 @@ func TestOpenAIWSHTTPBridgeRelaysSSEFramesAsWebSocketMessages(t *testing.T) { Concurrency: 1, Status: StatusActive, } - payload := []byte(`{"type":"response.create","generate":true,"model":"gpt-5","stream":true,"client_metadata":{"ws_request_header_x_openai_internal_codex_responses_lite":"true"},"input":"hi","tools":[{"type":"function","name":"lookup","parameters":{"type":"object"}}],"parallel_tool_calls":true}`) + payload := []byte(`{"type":"response.create","generate":true,"model":"gpt-5","stream":true,"client_metadata":{"ws_request_header_x_openai_internal_codex_responses_lite":"true"},"input":"hi","parallel_tool_calls":true}`) type bridgeResult struct { result *OpenAIForwardResult diff --git a/backend/internal/service/openai_ws_v2_passthrough_adapter.go b/backend/internal/service/openai_ws_v2_passthrough_adapter.go index d22e386e11..60e7b41416 100644 --- a/backend/internal/service/openai_ws_v2_passthrough_adapter.go +++ b/backend/internal/service/openai_ws_v2_passthrough_adapter.go @@ -735,7 +735,8 @@ func (s *OpenAIGatewayService) proxyResponsesWebSocketV2Passthrough( if capturedSessionModel != "" && capturedSessionModel != strings.TrimSpace(gjson.GetBytes(firstClientMessage, "model").String()) { firstClientMessage = s.ReplaceModelInBody(firstClientMessage, capturedSessionModel) } - if normalized, compatibilityChanged, normalizeErr := normalizeOpenAIResponsesWebSocketCompatibilityBody(firstClientMessage, account); normalizeErr != nil { + firstMessageResponsesLite := isOpenAIResponsesLiteWebSocketPayload(firstClientMessage) + if normalized, compatibilityChanged, normalizeErr := normalizeOpenAIResponsesWebSocketCompatibilityBody(firstClientMessage, account, firstMessageResponsesLite); normalizeErr != nil { return fmt.Errorf("normalize first websocket response.create: %w", normalizeErr) } else if compatibilityChanged { firstClientMessage = normalized @@ -984,8 +985,9 @@ func (s *OpenAIGatewayService) proxyResponsesWebSocketV2Passthrough( } }() } + responsesLite := isResponseCreate && isOpenAIResponsesLiteWebSocketPayload(payload) if isResponseCreate { - if normalized, compatibilityChanged, normalizeErr := normalizeOpenAIResponsesWebSocketCompatibilityBody(payload, account); normalizeErr != nil { + if normalized, compatibilityChanged, normalizeErr := normalizeOpenAIResponsesWebSocketCompatibilityBody(payload, account, responsesLite); normalizeErr != nil { return payload, nil, NewOpenAIWSClientCloseError(coderws.StatusPolicyViolation, "invalid websocket request payload", normalizeErr) } else if compatibilityChanged { payload = normalized @@ -1011,7 +1013,7 @@ func (s *OpenAIGatewayService) proxyResponsesWebSocketV2Passthrough( } } if isResponseCreate { - if isOpenAIResponsesLiteWebSocketPayload(payload) { + if responsesLite { litePayload, _, liteErr := normalizeOpenAIResponsesLitePayloadForAccount(payload, account) if liteErr != nil { return payload, nil, NewOpenAIWSClientCloseError(coderws.StatusPolicyViolation, liteErr.Error(), liteErr) diff --git a/backend/internal/service/openai_ws_v2_passthrough_lifecycle_test.go b/backend/internal/service/openai_ws_v2_passthrough_lifecycle_test.go index de3d5fdf27..ab7d704b04 100644 --- a/backend/internal/service/openai_ws_v2_passthrough_lifecycle_test.go +++ b/backend/internal/service/openai_ws_v2_passthrough_lifecycle_test.go @@ -190,13 +190,18 @@ func startPassthroughLifecycleServer( } func dialPassthroughLifecycleClient(t *testing.T, server *httptest.Server) *coderws.Conn { + t.Helper() + return dialPassthroughLifecycleClientWithPayload(t, server, `{"type":"response.create","model":"gpt-5.1","stream":false}`) +} + +func dialPassthroughLifecycleClientWithPayload(t *testing.T, server *httptest.Server, payload string) *coderws.Conn { t.Helper() dialCtx, cancelDial := context.WithTimeout(context.Background(), 3*time.Second) clientConn, _, err := coderws.Dial(dialCtx, "ws"+strings.TrimPrefix(server.URL, "http"), nil) cancelDial() require.NoError(t, err) writeCtx, cancelWrite := context.WithTimeout(context.Background(), 3*time.Second) - err = clientConn.Write(writeCtx, coderws.MessageText, []byte(`{"type":"response.create","model":"gpt-5.1","stream":false}`)) + err = clientConn.Write(writeCtx, coderws.MessageText, []byte(payload)) cancelWrite() require.NoError(t, err) return clientConn @@ -221,6 +226,35 @@ func requirePassthroughUpstreamWrite(t *testing.T, upstream *stagedPassthroughCo } } +func TestPassthroughLifecycle_ResponsesLiteFirstFramePinsParallelToolCalls(t *testing.T) { + gin.SetMode(gin.TestMode) + controlCtx, cancelControl := context.WithCancelCause(context.Background()) + defer cancelControl(context.Canceled) + upstream := newStagedPassthroughConn() + upstream.Send(`{"type":"response.completed","response":{"id":"resp_lite","model":"gpt-5.1","usage":{"input_tokens":1,"output_tokens":1}}}`) + server, serverErr := startPassthroughLifecycleServer(t, controlCtx, newPassthroughLifecycleService(passthroughLifecycleConfig(), upstream), passthroughLifecycleAccount()) + defer server.Close() + clientConn := dialPassthroughLifecycleClientWithPayload(t, server, `{ + "type":"response.create","model":"gpt-5.1","stream":false, + "parallel_tool_calls":true, + "client_metadata":{"ws_request_header_x_openai_internal_codex_responses_lite":"true"} + }`) + defer func() { _ = clientConn.CloseNow() }() + + upstreamBody := requirePassthroughUpstreamWrite(t, upstream, 3*time.Second) + require.Equal(t, gjson.False, gjson.GetBytes(upstreamBody, "parallel_tool_calls").Type, string(upstreamBody)) + + event, err := readPassthroughLifecycleFrame(t, clientConn, 3*time.Second) + require.NoError(t, err) + require.Equal(t, "response.completed", gjson.GetBytes(event, "type").String()) + require.NoError(t, clientConn.Close(coderws.StatusNormalClosure, "done")) + select { + case <-serverErr: + case <-time.After(3 * time.Second): + t.Fatal("Lite 首帧测试等待 passthrough 退出超时") + } +} + func TestOpenAIWSPassthroughTurnLifecycle_SerializesTerminalCommitAndNextTurn(t *testing.T) { clientFrameConn := &openAIWSClientFrameConn{interTurnStarted: make(chan struct{}, 1)} clientFrameConn.markTurnCompleted() From aa2c4e8d136b13553ac7bae3d76c25715333a554 Mon Sep 17 00:00:00 2001 From: "github-actions[bot]" <41898282+github-actions[bot]@users.noreply.github.com> Date: Tue, 25 Aug 2026 04:47:52 +0000 Subject: [PATCH 169/204] chore: sync VERSION to 0.1.182 [skip ci] --- backend/cmd/server/VERSION | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/backend/cmd/server/VERSION b/backend/cmd/server/VERSION index 7fcea722aa..ce08f35612 100644 --- a/backend/cmd/server/VERSION +++ b/backend/cmd/server/VERSION @@ -1 +1 @@ -0.1.181 +0.1.182 From 1a9898a6a4928b7686cb90045d20cc8ad81dff64 Mon Sep 17 00:00:00 2001 From: wucm667 Date: Tue, 25 Aug 2026 13:13:08 +0800 Subject: [PATCH 170/204] fix(antigravity): clamp compatible token limits --- .../service/antigravity_gateway_compat.go | 4 +- .../antigravity_gateway_compat_test.go | 37 +++++++++++++++++++ 2 files changed, 40 insertions(+), 1 deletion(-) diff --git a/backend/internal/service/antigravity_gateway_compat.go b/backend/internal/service/antigravity_gateway_compat.go index 49ca076884..1d6d39e1aa 100644 --- a/backend/internal/service/antigravity_gateway_compat.go +++ b/backend/internal/service/antigravity_gateway_compat.go @@ -29,6 +29,8 @@ const ( AntigravityCredentialRejectedReason GatewayFailureReason = "antigravity_oauth_credential_rejected" ) +const antigravityCompatMaxTokens = 64000 + type antigravityCompatRequest struct { protocol antigravityCompatProtocol originalBody []byte @@ -158,7 +160,7 @@ func preserveChatCompletionTokenLimit(request *apicompat.ChatCompletionsRequest, limit = request.MaxCompletionTokens } if limit != nil && *limit > 0 { - claudeRequest.MaxTokens = *limit + claudeRequest.MaxTokens = min(*limit, antigravityCompatMaxTokens) } } diff --git a/backend/internal/service/antigravity_gateway_compat_test.go b/backend/internal/service/antigravity_gateway_compat_test.go index 3df0b0081a..a92b1654c2 100644 --- a/backend/internal/service/antigravity_gateway_compat_test.go +++ b/backend/internal/service/antigravity_gateway_compat_test.go @@ -12,6 +12,7 @@ import ( "time" "github.com/Wei-Shaw/sub2api/internal/config" + "github.com/Wei-Shaw/sub2api/internal/pkg/apicompat" "github.com/gin-gonic/gin" "github.com/stretchr/testify/require" "github.com/tidwall/gjson" @@ -285,6 +286,21 @@ func TestAntigravityCompatPreservesChatTokenLimit(t *testing.T) { body: `{"model":"gemini-3.1-pro-high","messages":[{"role":"user","content":"ok"}],"max_tokens":8,"max_completion_tokens":13}`, want: 13, }, + { + name: "max_tokens at safe ceiling is preserved", + body: `{"model":"gemini-3.1-pro-high","messages":[{"role":"user","content":"ok"}],"max_tokens":64000}`, + want: 64000, + }, + { + name: "max_tokens above safe ceiling is clamped", + body: `{"model":"gemini-3.1-pro-high","messages":[{"role":"user","content":"ok"}],"max_tokens":64001}`, + want: 64000, + }, + { + name: "precedence applies before clamping", + body: `{"model":"gemini-3.1-pro-high","messages":[{"role":"user","content":"ok"}],"max_tokens":8,"max_completion_tokens":64001}`, + want: 64000, + }, } for _, tt := range tests { @@ -310,6 +326,27 @@ func TestAntigravityCompatPreservesChatTokenLimit(t *testing.T) { } } +func TestPreserveChatCompletionTokenLimitIgnoresAbsentAndNonPositiveValues(t *testing.T) { + tests := []struct { + name string + request apicompat.ChatCompletionsRequest + }{ + {name: "absent"}, + {name: "zero max_tokens", request: apicompat.ChatCompletionsRequest{MaxTokens: antigravityCompatIntPtr(0)}}, + {name: "negative max_completion_tokens takes precedence", request: apicompat.ChatCompletionsRequest{MaxTokens: antigravityCompatIntPtr(12), MaxCompletionTokens: antigravityCompatIntPtr(-1)}}, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + claudeRequest := &apicompat.AnthropicRequest{MaxTokens: 99} + preserveChatCompletionTokenLimit(&tt.request, claudeRequest) + require.Equal(t, 99, claudeRequest.MaxTokens) + }) + } +} + +func antigravityCompatIntPtr(v int) *int { return &v } + func TestAntigravityCompatRoutesByMappedModelFamily(t *testing.T) { gin.SetMode(gin.TestMode) tests := []struct { From 11ada80d58addc53fe70d567f4c06eea10463c2a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=88=98=E4=BD=B3=E6=9E=97?= Date: Tue, 25 Aug 2026 15:10:52 +0800 Subject: [PATCH 171/204] =?UTF-8?q?feat(usage):=20=E4=BD=BF=E7=94=A8?= =?UTF-8?q?=E8=AE=B0=E5=BD=95=E5=B1=95=E7=A4=BA=E6=98=A0=E5=B0=84=E5=89=8D?= =?UTF-8?q?=E7=9A=84=E6=8E=A8=E7=90=86=E5=BC=BA=E5=BA=A6?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 用量行新增 requested_reasoning_effort,记录分组策略与模型族改写前的客户端请求值;推理强度列与模型列一致,主行显示请求值,有映射时用 ↳ 展示实际转发值。 --- .../internal/handler/composite_platform.go | 30 +++++++ .../handler/composite_platform_test.go | 3 + backend/internal/handler/dto/mappers.go | 1 + .../handler/dto/mappers_usage_test.go | 25 ++++++ backend/internal/handler/dto/types.go | 4 +- backend/internal/handler/gateway_handler.go | 3 + .../gateway_handler_chat_completions.go | 2 + .../handler/gateway_handler_responses.go | 2 + .../handler/openai_chat_completions.go | 1 + .../handler/openai_gateway_handler.go | 2 + .../repository/usage_log_repo_insert.go | 21 +++-- .../repository/usage_log_repo_query.go | 7 +- .../usage_log_repo_request_type_test.go | 12 ++- .../usage_log_session_id_unit_test.go | 34 +++++++- backend/internal/service/gateway_service.go | 2 + .../internal/service/gateway_usage_billing.go | 85 ++++++++++--------- ...penai_gateway_messages_anthropic_native.go | 3 +- .../openai_gateway_record_usage_test.go | 35 ++++++++ .../service/openai_gateway_request_body.go | 84 ++++++++++++++++++ .../service/openai_gateway_service.go | 10 ++- .../internal/service/openai_gateway_usage.go | 51 +++++------ .../service/openai_reasoning_effort_policy.go | 31 +++++++ .../openai_reasoning_effort_policy_test.go | 28 ++++++ .../service/openai_ws_forwarder_ingress.go | 10 ++- .../service/openai_ws_forwarder_v2.go | 1 + .../internal/service/openai_ws_http_bridge.go | 1 + .../openai_ws_v2_passthrough_adapter.go | 23 ++++- ...i_ws_v2_passthrough_adapter_effort_test.go | 4 + backend/internal/service/usage_log.go | 6 +- backend/internal/service/usage_log_helpers.go | 12 +++ ...d_usage_log_requested_reasoning_effort.sql | 7 ++ .../src/components/admin/usage/UsageTable.vue | 20 ++++- .../admin/usage/__tests__/UsageTable.spec.ts | 57 +++++++++++++ frontend/src/i18n/locales/en/dashboard.ts | 1 + frontend/src/i18n/locales/zh/dashboard.ts | 1 + frontend/src/types/index.ts | 1 + .../__tests__/formatReasoningEffort.spec.ts | 33 +++++++ frontend/src/utils/format.ts | 31 ++++++- frontend/src/views/admin/UsageView.vue | 4 +- frontend/src/views/user/UsageView.vue | 4 +- 40 files changed, 595 insertions(+), 97 deletions(-) create mode 100644 backend/migrations/231_add_usage_log_requested_reasoning_effort.sql create mode 100644 frontend/src/utils/__tests__/formatReasoningEffort.spec.ts diff --git a/backend/internal/handler/composite_platform.go b/backend/internal/handler/composite_platform.go index 0d57c709c6..fad5e12b56 100644 --- a/backend/internal/handler/composite_platform.go +++ b/backend/internal/handler/composite_platform.go @@ -72,7 +72,36 @@ func openAIReasoningEffortPolicyForRequest(c *gin.Context, apiKey *service.APIKe return apiKey.Group.MaxReasoningEffort, apiKey.Group.ReasoningEffortMappings, true } +func bindRequestedReasoningEffort(c *gin.Context, body []byte, model string) { + if c == nil || c.Request == nil { + return + } + effort := service.CanonicalRequestedReasoningEffort(body, model) + if effort == nil { + return + } + c.Request = c.Request.WithContext(service.WithRequestedReasoningEffort(c.Request.Context(), *effort)) +} + +func stampOpenAIRequestedReasoningEffort(result *service.OpenAIForwardResult, c *gin.Context) { + if result == nil || result.RequestedReasoningEffort != nil { + return + } + if c == nil || c.Request == nil { + return + } + result.RequestedReasoningEffort = service.RequestedReasoningEffortFromContext(c.Request.Context()) +} + +func stampForwardRequestedReasoningEffort(result *service.ForwardResult, requested *string) { + if result == nil || result.RequestedReasoningEffort != nil { + return + } + result.RequestedReasoningEffort = requested +} + func applyOpenAIReasoningEffortPolicyForRequest(c *gin.Context, apiKey *service.APIKey, body []byte) ([]byte, bool) { + bindRequestedReasoningEffort(c, body, strings.TrimSpace(gjson.GetBytes(body, "model").String())) maxEffort, mappings, ok := openAIReasoningEffortPolicyForRequest(c, apiKey) if !ok { return body, false @@ -84,6 +113,7 @@ func bindOpenAIReasoningEffortPolicyForMessagesRequest(c *gin.Context, apiKey *s if c == nil || c.Request == nil { return } + bindRequestedReasoningEffort(c, body, strings.TrimSpace(gjson.GetBytes(body, "model").String())) // The Messages bridge synthesizes a default OpenAI effort when // output_config.effort is omitted. Bind the group policy only for an // explicit client value so the ceiling does not alter that default. diff --git a/backend/internal/handler/composite_platform_test.go b/backend/internal/handler/composite_platform_test.go index 6e068a4614..4d2c0f583f 100644 --- a/backend/internal/handler/composite_platform_test.go +++ b/backend/internal/handler/composite_platform_test.go @@ -120,6 +120,9 @@ func TestOpenAIReasoningEffortPolicyForCompositeTarget(t *testing.T) { got, changed := applyOpenAIReasoningEffortPolicyForRequest(openAICtx, apiKey, body) require.True(t, changed) require.JSONEq(t, `{"reasoning":{"effort":"medium"}}`, string(got)) + requested := service.RequestedReasoningEffortFromContext(openAICtx.Request.Context()) + require.NotNil(t, requested) + require.Equal(t, "max", *requested) bindOpenAIReasoningEffortPolicyForMessagesRequest(openAICtx, apiKey, []byte(`{"output_config":{"effort":"max"}}`)) bound, changed := service.ApplyOpenAIReasoningEffortPolicyFromContext(openAICtx.Request.Context(), body) diff --git a/backend/internal/handler/dto/mappers.go b/backend/internal/handler/dto/mappers.go index d5a9403a23..81aa8f8865 100644 --- a/backend/internal/handler/dto/mappers.go +++ b/backend/internal/handler/dto/mappers.go @@ -644,6 +644,7 @@ func usageLogFromServiceUser(l *service.UsageLog) UsageLog { Model: requestedModel, ServiceTier: l.ServiceTier, ReasoningEffort: l.ReasoningEffort, + RequestedReasoningEffort: l.RequestedReasoningEffort, InboundEndpoint: l.InboundEndpoint, GroupID: l.GroupID, SubscriptionID: l.SubscriptionID, diff --git a/backend/internal/handler/dto/mappers_usage_test.go b/backend/internal/handler/dto/mappers_usage_test.go index d396bbfa2f..43299000e9 100644 --- a/backend/internal/handler/dto/mappers_usage_test.go +++ b/backend/internal/handler/dto/mappers_usage_test.go @@ -179,6 +179,31 @@ func TestUsageLogFromService_KeepsUserBillingAndIPWithoutAdminCostFields(t *test require.NotContains(t, string(userJSON), "account_cost") } +func TestUsageLogFromService_IncludesRequestedReasoningEffort(t *testing.T) { + t.Parallel() + + requested := "max" + forwarded := "xhigh" + log := &service.UsageLog{ + RequestID: "req_effort", + Model: "gpt-5.4", + ReasoningEffort: &forwarded, + RequestedReasoningEffort: &requested, + } + + userDTO := UsageLogFromService(log) + adminDTO := UsageLogFromServiceAdmin(log) + + require.NotNil(t, userDTO.ReasoningEffort) + require.Equal(t, forwarded, *userDTO.ReasoningEffort) + require.NotNil(t, userDTO.RequestedReasoningEffort) + require.Equal(t, requested, *userDTO.RequestedReasoningEffort) + require.NotNil(t, adminDTO.ReasoningEffort) + require.Equal(t, forwarded, *adminDTO.ReasoningEffort) + require.NotNil(t, adminDTO.RequestedReasoningEffort) + require.Equal(t, requested, *adminDTO.RequestedReasoningEffort) +} + func TestUsageLogFromService_FallsBackToLegacyModelWhenRequestedModelMissing(t *testing.T) { t.Parallel() diff --git a/backend/internal/handler/dto/types.go b/backend/internal/handler/dto/types.go index 2cd623f7d6..72e89a0985 100644 --- a/backend/internal/handler/dto/types.go +++ b/backend/internal/handler/dto/types.go @@ -486,9 +486,11 @@ type UsageLog struct { Model string `json:"model"` // ServiceTier records the OpenAI service tier used for billing, e.g. "priority" / "flex". ServiceTier *string `json:"service_tier,omitempty"` - // ReasoningEffort is the request's reasoning effort level. + // ReasoningEffort is the effective effort after group policy / model-family remapping. // OpenAI: "low"/"medium"/"high"/"xhigh"; Claude: "low"/"medium"/"high"/"max". ReasoningEffort *string `json:"reasoning_effort,omitempty"` + // RequestedReasoningEffort is the client-requested effort before mapping. + RequestedReasoningEffort *string `json:"requested_reasoning_effort,omitempty"` // InboundEndpoint is the client-facing API endpoint path, e.g. /v1/chat/completions. InboundEndpoint *string `json:"inbound_endpoint,omitempty"` // UpstreamEndpoint is the normalized upstream endpoint path, e.g. /v1/responses. diff --git a/backend/internal/handler/gateway_handler.go b/backend/internal/handler/gateway_handler.go index 1128329be8..2e4987c54f 100644 --- a/backend/internal/handler/gateway_handler.go +++ b/backend/internal/handler/gateway_handler.go @@ -169,6 +169,7 @@ func (h *GatewayHandler) Messages(c *gin.Context) { body = parsedReq.Body.Bytes() reqModel := parsedReq.Model reqStream := parsedReq.Stream + bindRequestedReasoningEffort(c, body, reqModel) ensureCompositeTargetPlatform(c, apiKey, reqModel) reqLog = reqLog.With(zap.String("model", reqModel), zap.Bool("stream", reqStream)) @@ -541,6 +542,7 @@ func (h *GatewayHandler) Messages(c *gin.Context) { inboundEndpoint := GetInboundEndpoint(c) upstreamEndpoint := GetUpstreamEndpoint(c, account.Platform) + stampForwardRequestedReasoningEffort(result, service.NormalizeClaudeOutputEffort(parsedReq.OutputEffort)) if result.ReasoningEffort == nil { result.ReasoningEffort = service.NormalizeClaudeOutputEffort(parsedReq.OutputEffort) } @@ -882,6 +884,7 @@ func (h *GatewayHandler) Messages(c *gin.Context) { inboundEndpoint := GetInboundEndpoint(c) upstreamEndpoint := GetUpstreamEndpoint(c, account.Platform) + stampForwardRequestedReasoningEffort(result, service.NormalizeClaudeOutputEffort(attemptParsedReq.OutputEffort)) if result.ReasoningEffort == nil { result.ReasoningEffort = service.NormalizeClaudeOutputEffort(attemptParsedReq.OutputEffort) } diff --git a/backend/internal/handler/gateway_handler_chat_completions.go b/backend/internal/handler/gateway_handler_chat_completions.go index 951a93a6b3..7a98504596 100644 --- a/backend/internal/handler/gateway_handler_chat_completions.go +++ b/backend/internal/handler/gateway_handler_chat_completions.go @@ -76,6 +76,7 @@ func (h *GatewayHandler) ChatCompletions(c *gin.Context) { return } reqModel := modelResult.String() + bindRequestedReasoningEffort(c, body, reqModel) ensureCompositeTargetPlatform(c, apiKey, reqModel) if !compositeTargetPlatformResolved(c, apiKey, reqModel) { h.chatCompletionsErrorResponse(c, http.StatusBadRequest, "invalid_request_error", "Model is not supported by composite groups") @@ -335,6 +336,7 @@ func (h *GatewayHandler) ChatCompletions(c *gin.Context) { quotaPlatform := service.QuotaPlatform(c.Request.Context(), apiKey) sessionID := service.ExtractClientSessionID(c) + stampForwardRequestedReasoningEffort(result, service.RequestedReasoningEffortFromContext(c.Request.Context())) h.submitUsageRecordTask(c.Request.Context(), func(ctx context.Context) { if err := h.gatewayService.RecordUsage(ctx, &service.RecordUsageInput{ Result: result, diff --git a/backend/internal/handler/gateway_handler_responses.go b/backend/internal/handler/gateway_handler_responses.go index ac5a3d23fc..04a61cb16e 100644 --- a/backend/internal/handler/gateway_handler_responses.go +++ b/backend/internal/handler/gateway_handler_responses.go @@ -76,6 +76,7 @@ func (h *GatewayHandler) Responses(c *gin.Context) { return } reqModel := modelResult.String() + bindRequestedReasoningEffort(c, body, reqModel) ensureCompositeTargetPlatform(c, apiKey, reqModel) if !compositeTargetPlatformResolved(c, apiKey, reqModel) { h.responsesErrorResponse(c, http.StatusBadRequest, "invalid_request_error", "Model is not supported by composite groups") @@ -323,6 +324,7 @@ func (h *GatewayHandler) Responses(c *gin.Context) { quotaPlatform := service.QuotaPlatform(c.Request.Context(), apiKey) sessionID := service.ExtractClientSessionID(c) + stampForwardRequestedReasoningEffort(result, service.RequestedReasoningEffortFromContext(c.Request.Context())) h.submitUsageRecordTask(c.Request.Context(), func(ctx context.Context) { if err := h.gatewayService.RecordUsage(ctx, &service.RecordUsageInput{ Result: result, diff --git a/backend/internal/handler/openai_chat_completions.go b/backend/internal/handler/openai_chat_completions.go index aa2b610d70..be75ab8dea 100644 --- a/backend/internal/handler/openai_chat_completions.go +++ b/backend/internal/handler/openai_chat_completions.go @@ -267,6 +267,7 @@ func (h *OpenAIGatewayHandler) ChatCompletions(c *gin.Context) { if res == nil { return } + stampOpenAIRequestedReasoningEffort(res, c) userAgent := c.GetHeader("User-Agent") clientIP := ip.GetClientIP(c) inboundEndpoint := GetInboundEndpoint(c) diff --git a/backend/internal/handler/openai_gateway_handler.go b/backend/internal/handler/openai_gateway_handler.go index 32cea2f073..7ec0ca5bb3 100644 --- a/backend/internal/handler/openai_gateway_handler.go +++ b/backend/internal/handler/openai_gateway_handler.go @@ -702,6 +702,7 @@ func (h *OpenAIGatewayHandler) Responses(c *gin.Context) { if res == nil { return } + stampOpenAIRequestedReasoningEffort(res, c) userAgent := c.GetHeader("User-Agent") clientIP := ip.GetClientIP(c) requestPayloadHash := service.HashUsageRequestPayload(body) @@ -1266,6 +1267,7 @@ func (h *OpenAIGatewayHandler) Messages(c *gin.Context) { if res == nil { return } + stampOpenAIRequestedReasoningEffort(res, c) userAgent := c.GetHeader("User-Agent") clientIP := ip.GetClientIP(c) requestPayloadHash := service.HashUsageRequestPayload(body) diff --git a/backend/internal/repository/usage_log_repo_insert.go b/backend/internal/repository/usage_log_repo_insert.go index 6d932c0d43..67bf2937ae 100644 --- a/backend/internal/repository/usage_log_repo_insert.go +++ b/backend/internal/repository/usage_log_repo_insert.go @@ -72,6 +72,7 @@ var usageLogInsertArgTypes = [...]string{ "integer", // video_duration_seconds "text", // service_tier "text", // reasoning_effort + "text", // requested_reasoning_effort "text", // inbound_endpoint "text", // upstream_endpoint "boolean", // cache_ttl_overridden @@ -270,6 +271,7 @@ func (r *usageLogRepository) createSingle(ctx context.Context, sqlq sqlExecutor, video_duration_seconds, service_tier, reasoning_effort, + requested_reasoning_effort, inbound_endpoint, upstream_endpoint, cache_ttl_overridden, @@ -287,7 +289,7 @@ func (r *usageLogRepository) createSingle(ctx context.Context, sqlq sqlExecutor, $12, $13, $14, $15, $16, $17, $18, $19, $20, $21, $22, $23, $24, $25, - $26, $27, $28, $29, $30, $31, $32, $33, $34, $35, $36, $37, $38, $39, $40, $41, $42, $43, $44, $45, $46, $47, $48, $49, $50, $51, $52, $53, $54, $55, $56, $57, $58, $59 + $26, $27, $28, $29, $30, $31, $32, $33, $34, $35, $36, $37, $38, $39, $40, $41, $42, $43, $44, $45, $46, $47, $48, $49, $50, $51, $52, $53, $54, $55, $56, $57, $58, $59, $60 ) ON CONFLICT (request_id, api_key_id) DO NOTHING RETURNING id, created_at @@ -727,6 +729,7 @@ func buildUsageLogBatchInsertQuery(keys []string, preparedByKey map[string]usage video_duration_seconds, service_tier, reasoning_effort, + requested_reasoning_effort, inbound_endpoint, upstream_endpoint, cache_ttl_overridden, @@ -740,9 +743,9 @@ func buildUsageLogBatchInsertQuery(keys []string, preparedByKey map[string]usage created_at ) AS (VALUES `) - // Each batch row prepends the synthetic input_index before the 59 + // Each batch row prepends the synthetic input_index before the 60 // usage-log column values. - args := make([]any, 0, len(keys)*60) + args := make([]any, 0, len(keys)*61) argPos := 1 for idx, key := range keys { if idx > 0 { @@ -819,6 +822,7 @@ func buildUsageLogBatchInsertQuery(keys []string, preparedByKey map[string]usage video_duration_seconds, service_tier, reasoning_effort, + requested_reasoning_effort, inbound_endpoint, upstream_endpoint, cache_ttl_overridden, @@ -880,6 +884,7 @@ func buildUsageLogBatchInsertQuery(keys []string, preparedByKey map[string]usage video_duration_seconds, service_tier, reasoning_effort, + requested_reasoning_effort, inbound_endpoint, upstream_endpoint, cache_ttl_overridden, @@ -981,6 +986,7 @@ func buildUsageLogBestEffortInsertQuery(preparedList []usageLogInsertPrepared) ( video_duration_seconds, service_tier, reasoning_effort, + requested_reasoning_effort, inbound_endpoint, upstream_endpoint, cache_ttl_overridden, @@ -994,7 +1000,7 @@ func buildUsageLogBestEffortInsertQuery(preparedList []usageLogInsertPrepared) ( created_at ) AS (VALUES `) - args := make([]any, 0, len(preparedList)*59) + args := make([]any, 0, len(preparedList)*60) argPos := 1 for idx, prepared := range preparedList { if idx > 0 { @@ -1068,6 +1074,7 @@ func buildUsageLogBestEffortInsertQuery(preparedList []usageLogInsertPrepared) ( video_duration_seconds, service_tier, reasoning_effort, + requested_reasoning_effort, inbound_endpoint, upstream_endpoint, cache_ttl_overridden, @@ -1129,6 +1136,7 @@ func buildUsageLogBestEffortInsertQuery(preparedList []usageLogInsertPrepared) ( video_duration_seconds, service_tier, reasoning_effort, + requested_reasoning_effort, inbound_endpoint, upstream_endpoint, cache_ttl_overridden, @@ -1198,6 +1206,7 @@ func execUsageLogInsertNoResult(ctx context.Context, sqlq sqlExecutor, prepared video_duration_seconds, service_tier, reasoning_effort, + requested_reasoning_effort, inbound_endpoint, upstream_endpoint, cache_ttl_overridden, @@ -1215,7 +1224,7 @@ func execUsageLogInsertNoResult(ctx context.Context, sqlq sqlExecutor, prepared $12, $13, $14, $15, $16, $17, $18, $19, $20, $21, $22, $23, $24, $25, - $26, $27, $28, $29, $30, $31, $32, $33, $34, $35, $36, $37, $38, $39, $40, $41, $42, $43, $44, $45, $46, $47, $48, $49, $50, $51, $52, $53, $54, $55, $56, $57, $58, $59 + $26, $27, $28, $29, $30, $31, $32, $33, $34, $35, $36, $37, $38, $39, $40, $41, $42, $43, $44, $45, $46, $47, $48, $49, $50, $51, $52, $53, $54, $55, $56, $57, $58, $59, $60 ) ON CONFLICT (request_id, api_key_id) DO NOTHING `, prepared.args...) @@ -1250,6 +1259,7 @@ func prepareUsageLogInsert(log *service.UsageLog) usageLogInsertPrepared { videoDurationSeconds := nullInt(log.VideoDurationSeconds) serviceTier := nullString(log.ServiceTier) reasoningEffort := nullString(log.ReasoningEffort) + requestedReasoningEffort := nullString(log.RequestedReasoningEffort) inboundEndpoint := nullString(log.InboundEndpoint) upstreamEndpoint := nullString(log.UpstreamEndpoint) channelID := nullInt64(log.ChannelID) @@ -1324,6 +1334,7 @@ func prepareUsageLogInsert(log *service.UsageLog) usageLogInsertPrepared { videoDurationSeconds, serviceTier, reasoningEffort, + requestedReasoningEffort, inboundEndpoint, upstreamEndpoint, log.CacheTTLOverridden, diff --git a/backend/internal/repository/usage_log_repo_query.go b/backend/internal/repository/usage_log_repo_query.go index f2fa6e30b0..6ca471999e 100644 --- a/backend/internal/repository/usage_log_repo_query.go +++ b/backend/internal/repository/usage_log_repo_query.go @@ -19,7 +19,7 @@ import ( "github.com/Wei-Shaw/sub2api/internal/service" ) -const usageLogSelectColumns = "id, user_id, api_key_id, account_id, request_id, model, requested_model, upstream_model, upstream_response_model, upstream_model_mismatch, group_id, subscription_id, input_tokens, output_tokens, cache_creation_tokens, cache_read_tokens, cache_creation_5m_tokens, cache_creation_1h_tokens, image_output_tokens, image_output_cost, image_input_tokens, image_input_cost, input_cost, output_cost, cache_creation_cost, cache_read_cost, total_cost, actual_cost, rate_multiplier, account_rate_multiplier, billing_type, request_type, stream, openai_ws_mode, duration_ms, first_token_ms, user_agent, ip_address, image_count, image_size, image_input_size, image_output_size, image_size_source, image_size_breakdown, video_count, video_resolution, video_duration_seconds, service_tier, reasoning_effort, inbound_endpoint, upstream_endpoint, cache_ttl_overridden, long_context_billing_applied, channel_id, model_mapping_chain, billing_tier, billing_mode, account_stats_cost, session_id, created_at" +const usageLogSelectColumns = "id, user_id, api_key_id, account_id, request_id, model, requested_model, upstream_model, upstream_response_model, upstream_model_mismatch, group_id, subscription_id, input_tokens, output_tokens, cache_creation_tokens, cache_read_tokens, cache_creation_5m_tokens, cache_creation_1h_tokens, image_output_tokens, image_output_cost, image_input_tokens, image_input_cost, input_cost, output_cost, cache_creation_cost, cache_read_cost, total_cost, actual_cost, rate_multiplier, account_rate_multiplier, billing_type, request_type, stream, openai_ws_mode, duration_ms, first_token_ms, user_agent, ip_address, image_count, image_size, image_input_size, image_output_size, image_size_source, image_size_breakdown, video_count, video_resolution, video_duration_seconds, service_tier, reasoning_effort, requested_reasoning_effort, inbound_endpoint, upstream_endpoint, cache_ttl_overridden, long_context_billing_applied, channel_id, model_mapping_chain, billing_tier, billing_mode, account_stats_cost, session_id, created_at" func (r *usageLogRepository) GetByID(ctx context.Context, id int64) (log *service.UsageLog, err error) { query := "SELECT " + usageLogSelectColumns + " FROM usage_logs WHERE id = $1" @@ -488,6 +488,7 @@ func scanUsageLog(scanner interface{ Scan(...any) error }) (*service.UsageLog, e videoDurationSeconds sql.NullInt64 serviceTier sql.NullString reasoningEffort sql.NullString + requestedReasoningEffort sql.NullString inboundEndpoint sql.NullString upstreamEndpoint sql.NullString cacheTTLOverridden bool @@ -551,6 +552,7 @@ func scanUsageLog(scanner interface{ Scan(...any) error }) (*service.UsageLog, e &videoDurationSeconds, &serviceTier, &reasoningEffort, + &requestedReasoningEffort, &inboundEndpoint, &upstreamEndpoint, &cacheTTLOverridden, @@ -656,6 +658,9 @@ func scanUsageLog(scanner interface{ Scan(...any) error }) (*service.UsageLog, e if reasoningEffort.Valid { log.ReasoningEffort = &reasoningEffort.String } + if requestedReasoningEffort.Valid { + log.RequestedReasoningEffort = &requestedReasoningEffort.String + } if inboundEndpoint.Valid { log.InboundEndpoint = &inboundEndpoint.String } diff --git a/backend/internal/repository/usage_log_repo_request_type_test.go b/backend/internal/repository/usage_log_repo_request_type_test.go index a67c93c345..997f20d0ab 100644 --- a/backend/internal/repository/usage_log_repo_request_type_test.go +++ b/backend/internal/repository/usage_log_repo_request_type_test.go @@ -89,6 +89,7 @@ func TestUsageLogRepositoryCreateSyncRequestTypeAndLegacyFields(t *testing.T) { sqlmock.AnyArg(), // video_duration_seconds sqlmock.AnyArg(), // service_tier sqlmock.AnyArg(), // reasoning_effort + sqlmock.AnyArg(), // requested_reasoning_effort sqlmock.AnyArg(), // inbound_endpoint sqlmock.AnyArg(), // upstream_endpoint log.CacheTTLOverridden, @@ -180,9 +181,10 @@ func TestUsageLogRepositoryCreate_PersistsServiceTier(t *testing.T) { sqlmock.AnyArg(), // video_resolution sqlmock.AnyArg(), // video_duration_seconds serviceTier, - sqlmock.AnyArg(), - sqlmock.AnyArg(), - sqlmock.AnyArg(), + sqlmock.AnyArg(), // reasoning_effort + sqlmock.AnyArg(), // requested_reasoning_effort + sqlmock.AnyArg(), // inbound_endpoint + sqlmock.AnyArg(), // upstream_endpoint log.CacheTTLOverridden, log.LongContextBillingApplied, sqlmock.AnyArg(), // channel_id @@ -831,6 +833,7 @@ func TestScanUsageLogRequestTypeAndLegacyFallback(t *testing.T) { sql.NullString{}, sql.NullString{}, sql.NullString{}, + sql.NullString{}, false, false, sql.NullInt64{}, @@ -908,6 +911,7 @@ func TestScanUsageLogRequestTypeAndLegacyFallback(t *testing.T) { sql.NullString{}, sql.NullString{}, sql.NullString{}, + sql.NullString{}, false, false, sql.NullInt64{}, // channel_id @@ -968,6 +972,7 @@ func TestScanUsageLogRequestTypeAndLegacyFallback(t *testing.T) { sql.NullString{}, sql.NullString{}, sql.NullString{}, + sql.NullString{}, false, false, sql.NullInt64{}, // channel_id @@ -1028,6 +1033,7 @@ func TestScanUsageLogRequestTypeAndLegacyFallback(t *testing.T) { sql.NullString{}, sql.NullString{}, sql.NullString{}, + sql.NullString{}, false, false, sql.NullInt64{}, // channel_id diff --git a/backend/internal/repository/usage_log_session_id_unit_test.go b/backend/internal/repository/usage_log_session_id_unit_test.go index 64c1c1bab2..e4ff0ebe53 100644 --- a/backend/internal/repository/usage_log_session_id_unit_test.go +++ b/backend/internal/repository/usage_log_session_id_unit_test.go @@ -32,7 +32,7 @@ func newSessionIDUsageLog(sessionID *string) *service.UsageLog { // arg slice / arg-type table so the five INSERT column lists stay in sync. session_id // is the penultimate arg (created_at is always last). func TestPrepareUsageLogInsert_SessionIDArgWiring(t *testing.T) { - require.Len(t, usageLogInsertArgTypes, 59, "arg-type table must include session_id") + require.Len(t, usageLogInsertArgTypes, 60, "arg-type table must include session_id") sessionID := "sess-persisted-123" prepared := prepareUsageLogInsert(newSessionIDUsageLog(&sessionID)) @@ -66,9 +66,40 @@ func TestPrepareUsageLogInsert_SessionIDNullWhenAbsent(t *testing.T) { require.False(t, nsEmpty.Valid, "empty session id must also be NULL") } +func TestPrepareUsageLogInsert_RequestedReasoningEffortArgWiring(t *testing.T) { + requested := "max" + forwarded := "xhigh" + prepared := prepareUsageLogInsert(&service.UsageLog{ + UserID: 1, + APIKeyID: 2, + AccountID: 3, + RequestID: "req-requested-effort", + Model: "gpt-5.4", + ReasoningEffort: &forwarded, + RequestedReasoningEffort: &requested, + CreatedAt: time.Now().UTC(), + }) + + require.Len(t, prepared.args, len(usageLogInsertArgTypes)) + require.Equal(t, "text", usageLogInsertArgTypes[48], "requested_reasoning_effort must follow reasoning_effort") + require.Equal(t, "text", usageLogInsertArgTypes[47], "reasoning_effort arg type must stay text") + + forwardedArg, ok := prepared.args[47].(sql.NullString) + require.True(t, ok) + require.True(t, forwardedArg.Valid) + require.Equal(t, forwarded, forwardedArg.String) + + requestedArg, ok := prepared.args[48].(sql.NullString) + require.True(t, ok) + require.True(t, requestedArg.Valid) + require.Equal(t, requested, requestedArg.String) +} + // TestUsageLogInsertQueries_IncludeSessionID guards that every generated INSERT path // and the SELECT column list reference session_id. func TestUsageLogInsertQueries_IncludeSessionID(t *testing.T) { + require.Contains(t, usageLogSelectColumns, "requested_reasoning_effort", + "SELECT column list must include requested_reasoning_effort") require.Contains(t, usageLogSelectColumns, "session_id", "SELECT column list must include session_id") @@ -80,6 +111,7 @@ func TestUsageLogInsertQueries_IncludeSessionID(t *testing.T) { batchQuery, batchArgs := buildUsageLogBatchInsertQuery([]string{key}, map[string]usageLogInsertPrepared{key: prepared}) require.Contains(t, batchQuery, "session_id") + require.Contains(t, batchQuery, "requested_reasoning_effort") // Two column references (INSERT column list + SELECT ... FROM input) plus the CTE def. require.GreaterOrEqual(t, strings.Count(batchQuery, "session_id"), 3) require.Len(t, batchArgs, len(prepared.args)+1, diff --git a/backend/internal/service/gateway_service.go b/backend/internal/service/gateway_service.go index 37bab2f97d..d934eaa0dd 100644 --- a/backend/internal/service/gateway_service.go +++ b/backend/internal/service/gateway_service.go @@ -622,6 +622,8 @@ type ForwardResult struct { FirstTokenMs *int // 首字时间(流式请求) ClientDisconnect bool // 客户端是否在流式传输过程中断开 ReasoningEffort *string + // RequestedReasoningEffort is the client-requested effort before mapping. + RequestedReasoningEffort *string // ServiceTier records the tier requested by the client. OpenAI uses // service_tier; Anthropic speed=fast is normalized to "fast". Usage recording // lowers it to UpstreamResponseServiceTier when the upstream reports a diff --git a/backend/internal/service/gateway_usage_billing.go b/backend/internal/service/gateway_usage_billing.go index 1832dd6d32..4d47720f05 100644 --- a/backend/internal/service/gateway_usage_billing.go +++ b/backend/internal/service/gateway_usage_billing.go @@ -1211,48 +1211,49 @@ func (s *GatewayService) buildRecordUsageLog( ) } usageLog := &UsageLog{ - UserID: user.ID, - APIKeyID: apiKey.ID, - AccountID: account.ID, - RequestID: requestID, - Model: result.Model, - RequestedModel: requestedModel, - UpstreamModel: optionalTrimmedStringPtr(result.UpstreamModel), - UpstreamResponseModel: optionalTrimmedStringPtr(result.UpstreamResponseModel), - UpstreamModelMismatch: upstreamModelMismatch(sentModel, result.UpstreamResponseModel), - ServiceTier: result.ServiceTier, - ReasoningEffort: result.ReasoningEffort, - InboundEndpoint: optionalTrimmedStringPtr(input.InboundEndpoint), - UpstreamEndpoint: optionalTrimmedStringPtr(input.UpstreamEndpoint), - InputTokens: result.Usage.InputTokens, - OutputTokens: result.Usage.OutputTokens, - CacheCreationTokens: result.Usage.CacheCreationInputTokens, - CacheReadTokens: result.Usage.CacheReadInputTokens, - CacheCreation5mTokens: result.Usage.CacheCreation5mTokens, - CacheCreation1hTokens: result.Usage.CacheCreation1hTokens, - ImageOutputTokens: result.Usage.ImageOutputTokens, - RateMultiplier: multiplier, - AccountRateMultiplier: &accountRateMultiplier, - BillingType: billingType, - BillingMode: resolveBillingMode(result, cost), - Stream: result.Stream, - DurationMs: &durationMs, - FirstTokenMs: result.FirstTokenMs, - ImageCount: result.ImageCount, - ImageSize: optionalTrimmedStringPtr(result.ImageSize), - ImageInputSize: optionalTrimmedStringPtr(result.ImageInputSize), - ImageOutputSize: optionalTrimmedStringPtr(result.ImageOutputSize), - ImageSizeSource: optionalTrimmedStringPtr(result.ImageSizeSource), - ImageSizeBreakdown: result.ImageSizeBreakdown, - CacheTTLOverridden: cacheTTLOverridden, - ChannelID: optionalInt64Ptr(input.ChannelID), - ModelMappingChain: optionalTrimmedStringPtr(input.ModelMappingChain), - UserAgent: optionalTrimmedStringPtr(input.UserAgent), - IPAddress: optionalTrimmedStringPtr(input.IPAddress), - SessionID: optionalTrimmedStringPtr(input.SessionID), - GroupID: apiKey.GroupID, - SubscriptionID: optionalSubscriptionID(subscription), - CreatedAt: time.Now(), + UserID: user.ID, + APIKeyID: apiKey.ID, + AccountID: account.ID, + RequestID: requestID, + Model: result.Model, + RequestedModel: requestedModel, + UpstreamModel: optionalTrimmedStringPtr(result.UpstreamModel), + UpstreamResponseModel: optionalTrimmedStringPtr(result.UpstreamResponseModel), + UpstreamModelMismatch: upstreamModelMismatch(sentModel, result.UpstreamResponseModel), + ServiceTier: result.ServiceTier, + ReasoningEffort: result.ReasoningEffort, + RequestedReasoningEffort: coalesceRequestedReasoningEffort(result.RequestedReasoningEffort, result.ReasoningEffort), + InboundEndpoint: optionalTrimmedStringPtr(input.InboundEndpoint), + UpstreamEndpoint: optionalTrimmedStringPtr(input.UpstreamEndpoint), + InputTokens: result.Usage.InputTokens, + OutputTokens: result.Usage.OutputTokens, + CacheCreationTokens: result.Usage.CacheCreationInputTokens, + CacheReadTokens: result.Usage.CacheReadInputTokens, + CacheCreation5mTokens: result.Usage.CacheCreation5mTokens, + CacheCreation1hTokens: result.Usage.CacheCreation1hTokens, + ImageOutputTokens: result.Usage.ImageOutputTokens, + RateMultiplier: multiplier, + AccountRateMultiplier: &accountRateMultiplier, + BillingType: billingType, + BillingMode: resolveBillingMode(result, cost), + Stream: result.Stream, + DurationMs: &durationMs, + FirstTokenMs: result.FirstTokenMs, + ImageCount: result.ImageCount, + ImageSize: optionalTrimmedStringPtr(result.ImageSize), + ImageInputSize: optionalTrimmedStringPtr(result.ImageInputSize), + ImageOutputSize: optionalTrimmedStringPtr(result.ImageOutputSize), + ImageSizeSource: optionalTrimmedStringPtr(result.ImageSizeSource), + ImageSizeBreakdown: result.ImageSizeBreakdown, + CacheTTLOverridden: cacheTTLOverridden, + ChannelID: optionalInt64Ptr(input.ChannelID), + ModelMappingChain: optionalTrimmedStringPtr(input.ModelMappingChain), + UserAgent: optionalTrimmedStringPtr(input.UserAgent), + IPAddress: optionalTrimmedStringPtr(input.IPAddress), + SessionID: optionalTrimmedStringPtr(input.SessionID), + GroupID: apiKey.GroupID, + SubscriptionID: optionalSubscriptionID(subscription), + CreatedAt: time.Now(), } if result.ImageCount > 0 && (cost == nil || cost.BillingMode != string(BillingModeToken)) { usageLog.RateMultiplier = imageMultiplier diff --git a/backend/internal/service/openai_gateway_messages_anthropic_native.go b/backend/internal/service/openai_gateway_messages_anthropic_native.go index a4bc7b9f3a..4fb5c2ec5a 100644 --- a/backend/internal/service/openai_gateway_messages_anthropic_native.go +++ b/backend/internal/service/openai_gateway_messages_anthropic_native.go @@ -61,8 +61,9 @@ func (s *OpenAIGatewayService) forwardAnthropicViaNativeAnthropicEndpoint( // 记录客户端请求的推理强度:优先 Claude 协议的 output_config.effort; // 缺失且 thinking 已启用时,按国产 passback-required 模型兜底为 high // (对齐 Anthropic 网关 gateway_handler 的记录语义,避免该路径长期落 NULL)。 + requestedReasoningEffort := NormalizeClaudeOutputEffort(gjson.GetBytes(body, "output_config.effort").String()) reasoningEffort := ApplyThinkingEnabledFallback( - NormalizeClaudeOutputEffort(gjson.GetBytes(body, "output_config.effort").String()), + requestedReasoningEffort, body, billingModel, ) diff --git a/backend/internal/service/openai_gateway_record_usage_test.go b/backend/internal/service/openai_gateway_record_usage_test.go index 9f9c7b4c6a..c3bca27176 100644 --- a/backend/internal/service/openai_gateway_record_usage_test.go +++ b/backend/internal/service/openai_gateway_record_usage_test.go @@ -1527,6 +1527,8 @@ func TestOpenAIGatewayServiceRecordUsage_UsesRequestedModelAndUpstreamModelMetad require.Equal(t, serviceTier, *usageRepo.lastLog.ServiceTier) require.NotNil(t, usageRepo.lastLog.ReasoningEffort) require.Equal(t, reasoning, *usageRepo.lastLog.ReasoningEffort) + require.NotNil(t, usageRepo.lastLog.RequestedReasoningEffort) + require.Equal(t, reasoning, *usageRepo.lastLog.RequestedReasoningEffort) require.NotNil(t, usageRepo.lastLog.UserAgent) require.Equal(t, "codex-cli/1.0", *usageRepo.lastLog.UserAgent) require.NotNil(t, usageRepo.lastLog.IPAddress) @@ -1536,6 +1538,39 @@ func TestOpenAIGatewayServiceRecordUsage_UsesRequestedModelAndUpstreamModelMetad require.Equal(t, 1, userRepo.deductCalls) } +func TestOpenAIGatewayServiceRecordUsage_PersistsRequestedReasoningEffort(t *testing.T) { + usageRepo := &openAIRecordUsageLogRepoStub{inserted: true} + userRepo := &openAIRecordUsageUserRepoStub{} + subRepo := &openAIRecordUsageSubRepoStub{} + svc := newOpenAIRecordUsageServiceForTest(usageRepo, userRepo, subRepo, nil) + requested := "max" + forwarded := "xhigh" + + err := svc.RecordUsage(context.Background(), &OpenAIRecordUsageInput{ + Result: &OpenAIForwardResult{ + RequestID: "resp_requested_effort", + Model: "gpt-5.4", + ReasoningEffort: &forwarded, + RequestedReasoningEffort: &requested, + Usage: OpenAIUsage{ + InputTokens: 20, + OutputTokens: 10, + }, + Duration: time.Second, + }, + APIKey: &APIKey{ID: 10}, + User: &User{ID: 20}, + Account: &Account{ID: 30}, + }) + + require.NoError(t, err) + require.NotNil(t, usageRepo.lastLog) + require.NotNil(t, usageRepo.lastLog.ReasoningEffort) + require.Equal(t, forwarded, *usageRepo.lastLog.ReasoningEffort) + require.NotNil(t, usageRepo.lastLog.RequestedReasoningEffort) + require.Equal(t, requested, *usageRepo.lastLog.RequestedReasoningEffort) +} + func TestOpenAIGatewayServiceRecordUsage_PreservesChannelMappedUpstreamModel(t *testing.T) { usageRepo := &openAIRecordUsageLogRepoStub{inserted: true} userRepo := &openAIRecordUsageUserRepoStub{} diff --git a/backend/internal/service/openai_gateway_request_body.go b/backend/internal/service/openai_gateway_request_body.go index 6272875cc5..0523937d17 100644 --- a/backend/internal/service/openai_gateway_request_body.go +++ b/backend/internal/service/openai_gateway_request_body.go @@ -1220,6 +1220,65 @@ func extractOpenAIReasoningEffortFromBody(body []byte, modelCandidates ...string return &value } +func explicitRequestedReasoningEffortFromBody(body []byte) string { + raw := strings.TrimSpace(gjson.GetBytes(body, "reasoning.effort").String()) + if raw == "" { + raw = strings.TrimSpace(gjson.GetBytes(body, "reasoning_effort").String()) + } + if raw == "" { + raw = strings.TrimSpace(gjson.GetBytes(body, "output_config.effort").String()) + } + return raw +} + +// CanonicalRequestedReasoningEffort extracts the client-requested effort before +// group policy rewriting and before model-family remapping (max -> xhigh). +// Empty or unknown values return nil. "max" is preserved even for models that +// later persist "xhigh". +func CanonicalRequestedReasoningEffort(body []byte, modelCandidates ...string) *string { + if raw := explicitRequestedReasoningEffortFromBody(body); raw != "" { + canonical := NormalizeMaxReasoningEffort(raw) + if canonical == "" { + return nil + } + return &canonical + } + for _, model := range modelCandidates { + if value := canonicalReasoningEffortFromModelSuffix(model); value != "" { + return &value + } + } + if model := strings.TrimSpace(gjson.GetBytes(body, "model").String()); model != "" { + if value := canonicalReasoningEffortFromModelSuffix(model); value != "" { + return &value + } + } + return nil +} + +func canonicalReasoningEffortFromModelSuffix(model string) string { + if strings.TrimSpace(model) == "" { + return "" + } + modelID := strings.TrimSpace(model) + if strings.Contains(modelID, "/") { + parts := strings.Split(modelID, "/") + modelID = parts[len(parts)-1] + } + parts := strings.FieldsFunc(strings.ToLower(modelID), func(r rune) bool { + switch r { + case '-', '_', ' ': + return true + default: + return false + } + }) + if len(parts) == 0 { + return "" + } + return NormalizeMaxReasoningEffort(parts[len(parts)-1]) +} + func extractOpenAIServiceTier(reqBody map[string]any) *string { if reqBody == nil { return nil @@ -1889,6 +1948,31 @@ func extractOpenAIReasoningEffort(reqBody map[string]any, modelCandidates ...str return &value } +func CanonicalRequestedReasoningEffortFromReqBody(reqBody map[string]any, modelCandidates ...string) *string { + if reqBody == nil { + return CanonicalRequestedReasoningEffort(nil, modelCandidates...) + } + raw := "" + if reasoning, ok := reqBody["reasoning"].(map[string]any); ok { + if effort, ok := reasoning["effort"].(string); ok { + raw = strings.TrimSpace(effort) + } + } + if raw == "" { + if effort, ok := reqBody["reasoning_effort"].(string); ok { + raw = strings.TrimSpace(effort) + } + } + if raw != "" { + canonical := NormalizeMaxReasoningEffort(raw) + if canonical == "" { + return nil + } + return &canonical + } + return CanonicalRequestedReasoningEffort(nil, modelCandidates...) +} + func normalizeOpenAIReasoningEffort(raw string) string { value := strings.ToLower(strings.TrimSpace(raw)) if value == "" { diff --git a/backend/internal/service/openai_gateway_service.go b/backend/internal/service/openai_gateway_service.go index c4d085b024..621de5c257 100644 --- a/backend/internal/service/openai_gateway_service.go +++ b/backend/internal/service/openai_gateway_service.go @@ -256,11 +256,15 @@ type OpenAIForwardResult struct { // ServiceTier 优先取上游实际响应回显的 tier;缺失时回退到最终出站 body 的 // tier。nil 表示两者都无识别 tier。 ServiceTier *string - // ReasoningEffort is extracted from request body (reasoning.effort) or derived from model suffix. + // ReasoningEffort is extracted from request body (reasoning.effort) or derived from model suffix + // after group policy rewriting and model-family remapping. // Stored for usage records display; nil means not provided / not applicable. ReasoningEffort *string - Stream bool - OpenAIWSMode bool + // RequestedReasoningEffort is the client-requested effort before mapping. + // Empty/nil means it should fall back to ReasoningEffort at persistence. + RequestedReasoningEffort *string + Stream bool + OpenAIWSMode bool // UpstreamTerminalEvent is the normalized terminal event observed on an // upstream Responses WebSocket turn. Empty preserves legacy/non-WS success. UpstreamTerminalEvent string diff --git a/backend/internal/service/openai_gateway_usage.go b/backend/internal/service/openai_gateway_usage.go index 7489456bb8..d6579b2068 100644 --- a/backend/internal/service/openai_gateway_usage.go +++ b/backend/internal/service/openai_gateway_usage.go @@ -321,31 +321,32 @@ func (s *OpenAIGatewayService) RecordUsage(ctx context.Context, input *OpenAIRec } usageLog := &UsageLog{ - UserID: user.ID, - APIKeyID: apiKey.ID, - AccountID: account.ID, - RequestID: requestID, - Model: result.Model, - RequestedModel: requestedModel, - UpstreamModel: optionalTrimmedStringPtr(result.UpstreamModel), - UpstreamResponseModel: optionalTrimmedStringPtr(result.UpstreamResponseModel), - UpstreamModelMismatch: upstreamModelMismatch(sentModel, result.UpstreamResponseModel), - ServiceTier: result.ServiceTier, - ReasoningEffort: result.ReasoningEffort, - InboundEndpoint: optionalTrimmedStringPtr(input.InboundEndpoint), - UpstreamEndpoint: optionalTrimmedStringPtr(input.UpstreamEndpoint), - InputTokens: actualInputTokens, - OutputTokens: result.Usage.OutputTokens, - CacheCreationTokens: result.Usage.CacheCreationInputTokens, - CacheReadTokens: result.Usage.CacheReadInputTokens, - ImageInputTokens: result.Usage.ImageInputTokens, - ImageOutputTokens: result.Usage.ImageOutputTokens, - ImageCount: result.ImageCount, - ImageSize: optionalTrimmedStringPtr(result.ImageSize), - ImageInputSize: optionalTrimmedStringPtr(result.ImageInputSize), - ImageOutputSize: optionalTrimmedStringPtr(result.ImageOutputSize), - ImageSizeSource: optionalTrimmedStringPtr(result.ImageSizeSource), - ImageSizeBreakdown: result.ImageSizeBreakdown, + UserID: user.ID, + APIKeyID: apiKey.ID, + AccountID: account.ID, + RequestID: requestID, + Model: result.Model, + RequestedModel: requestedModel, + UpstreamModel: optionalTrimmedStringPtr(result.UpstreamModel), + UpstreamResponseModel: optionalTrimmedStringPtr(result.UpstreamResponseModel), + UpstreamModelMismatch: upstreamModelMismatch(sentModel, result.UpstreamResponseModel), + ServiceTier: result.ServiceTier, + ReasoningEffort: result.ReasoningEffort, + RequestedReasoningEffort: coalesceRequestedReasoningEffort(result.RequestedReasoningEffort, result.ReasoningEffort), + InboundEndpoint: optionalTrimmedStringPtr(input.InboundEndpoint), + UpstreamEndpoint: optionalTrimmedStringPtr(input.UpstreamEndpoint), + InputTokens: actualInputTokens, + OutputTokens: result.Usage.OutputTokens, + CacheCreationTokens: result.Usage.CacheCreationInputTokens, + CacheReadTokens: result.Usage.CacheReadInputTokens, + ImageInputTokens: result.Usage.ImageInputTokens, + ImageOutputTokens: result.Usage.ImageOutputTokens, + ImageCount: result.ImageCount, + ImageSize: optionalTrimmedStringPtr(result.ImageSize), + ImageInputSize: optionalTrimmedStringPtr(result.ImageInputSize), + ImageOutputSize: optionalTrimmedStringPtr(result.ImageOutputSize), + ImageSizeSource: optionalTrimmedStringPtr(result.ImageSizeSource), + ImageSizeBreakdown: result.ImageSizeBreakdown, } isVideoUsage := isGrokVideoUsageResult(result, billingModels) if isVideoUsage { diff --git a/backend/internal/service/openai_reasoning_effort_policy.go b/backend/internal/service/openai_reasoning_effort_policy.go index 73453c2260..17432e49c7 100644 --- a/backend/internal/service/openai_reasoning_effort_policy.go +++ b/backend/internal/service/openai_reasoning_effort_policy.go @@ -17,6 +17,7 @@ const ( var openAIReasoningEffortValues = []string{"minimal", "low", "medium", "high", "xhigh", "max"} type openAIReasoningEffortPolicyContextKey struct{} +type requestedReasoningEffortContextKey struct{} type openAIReasoningEffortPolicy struct { maxEffort string @@ -136,6 +137,36 @@ func NormalizeReasoningEffortMappings(platform string, raw []ReasoningEffortMapp return normalized, nil } +// WithRequestedReasoningEffort stores the client-requested effort captured from +// the inbound body before group policy or model-family remapping. +func WithRequestedReasoningEffort(ctx context.Context, effort string) context.Context { + if ctx == nil { + ctx = context.Background() + } + effort = strings.TrimSpace(effort) + if effort == "" { + return ctx + } + return context.WithValue(ctx, requestedReasoningEffortContextKey{}, effort) +} + +// RequestedReasoningEffortFromContext returns the inbound requested effort bound +// to ctx, or nil when none was captured. +func RequestedReasoningEffortFromContext(ctx context.Context) *string { + if ctx == nil { + return nil + } + value, ok := ctx.Value(requestedReasoningEffortContextKey{}).(string) + if !ok { + return nil + } + value = strings.TrimSpace(value) + if value == "" { + return nil + } + return &value +} + // WithOpenAIReasoningEffortPolicy binds a group policy to a request after its // concrete target platform has been resolved to OpenAI. The policy is copied so // retries and asynchronous forwarding cannot observe later slice mutations. diff --git a/backend/internal/service/openai_reasoning_effort_policy_test.go b/backend/internal/service/openai_reasoning_effort_policy_test.go index 4b501f48db..2ef836cc31 100644 --- a/backend/internal/service/openai_reasoning_effort_policy_test.go +++ b/backend/internal/service/openai_reasoning_effort_policy_test.go @@ -8,6 +8,34 @@ import ( "github.com/tidwall/gjson" ) +func TestCanonicalRequestedReasoningEffort(t *testing.T) { + t.Parallel() + + max := CanonicalRequestedReasoningEffort([]byte(`{"model":"gpt-5.4","reasoning":{"effort":"MAX"}}`), "gpt-5.4") + require.NotNil(t, max) + require.Equal(t, "max", *max) + + fromSuffix := CanonicalRequestedReasoningEffort([]byte(`{"model":"gpt-5.4-max"}`), "gpt-5.4-max") + require.NotNil(t, fromSuffix) + require.Equal(t, "max", *fromSuffix) + + claude := CanonicalRequestedReasoningEffort([]byte(`{"model":"claude-sonnet-4","output_config":{"effort":"high"}}`)) + require.NotNil(t, claude) + require.Equal(t, "high", *claude) + + require.Nil(t, CanonicalRequestedReasoningEffort([]byte(`{"model":"gpt-5.4"}`), "gpt-5.4")) +} + +func TestRequestedReasoningEffortContext(t *testing.T) { + t.Parallel() + + require.Nil(t, RequestedReasoningEffortFromContext(context.Background())) + ctx := WithRequestedReasoningEffort(context.Background(), " max ") + got := RequestedReasoningEffortFromContext(ctx) + require.NotNil(t, got) + require.Equal(t, "max", *got) +} + func TestNormalizeMaxReasoningEffort(t *testing.T) { tests := []struct { name string diff --git a/backend/internal/service/openai_ws_forwarder_ingress.go b/backend/internal/service/openai_ws_forwarder_ingress.go index 8dbb5b1abb..aff0a5d067 100644 --- a/backend/internal/service/openai_ws_forwarder_ingress.go +++ b/backend/internal/service/openai_ws_forwarder_ingress.go @@ -194,6 +194,7 @@ func (s *OpenAIGatewayService) ProxyResponsesWebSocketFromClient( imageSizeTier string imageInputSize string payloadBytes int + requestedReasoningEffort *string } ingressSessionOriginalModel := "" @@ -257,6 +258,7 @@ func (s *OpenAIGatewayService) ProxyResponsesWebSocketFromClient( nil, ) } + requestedReasoningEffort := CanonicalRequestedReasoningEffort(normalized, strings.TrimSpace(values[1].String())) if hooks != nil && (hooks.MaxReasoningEffort != "" || len(hooks.ReasoningEffortMappings) > 0) { if capped, changed := ApplyOpenAIReasoningEffortPolicy(normalized, hooks.MaxReasoningEffort, hooks.ReasoningEffortMappings); changed { normalized = capped @@ -473,6 +475,7 @@ func (s *OpenAIGatewayService) ProxyResponsesWebSocketFromClient( imageSizeTier: imageSizeTier, imageInputSize: imageInputSize, payloadBytes: len(normalized), + requestedReasoningEffort: requestedReasoningEffort, }, nil } @@ -909,7 +912,7 @@ func (s *OpenAIGatewayService) ProxyResponsesWebSocketFromClient( } var rejectedFieldRetryState *openAIResponsesRejectedFieldRetryState - sendAndRelay := func(turn int, lease *openAIWSConnLease, payload []byte, payloadBytes int, originalModel string, imageBillingModel string, imageSizeTier string, imageInputSize string) (*OpenAIForwardResult, error) { + sendAndRelay := func(turn int, lease *openAIWSConnLease, payload []byte, payloadBytes int, originalModel string, imageBillingModel string, imageSizeTier string, imageInputSize string, requestedReasoningEffort *string) (*OpenAIForwardResult, error) { responseModelObserver := &upstreamResponseModelObserver{} if lease == nil { return nil, errors.New("upstream websocket lease is nil") @@ -1180,6 +1183,7 @@ func (s *OpenAIGatewayService) ProxyResponsesWebSocketFromClient( UpstreamResponseServiceTier: responseModelObserver.ServiceTier(), ServiceTier: resolvedOpenAIUpstreamServiceTierFromObserver(responseModelObserver, extractOpenAIServiceTierFromBody(payload)), ReasoningEffort: ApplyThinkingEnabledFallback(extractOpenAIReasoningEffortFromBody(payload, mappedModel, originalModel), payload, mappedModel), + RequestedReasoningEffort: requestedReasoningEffort, Stream: reqStream, OpenAIWSMode: true, UpstreamTerminalEvent: terminalEvent, @@ -1209,6 +1213,7 @@ func (s *OpenAIGatewayService) ProxyResponsesWebSocketFromClient( currentImageSizeTier := firstPayload.imageSizeTier currentImageInputSize := firstPayload.imageInputSize currentPayloadBytes := firstPayload.payloadBytes + currentRequestedReasoningEffort := firstPayload.requestedReasoningEffort isStrictAffinityTurn := func(payload []byte) bool { if !storeDisabled { return false @@ -1697,7 +1702,7 @@ func (s *OpenAIGatewayService) ProxyResponsesWebSocketFromClient( ) } - result, relayErr := sendAndRelay(turn, sessionLease, currentPayload, currentPayloadBytes, currentOriginalModel, currentImageBillingModel, currentImageSizeTier, currentImageInputSize) + result, relayErr := sendAndRelay(turn, sessionLease, currentPayload, currentPayloadBytes, currentOriginalModel, currentImageBillingModel, currentImageSizeTier, currentImageInputSize, currentRequestedReasoningEffort) if relayErr != nil { lastTurnClean = false if isOpenAIWSSessionPreempted(ctx) { @@ -1859,6 +1864,7 @@ func (s *OpenAIGatewayService) ProxyResponsesWebSocketFromClient( currentImageSizeTier = nextPayload.imageSizeTier currentImageInputSize = nextPayload.imageInputSize currentPayloadBytes = nextPayload.payloadBytes + currentRequestedReasoningEffort = nextPayload.requestedReasoningEffort rejectedFieldRetryState = newOpenAIResponsesRejectedFieldRetryState(currentPayload) storeDisabled = s.isOpenAIWSStoreDisabledInRequestRaw(currentPayload, account) if !storeDisabled { diff --git a/backend/internal/service/openai_ws_forwarder_v2.go b/backend/internal/service/openai_ws_forwarder_v2.go index 7702ebe797..f977edc558 100644 --- a/backend/internal/service/openai_ws_forwarder_v2.go +++ b/backend/internal/service/openai_ws_forwarder_v2.go @@ -784,6 +784,7 @@ func (s *OpenAIGatewayService) forwardOpenAIWSV2( ImageOutputSizes: imageCounter.Sizes(), ServiceTier: resolvedOpenAIUpstreamServiceTierFromObserver(responseModelObserver, extractOpenAIServiceTier(reqBody)), ReasoningEffort: extractOpenAIReasoningEffort(reqBody, mappedModel, originalModel), + RequestedReasoningEffort: CanonicalRequestedReasoningEffortFromReqBody(reqBody, originalModel, mappedModel), Stream: reqStream, OpenAIWSMode: true, UpstreamTerminalEvent: upstreamTerminalEvent, diff --git a/backend/internal/service/openai_ws_http_bridge.go b/backend/internal/service/openai_ws_http_bridge.go index 2bb0c200b5..8993e89735 100644 --- a/backend/internal/service/openai_ws_http_bridge.go +++ b/backend/internal/service/openai_ws_http_bridge.go @@ -525,6 +525,7 @@ func (s *OpenAIGatewayService) proxyOpenAIWSHTTPBridgeTurn( UpstreamResponseServiceTier: responseModelObserver.ServiceTier(), ServiceTier: resolvedOpenAIUpstreamServiceTierFromObserver(responseModelObserver, extractOpenAIServiceTierFromBody(body)), ReasoningEffort: ApplyThinkingEnabledFallback(extractOpenAIReasoningEffortFromBody(body, mappedModel, originalModel), body, mappedModel), + RequestedReasoningEffort: CanonicalRequestedReasoningEffort(body, originalModel, mappedModel), Stream: reqStream, OpenAIWSMode: true, UpstreamTerminalEvent: upstreamTerminalEvent, diff --git a/backend/internal/service/openai_ws_v2_passthrough_adapter.go b/backend/internal/service/openai_ws_v2_passthrough_adapter.go index 60e7b41416..6fd9dfb50d 100644 --- a/backend/internal/service/openai_ws_v2_passthrough_adapter.go +++ b/backend/internal/service/openai_ws_v2_passthrough_adapter.go @@ -133,10 +133,11 @@ func openAIWSPassthroughPolicyModelFromSessionFrame(account *Account, payload [] } type openAIWSPassthroughUsageMeta struct { - serviceTier atomic.Pointer[string] - reasoningEffort atomic.Pointer[string] - requestModel atomic.Pointer[string] - upstreamModel atomic.Pointer[string] + serviceTier atomic.Pointer[string] + reasoningEffort atomic.Pointer[string] + requestedReasoningEffort atomic.Pointer[string] + requestModel atomic.Pointer[string] + upstreamModel atomic.Pointer[string] // 仅在 client->upstream filter goroutine 中读写;Load 侧通过上方原子指针同步。 sessionRequestModel string @@ -161,6 +162,14 @@ func (m *openAIWSPassthroughUsageMeta) initFromFirstFrame(policyOutput []byte, m m.storeTurnModels(m.sessionRequestModel, policyOutput) } +func (m *openAIWSPassthroughUsageMeta) captureRequestedReasoningEffort(originalBody []byte, modelCandidates ...string) { + if m == nil { + return + } + candidates := append([]string{m.sessionRequestModel}, modelCandidates...) + m.requestedReasoningEffort.Store(CanonicalRequestedReasoningEffort(originalBody, candidates...)) +} + func (m *openAIWSPassthroughUsageMeta) updateSessionRequestModel(payload []byte) { if m == nil { return @@ -686,6 +695,7 @@ func (s *OpenAIGatewayService) proxyResponsesWebSocketV2Passthrough( } firstClientMessage = liteFirstMessage } + originalFirstClientMessage := firstClientMessage if hooks != nil && (hooks.MaxReasoningEffort != "" || len(hooks.ReasoningEffortMappings) > 0) { if capped, changed := ApplyOpenAIReasoningEffortPolicy(firstClientMessage, hooks.MaxReasoningEffort, hooks.ReasoningEffortMappings); changed { firstClientMessage = capped @@ -796,6 +806,7 @@ func (s *OpenAIGatewayService) proxyResponsesWebSocketV2Passthrough( // goroutine)和 OnTurnComplete / final result(runUpstreamToClient // goroutine)之间同步当前 turn 的 usage metadata。 usageMeta.initFromFirstFrame(firstClientMessage, capturedSessionModel) + usageMeta.captureRequestedReasoningEffort(originalFirstClientMessage, capturedSessionModel) _, initialUpstreamModel := usageMeta.turnModels(initialRequestModel) SetOpsUpstreamModel(c, initialUpstreamModel) wsURL, err := s.buildOpenAIResponsesWSURL(account) @@ -1020,11 +1031,13 @@ func (s *OpenAIGatewayService) proxyResponsesWebSocketV2Passthrough( } payload = litePayload } + originalResponseCreate := payload if hooks != nil && (hooks.MaxReasoningEffort != "" || len(hooks.ReasoningEffortMappings) > 0) { if capped, changed := ApplyOpenAIReasoningEffortPolicy(payload, hooks.MaxReasoningEffort, hooks.ReasoningEffortMappings); changed { payload = capped } } + usageMeta.captureRequestedReasoningEffort(originalResponseCreate) } turnNo := int(completedTurns.Load()) + 1 if turnNo < 2 { @@ -1201,6 +1214,7 @@ func (s *OpenAIGatewayService) proxyResponsesWebSocketV2Passthrough( UpstreamResponseServiceTier: normalizeObservedOpenAIServiceTier(turn.ResponseServiceTier), ServiceTier: usageMeta.serviceTier.Load(), ReasoningEffort: usageMeta.reasoningEffort.Load(), + RequestedReasoningEffort: usageMeta.requestedReasoningEffort.Load(), Stream: true, OpenAIWSMode: true, UpstreamTerminalEvent: normalizeOpenAIWSTerminalEvent(turn.TerminalEventType), @@ -1327,6 +1341,7 @@ func (s *OpenAIGatewayService) proxyResponsesWebSocketV2Passthrough( UpstreamResponseServiceTier: normalizeObservedOpenAIServiceTier(relayResult.ResponseServiceTier), ServiceTier: usageMeta.serviceTier.Load(), ReasoningEffort: usageMeta.reasoningEffort.Load(), + RequestedReasoningEffort: usageMeta.requestedReasoningEffort.Load(), Stream: true, OpenAIWSMode: true, UpstreamTerminalEvent: normalizeOpenAIWSTerminalEvent(relayResult.TerminalEventType), diff --git a/backend/internal/service/openai_ws_v2_passthrough_adapter_effort_test.go b/backend/internal/service/openai_ws_v2_passthrough_adapter_effort_test.go index 82c9eaac85..5d337257e0 100644 --- a/backend/internal/service/openai_ws_v2_passthrough_adapter_effort_test.go +++ b/backend/internal/service/openai_ws_v2_passthrough_adapter_effort_test.go @@ -24,10 +24,14 @@ func TestWSPassthroughUsageMeta_InitFromFirstFrame_NonGPT56FallsBackToXHigh(t *t meta := newOpenAIWSPassthroughUsageMeta("gpt-5.4", body) meta.initFromFirstFrame(body, "gpt-5.4") + meta.captureRequestedReasoningEffort(body, "gpt-5.4") got := meta.reasoningEffort.Load() require.NotNil(t, got) require.Equal(t, "xhigh", *got, "non-5.6 model should normalize max to xhigh") + requested := meta.requestedReasoningEffort.Load() + require.NotNil(t, requested) + require.Equal(t, "max", *requested, "usage should keep the pre-mapping requested effort") } func TestWSPassthroughUsageMeta_UpdateFromResponseCreate_MappedModelCandidate(t *testing.T) { diff --git a/backend/internal/service/usage_log.go b/backend/internal/service/usage_log.go index b6dc2a9d0e..3808d1f467 100644 --- a/backend/internal/service/usage_log.go +++ b/backend/internal/service/usage_log.go @@ -131,10 +131,14 @@ type UsageLog struct { // ServiceTier records the billable request tier, e.g. OpenAI "priority" / "flex" // or Anthropic "fast". ServiceTier *string - // ReasoningEffort is the request's reasoning effort level. + // ReasoningEffort is the effective effort recorded for this request after + // group policy rewriting and model-family remapping (e.g. max -> xhigh). // OpenAI: "low" / "medium" / "high" / "xhigh"; Claude: "low" / "medium" / "high" / "max". // Nil means not provided / not applicable. ReasoningEffort *string + // RequestedReasoningEffort is the client-requested effort before mapping. + // Nil means historical rows, or that no explicit/suffix-derived effort was observed. + RequestedReasoningEffort *string // InboundEndpoint is the client-facing API endpoint path, e.g. /v1/chat/completions. InboundEndpoint *string // UpstreamEndpoint is the normalized upstream endpoint path, e.g. /v1/responses. diff --git a/backend/internal/service/usage_log_helpers.go b/backend/internal/service/usage_log_helpers.go index deb102e736..dda3099070 100644 --- a/backend/internal/service/usage_log_helpers.go +++ b/backend/internal/service/usage_log_helpers.go @@ -17,6 +17,18 @@ func optionalStringValue(value *string) string { return strings.TrimSpace(*value) } +// coalesceRequestedReasoningEffort prefers the client-requested value and falls +// back to the effective/forwarded effort for historical or unmapped rows. +func coalesceRequestedReasoningEffort(requested, forwarded *string) *string { + if trimmed := optionalStringValue(requested); trimmed != "" { + return &trimmed + } + if trimmed := optionalStringValue(forwarded); trimmed != "" { + return &trimmed + } + return nil +} + func forwardResultBillingModel(requestedModel, upstreamModel string) string { if trimmed := strings.TrimSpace(requestedModel); trimmed != "" { return trimmed diff --git a/backend/migrations/231_add_usage_log_requested_reasoning_effort.sql b/backend/migrations/231_add_usage_log_requested_reasoning_effort.sql new file mode 100644 index 0000000000..8f35a714cf --- /dev/null +++ b/backend/migrations/231_add_usage_log_requested_reasoning_effort.sql @@ -0,0 +1,7 @@ +-- Persist the client-requested reasoning effort before group policy rewriting +-- and model-family remapping (e.g. max -> xhigh). NULL means historical rows +-- written before this dual-write, or requests that never declared an effort. +-- +-- Nullable with no default: on PostgreSQL 11+ this is a metadata-only change +-- and does not rewrite the (potentially large, partitioned) usage_logs table. +ALTER TABLE usage_logs ADD COLUMN IF NOT EXISTS requested_reasoning_effort VARCHAR(20); diff --git a/frontend/src/components/admin/usage/UsageTable.vue b/frontend/src/components/admin/usage/UsageTable.vue index f7f619dbb4..dac6098e57 100644 --- a/frontend/src/components/admin/usage/UsageTable.vue +++ b/frontend/src/components/admin/usage/UsageTable.vue @@ -91,8 +91,16 @@ @@ -500,7 +508,7 @@ import { computed, ref } from 'vue' import { useI18n } from 'vue-i18n' import { useAppStore } from '@/stores/app' -import { formatDateTime, formatReasoningEffort } from '@/utils/format' +import { formatDateTime, formatReasoningEffort, reasoningEffortValuesEqual } from '@/utils/format' import { formatCacheTokens, formatMultiplier } from '@/utils/formatters' import { formatTokenPricePerMillion } from '@/utils/usagePricing' import { getUsageServiceTierLabel } from '@/utils/usageServiceTier' @@ -587,6 +595,12 @@ const ipGeoBatchLoading = ref(false) const showIpGeoToolbar = computed(() => props.columns.some((col) => col.key === 'ip_address')) +const hasReasoningEffortMapping = (row: AdminUsageLog): boolean => { + const requested = row.requested_reasoning_effort?.trim() || '' + const forwarded = row.reasoning_effort?.trim() || '' + return requested !== '' && forwarded !== '' && !reasoningEffortValuesEqual(requested, forwarded) +} + const sentUpstreamModel = (row: AdminUsageLog): string => row.upstream_model?.trim() || row.model?.trim() || '' const normalizeModelVariant = (model: string): string => model diff --git a/frontend/src/components/admin/usage/__tests__/UsageTable.spec.ts b/frontend/src/components/admin/usage/__tests__/UsageTable.spec.ts index 56c0932108..a8bf2df1db 100644 --- a/frontend/src/components/admin/usage/__tests__/UsageTable.spec.ts +++ b/frontend/src/components/admin/usage/__tests__/UsageTable.spec.ts @@ -84,6 +84,7 @@ const DataTableStub = {
+ @@ -256,6 +257,61 @@ describe('admin UsageTable tooltip', () => { expect(text).toContain('claude-sonnet-4-20250514') }) + it('shows requested and forwarded reasoning effort separately when they differ', () => { + const wrapper = mount(UsageTable, { + props: { + data: [{ + request_id: 'req-admin-effort-1', + model: 'gpt-5.4', + requested_reasoning_effort: 'max', + reasoning_effort: 'xhigh', + }], + loading: false, + columns: [], + }, + global: { + stubs: { + DataTable: DataTableStub, + EmptyState: true, + Icon: true, + Teleport: true, + }, + }, + }) + + const text = wrapper.text() + expect(text).toContain('Max') + expect(text).toContain('XHigh') + expect(text).toContain('↳') + }) + + it('shows a single reasoning effort when requested matches forwarded', () => { + const wrapper = mount(UsageTable, { + props: { + data: [{ + request_id: 'req-admin-effort-2', + model: 'gpt-5.6-sol', + requested_reasoning_effort: 'max', + reasoning_effort: 'max', + }], + loading: false, + columns: [], + }, + global: { + stubs: { + DataTable: DataTableStub, + EmptyState: true, + Icon: true, + Teleport: true, + }, + }, + }) + + const text = wrapper.text() + expect(text).toContain('Max') + expect(text).not.toContain('↳') + }) + it.each([ { name: 'possible version variant', @@ -561,6 +617,7 @@ const DataTableStubWithUser = {
+ diff --git a/frontend/src/i18n/locales/en/dashboard.ts b/frontend/src/i18n/locales/en/dashboard.ts index 65fa9f480c..30e9e80595 100644 --- a/frontend/src/i18n/locales/en/dashboard.ts +++ b/frontend/src/i18n/locales/en/dashboard.ts @@ -309,6 +309,7 @@ export default { modelVariant: 'Possible version variant', modelMismatch: 'Different model', reasoningEffort: 'Reasoning Effort', + requestedReasoningEffort: 'Requested reasoning effort', endpoint: 'Endpoint', endpointDistribution: 'Endpoint Distribution', inbound: 'Inbound', diff --git a/frontend/src/i18n/locales/zh/dashboard.ts b/frontend/src/i18n/locales/zh/dashboard.ts index 044c2e1bf0..d0fb902c71 100644 --- a/frontend/src/i18n/locales/zh/dashboard.ts +++ b/frontend/src/i18n/locales/zh/dashboard.ts @@ -314,6 +314,7 @@ export default { modelVariant: '疑似版本变体', modelMismatch: '模型不一致', reasoningEffort: '推理强度', + requestedReasoningEffort: '请求推理强度', endpoint: '端点', endpointDistribution: '端点分布', inbound: '入站', diff --git a/frontend/src/types/index.ts b/frontend/src/types/index.ts index 10a72a0a17..21b2f31729 100644 --- a/frontend/src/types/index.ts +++ b/frontend/src/types/index.ts @@ -1639,6 +1639,7 @@ export interface UsageLog { model: string service_tier?: string | null reasoning_effort?: string | null + requested_reasoning_effort?: string | null inbound_endpoint?: string | null upstream_endpoint?: string | null diff --git a/frontend/src/utils/__tests__/formatReasoningEffort.spec.ts b/frontend/src/utils/__tests__/formatReasoningEffort.spec.ts new file mode 100644 index 0000000000..aaac5d156c --- /dev/null +++ b/frontend/src/utils/__tests__/formatReasoningEffort.spec.ts @@ -0,0 +1,33 @@ +import { describe, expect, it } from 'vitest' +import { + formatReasoningEffort, + formatReasoningEffortMapping, + reasoningEffortValuesEqual, +} from '@/utils/format' + +describe('formatReasoningEffort', () => { + it('title-cases known effort values', () => { + expect(formatReasoningEffort('max')).toBe('Max') + expect(formatReasoningEffort('x-high')).toBe('XHigh') + expect(formatReasoningEffort(null)).toBe('-') + }) +}) + +describe('formatReasoningEffortMapping', () => { + it('shows a single value when requested and forwarded match', () => { + expect(formatReasoningEffortMapping('max', 'max')).toBe('Max') + expect(formatReasoningEffortMapping(null, 'high')).toBe('High') + }) + + it('shows requested then forwarded when mapping changed the value', () => { + expect(formatReasoningEffortMapping('max', 'xhigh')).toBe('Max → XHigh') + expect(formatReasoningEffortMapping('high', 'medium')).toBe('High → Medium') + }) +}) + +describe('reasoningEffortValuesEqual', () => { + it('treats x-high aliases as equal', () => { + expect(reasoningEffortValuesEqual('x-high', 'xhigh')).toBe(true) + expect(reasoningEffortValuesEqual('max', 'xhigh')).toBe(false) + }) +}) diff --git a/frontend/src/utils/format.ts b/frontend/src/utils/format.ts index 787bd4b545..17ba82e098 100644 --- a/frontend/src/utils/format.ts +++ b/frontend/src/utils/format.ts @@ -211,11 +211,15 @@ export function parseDateTimeLocalInput(value: string): number | null { * @param effort 原始 effort(如 "low" / "medium" / "high" / "xhigh") * @returns 格式化后的字符串(Low / Medium / High / Xhigh),无值返回 "-" */ +function normalizeReasoningEffortKey(effort: string | null | undefined): string { + return (effort ?? '').toString().trim().toLowerCase().replace(/[-_\s]/g, '') +} + export function formatReasoningEffort(effort: string | null | undefined): string { const raw = (effort ?? '').toString().trim() if (!raw) return '-' - const normalized = raw.toLowerCase().replace(/[-_\s]/g, '') + const normalized = normalizeReasoningEffortKey(raw) switch (normalized) { case 'low': return 'Low' @@ -237,6 +241,31 @@ export function formatReasoningEffort(effort: string | null | undefined): string } } +export function reasoningEffortValuesEqual( + left: string | null | undefined, + right: string | null | undefined, +): boolean { + const a = normalizeReasoningEffortKey(left) + const b = normalizeReasoningEffortKey(right) + if (!a && !b) return true + return a !== '' && a === b +} + +/** Requested vs forwarded effort for usage export; one value when they match. */ +export function formatReasoningEffortMapping( + requested: string | null | undefined, + forwarded: string | null | undefined, +): string { + const requestedLabel = formatReasoningEffort(requested) + const forwardedLabel = formatReasoningEffort(forwarded) + if (requestedLabel === '-' && forwardedLabel === '-') return '-' + if (requestedLabel === '-' || reasoningEffortValuesEqual(requested, forwarded)) { + return forwardedLabel === '-' ? requestedLabel : forwardedLabel + } + if (forwardedLabel === '-') return requestedLabel + return `${requestedLabel} → ${forwardedLabel}` +} + /** * 格式化时间(显示时分秒) * @param date 日期字符串或 Date 对象 diff --git a/frontend/src/views/admin/UsageView.vue b/frontend/src/views/admin/UsageView.vue index b598f610ab..1e5967dafb 100644 --- a/frontend/src/views/admin/UsageView.vue +++ b/frontend/src/views/admin/UsageView.vue @@ -575,7 +575,7 @@ const exportToExcel = async () => { const XLSX = await import('xlsx') const headers = [ t('usage.time'), t('admin.usage.user'), t('usage.apiKeyFilter'), - t('admin.usage.account'), t('usage.requestedModel'), t('usage.sentUpstreamModel'), t('usage.upstreamResponseModel'), t('usage.upstreamModelMismatch'), t('usage.reasoningEffort'), t('admin.usage.group'), + t('admin.usage.account'), t('usage.requestedModel'), t('usage.sentUpstreamModel'), t('usage.upstreamResponseModel'), t('usage.upstreamModelMismatch'), t('usage.requestedReasoningEffort'), t('usage.reasoningEffort'), t('admin.usage.group'), t('usage.inboundEndpoint'), t('usage.upstreamEndpoint'), t('usage.type'), t('admin.usage.inputTokens'), t('admin.usage.outputTokens'), @@ -595,7 +595,7 @@ const exportToExcel = async () => { if (c.signal.aborted) break; if (p === 1) { total = res.total; exportProgress.total = total } const rows = (res.items || []).map((log: AdminUsageLog) => [ log.created_at, log.user?.email || '', log.api_key?.name || '', log.account?.name || '', log.model, - log.upstream_model || log.model, log.upstream_response_model || '', log.upstream_model_mismatch == null ? '' : t(log.upstream_model_mismatch ? 'common.yes' : 'common.no'), formatReasoningEffort(log.reasoning_effort), log.group?.name || '', + log.upstream_model || log.model, log.upstream_response_model || '', log.upstream_model_mismatch == null ? '' : t(log.upstream_model_mismatch ? 'common.yes' : 'common.no'), formatReasoningEffort(log.requested_reasoning_effort || log.reasoning_effort), formatReasoningEffort(log.reasoning_effort), log.group?.name || '', log.inbound_endpoint || '', log.upstream_endpoint || '', getRequestTypeLabel(log), log.input_tokens, log.output_tokens, log.cache_read_tokens, log.cache_creation_tokens, log.input_cost?.toFixed(6) || '0.000000', log.output_cost?.toFixed(6) || '0.000000', diff --git a/frontend/src/views/user/UsageView.vue b/frontend/src/views/user/UsageView.vue index d836936a5a..bf536821f7 100644 --- a/frontend/src/views/user/UsageView.vue +++ b/frontend/src/views/user/UsageView.vue @@ -230,7 +230,7 @@ import TokenUsageTrend from '@/components/charts/TokenUsageTrend.vue' import Icon from '@/components/icons/Icon.vue' import UserErrorRequestsTable from '@/components/user/UserErrorRequestsTable.vue' import { getPersistedPageSize } from '@/composables/usePersistedPageSize' -import { formatReasoningEffort } from '@/utils/format' +import { formatReasoningEffortMapping } from '@/utils/format' import { getBillingModeLabel, getDisplayBillingMode as resolveDisplayBillingMode } from '@/utils/billingMode' import { resolveUsageRequestType, requestTypeToLegacyStream } from '@/utils/usageRequestType' import type { @@ -658,7 +658,7 @@ const exportToCSV = async () => { log.created_at, log.api_key?.name || '', log.model, - formatReasoningEffort(log.reasoning_effort), + formatReasoningEffortMapping(log.requested_reasoning_effort, log.reasoning_effort), log.inbound_endpoint || '', log.ip_address || '', getRequestTypeExportText(log), From 5705f4a4aab54a4d12f140cf30cd595ee9c7bcd9 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=88=98=E4=BD=B3=E6=9E=97?= Date: Tue, 25 Aug 2026 15:36:22 +0800 Subject: [PATCH 172/204] fix(usage): hide mapped reasoning effort from users Users only see the reasoning effort they requested. Admins still see the requested value plus the forwarded mapped value, matching the model column's requested vs upstream split. --- backend/internal/handler/dto/mappers.go | 59 +++++++++++++++---- .../handler/dto/mappers_usage_test.go | 44 +++++++++++--- backend/internal/handler/dto/types.go | 8 ++- .../src/components/admin/usage/UsageTable.vue | 10 ++-- .../admin/usage/__tests__/UsageTable.spec.ts | 31 +++++++++- frontend/src/types/index.ts | 2 +- frontend/src/views/admin/UsageView.vue | 2 +- frontend/src/views/user/UsageView.vue | 4 +- 8 files changed, 125 insertions(+), 35 deletions(-) diff --git a/backend/internal/handler/dto/mappers.go b/backend/internal/handler/dto/mappers.go index 81aa8f8865..e59aa39730 100644 --- a/backend/internal/handler/dto/mappers.go +++ b/backend/internal/handler/dto/mappers.go @@ -3,6 +3,7 @@ package dto import ( "strconv" + "strings" "time" "github.com/Wei-Shaw/sub2api/internal/service" @@ -643,8 +644,7 @@ func usageLogFromServiceUser(l *service.UsageLog) UsageLog { RequestID: l.RequestID, Model: requestedModel, ServiceTier: l.ServiceTier, - ReasoningEffort: l.ReasoningEffort, - RequestedReasoningEffort: l.RequestedReasoningEffort, + ReasoningEffort: userFacingReasoningEffort(l), InboundEndpoint: l.InboundEndpoint, GroupID: l.GroupID, SubscriptionID: l.SubscriptionID, @@ -711,20 +711,53 @@ func UsageLogFromServiceAdmin(l *service.UsageLog) *AdminUsageLog { usageLog := usageLogFromServiceUser(l) usageLog.UpstreamEndpoint = l.UpstreamEndpoint return &AdminUsageLog{ - UsageLog: usageLog, - UpstreamModel: l.UpstreamModel, - UpstreamResponseModel: l.UpstreamResponseModel, - UpstreamModelMismatch: l.UpstreamModelMismatch, - ChannelID: l.ChannelID, - ModelMappingChain: l.ModelMappingChain, - BillingTier: l.BillingTier, - AccountRateMultiplier: l.AccountRateMultiplier, - AccountStatsCost: l.AccountStatsCost, - IPAddress: l.IPAddress, - Account: AccountSummaryFromService(l.Account), + UsageLog: usageLog, + UpstreamModel: l.UpstreamModel, + UpstreamReasoningEffort: adminUpstreamReasoningEffort(l), + UpstreamResponseModel: l.UpstreamResponseModel, + UpstreamModelMismatch: l.UpstreamModelMismatch, + ChannelID: l.ChannelID, + ModelMappingChain: l.ModelMappingChain, + BillingTier: l.BillingTier, + AccountRateMultiplier: l.AccountRateMultiplier, + AccountStatsCost: l.AccountStatsCost, + IPAddress: l.IPAddress, + Account: AccountSummaryFromService(l.Account), } } +func userFacingReasoningEffort(l *service.UsageLog) *string { + if l == nil { + return nil + } + if requested := strings.TrimSpace(derefString(l.RequestedReasoningEffort)); requested != "" { + return &requested + } + return l.ReasoningEffort +} + +func adminUpstreamReasoningEffort(l *service.UsageLog) *string { + if l == nil { + return nil + } + forwarded := strings.TrimSpace(derefString(l.ReasoningEffort)) + if forwarded == "" { + return nil + } + requested := userFacingReasoningEffort(l) + if requested != nil && service.NormalizeMaxReasoningEffort(*requested) == service.NormalizeMaxReasoningEffort(forwarded) { + return nil + } + return &forwarded +} + +func derefString(value *string) string { + if value == nil { + return "" + } + return *value +} + func UsageCleanupTaskFromService(task *service.UsageCleanupTask) *UsageCleanupTask { if task == nil { return nil diff --git a/backend/internal/handler/dto/mappers_usage_test.go b/backend/internal/handler/dto/mappers_usage_test.go index 43299000e9..3923d9cd20 100644 --- a/backend/internal/handler/dto/mappers_usage_test.go +++ b/backend/internal/handler/dto/mappers_usage_test.go @@ -179,7 +179,7 @@ func TestUsageLogFromService_KeepsUserBillingAndIPWithoutAdminCostFields(t *test require.NotContains(t, string(userJSON), "account_cost") } -func TestUsageLogFromService_IncludesRequestedReasoningEffort(t *testing.T) { +func TestUsageLogFromService_UsersSeeRequestedReasoningEffortOnly(t *testing.T) { t.Parallel() requested := "max" @@ -195,13 +195,43 @@ func TestUsageLogFromService_IncludesRequestedReasoningEffort(t *testing.T) { adminDTO := UsageLogFromServiceAdmin(log) require.NotNil(t, userDTO.ReasoningEffort) - require.Equal(t, forwarded, *userDTO.ReasoningEffort) - require.NotNil(t, userDTO.RequestedReasoningEffort) - require.Equal(t, requested, *userDTO.RequestedReasoningEffort) + require.Equal(t, requested, *userDTO.ReasoningEffort) require.NotNil(t, adminDTO.ReasoningEffort) - require.Equal(t, forwarded, *adminDTO.ReasoningEffort) - require.NotNil(t, adminDTO.RequestedReasoningEffort) - require.Equal(t, requested, *adminDTO.RequestedReasoningEffort) + require.Equal(t, requested, *adminDTO.ReasoningEffort) + require.NotNil(t, adminDTO.UpstreamReasoningEffort) + require.Equal(t, forwarded, *adminDTO.UpstreamReasoningEffort) + + userJSON, err := json.Marshal(userDTO) + require.NoError(t, err) + require.Contains(t, string(userJSON), `"reasoning_effort":"max"`) + require.NotContains(t, string(userJSON), "upstream_reasoning_effort") + require.NotContains(t, string(userJSON), "requested_reasoning_effort") + + adminJSON, err := json.Marshal(adminDTO) + require.NoError(t, err) + require.Contains(t, string(adminJSON), `"reasoning_effort":"max"`) + require.Contains(t, string(adminJSON), `"upstream_reasoning_effort":"xhigh"`) +} + +func TestUsageLogFromService_OmitsUpstreamReasoningEffortWhenUnmapped(t *testing.T) { + t.Parallel() + + effort := "high" + log := &service.UsageLog{ + RequestID: "req_effort_same", + Model: "gpt-5.4", + ReasoningEffort: &effort, + RequestedReasoningEffort: &effort, + } + + adminDTO := UsageLogFromServiceAdmin(log) + require.NotNil(t, adminDTO.ReasoningEffort) + require.Equal(t, effort, *adminDTO.ReasoningEffort) + require.Nil(t, adminDTO.UpstreamReasoningEffort) + + adminJSON, err := json.Marshal(adminDTO) + require.NoError(t, err) + require.NotContains(t, string(adminJSON), "upstream_reasoning_effort") } func TestUsageLogFromService_FallsBackToLegacyModelWhenRequestedModelMissing(t *testing.T) { diff --git a/backend/internal/handler/dto/types.go b/backend/internal/handler/dto/types.go index 72e89a0985..ba989ce86c 100644 --- a/backend/internal/handler/dto/types.go +++ b/backend/internal/handler/dto/types.go @@ -486,11 +486,10 @@ type UsageLog struct { Model string `json:"model"` // ServiceTier records the OpenAI service tier used for billing, e.g. "priority" / "flex". ServiceTier *string `json:"service_tier,omitempty"` - // ReasoningEffort is the effective effort after group policy / model-family remapping. + // ReasoningEffort is the client-requested effort (mapping-hidden, like Model). // OpenAI: "low"/"medium"/"high"/"xhigh"; Claude: "low"/"medium"/"high"/"max". + // Historical rows without requested_reasoning_effort fall back to the stored effective value. ReasoningEffort *string `json:"reasoning_effort,omitempty"` - // RequestedReasoningEffort is the client-requested effort before mapping. - RequestedReasoningEffort *string `json:"requested_reasoning_effort,omitempty"` // InboundEndpoint is the client-facing API endpoint path, e.g. /v1/chat/completions. InboundEndpoint *string `json:"inbound_endpoint,omitempty"` // UpstreamEndpoint is the normalized upstream endpoint path, e.g. /v1/responses. @@ -565,6 +564,9 @@ type AdminUsageLog struct { // UpstreamModel is the actual model sent to the upstream provider after mapping. // Omitted when no mapping was applied (requested model was used as-is). UpstreamModel *string `json:"upstream_model,omitempty"` + // UpstreamReasoningEffort is the effort actually forwarded after group policy / + // model-family remapping. Omitted when it matches the client-requested value. + UpstreamReasoningEffort *string `json:"upstream_reasoning_effort,omitempty"` // UpstreamResponseModel is the raw model declared by the upstream response. UpstreamResponseModel *string `json:"upstream_response_model,omitempty"` // UpstreamModelMismatch is nil when the upstream did not declare a model. diff --git a/frontend/src/components/admin/usage/UsageTable.vue b/frontend/src/components/admin/usage/UsageTable.vue index dac6098e57..bdba892581 100644 --- a/frontend/src/components/admin/usage/UsageTable.vue +++ b/frontend/src/components/admin/usage/UsageTable.vue @@ -93,14 +93,14 @@ @@ -596,8 +596,8 @@ const ipGeoBatchLoading = ref(false) const showIpGeoToolbar = computed(() => props.columns.some((col) => col.key === 'ip_address')) const hasReasoningEffortMapping = (row: AdminUsageLog): boolean => { - const requested = row.requested_reasoning_effort?.trim() || '' - const forwarded = row.reasoning_effort?.trim() || '' + const requested = row.reasoning_effort?.trim() || '' + const forwarded = row.upstream_reasoning_effort?.trim() || '' return requested !== '' && forwarded !== '' && !reasoningEffortValuesEqual(requested, forwarded) } diff --git a/frontend/src/components/admin/usage/__tests__/UsageTable.spec.ts b/frontend/src/components/admin/usage/__tests__/UsageTable.spec.ts index a8bf2df1db..e0ee74154c 100644 --- a/frontend/src/components/admin/usage/__tests__/UsageTable.spec.ts +++ b/frontend/src/components/admin/usage/__tests__/UsageTable.spec.ts @@ -263,8 +263,8 @@ describe('admin UsageTable tooltip', () => { data: [{ request_id: 'req-admin-effort-1', model: 'gpt-5.4', - requested_reasoning_effort: 'max', - reasoning_effort: 'xhigh', + reasoning_effort: 'max', + upstream_reasoning_effort: 'xhigh', }], loading: false, columns: [], @@ -291,7 +291,6 @@ describe('admin UsageTable tooltip', () => { data: [{ request_id: 'req-admin-effort-2', model: 'gpt-5.6-sol', - requested_reasoning_effort: 'max', reasoning_effort: 'max', }], loading: false, @@ -312,6 +311,32 @@ describe('admin UsageTable tooltip', () => { expect(text).not.toContain('↳') }) + it('hides mapped reasoning effort for user rows that only have the requested value', () => { + const wrapper = mount(UsageTable, { + props: { + data: [{ + request_id: 'req-user-effort-1', + model: 'gpt-5.4', + reasoning_effort: 'max', + }], + loading: false, + columns: [], + }, + global: { + stubs: { + DataTable: DataTableStub, + EmptyState: true, + Icon: true, + Teleport: true, + }, + }, + }) + + expect(wrapper.text()).toContain('Max') + expect(wrapper.text()).not.toContain('XHigh') + expect(wrapper.text()).not.toContain('↳') + }) + it.each([ { name: 'possible version variant', diff --git a/frontend/src/types/index.ts b/frontend/src/types/index.ts index 21b2f31729..5c605d971b 100644 --- a/frontend/src/types/index.ts +++ b/frontend/src/types/index.ts @@ -1639,7 +1639,6 @@ export interface UsageLog { model: string service_tier?: string | null reasoning_effort?: string | null - requested_reasoning_effort?: string | null inbound_endpoint?: string | null upstream_endpoint?: string | null @@ -1706,6 +1705,7 @@ export interface UsageLogAccountSummary { export interface AdminUsageLog extends UsageLog { upstream_model?: string | null + upstream_reasoning_effort?: string | null upstream_response_model?: string | null upstream_model_mismatch?: boolean | null model_mapping_chain?: string | null diff --git a/frontend/src/views/admin/UsageView.vue b/frontend/src/views/admin/UsageView.vue index 1e5967dafb..3f8215e134 100644 --- a/frontend/src/views/admin/UsageView.vue +++ b/frontend/src/views/admin/UsageView.vue @@ -595,7 +595,7 @@ const exportToExcel = async () => { if (c.signal.aborted) break; if (p === 1) { total = res.total; exportProgress.total = total } const rows = (res.items || []).map((log: AdminUsageLog) => [ log.created_at, log.user?.email || '', log.api_key?.name || '', log.account?.name || '', log.model, - log.upstream_model || log.model, log.upstream_response_model || '', log.upstream_model_mismatch == null ? '' : t(log.upstream_model_mismatch ? 'common.yes' : 'common.no'), formatReasoningEffort(log.requested_reasoning_effort || log.reasoning_effort), formatReasoningEffort(log.reasoning_effort), log.group?.name || '', + log.upstream_model || log.model, log.upstream_response_model || '', log.upstream_model_mismatch == null ? '' : t(log.upstream_model_mismatch ? 'common.yes' : 'common.no'), formatReasoningEffort(log.reasoning_effort), formatReasoningEffort(log.upstream_reasoning_effort || log.reasoning_effort), log.group?.name || '', log.inbound_endpoint || '', log.upstream_endpoint || '', getRequestTypeLabel(log), log.input_tokens, log.output_tokens, log.cache_read_tokens, log.cache_creation_tokens, log.input_cost?.toFixed(6) || '0.000000', log.output_cost?.toFixed(6) || '0.000000', diff --git a/frontend/src/views/user/UsageView.vue b/frontend/src/views/user/UsageView.vue index bf536821f7..d836936a5a 100644 --- a/frontend/src/views/user/UsageView.vue +++ b/frontend/src/views/user/UsageView.vue @@ -230,7 +230,7 @@ import TokenUsageTrend from '@/components/charts/TokenUsageTrend.vue' import Icon from '@/components/icons/Icon.vue' import UserErrorRequestsTable from '@/components/user/UserErrorRequestsTable.vue' import { getPersistedPageSize } from '@/composables/usePersistedPageSize' -import { formatReasoningEffortMapping } from '@/utils/format' +import { formatReasoningEffort } from '@/utils/format' import { getBillingModeLabel, getDisplayBillingMode as resolveDisplayBillingMode } from '@/utils/billingMode' import { resolveUsageRequestType, requestTypeToLegacyStream } from '@/utils/usageRequestType' import type { @@ -658,7 +658,7 @@ const exportToCSV = async () => { log.created_at, log.api_key?.name || '', log.model, - formatReasoningEffortMapping(log.requested_reasoning_effort, log.reasoning_effort), + formatReasoningEffort(log.reasoning_effort), log.inbound_endpoint || '', log.ip_address || '', getRequestTypeExportText(log), From a8cfe746b3d1cdef800c9d3038236e862af2356e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=88=98=E4=BD=B3=E6=9E=97?= Date: Tue, 25 Aug 2026 15:49:04 +0800 Subject: [PATCH 173/204] test(usage): cover user and admin reasoning effort page display Mount the real usage tables and assert users only see the requested effort, while admins can reveal mapped effort via column settings. --- .../usage-reasoning-effort.spec.ts | 322 ++++++++++++++++++ .../src/components/admin/usage/UsageTable.vue | 4 +- frontend/src/views/admin/UsageView.vue | 2 + frontend/src/views/user/UsageView.vue | 2 + 4 files changed, 328 insertions(+), 2 deletions(-) create mode 100644 frontend/src/__tests__/integration/usage-reasoning-effort.spec.ts diff --git a/frontend/src/__tests__/integration/usage-reasoning-effort.spec.ts b/frontend/src/__tests__/integration/usage-reasoning-effort.spec.ts new file mode 100644 index 0000000000..8d6edf2c00 --- /dev/null +++ b/frontend/src/__tests__/integration/usage-reasoning-effort.spec.ts @@ -0,0 +1,322 @@ +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' +import { flushPromises, mount } from '@vue/test-utils' +import { defineComponent } from 'vue' + +import UserUsageView from '@/views/user/UsageView.vue' +import AdminUsageView from '@/views/admin/UsageView.vue' + +const { + userQuery, + userGetStats, + userGetDashboardModels, + userGetDashboardSnapshotV2, + userKeysList, + userGroupsGetAvailable, + adminList, + adminGetStats, + adminGetSnapshotV2, + adminGetModelStats, + adminGetById, + listErrorLogs, +} = vi.hoisted(() => ({ + userQuery: vi.fn(), + userGetStats: vi.fn(), + userGetDashboardModels: vi.fn(), + userGetDashboardSnapshotV2: vi.fn(), + userKeysList: vi.fn(), + userGroupsGetAvailable: vi.fn(), + adminList: vi.fn(), + adminGetStats: vi.fn(), + adminGetSnapshotV2: vi.fn(), + adminGetModelStats: vi.fn(), + adminGetById: vi.fn(), + listErrorLogs: vi.fn(), +})) + +const messages: Record = { + 'admin.dashboard.timeRange': 'Time range', + 'admin.dashboard.granularity': 'Granularity', + 'admin.dashboard.day': 'Day', + 'admin.dashboard.hour': 'Hour', + 'admin.users.columnSettings': 'Columns', + 'admin.usage.group': 'Group', + 'admin.usage.user': 'User', + 'admin.usage.account': 'Account', + 'admin.usage.billingType': 'Billing type', + 'admin.usage.billingMode': 'Billing mode', + 'admin.usage.allTypes': 'All types', + 'admin.usage.allBillingTypes': 'All billing types', + 'admin.usage.billingTypeBalance': 'Balance', + 'admin.usage.billingTypeSubscription': 'Subscription', + 'admin.usage.allBillingModes': 'All billing modes', + 'admin.usage.billingModeToken': 'Token', + 'admin.usage.billingModePerRequest': 'Per request', + 'admin.usage.billingModeImage': 'Image', + 'admin.usage.allGroups': 'All groups', + 'admin.usage.allModels': 'All models', + 'admin.usage.ipAddress': 'IP', + 'usage.allApiKeys': 'All API Keys', + 'usage.apiKeyFilter': 'API Key', + 'usage.model': 'Model', + 'usage.type': 'Type', + 'usage.reasoningEffort': 'Reasoning Effort', + 'usage.endpoint': 'Endpoint', + 'usage.tokens': 'Tokens', + 'usage.cost': 'Cost', + 'usage.latency': 'Latency', + 'usage.time': 'Time', + 'usage.userAgent': 'User Agent', + 'usage.ws': 'WS', + 'usage.stream': 'Stream', + 'usage.sync': 'Sync', + 'usage.exporting': 'Exporting', + 'usage.exportCsv': 'Export CSV', + 'usage.failedToLoad': 'Failed to load', + 'usage.noRecords': 'No records', + 'empty.noData': 'No data', + 'common.refresh': 'Refresh', + 'common.reset': 'Reset', +} + +vi.mock('@/api', () => ({ + usageAPI: { + query: userQuery, + getStats: userGetStats, + getDashboardModels: userGetDashboardModels, + getDashboardSnapshotV2: userGetDashboardSnapshotV2, + }, + keysAPI: { + list: userKeysList, + }, + userGroupsAPI: { + getAvailable: userGroupsGetAvailable, + }, +})) + +vi.mock('@/api/admin', () => ({ + adminAPI: { + usage: { + list: adminList, + getStats: adminGetStats, + }, + dashboard: { + getSnapshotV2: adminGetSnapshotV2, + getModelStats: adminGetModelStats, + }, + users: { + getById: adminGetById, + }, + }, +})) + +vi.mock('@/api/admin/usage', () => ({ + adminUsageAPI: { + list: adminList, + }, +})) + +vi.mock('@/api/admin/ops', () => ({ + listErrorLogs, +})) + +vi.mock('@/stores/app', () => ({ + useAppStore: () => ({ + showError: vi.fn(), + showWarning: vi.fn(), + showSuccess: vi.fn(), + showInfo: vi.fn(), + }), +})) + +vi.mock('vue-i18n', async () => { + const actual = await vi.importActual('vue-i18n') + return { + ...actual, + useI18n: () => ({ + t: (key: string) => messages[key] ?? key, + }), + } +}) + +vi.mock('vue-router', () => ({ + useRoute: () => ({ query: {} }), +})) + +const layoutStub = { template: '
' } +const chartStub = { template: '
' } +const iconStub = { template: '' } +const adminFiltersStub = defineComponent({ + template: '
', +}) + +const emptyStats = { + total_requests: 1, + total_input_tokens: 10, + total_output_tokens: 20, + total_cache_tokens: 0, + total_tokens: 30, + total_cost: 0.1, + total_actual_cost: 0.08, + average_duration_ms: 12, + endpoints: [], + upstream_endpoints: [], + endpoint_paths: [], +} + +const userMappedLog = { + id: 11, + request_id: 'req-user-mapped', + created_at: '2026-08-25T00:00:00Z', + model: 'gpt-5.4', + reasoning_effort: 'max', + actual_cost: 0.01, + total_cost: 0.01, + rate_multiplier: 1, + input_cost: 0.01, + output_cost: 0, + cache_creation_cost: 0, + cache_read_cost: 0, + input_tokens: 8, + output_tokens: 2, + cache_creation_tokens: 0, + cache_read_tokens: 0, + cache_creation_5m_tokens: 0, + cache_creation_1h_tokens: 0, + image_count: 0, + billing_mode: 'token', + request_type: 'sync', + stream: false, + api_key: { name: 'user-key' }, +} + +const adminMappedLog = { + ...userMappedLog, + request_id: 'req-admin-mapped', + user_id: 7, + user: { email: 'liu.jialin@code-dance.com' }, + account: { name: 'codex-wang' }, + upstream_reasoning_effort: 'xhigh', +} + +const sharedPageStubs = { + AppLayout: layoutStub, + Pagination: true, + Select: true, + DateRangePicker: true, + Icon: iconStub, + UsageStatsCards: chartStub, + ModelDistributionChart: chartStub, + GroupDistributionChart: chartStub, + EndpointDistributionChart: chartStub, + TokenUsageTrend: chartStub, + IpGeoCell: true, + EmptyState: true, +} + +function reasoningCellText(wrapper: ReturnType): string { + return wrapper.get('[data-testid="reasoning-effort-cell"]').text() +} + +describe('usage reasoning effort page display', () => { + beforeEach(() => { + localStorage.clear() + userQuery.mockReset().mockResolvedValue({ items: [userMappedLog], total: 1, pages: 1 }) + userGetStats.mockReset().mockResolvedValue(emptyStats) + userGetDashboardModels.mockReset().mockResolvedValue({ models: [], start_date: '2026-08-25', end_date: '2026-08-25' }) + userGetDashboardSnapshotV2.mockReset().mockResolvedValue({ + generated_at: '2026-08-25T00:00:00Z', + start_date: '2026-08-25', + end_date: '2026-08-25', + granularity: 'hour', + trend: [], + groups: [], + }) + userKeysList.mockReset().mockResolvedValue({ items: [{ id: 1, name: 'user-key' }] }) + userGroupsGetAvailable.mockReset().mockResolvedValue([{ id: 1, name: 'default' }]) + + adminList.mockReset().mockResolvedValue({ items: [adminMappedLog], total: 1, pages: 1 }) + adminGetStats.mockReset().mockResolvedValue(emptyStats) + adminGetSnapshotV2.mockReset().mockResolvedValue({ trend: [], models: [], groups: [] }) + adminGetModelStats.mockReset().mockResolvedValue({ models: [] }) + adminGetById.mockReset().mockResolvedValue({ id: 7, email: 'liu.jialin@code-dance.com' }) + listErrorLogs.mockReset().mockResolvedValue({ items: [], total: 0 }) + }) + + afterEach(() => { + localStorage.clear() + }) + + it('user usage page only shows the requested reasoning effort', async () => { + const wrapper = mount(UserUsageView, { + global: { stubs: sharedPageStubs }, + }) + await flushPromises() + + const cell = reasoningCellText(wrapper) + expect(cell).toContain('Max') + expect(cell).not.toContain('XHigh') + expect(cell).not.toContain('↳') + expect(wrapper.text()).not.toContain('XHigh') + }) + + it('admin usage page shows requested and mapped effort after the column is enabled', async () => { + const wrapper = mount(AdminUsageView, { + global: { + stubs: { + ...sharedPageStubs, + UsageFilters: adminFiltersStub, + UsageExportProgress: true, + UsageCleanupDialog: true, + UserBalanceHistoryModal: true, + UserTokenRanking: true, + OpsErrorLogTable: true, + OpsErrorDetailModal: true, + }, + }, + }) + await flushPromises() + + expect(wrapper.find('[data-testid="reasoning-effort-cell"]').exists()).toBe(false) + + await wrapper.get('[data-testid="usage-column-settings"]').trigger('click') + await wrapper.get('[data-testid="usage-column-toggle-reasoning_effort"]').trigger('click') + await flushPromises() + + const cell = reasoningCellText(wrapper) + expect(cell).toContain('Max') + expect(cell).toContain('XHigh') + expect(cell).toContain('↳') + }) + + it('admin usage page shows a single value when reasoning effort was not mapped', async () => { + adminList.mockResolvedValue({ + items: [{ ...adminMappedLog, request_id: 'req-admin-plain', reasoning_effort: 'high', upstream_reasoning_effort: null }], + total: 1, + pages: 1, + }) + + const wrapper = mount(AdminUsageView, { + global: { + stubs: { + ...sharedPageStubs, + UsageFilters: adminFiltersStub, + UsageExportProgress: true, + UsageCleanupDialog: true, + UserBalanceHistoryModal: true, + UserTokenRanking: true, + OpsErrorLogTable: true, + OpsErrorDetailModal: true, + }, + }, + }) + await flushPromises() + + await wrapper.get('[data-testid="usage-column-settings"]').trigger('click') + await wrapper.get('[data-testid="usage-column-toggle-reasoning_effort"]').trigger('click') + await flushPromises() + + const cell = reasoningCellText(wrapper) + expect(cell).toContain('High') + expect(cell).not.toContain('↳') + }) +}) diff --git a/frontend/src/components/admin/usage/UsageTable.vue b/frontend/src/components/admin/usage/UsageTable.vue index bdba892581..3a613c3b03 100644 --- a/frontend/src/components/admin/usage/UsageTable.vue +++ b/frontend/src/components/admin/usage/UsageTable.vue @@ -91,7 +91,7 @@ diff --git a/frontend/src/views/admin/UsageView.vue b/frontend/src/views/admin/UsageView.vue index 3f8215e134..1fa950e75b 100644 --- a/frontend/src/views/admin/UsageView.vue +++ b/frontend/src/views/admin/UsageView.vue @@ -87,6 +87,7 @@