diff --git a/.gitignore b/.gitignore index a5ff9a969f..fb355d7e05 100644 --- a/.gitignore +++ b/.gitignore @@ -141,6 +141,7 @@ docs/* !docs/PAYMENT_CN.md !docs/ADMIN_PAYMENT_INTEGRATION_API.md !docs/ASYNC_IMAGE_TASKS.md +!docs/OPENAI_IMAGES_CODEX.md !docs/BATCH_IMAGE_MVP.md !docs/COMPOSITE_GROUPS.md !docs/PLUGIN_DEVELOPMENT.md diff --git a/backend/internal/handler/auth_oauth_pending_flow_test.go b/backend/internal/handler/auth_oauth_pending_flow_test.go index dd8e1c03fe..730d3299d9 100644 --- a/backend/internal/handler/auth_oauth_pending_flow_test.go +++ b/backend/internal/handler/auth_oauth_pending_flow_test.go @@ -2881,6 +2881,10 @@ func (s *oauthPendingFlowRefreshTokenCacheStub) DeleteTokenFamily(context.Contex return nil } +func (s *oauthPendingFlowRefreshTokenCacheStub) ConsumeRefreshToken(context.Context, string) (*service.RefreshTokenData, error) { + return nil, service.ErrRefreshTokenNotFound +} + func (s *oauthPendingFlowRefreshTokenCacheStub) AddToUserTokenSet(context.Context, int64, string, time.Duration) error { return nil } diff --git a/backend/internal/handler/auth_wechat_oauth_test.go b/backend/internal/handler/auth_wechat_oauth_test.go index e291b7e7db..9b8a01ecac 100644 --- a/backend/internal/handler/auth_wechat_oauth_test.go +++ b/backend/internal/handler/auth_wechat_oauth_test.go @@ -1478,6 +1478,10 @@ func (s *wechatOAuthRefreshTokenCacheStub) DeleteTokenFamily(context.Context, st return nil } +func (s *wechatOAuthRefreshTokenCacheStub) ConsumeRefreshToken(context.Context, string) (*service.RefreshTokenData, error) { + return nil, service.ErrRefreshTokenNotFound +} + func (s *wechatOAuthRefreshTokenCacheStub) AddToUserTokenSet(context.Context, int64, string, time.Duration) error { return nil } diff --git a/backend/internal/handler/composite_platform.go b/backend/internal/handler/composite_platform.go index 6e613aa3e4..83f2058356 100644 --- a/backend/internal/handler/composite_platform.go +++ b/backend/internal/handler/composite_platform.go @@ -163,16 +163,20 @@ func bindOpenAIReasoningEffortPolicyForMessagesRequest(c *gin.Context, apiKey *s 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. - effort := gjson.GetBytes(body, "output_config.effort") - if !effort.Exists() || effort.Type != gjson.String || strings.TrimSpace(effort.String()) == "" { - return + isCNTarget := service.IsCNProvider(effectiveAPIKeyPlatform(c, apiKey)) + if isCNTarget { + effort := gjson.GetBytes(body, "output_config.effort") + if effort.Type != gjson.String || strings.TrimSpace(effort.String()) == "" { + return + } } maxEffort, mappings, overLimit, ok := openAIReasoningEffortPolicyForRequest(c, apiKey) if !ok { return } - c.Request = c.Request.WithContext(service.WithOpenAIReasoningEffortPolicy(c.Request.Context(), maxEffort, mappings, overLimit)) + if isCNTarget { + c.Request = c.Request.WithContext(service.WithOpenAIReasoningEffortPolicy(c.Request.Context(), maxEffort, mappings, overLimit)) + return + } + c.Request = c.Request.WithContext(service.WithOpenAIReasoningEffortPolicyForMessages(c.Request.Context(), body, maxEffort, mappings, overLimit)) } diff --git a/backend/internal/handler/composite_platform_test.go b/backend/internal/handler/composite_platform_test.go index 7704a129a0..ee3d4ad859 100644 --- a/backend/internal/handler/composite_platform_test.go +++ b/backend/internal/handler/composite_platform_test.go @@ -133,14 +133,34 @@ func TestOpenAIReasoningEffortPolicyForCompositeTarget(t *testing.T) { require.True(t, changed) require.JSONEq(t, `{"reasoning":{"effort":"medium"}}`, string(bound)) - omittedCtx, _ := gin.CreateTestContext(httptest.NewRecorder()) - omittedCtx.Request = httptest.NewRequest("POST", "/v1/messages", nil) - omittedCtx.Request = omittedCtx.Request.WithContext(service.WithResolvedTargetPlatform(omittedCtx.Request.Context(), service.PlatformOpenAI)) - bindOpenAIReasoningEffortPolicyForMessagesRequest(omittedCtx, apiKey, []byte(`{"model":"gpt-5"}`)) - omitted, changed, err := service.ApplyOpenAIReasoningEffortPolicyFromContext(omittedCtx.Request.Context(), body) - require.NoError(t, err) - require.False(t, changed) - require.Equal(t, body, omitted) + synthesizedGroup := &service.Group{ + Platform: service.PlatformComposite, + ReasoningEffortMappings: []service.ReasoningEffortMapping{ + {From: "medium", To: "low"}, + {From: "none", To: "low"}, + }, + } + synthesizedAPIKey := &service.APIKey{Group: synthesizedGroup} + for _, tc := range []struct { + name string + request string + response string + want string + }{ + {name: "default medium", request: `{"model":"gpt-5"}`, response: `{"reasoning":{"effort":"medium"}}`, want: "medium"}, + {name: "disabled thinking none", request: `{"model":"gpt-5","thinking":{"type":"disabled"}}`, response: `{"reasoning":{"effort":"none"}}`, want: "low"}, + } { + t.Run(tc.name, func(t *testing.T) { + omittedCtx, _ := gin.CreateTestContext(httptest.NewRecorder()) + omittedCtx.Request = httptest.NewRequest("POST", "/v1/messages", nil) + omittedCtx.Request = omittedCtx.Request.WithContext(service.WithResolvedTargetPlatform(omittedCtx.Request.Context(), service.PlatformOpenAI)) + bindOpenAIReasoningEffortPolicyForMessagesRequest(omittedCtx, synthesizedAPIKey, []byte(tc.request)) + got, changed, err := service.ApplyOpenAIReasoningEffortPolicyFromContext(omittedCtx.Request.Context(), []byte(tc.response)) + require.NoError(t, err) + require.Equal(t, tc.want != "medium", changed) + require.Equal(t, tc.want, gjson.GetBytes(got, "reasoning.effort").String()) + }) + } denyGroup := *group denyGroup.MaxReasoningEffortOverLimit = service.ReasoningEffortOverLimitDeny diff --git a/backend/internal/handler/messages_effort_policy_test.go b/backend/internal/handler/messages_effort_policy_test.go new file mode 100644 index 0000000000..5c6eb93869 --- /dev/null +++ b/backend/internal/handler/messages_effort_policy_test.go @@ -0,0 +1,106 @@ +package handler + +import ( + "net/http/httptest" + "testing" + + "github.com/Wei-Shaw/sub2api/internal/service" + "github.com/gin-gonic/gin" + "github.com/stretchr/testify/require" + "github.com/tidwall/gjson" +) + +func TestMessagesEffortPolicyBinding(t *testing.T) { + for _, platform := range []string{service.PlatformOpenAI, service.PlatformComposite} { + for _, test := range []struct { + name string + preference string + effort string + mappings []service.ReasoningEffortMapping + ceiling string + overLimit string + want string + deny bool + }{ + {name: "omitted unchanged", effort: "medium", want: "medium"}, + {name: "omitted ignores medium mapping", effort: "medium", mappings: []service.ReasoningEffortMapping{{From: "medium", To: "low"}}, want: "medium"}, + {name: "omitted ignores ceiling", effort: "medium", ceiling: "low", want: "medium"}, + {name: "omitted ignores deny ceiling", effort: "medium", ceiling: "low", overLimit: service.ReasoningEffortOverLimitDeny, want: "medium"}, + {name: "numeric effort is not explicit", preference: `,"output_config":{"effort":123}`, effort: "medium", ceiling: "low", mappings: []service.ReasoningEffortMapping{{From: "medium", To: "deny"}}, want: "medium"}, + {name: "boolean effort is not explicit", preference: `,"output_config":{"effort":true}`, effort: "medium", ceiling: "low", want: "medium"}, + {name: "object effort is not explicit", preference: `,"output_config":{"effort":{"value":"high"}}`, effort: "medium", ceiling: "low", want: "medium"}, + {name: "blank effort is omitted", preference: `,"output_config":{"effort":" "}`, effort: "medium", ceiling: "low", want: "medium"}, + {name: "omitted none mapping does not cap medium default", effort: "medium", ceiling: "low", mappings: []service.ReasoningEffortMapping{{From: "none", To: "low"}}, want: "medium"}, + {name: "disabled omitted applies none only once", preference: `,"thinking":{"type":"disabled"}`, effort: "none", mappings: []service.ReasoningEffortMapping{{From: "none", To: "low"}, {From: "low", To: "high"}}, want: "low"}, + {name: "disabled omitted mapping capped", preference: `,"thinking":{"type":"disabled"}`, effort: "none", mappings: []service.ReasoningEffortMapping{{From: "none", To: "xhigh"}}, ceiling: "low", want: "low"}, + {name: "disabled omitted mapping denied", preference: `,"thinking":{"type":"disabled"}`, effort: "none", mappings: []service.ReasoningEffortMapping{{From: "none", To: "xhigh"}}, ceiling: "low", overLimit: service.ReasoningEffortOverLimitDeny, deny: true}, + {name: "disabled unmapped none not capped", preference: `,"thinking":{"type":"disabled"}`, effort: "none", ceiling: "low", overLimit: service.ReasoningEffortOverLimitDeny, want: "none"}, + {name: "disabled explicit applies none", preference: `,"output_config":{"effort":"max"},"thinking":{"type":"disabled"}`, effort: "none", mappings: []service.ReasoningEffortMapping{{From: "none", To: "low"}}, want: "low"}, + {name: "explicit adaptive retains policy", preference: `,"output_config":{"effort":"high"},"thinking":{"type":"adaptive"}`, effort: "high", ceiling: "medium", want: "medium"}, + {name: "omitted retains model scope", preference: `,"thinking":{"type":"disabled"}`, effort: "none", mappings: []service.ReasoningEffortMapping{{From: "none", To: "low", Model: "gpt-6-sol", MatchType: "exact"}}, want: "none"}, + } { + t.Run(platform+"/"+test.name, func(t *testing.T) { + c, _ := gin.CreateTestContext(httptest.NewRecorder()) + c.Request = httptest.NewRequest("POST", "/v1/messages", nil) + apiKey := &service.APIKey{Group: &service.Group{Platform: platform, MaxReasoningEffort: test.ceiling, ReasoningEffortMappings: test.mappings, MaxReasoningEffortOverLimit: test.overLimit}} + body := []byte(`{"model":"gpt-6.1-sol"` + test.preference + `}`) + ensureCompositeTargetPlatform(c, apiKey, "gpt-6.1-sol") + bindOpenAIReasoningEffortPolicyForMessagesRequest(c, apiKey, body) + converted := []byte(`{"model":"gpt-6.1-sol","reasoning":{"effort":"` + test.effort + `"}}`) + got, changed, err := service.ApplyOpenAIReasoningEffortPolicyFromContext(c.Request.Context(), converted) + if test.deny { + var overLimit *service.ReasoningEffortOverLimitError + require.ErrorAs(t, err, &overLimit) + require.Equal(t, "xhigh", overLimit.Requested) + require.Equal(t, "low", overLimit.Max) + require.False(t, changed) + require.Equal(t, converted, got) + return + } + require.NoError(t, err) + require.Equal(t, test.want, gjson.GetBytes(got, "reasoning.effort").String()) + require.Equal(t, test.effort != test.want, changed) + if !changed { + require.Equal(t, converted, got) + } + }) + } + } +} + +func TestMessagesEffortPolicyBindingCNTargetsOmitted(t *testing.T) { + for _, target := range []string{service.PlatformKimi, service.PlatformZhipu, service.PlatformDeepseek, service.PlatformMiniMax} { + for _, platform := range []string{target, service.PlatformComposite, service.PlatformOpenAI} { + for _, preference := range []string{ + ``, + `,"thinking":{"type":"disabled"}`, + `,"thinking":{"type":"adaptive"}`, + `,"thinking":{"type":"disabled"},"output_config":{"effort":" "}`, + `,"thinking":{"type":"disabled"},"output_config":{"effort":123}`, + `,"thinking":{"type":"disabled"},"output_config":{"effort":true}`, + `,"thinking":{"type":"disabled"},"output_config":{"effort":null}`, + `,"thinking":{"type":"disabled"},"output_config":{"effort":{}}`, + } { + t.Run(target+"/"+platform+"/"+preference, func(t *testing.T) { + requestContext, _ := gin.CreateTestContext(httptest.NewRecorder()) + requestContext.Request = httptest.NewRequest("POST", "/v1/messages", nil) + if platform != target { + requestContext.Request = requestContext.Request.WithContext(service.WithResolvedTargetPlatform(requestContext.Request.Context(), target)) + } + apiKey := &service.APIKey{Group: &service.Group{ + Platform: platform, MaxReasoningEffort: "low", MaxReasoningEffortOverLimit: service.ReasoningEffortOverLimitDeny, + ReasoningEffortMappings: []service.ReasoningEffortMapping{{From: "none", To: "deny"}, {From: "medium", To: "deny"}}, + }} + bindOpenAIReasoningEffortPolicyForMessagesRequest(requestContext, apiKey, []byte(`{"model":"glm-5.2"`+preference+`}`)) + for _, effort := range []string{"none", "medium", "high"} { + converted := []byte(`{"model":"glm-5.2","reasoning_effort":"` + effort + `"}`) + got, changed, err := service.ApplyOpenAIReasoningEffortPolicyFromContext(requestContext.Request.Context(), converted) + require.NoError(t, err) + require.False(t, changed) + require.Equal(t, converted, got) + } + }) + } + } + } +} diff --git a/backend/internal/handler/openai_gateway_handler.go b/backend/internal/handler/openai_gateway_handler.go index 05d9ab3191..f70bce78b2 100644 --- a/backend/internal/handler/openai_gateway_handler.go +++ b/backend/internal/handler/openai_gateway_handler.go @@ -15,6 +15,7 @@ import ( "sync" "sync/atomic" "time" + "unicode/utf8" "github.com/Wei-Shaw/sub2api/internal/config" "github.com/Wei-Shaw/sub2api/internal/domain" @@ -437,6 +438,13 @@ func (h *OpenAIGatewayHandler) Responses(c *gin.Context) { return } + // Reject invalid UTF-8 before JSON transformation so malformed bytes do not + // become retryable upstream errors. + if !utf8.Valid(body) { + h.errorResponse(c, http.StatusBadRequest, "invalid_request_error", "Request body must be valid UTF-8 JSON. Send UTF-8 encoded bytes.") + return + } + setOpsRequestContext(c, "", false) sessionHashBody := body body, ok = h.normalizeOpenAIResponsesCompactRequest(c, reqLog, body) @@ -481,6 +489,12 @@ func (h *OpenAIGatewayHandler) Responses(c *gin.Context) { } else if changed { body = cappedBody } + if normalizedBody, changed := normalizeCodexPageContext(body); changed { + body = normalizedBody + reqLog.Info("openai.codex_page_context_normalized", + zap.String("normalization", "call_output_to_user_message"), + ) + } if normalizedBody, changed := normalizeCodexAutomationBootstrap(body); changed { body = normalizedBody reqLog.Info("openai.codex_automation_bootstrap_normalized", diff --git a/backend/internal/handler/openai_gateway_handler_test.go b/backend/internal/handler/openai_gateway_handler_test.go index 894d2623cc..b17d922556 100644 --- a/backend/internal/handler/openai_gateway_handler_test.go +++ b/backend/internal/handler/openai_gateway_handler_test.go @@ -2472,23 +2472,76 @@ func TestOpenAIResponses_APIKeyPassthroughSSERateLimitUsesConfiguredPoolRetry(t } func TestOpenAIResponsesWebSocket_FailoverOnUpstreamUsageLimitEvent(t *testing.T) { + for _, mode := range []string{service.OpenAIWSIngressModePassthrough, service.OpenAIWSIngressModeCtxPool} { + t.Run(mode, func(t *testing.T) { + runOpenAIResponsesWebSocketUsageLimitCase(t, mode, nil, false) + }) + } +} + +func TestOpenAIResponsesWebSocket_NativeLaterTurnUsageLimitDoesNotReplayFirstMessage(t *testing.T) { + for _, continuation := range []struct { + name string + input string + handshakeLimit bool + }{ + {name: "user message", input: `[{"role":"user","content":"continue the task"}]`}, + {name: "tool result", input: `[{"type":"function_call_output","call_id":"call_inspect","output":"file contents"}]`}, + {name: "handshake after disconnect", input: `[{"role":"user","content":"continue the task"}]`, handshakeLimit: true}, + } { + t.Run(continuation.name, func(t *testing.T) { + runOpenAIResponsesWebSocketUsageLimitCase(t, service.OpenAIWSIngressModeCtxPool, []string{ + `{"type":"response.create","model":"gpt-5.1","instructions":"Inspect the project before editing it.","tools":[{"type":"function","name":"inspect","parameters":{"type":"object"}}],"input":[{"role":"user","content":"fix the project"}]}`, + fmt.Sprintf(`{"type":"response.create","model":"gpt-5.1","store":%t,"previous_response_id":"resp_ws_turn_2","input":%s}`, continuation.handshakeLimit, continuation.input), + }, continuation.handshakeLimit) + }) + } +} + +func runOpenAIResponsesWebSocketUsageLimitCase(t *testing.T, mode string, followups []string, handshakeLimit bool) { + t.Helper() gin.SetMode(gin.TestMode) - firstHitCh := make(chan []byte, 1) + firstHitCh := make(chan []byte, len(followups)+1) secondHitCh := make(chan []byte, 1) + var firstConnections atomic.Int32 + var secondConnections atomic.Int32 firstUpstream := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if firstConnections.Add(1) > 1 && handshakeLimit { + w.WriteHeader(http.StatusTooManyRequests) + return + } conn, err := coderws.Accept(w, r, &coderws.AcceptOptions{CompressionMode: coderws.CompressionContextTakeover}) if err != nil { return } defer func() { _ = conn.CloseNow() }() - readCtx, cancelRead := context.WithTimeout(r.Context(), 3*time.Second) - _, payload, readErr := conn.Read(readCtx) - cancelRead() - if readErr == nil { + for turn := 0; turn <= len(followups); turn++ { + readCtx, cancelRead := context.WithTimeout(r.Context(), 3*time.Second) + _, payload, readErr := conn.Read(readCtx) + cancelRead() + if readErr != nil { + return + } firstHitCh <- payload + if turn < len(followups) { + output := `[]` + if turn > 0 { + output = `[{"type":"function_call","call_id":"call_inspect","name":"inspect","arguments":"{}"}]` + } + completed := fmt.Sprintf(`{"type":"response.completed","response":{"id":"resp_ws_turn_%d","model":"gpt-5.1","output":%s,"usage":{"input_tokens":1,"output_tokens":1}}}`, turn+1, output) + writeCtx, cancelWrite := context.WithTimeout(r.Context(), 3*time.Second) + writeErr := conn.Write(writeCtx, coderws.MessageText, []byte(completed)) + cancelWrite() + if writeErr != nil { + return + } + if handshakeLimit && turn == len(followups)-1 { + return + } + } } writeCtx, cancelWrite := context.WithTimeout(r.Context(), 3*time.Second) @@ -2498,6 +2551,7 @@ func TestOpenAIResponsesWebSocket_FailoverOnUpstreamUsageLimitEvent(t *testing.T defer firstUpstream.Close() secondUpstream := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + secondConnections.Add(1) conn, err := coderws.Accept(w, r, &coderws.AcceptOptions{CompressionMode: coderws.CompressionContextTakeover}) if err != nil { return @@ -2535,7 +2589,7 @@ func TestOpenAIResponsesWebSocket_FailoverOnUpstreamUsageLimitEvent(t *testing.T }, Extra: map[string]any{ "openai_apikey_responses_websockets_v2_enabled": true, - "openai_apikey_responses_websockets_v2_mode": service.OpenAIWSIngressModePassthrough, + "openai_apikey_responses_websockets_v2_mode": mode, }, }, { @@ -2553,7 +2607,7 @@ func TestOpenAIResponsesWebSocket_FailoverOnUpstreamUsageLimitEvent(t *testing.T }, Extra: map[string]any{ "openai_apikey_responses_websockets_v2_enabled": true, - "openai_apikey_responses_websockets_v2_mode": service.OpenAIWSIngressModePassthrough, + "openai_apikey_responses_websockets_v2_mode": mode, }, }, } @@ -2575,6 +2629,7 @@ func TestOpenAIResponsesWebSocket_FailoverOnUpstreamUsageLimitEvent(t *testing.T accountRepo := &openAIWSFailoverHandlerAccountRepoStub{accounts: accounts} rateLimitSvc := service.NewRateLimitService(accountRepo, nil, cfg, nil, nil) billingCacheSvc := service.NewBillingCacheService(nil, nil, nil, nil, nil, nil, cfg, nil) + t.Cleanup(billingCacheSvc.Stop) gatewaySvc := service.NewOpenAIGatewayService( accountRepo, nil, @@ -2628,7 +2683,11 @@ func TestOpenAIResponsesWebSocket_FailoverOnUpstreamUsageLimitEvent(t *testing.T c.Set(string(middleware.ContextKeyUser), middleware.AuthSubject{UserID: apiKey.User.ID, Concurrency: 1}) c.Next() }) - router.GET("/openai/v1/responses", h.ResponsesWebSocket) + handlerDone := make(chan struct{}) + router.GET("/openai/v1/responses", func(c *gin.Context) { + h.ResponsesWebSocket(c) + close(handlerDone) + }) handlerServer := httptest.NewServer(router) defer handlerServer.Close() @@ -2647,22 +2706,52 @@ func TestOpenAIResponsesWebSocket_FailoverOnUpstreamUsageLimitEvent(t *testing.T cancelWrite() require.NoError(t, err) + for _, followup := range followups { + readCtx, cancelRead := context.WithTimeout(context.Background(), 5*time.Second) + _, event, readErr := clientConn.Read(readCtx) + cancelRead() + require.NoError(t, readErr) + require.Equal(t, "response.completed", gjson.GetBytes(event, "type").String()) + + writeCtx, cancelWrite := context.WithTimeout(context.Background(), 3*time.Second) + writeErr := clientConn.Write(writeCtx, coderws.MessageText, []byte(followup)) + cancelWrite() + require.NoError(t, writeErr) + } + readCtx, cancelRead := context.WithTimeout(context.Background(), 5*time.Second) _, event, err := clientConn.Read(readCtx) cancelRead() - require.NoError(t, err) - require.Equal(t, "response.completed", gjson.GetBytes(event, "type").String()) - require.Equal(t, "resp_ws_failover_ok", gjson.GetBytes(event, "response.id").String()) - - select { - case <-firstHitCh: - case <-time.After(3 * time.Second): - t.Fatal("等待第一个上游收到首帧超时") + if len(followups) > 0 { + require.Equal(t, coderws.StatusTryAgainLater, coderws.CloseStatus(err), "a later-turn limit must not turn into a successful replay: %s", event) + require.ErrorContains(t, err, "rate limit") + } else { + require.NoError(t, err) + require.Equal(t, "response.completed", gjson.GetBytes(event, "type").String()) + require.Equal(t, "resp_ws_failover_ok", gjson.GetBytes(event, "response.id").String()) } + _ = clientConn.CloseNow() select { - case <-secondHitCh: - case <-time.After(3 * time.Second): - t.Fatal("等待第二个上游收到重放首帧超时") + case <-handlerDone: + case <-time.After(5 * time.Second): + t.Fatal("timed out waiting for websocket handler") + } + + expectedFrames := len(followups) + 1 + if handshakeLimit { + expectedFrames-- + require.Equal(t, int32(2), firstConnections.Load(), "the same account must reject the replacement handshake") + } + require.Len(t, firstHitCh, expectedFrames) + if len(followups) > 0 { + require.Zero(t, secondConnections.Load(), "the replacement account must not receive the original connection message") + require.Empty(t, secondHitCh) + } else { + select { + case <-secondHitCh: + case <-time.After(3 * time.Second): + t.Fatal("等待第二个上游收到重放首帧超时") + } } require.Equal(t, []int64{int64(9902)}, accountRepo.rateLimitedIDs) } diff --git a/backend/internal/handler/openai_images_native_route_test.go b/backend/internal/handler/openai_images_native_route_test.go new file mode 100644 index 0000000000..e63e1544e2 --- /dev/null +++ b/backend/internal/handler/openai_images_native_route_test.go @@ -0,0 +1,203 @@ +//go:build unit + +package handler + +import ( + "bytes" + "context" + "fmt" + "io" + "mime/multipart" + "net/http" + "net/http/httptest" + "net/http/httputil" + "net/url" + "strings" + "sync/atomic" + "testing" + "time" + + "github.com/Wei-Shaw/sub2api/internal/config" + "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" + "github.com/tidwall/gjson" +) + +// Run the real Images handler, scheduler, parser and forwarding service over +// HTTP with fixture authentication, an account repository and a local upstream. +type nativeImageRouteUpstream struct { + service.HTTPUpstream + target *url.URL + client *http.Client +} + +func (u *nativeImageRouteUpstream) Do(req *http.Request, _ string, _ int64, _ int) (*http.Response, error) { + forwarded := req.Clone(req.Context()) + forwarded.URL.Scheme = u.target.Scheme + forwarded.URL.Host = u.target.Host + return u.client.Do(forwarded) +} + +func newNativeImageRoute(t *testing.T, delay time.Duration, status int) (*httptest.Server, *atomic.Int64) { + t.Helper() + gin.SetMode(gin.TestMode) + var calls atomic.Int64 + upstream := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + calls.Add(1) + require.Equal(t, http.MethodPost, r.Method) + switch r.URL.Path { + case "/v1/images/generations": + body, err := io.ReadAll(r.Body) + require.NoError(t, err) + require.Equal(t, "gpt-image-1", gjson.GetBytes(body, "model").String()) + case "/v1/images/edits": + require.NoError(t, r.ParseMultipartForm(1<<20)) + defer func() { + if r.MultipartForm != nil { + _ = r.MultipartForm.RemoveAll() + } + }() + require.Equal(t, "gpt-image-1", r.FormValue("model")) + part, _, err := r.FormFile("image") + require.NoError(t, err) + _ = part.Close() + default: + t.Errorf("unexpected upstream path: %s", r.URL.Path) + } + time.Sleep(delay) + w.Header().Set("Content-Type", "application/json") + w.WriteHeader(status) + if status == http.StatusOK { + _, _ = io.WriteString(w, `{"created":1710000000,"data":[{"b64_json":"aW1hZ2U="}]}`) + } else { + _, _ = io.WriteString(w, `{"error":{"type":"invalid_request_error","code":"native_route_rejected","message":"delayed image rejection"}}`) + } + })) + t.Cleanup(upstream.Close) + target, err := url.Parse(upstream.URL) + require.NoError(t, err) + cfg := &config.Config{RunMode: config.RunModeSimple} + cfg.Gateway.ImageNonstreamKeepaliveInterval = 1 + repo := openAIImagesFailoverAccountRepo{accounts: []service.Account{{ID: 1, Name: "fixture", Platform: service.PlatformOpenAI, Type: service.AccountTypeAPIKey, Status: service.StatusActive, Schedulable: true, Credentials: map[string]any{"api_key": "fixture-key", "base_url": "https://fixture.example/v1"}}}} + transport := &nativeImageRouteUpstream{target: target, client: upstream.Client()} + deferred := service.NewDeferredService(repo, nil, time.Minute) + gateway := service.NewOpenAIGatewayService(repo, nil, nil, nil, nil, nil, nil, cfg, nil, nil, service.NewBillingService(cfg, nil), nil, nil, transport, deferred, nil, nil, nil, nil, nil, nil, nil) + billing := service.NewBillingCacheService(nil, nil, nil, nil, nil, nil, cfg, nil) + t.Cleanup(billing.Stop) + handler := NewOpenAIGatewayHandler(gateway, service.NewConcurrencyService(nil), billing, service.NewAPIKeyService(nil, nil, nil, nil, nil, nil, cfg), nil, nil, nil, nil, cfg) + router := gin.New() + router.Use(func(c *gin.Context) { + groupID := int64(1) + c.Set(string(middleware.ContextKeyAPIKey), &service.APIKey{ID: 1, GroupID: &groupID, Group: &service.Group{ID: 1, AllowImageGeneration: true}, User: &service.User{ID: 1}}) + c.Set(string(middleware.ContextKeyUser), middleware.AuthSubject{UserID: 1}) + }) + router.POST("/v1/images/generations", handler.Images) + router.POST("/v1/images/edits", handler.Images) + server := httptest.NewServer(router) + t.Cleanup(server.Close) + return server, &calls +} + +func nativeImageRequest(t *testing.T, endpoint string, native bool) *http.Request { + t.Helper() + var body bytes.Buffer + contentType := "application/json" + if strings.HasSuffix(endpoint, "/edits") { + writer := multipart.NewWriter(&body) + require.NoError(t, writer.WriteField("model", "gpt-image-1")) + require.NoError(t, writer.WriteField("prompt", "edit fixture")) + part, err := writer.CreateFormFile("image", "input.png") + require.NoError(t, err) + _, err = part.Write([]byte("fixture-image")) + require.NoError(t, err) + require.NoError(t, writer.Close()) + contentType = writer.FormDataContentType() + } else { + _, _ = body.WriteString(`{"model":"gpt-image-1","prompt":"fixture"}`) + } + req, err := http.NewRequestWithContext(context.Background(), http.MethodPost, endpoint, &body) + require.NoError(t, err) + req.Header.Set("Content-Type", contentType) + if native { + req.Header.Set("X-Codex-Image-Turn-Id", "fixture-turn") + } + return req +} + +func TestNativeImagesRoutesDelayedResponse(t *testing.T) { + for _, path := range []string{"/v1/images/generations", "/v1/images/edits"} { + for _, status := range []int{http.StatusBadRequest, http.StatusOK} { + t.Run(fmt.Sprintf("%s/%d", path, status), func(t *testing.T) { + gateway, calls := newNativeImageRoute(t, 1200*time.Millisecond, status) + target, err := url.Parse(gateway.URL) + require.NoError(t, err) + proxy := httputil.NewSingleHostReverseProxy(target) + baseTransport, ok := http.DefaultTransport.(*http.Transport) + require.True(t, ok) + transport := baseTransport.Clone() + transport.ResponseHeaderTimeout = 3 * time.Second + defer transport.CloseIdleConnections() + proxy.Transport = transport + downstream := httptest.NewServer(proxy) + defer downstream.Close() + started := time.Now() + resp, err := downstream.Client().Do(nativeImageRequest(t, downstream.URL+path, true)) + require.NoError(t, err) + defer func() { _ = resp.Body.Close() }() + require.GreaterOrEqual(t, time.Since(started), 1200*time.Millisecond, "no heartbeat may commit early headers") + body, err := io.ReadAll(resp.Body) + require.NoError(t, err) + require.Equal(t, status, resp.StatusCode, string(body)) + require.EqualValues(t, 1, calls.Load()) + require.True(t, gjson.ValidBytes(body), string(body)) + require.NotContains(t, string(body), "event:") + if status == http.StatusOK { + require.EqualValues(t, 1710000000, gjson.GetBytes(body, "created").Int()) + require.Equal(t, "aW1hZ2U=", gjson.GetBytes(body, "data.0.b64_json").String()) + } else { + require.Equal(t, "native_route_rejected", gjson.GetBytes(body, "error.code").String()) + require.Equal(t, "delayed image rejection", gjson.GetBytes(body, "error.message").String()) + } + }) + } + } +} + +// This is a real HTTP proxy header deadline. Native clients intentionally get +// no heartbeat: a deadline below image latency fails, while a sufficiently long +// deadline is covered above. Ordinary clients retain their heartbeat behavior. +func TestNativeImagesRoutesProxyTimeout(t *testing.T) { + for _, path := range []string{"/v1/images/generations", "/v1/images/edits"} { + for _, native := range []bool{true, false} { + t.Run(fmt.Sprintf("%s/native=%t", path, native), func(t *testing.T) { + gateway, calls := newNativeImageRoute(t, 1600*time.Millisecond, http.StatusOK) + target, err := url.Parse(gateway.URL) + require.NoError(t, err) + proxy := httputil.NewSingleHostReverseProxy(target) + baseTransport, ok := http.DefaultTransport.(*http.Transport) + require.True(t, ok) + transport := baseTransport.Clone() + transport.ResponseHeaderTimeout = 1300 * time.Millisecond + defer transport.CloseIdleConnections() + proxy.Transport = transport + proxy.ErrorHandler = func(w http.ResponseWriter, _ *http.Request, _ error) { w.WriteHeader(http.StatusGatewayTimeout) } + downstream := httptest.NewServer(proxy) + defer downstream.Close() + resp, err := downstream.Client().Do(nativeImageRequest(t, downstream.URL+path, native)) + require.NoError(t, err) + defer func() { _ = resp.Body.Close() }() + body, err := io.ReadAll(resp.Body) + require.NoError(t, err) + if native { + require.Equal(t, http.StatusGatewayTimeout, resp.StatusCode) + } else { + require.Equal(t, http.StatusOK, resp.StatusCode) + require.Equal(t, "aW1hZ2U=", gjson.GetBytes(body, "data.0.b64_json").String()) + } + require.EqualValues(t, 1, calls.Load()) + }) + } + } +} diff --git a/backend/internal/handler/openai_page_context.go b/backend/internal/handler/openai_page_context.go new file mode 100644 index 0000000000..c61e830425 --- /dev/null +++ b/backend/internal/handler/openai_page_context.go @@ -0,0 +1,123 @@ +package handler + +import ( + "bytes" + "encoding/json" + "fmt" + "regexp" + "strconv" + "strings" +) + +var codexSelectedPageName = regexp.MustCompile(`^codex_apps_selected_page_part_([1-9][0-9]*)_of_([1-9][0-9]*)$`) + +// Desktop injects page snapshots as standalone outputs, without a model tool call. +// Keep them as untrusted user text, including on history replay and mixed bootstrap turns. +func normalizeCodexPageContext(body []byte) ([]byte, bool) { + if !mayContainCodexCallOutputCandidate(body, "codex_apps_open_page", "codex_apps_selected_page_part_") || !hasUniqueJSONMembers(body) { + return body, false + } + var request map[string]json.RawMessage + if json.Unmarshal(body, &request) != nil { + return body, false + } + var input []json.RawMessage + if json.Unmarshal(request["input"], &input) != nil { + return body, false + } + changed := false + for i, raw := range input { + var item map[string]json.RawMessage + if json.Unmarshal(raw, &item) != nil { + continue + } + readString := func(key string) string { + var value string + _ = json.Unmarshal(item[key], &value) + return value + } + if readString("type") != "function_call_output" || readString("namespace") != "agent" { + continue + } + if callID, exists := item["call_id"]; exists { + var value string + if bytes.Equal(bytes.TrimSpace(callID), []byte("null")) || json.Unmarshal(callID, &value) != nil || strings.TrimSpace(value) != "" { + continue + } + } + name, output := readString("name"), readString("output") + if !validCodexPageContext(name, output) { + continue + } + message := map[string]any{ + "type": "message", + "role": "user", + "content": []map[string]string{{ + "type": "input_text", + "text": "\n" + output + "\n", + }}, + } + encoded, err := json.Marshal(message) + if err != nil { + return body, false + } + input[i] = encoded + changed = true + } + if !changed { + return body, false + } + encodedInput, err := json.Marshal(input) + if err != nil { + return body, false + } + request["input"] = encodedInput + encoded, err := json.Marshal(request) + if err != nil { + return body, false + } + return encoded, true +} + +func validCodexPageContext(name, output string) bool { + if name == "codex_apps_open_page" { + return validCodexPageSnapshot(output) + } + parts := codexSelectedPageName.FindStringSubmatch(name) + if len(parts) != 3 { + return false + } + part, err := strconv.Atoi(parts[1]) + if err != nil { + return false + } + total, err := strconv.Atoi(parts[2]) + if err != nil || part > total { + return false + } + header, snapshot, ok := strings.Cut(output, "\n") + if !ok || strings.TrimSuffix(header, "\r") != fmt.Sprintf("Companion Page snapshot part %d of %d:", part, total) || strings.TrimSpace(snapshot) == "" { + return false + } + // A multi-part snapshot may split inside a JSON string; preserve each chunk verbatim. + return total > 1 || validCodexPageSnapshot(snapshot) +} + +func validCodexPageSnapshot(text string) bool { + if !hasUniqueJSONMembers([]byte(text)) { + return false + } + var snapshot map[string]json.RawMessage + if json.Unmarshal([]byte(text), &snapshot) != nil { + return false + } + id, exists := snapshot["page_id"] + if !exists { + return false + } + if bytes.Equal(bytes.TrimSpace(id), []byte("null")) { + return true + } + var value string + return json.Unmarshal(id, &value) == nil && strings.TrimSpace(value) != "" +} diff --git a/backend/internal/handler/openai_page_context_test.go b/backend/internal/handler/openai_page_context_test.go new file mode 100644 index 0000000000..dccdc6fd82 --- /dev/null +++ b/backend/internal/handler/openai_page_context_test.go @@ -0,0 +1,135 @@ +package handler + +import ( + "encoding/json" + "net/http/httptest" + "testing" + + "github.com/Wei-Shaw/sub2api/internal/service" + "github.com/gin-gonic/gin" + "github.com/stretchr/testify/require" + "github.com/tidwall/gjson" + "go.uber.org/zap" +) + +func pageContextItem(name, output string) map[string]any { + return map[string]any{"type": "function_call_output", "id": "fco_page", "namespace": "agent", "name": name, "output": output} +} + +func pageContextRequest(t *testing.T, items ...any) []byte { + t.Helper() + body, err := json.Marshal(map[string]any{"model": "gpt-5", "input": items}) + require.NoError(t, err) + return body +} + +func TestNormalizeCodexPageContextFirstMessage(t *testing.T) { + open := `{"page_id":null}` + selected := "Companion Page snapshot part 1 of 1:\n" + `{"page_id":null,"document_view":null}` + body := pageContextRequest(t, pageContextItem("codex_apps_open_page", open), pageContextItem("codex_apps_selected_page_part_1_of_1", selected), map[string]any{"role": "user", "content": "hello"}) + h := &OpenAIGatewayHandler{} + w := httptest.NewRecorder() + c, _ := gin.CreateTestContext(w) + require.False(t, h.validateFunctionCallOutputRequest(c, body, zap.NewNop())) + require.Equal(t, 400, w.Code) + require.Contains(t, w.Body.String(), "function_call_output requires call_id") + + got, changed := normalizeCodexPageContext(body) + require.True(t, changed) + w = httptest.NewRecorder() + c, _ = gin.CreateTestContext(w) + require.True(t, h.validateFunctionCallOutputRequest(c, got, zap.NewNop())) + require.False(t, c.Writer.Written()) + for i, original := range []string{open, selected} { + item := gjson.GetBytes(got, "input").Array()[i] + require.Equal(t, "message", item.Get("type").String()) + require.Equal(t, "user", item.Get("role").String()) + require.Contains(t, item.Get("content.0.text").String(), original) + require.False(t, item.Get("call_id").Exists()) + require.False(t, item.Get("id").Exists()) + } + require.Equal(t, "hello", gjson.GetBytes(got, "input.2.content").String()) + again, changed := normalizeCodexPageContext(got) + require.False(t, changed) + require.Equal(t, got, again) +} + +func TestNormalizeCodexPageContextPreservesHistoryAndToolValidation(t *testing.T) { + body := []byte(`{"model":"gpt-5","previous_response_id":"resp_history","metadata":{"large":9007199254740993},"input":[{"type":"function_call","name":"read_file","call_id":"call_real","arguments":"{}"},{"type":"function_call_output","call_id":"call_real","output":"result"},{"type":"function_call_output","namespace":"agent","name":"codex_apps_open_page","output":"{\"page_id\":\"page_1\"}"}]}`) + got, changed := normalizeCodexPageContext(body) + require.True(t, changed) + require.Equal(t, "resp_history", gjson.GetBytes(got, "previous_response_id").String()) + require.Equal(t, "9007199254740993", gjson.GetBytes(got, "metadata.large").Raw) + for _, index := range []string{"input.0", "input.1"} { + require.JSONEq(t, gjson.GetBytes(body, index).Raw, gjson.GetBytes(got, index).Raw) + } + + badTool := pageContextItem("read_file", "result") + body = pageContextRequest(t, pageContextItem("codex_apps_open_page", `{"page_id":null}`), badTool) + got, changed = normalizeCodexPageContext(body) + require.True(t, changed) + require.True(t, service.ValidateFunctionCallOutputContextBytes(got).HasFunctionCallOutputMissingCallID) +} + +func TestNormalizeCodexPageContextMixedBootstrap(t *testing.T) { + for _, item := range []map[string]any{ + {"type": "function_call_output", "namespace": "codex_app", "name": "create_thread", "output": delegationEnvelope}, + {"type": "function_call_output", "namespace": "codex_app", "name": "automation_update", "output": "test"}, + } { + body := pageContextRequest(t, pageContextItem("codex_apps_open_page", `{"page_id":null}`), item) + got, changed := normalizeCodexPageContext(body) + require.True(t, changed) + got, _ = normalizeCodexAutomationBootstrap(got) + got, _ = normalizeCodexDelegationBootstrap(got) + require.False(t, service.ValidateFunctionCallOutputContextBytes(got).HasFunctionCallOutput) + } +} + +func TestNormalizeCodexPageContextMultipart(t *testing.T) { + first := "Companion Page snapshot part 1 of 2:\n" + `{"page_id":"page1","document_view":"hello` + second := "Companion Page snapshot part 2 of 2:\n" + ` world"}` + body := pageContextRequest(t, pageContextItem("codex_apps_selected_page_part_1_of_2", first), pageContextItem("codex_apps_selected_page_part_2_of_2", second)) + got, changed := normalizeCodexPageContext(body) + require.True(t, changed) + require.Contains(t, gjson.GetBytes(got, "input.0.content.0.text").String(), first) + require.Contains(t, gjson.GetBytes(got, "input.1.content.0.text").String(), second) +} + +func TestNormalizeCodexPageContextRejectsUnrelatedOrMalformedItems(t *testing.T) { + for _, tc := range []struct { + name string + key string + value any + }{ + {"real call", "call_id", "call_real"}, + {"invalid call id", "call_id", 42}, + {"null call id", "call_id", nil}, + {"other namespace", "namespace", "codex_app"}, + {"missing namespace", "namespace", ""}, + {"other tool", "name", "read_file"}, + {"other type", "type", "custom_tool_call_output"}, + {"not JSON", "output", "some text"}, + {"not snapshot", "output", `{"other":null}`}, + {"wrong page id", "output", `{"page_id":1}`}, + {"duplicate snapshot key", "output", `{"page_id":null,"page_id":"other"}`}, + {"part without header", "name", "codex_apps_selected_page_part_1_of_1"}, + {"part out of range", "name", "codex_apps_selected_page_part_2_of_1"}, + } { + t.Run(tc.name, func(t *testing.T) { + item := pageContextItem("codex_apps_open_page", `{"page_id":null}`) + item[tc.key] = tc.value + body := pageContextRequest(t, item) + got, changed := normalizeCodexPageContext(body) + require.False(t, changed) + require.Equal(t, body, got) + }) + } + for _, body := range []string{ + `{"input":[{"type":"function_call_output","namespace":"agent","name":"codex_apps_open_page","call_id":"real","call_id":"","output":"{\"page_id\":null}"}]}`, + `{"input":[{"type":"function_call_output","namespace":"agent","name":"codex_apps_open_page","output":"{\"page_id\":null}"}]} trailing`, + } { + got, changed := normalizeCodexPageContext([]byte(body)) + require.False(t, changed) + require.Equal(t, body, string(got)) + } +} diff --git a/backend/internal/handler/openai_responses_utf8_test.go b/backend/internal/handler/openai_responses_utf8_test.go new file mode 100644 index 0000000000..06e89ebe81 --- /dev/null +++ b/backend/internal/handler/openai_responses_utf8_test.go @@ -0,0 +1,52 @@ +package handler + +import ( + "bytes" + "fmt" + "net/http" + "net/http/httptest" + "testing" + + "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" +) + +func TestOpenAIResponses_RejectsInvalidUTF8BeforeRouting(t *testing.T) { + gin.SetMode(gin.TestMode) + for _, suffix := range []string{"", `,"stream":false`, `,"stream":true`} { + for _, invalid := range [][]byte{{0xbb, 0xd8, 0xb8, 0xb4}, {0xe4, 0xbd}, {0xff}} { + t.Run(fmt.Sprintf("%s/%x", suffix, invalid), func(t *testing.T) { + body := append([]byte(`{"input":"`), invalid...) + body = append(body, []byte(`"`+suffix+`}`)...) + w := httptest.NewRecorder() + c, _ := gin.CreateTestContext(w) + c.Request = httptest.NewRequest(http.MethodPost, "/v1/responses", bytes.NewReader(body)) + groupID := int64(2) + c.Set(string(middleware.ContextKeyAPIKey), &service.APIKey{ID: 101, 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(), "valid UTF-8 JSON") + require.Contains(t, w.Body.String(), "invalid_request_error") + }) + } + } +} + +func TestOpenAIResponses_ValidUnicodeReachesFieldValidation(t *testing.T) { + gin.SetMode(gin.TestMode) + w := httptest.NewRecorder() + c, _ := gin.CreateTestContext(w) + c.Request = httptest.NewRequest(http.MethodPost, "/v1/responses", bytes.NewBufferString(`{"input":"回复 ok 🌍"}`)) + groupID := int64(2) + c.Set(string(middleware.ContextKeyAPIKey), &service.APIKey{ID: 101, 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(), "model is required") + require.NotContains(t, w.Body.String(), "UTF-8") +} diff --git a/backend/internal/handler/user_handler_test.go b/backend/internal/handler/user_handler_test.go index 796c64f339..14df95bb7e 100644 --- a/backend/internal/handler/user_handler_test.go +++ b/backend/internal/handler/user_handler_test.go @@ -440,6 +440,10 @@ func (s *userHandlerRefreshTokenCacheStub) DeleteTokenFamily(context.Context, st return nil } +func (s *userHandlerRefreshTokenCacheStub) ConsumeRefreshToken(context.Context, string) (*service.RefreshTokenData, error) { + return nil, service.ErrRefreshTokenNotFound +} + func (s *userHandlerRefreshTokenCacheStub) AddToUserTokenSet(context.Context, int64, string, time.Duration) error { return nil } diff --git a/backend/internal/payment/provider/easypay.go b/backend/internal/payment/provider/easypay.go index 76469a2b36..a5426e4ccf 100644 --- a/backend/internal/payment/provider/easypay.go +++ b/backend/internal/payment/provider/easypay.go @@ -50,7 +50,8 @@ type easyPayCustomMethod struct { } // NewEasyPay creates a new EasyPay provider. -// config keys: pid, pkey, apiBase, notifyUrl, returnUrl, cid, cidAlipay, cidWxpay +// config keys: pid, pkey, apiBase, notifyUrl, returnUrl, cid, cidAlipay, cidWxpay, +// refundSuccessCode (0 or 1; defaults to 1). func NewEasyPay(instanceID string, config map[string]string) (*EasyPay, error) { for _, k := range []string{"pid", "pkey", "apiBase", "notifyUrl", "returnUrl"} { if strings.TrimSpace(config[k]) == "" { @@ -61,6 +62,9 @@ func NewEasyPay(instanceID string, config map[string]string) (*EasyPay, error) { for k, v := range config { cfg[k] = v } + if code := strings.TrimSpace(cfg["refundSuccessCode"]); code != "" && code != "0" && code != "1" { + return nil, fmt.Errorf("easypay refundSuccessCode must be 0 or 1") + } cfg["apiBase"] = normalizeEasyPayAPIBase(cfg["apiBase"]) return &EasyPay{ instanceID: instanceID, @@ -371,7 +375,7 @@ func (e *EasyPay) queryOrder(ctx context.Context, outTradeNo string) (*easyPayQu } // An explicit failure code wins over any paid-looking status field that // may accompany it. - if resp.Code != nil && !easyPayResponseCodeIsSuccess(resp.Code) { + if resp.Code != nil && !easyPayResponseCodeIsSuccess(resp.Code, easypayCodeSuccess) { msg := strings.TrimSpace(resp.Msg) if msg == "" { msg = summarizeEasyPayResponse(body) @@ -506,6 +510,12 @@ func (e *EasyPay) VerifyNotification(_ context.Context, rawBody string, _ map[st } func (e *EasyPay) Refund(ctx context.Context, req payment.RefundRequest) (*payment.RefundResponse, error) { + // Compatible gateways disagree on refund codes. Keep the existing default + // unless this instance explicitly selects a zero-success refund protocol. + successCode := easypayCodeSuccess + if strings.TrimSpace(e.config["refundSuccessCode"]) == "0" { + successCode = 0 + } attempts := e.refundAttempts(req) if len(attempts) == 0 { return nil, fmt.Errorf("easypay refund missing order identifier") @@ -516,7 +526,7 @@ func (e *EasyPay) Refund(ctx context.Context, req payment.RefundRequest) (*payme if err != nil { return nil, fmt.Errorf("easypay refund request: %w", err) } - if err := parseEasyPayRefundResponse(status, body); err != nil { + if err := parseEasyPayRefundResponse(status, body, successCode); err != nil { if firstErr == nil { firstErr = err } @@ -573,7 +583,7 @@ func isEasyPayRefundOrderNotFound(err error) bool { strings.Contains(lower, "not exist") } -func parseEasyPayRefundResponse(status int, body []byte) error { +func parseEasyPayRefundResponse(status int, body []byte, successCode int) error { summary := summarizeEasyPayResponse(body) if status < http.StatusOK || status >= http.StatusMultipleChoices { return fmt.Errorf("easypay refund HTTP %d: %s", status, summary) @@ -597,7 +607,7 @@ func parseEasyPayRefundResponse(status int, body []byte) error { if err := json.Unmarshal(body, &resp); err != nil { return fmt.Errorf("easypay refund non-JSON response (HTTP %d): %s", status, summary) } - if !easyPayResponseCodeIsSuccess(resp.Code) { + if !easyPayResponseCodeIsSuccess(resp.Code, successCode) { msg := strings.TrimSpace(resp.Msg) if msg == "" { msg = summary @@ -607,13 +617,13 @@ func parseEasyPayRefundResponse(status int, body []byte) error { return nil } -func easyPayResponseCodeIsSuccess(code any) bool { +func easyPayResponseCodeIsSuccess(code any, successCode int) bool { switch v := code.(type) { case float64: - return int(v) == easypayCodeSuccess + return v == float64(successCode) case string: n, err := strconv.Atoi(strings.TrimSpace(v)) - return err == nil && n == easypayCodeSuccess + return err == nil && n == successCode default: return false } diff --git a/backend/internal/payment/provider/easypay_refund_test.go b/backend/internal/payment/provider/easypay_refund_test.go index 730e82feff..d1e811d19e 100644 --- a/backend/internal/payment/provider/easypay_refund_test.go +++ b/backend/internal/payment/provider/easypay_refund_test.go @@ -180,6 +180,60 @@ func TestEasyPayRefundResponseErrors(t *testing.T) { } } +func TestEasyPayRefundSuccessCode(t *testing.T) { + t.Parallel() + + for _, successCode := range []string{"", "1", "0"} { + t.Run("configured="+successCode, func(t *testing.T) { + t.Parallel() + for _, code := range []string{`0`, `"0"`, `1`, `"1"`, `-1`, `1.5`, `0.5`, `null`, `false`, `""`} { + t.Run("response="+code, func(t *testing.T) { + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { + _, _ = w.Write([]byte(`{"code":` + code + `,"msg":"gateway result"}`)) + })) + defer server.Close() + provider, err := NewEasyPay("test-instance", map[string]string{ + "pid": "1001", "pkey": "test-key", "apiBase": server.URL, + "notifyUrl": "https://site.example/notify", "returnUrl": "https://site.example/return", + "refundSuccessCode": successCode, + }) + if err != nil { + t.Fatal(err) + } + resp, err := provider.Refund(context.Background(), payment.RefundRequest{OrderID: "out-456", Amount: "1.50"}) + wantSuccess := code == `1` || code == `"1"` + if successCode == "0" { + wantSuccess = code == `0` || code == `"0"` + } + if wantSuccess { + if err != nil || resp == nil || resp.Status != payment.ProviderStatusSuccess { + t.Fatalf("Refund() = %+v, %v; want success", resp, err) + } + } else if err == nil || resp != nil { + t.Fatalf("Refund() = %+v, %v; want rejection", resp, err) + } + }) + } + }) + } +} + +func TestNewEasyPayRejectsInvalidRefundSuccessCode(t *testing.T) { + t.Parallel() + for _, code := range []string{"-1", "2", "0.5", "0,1", "auto"} { + t.Run(code, func(t *testing.T) { + _, err := NewEasyPay("test-instance", map[string]string{ + "pid": "1001", "pkey": "test-key", "apiBase": "https://pay.example", + "notifyUrl": "https://site.example/notify", "returnUrl": "https://site.example/return", + "refundSuccessCode": code, + }) + if err == nil { + t.Fatal("NewEasyPay accepted an invalid refund success code") + } + }) + } +} + func TestSummarizeEasyPayResponsePreservesUTF8(t *testing.T) { t.Parallel() diff --git a/backend/internal/pkg/antigravity/request_transformer.go b/backend/internal/pkg/antigravity/request_transformer.go index 0b3396edb2..d0cac85d9d 100644 --- a/backend/internal/pkg/antigravity/request_transformer.go +++ b/backend/internal/pkg/antigravity/request_transformer.go @@ -504,6 +504,7 @@ func buildParts(content json.RawMessage, toolIDToName map[string]string, allowDu return nil, false, fmt.Errorf("parse content blocks: %w", err) } + var toolMediaParts []GeminiPart for _, block := range blocks { switch block.Type { case "text": @@ -591,14 +592,15 @@ func buildParts(content json.RawMessage, toolIDToName map[string]string, allowDu for _, part := range media { response.Parts = append(response.Parts, GeminiFunctionResponsePart{InlineData: part.InlineData}) } + } else { + toolMediaParts = append(toolMediaParts, media...) } parts = append(parts, GeminiPart{FunctionResponse: response}) - if !multimodalToolResults { - parts = append(parts, media...) - } } } + parts = append(parts, toolMediaParts...) + return parts, strippedThinking, nil } diff --git a/backend/internal/pkg/antigravity/request_transformer_test.go b/backend/internal/pkg/antigravity/request_transformer_test.go index eb703da14a..66bbe68377 100644 --- a/backend/internal/pkg/antigravity/request_transformer_test.go +++ b/backend/internal/pkg/antigravity/request_transformer_test.go @@ -743,13 +743,13 @@ func TestTransformClaudeToGemini_ToolResultImagesReachUpstream(t *testing.T) { require.Equal(t, "toolu_img_1", userParts[0].FunctionResponse.ID) require.Equal(t, "loaded colors.png", userParts[0].FunctionResponse.Response["result"]) - require.NotNil(t, userParts[1].InlineData) - require.Equal(t, "image/png", userParts[1].InlineData.MimeType) - require.Equal(t, "aGVsbG8=", userParts[1].InlineData.Data) + require.NotNil(t, userParts[1].FunctionResponse) + require.Equal(t, "read_image", userParts[1].FunctionResponse.Name) + require.Equal(t, "Command executed successfully.", userParts[1].FunctionResponse.Response["result"]) - require.NotNil(t, userParts[2].FunctionResponse) - require.Equal(t, "read_image", userParts[2].FunctionResponse.Name) - require.Equal(t, "Command executed successfully.", userParts[2].FunctionResponse.Response["result"]) + require.NotNil(t, userParts[2].InlineData) + require.Equal(t, "image/png", userParts[2].InlineData.MimeType) + require.Equal(t, "aGVsbG8=", userParts[2].InlineData.Data) require.NotNil(t, userParts[3].InlineData) require.Equal(t, "image/jpeg", userParts[3].InlineData.MimeType) diff --git a/backend/internal/pkg/antigravity/tool_result_images_test.go b/backend/internal/pkg/antigravity/tool_result_images_test.go index 87e359450e..6f68f78886 100644 --- a/backend/internal/pkg/antigravity/tool_result_images_test.go +++ b/backend/internal/pkg/antigravity/tool_result_images_test.go @@ -101,3 +101,45 @@ func TestToolResultMediaPlacement(t *testing.T) { }) } } + +func TestParallelToolResultsKeepFunctionResponsesContiguousBeforeMedia(t *testing.T) { + for _, model := range []string{"claude-opus-5-5-medium", "claude-sonnet-4-6", "gemini-2.5-flash"} { + t.Run(model, func(t *testing.T) { + raw := []byte(`{"model":"` + model + `","input":[ + {"type":"function_call","call_id":"call_img_1","name":"view_image","arguments":"{\"path\":\"a.png\"}"}, + {"type":"function_call","call_id":"call_img_2","name":"view_image","arguments":"{\"path\":\"b.jpg\"}"}, + {"type":"function_call","call_id":"call_cmd_3","name":"exec_command","arguments":"{\"cmd\":\"ls\"}"}, + {"type":"function_call_output","call_id":"call_img_1","output":[{"type":"input_image","image_url":"data:image/png;base64,AQID"}]}, + {"type":"function_call_output","call_id":"call_img_2","output":[{"type":"input_text","text":"loaded b.jpg"},{"type":"input_image","image_url":"data:image/jpeg;base64,BAUG"}]}, + {"type":"function_call_output","call_id":"call_cmd_3","output":"README.md"} + ]}`) + var req apicompat.ResponsesRequest + require.NoError(t, json.Unmarshal(raw, &req)) + anthropic, err := apicompat.ResponsesToAnthropicRequest(&req) + require.NoError(t, err) + body, err := json.Marshal(anthropic) + require.NoError(t, err) + var claude ClaudeRequest + require.NoError(t, json.Unmarshal(body, &claude)) + wire, err := TransformClaudeToGeminiWithOptions(&claude, "test-project", model, TransformOptions{}) + require.NoError(t, err) + + parts := gjson.GetBytes(wire, "request.contents.1.parts").Array() + require.Len(t, parts, 5) + + require.Equal(t, "call_img_1", parts[0].Get("functionResponse.id").String()) + require.Equal(t, "view_image", parts[0].Get("functionResponse.name").String()) + require.Equal(t, "call_img_2", parts[1].Get("functionResponse.id").String()) + require.Equal(t, "view_image", parts[1].Get("functionResponse.name").String()) + require.Equal(t, "loaded b.jpg", parts[1].Get("functionResponse.response.result").String()) + require.Equal(t, "call_cmd_3", parts[2].Get("functionResponse.id").String()) + require.Equal(t, "exec_command", parts[2].Get("functionResponse.name").String()) + require.Equal(t, "README.md", parts[2].Get("functionResponse.response.result").String()) + + require.Equal(t, "image/png", parts[3].Get("inlineData.mimeType").String()) + require.Equal(t, "AQID", parts[3].Get("inlineData.data").String()) + require.Equal(t, "image/jpeg", parts[4].Get("inlineData.mimeType").String()) + require.Equal(t, "BAUG", parts[4].Get("inlineData.data").String()) + }) + } +} diff --git a/backend/internal/pkg/apicompat/anthropic_effort_validation_test.go b/backend/internal/pkg/apicompat/anthropic_effort_validation_test.go new file mode 100644 index 0000000000..d72ce9e907 --- /dev/null +++ b/backend/internal/pkg/apicompat/anthropic_effort_validation_test.go @@ -0,0 +1,35 @@ +package apicompat + +import ( + "testing" + + "github.com/stretchr/testify/require" +) + +func TestAnthropicToResponsesDeferredEffortValidation(t *testing.T) { + for _, effort := range []string{"", "low", "high", "max"} { + t.Run(effort, func(t *testing.T) { + req := &AnthropicRequest{ + Model: "gpt-6.1-sol", + MaxTokens: 1, + Thinking: &AnthropicThinking{Type: "disabled"}, + OutputConfig: &AnthropicOutputConfig{Effort: effort}, + } + _, err := AnthropicToResponses(req) + require.Error(t, err) + _, err = AnthropicToResponsesWithMinOutputTokens(req, 32) + require.Error(t, err) + converted, err := AnthropicToResponsesWithOptions(req, AnthropicToResponsesOptions{ + MinOutputTokens: 32, + DeferReasoningEffortValidation: true, + }) + require.NoError(t, err) + require.Equal(t, "gpt-6.1-sol", converted.Model) + require.Equal(t, "none", converted.Reasoning.Effort) + require.Empty(t, converted.Reasoning.Summary) + require.Equal(t, 32, *converted.MaxOutputTokens) + require.Equal(t, "disabled", req.Thinking.Type) + require.Equal(t, effort, req.OutputConfig.Effort) + }) + } +} diff --git a/backend/internal/pkg/apicompat/anthropic_responses_test.go b/backend/internal/pkg/apicompat/anthropic_responses_test.go index 700af63d4d..6755533b00 100644 --- a/backend/internal/pkg/apicompat/anthropic_responses_test.go +++ b/backend/internal/pkg/apicompat/anthropic_responses_test.go @@ -1,6 +1,7 @@ package apicompat import ( + "encoding/base64" "encoding/json" "testing" @@ -197,6 +198,50 @@ func TestAnthropicToResponses_ThinkingSignatureBecomesReasoning(t *testing.T) { assert.Equal(t, "function_call", items[3].Type) } +func TestAnthropicToResponses_ForeignReasoningEnvelopePreservesToolHistory(t *testing.T) { + envelope := "ccswitch-openai-reasoning-v1:" + base64.RawURLEncoding.EncodeToString([]byte( + `{"type":"reasoning","id":"rs_1","summary":[],"encrypted_content":"gAAAA-foreign"}`, + )) + for _, tc := range []struct{ name, signature string }{ + {"valid envelope", envelope}, + {"surrounding whitespace", " \n" + envelope + "\t"}, + {"malformed envelope", "ccswitch-openai-reasoning-v1:not-base64!"}, + } { + t.Run(tc.name, func(t *testing.T) { + blocks, err := json.Marshal([]AnthropicContentBlock{ + {Type: "thinking", Signature: tc.signature}, + {Type: "thinking", Signature: "native-ciphertext"}, + {Type: "text", Text: "Checking now."}, + {Type: "tool_use", ID: "call_1", Name: "lookup", Input: json.RawMessage(`{"key":"value"}`)}, + }) + require.NoError(t, err) + resp, err := AnthropicToResponses(&AnthropicRequest{ + Model: "gpt-6.1-sol", MaxTokens: 1024, + Messages: []AnthropicMessage{ + {Role: "user", Content: json.RawMessage(`"Check this"`)}, + {Role: "assistant", Content: blocks}, + {Role: "user", Content: json.RawMessage(`[{"type":"tool_result","tool_use_id":"call_1","content":"found"}]`)}, + }, + }) + require.NoError(t, err) + var items []ResponsesInputItem + require.NoError(t, json.Unmarshal(resp.Input, &items)) + require.Len(t, items, 5) + require.Equal(t, "reasoning", items[1].Type) + require.Equal(t, "native-ciphertext", items[1].EncryptedContent) + require.Equal(t, "assistant", items[2].Role) + require.JSONEq(t, `[{"type":"output_text","text":"Checking now."}]`, string(items[2].Content)) + require.Equal(t, "function_call", items[3].Type) + require.Equal(t, "call_1", items[3].CallID) + require.Equal(t, "lookup", items[3].Name) + require.JSONEq(t, `{"key":"value"}`, items[3].Arguments) + require.Equal(t, "function_call_output", items[4].Type) + require.Equal(t, "call_1", items[4].CallID) + require.Equal(t, "found", items[4].Output) + }) + } +} + func TestAnthropicToResponses_MaxTokensFloor(t *testing.T) { req := &AnthropicRequest{ Model: "gpt-5.2", diff --git a/backend/internal/pkg/apicompat/anthropic_to_responses.go b/backend/internal/pkg/apicompat/anthropic_to_responses.go index df7c967f2b..b326241aa9 100644 --- a/backend/internal/pkg/apicompat/anthropic_to_responses.go +++ b/backend/internal/pkg/apicompat/anthropic_to_responses.go @@ -19,8 +19,22 @@ func AnthropicToResponses(req *AnthropicRequest) (*ResponsesRequest, error) { // AnthropicToResponsesWithMinOutputTokens converts an Anthropic request using // the supplied max_output_tokens floor. func AnthropicToResponsesWithMinOutputTokens(req *AnthropicRequest, minOutputTokens int) (*ResponsesRequest, error) { - if err := openai.ValidateGPT61ReasoningEffort(req.Model, anthropicReasoningEffort(req)); err != nil { - return nil, err + return AnthropicToResponsesWithOptions(req, AnthropicToResponsesOptions{MinOutputTokens: minOutputTokens}) +} + +// AnthropicToResponsesOptions controls conversion and optional deferred effort +// validation. Callers deferring validation must validate raw selections before +// conversion and the final effort after applying their policy. +type AnthropicToResponsesOptions struct { + MinOutputTokens int + DeferReasoningEffortValidation bool +} + +func AnthropicToResponsesWithOptions(req *AnthropicRequest, options AnthropicToResponsesOptions) (*ResponsesRequest, error) { + if !options.DeferReasoningEffortValidation { + if err := openai.ValidateGPT61ReasoningEffort(req.Model, anthropicReasoningEffort(req)); err != nil { + return nil, err + } } input, err := convertAnthropicToResponsesInput(req.System, req.Messages) if err != nil { @@ -56,8 +70,8 @@ func AnthropicToResponsesWithMinOutputTokens(req *AnthropicRequest, minOutputTok if req.MaxTokens > 0 { v := req.MaxTokens - if v < minOutputTokens { - v = minOutputTokens + if v < options.MinOutputTokens { + v = options.MinOutputTokens } out.MaxOutputTokens = &v } @@ -302,6 +316,11 @@ func anthropicAssistantToResponses(raw json.RawMessage) ([]ResponsesInputItem, e if sig == "" || strings.HasPrefix(sig, "gAAAA") { continue } + // CC Switch carries a JSON reasoning item in this versioned envelope, + // not provider ciphertext. Ignore the foreign state when resuming directly. + if strings.HasPrefix(sig, "ccswitch-openai-reasoning-v1:") { + continue + } items = append(items, ResponsesInputItem{ Type: "reasoning", EncryptedContent: sig, diff --git a/backend/internal/pkg/apicompat/responses_to_chatcompletions.go b/backend/internal/pkg/apicompat/responses_to_chatcompletions.go index 3616da3288..f33d4792b1 100644 --- a/backend/internal/pkg/apicompat/responses_to_chatcompletions.go +++ b/backend/internal/pkg/apicompat/responses_to_chatcompletions.go @@ -498,10 +498,12 @@ func generateChatCmplID() string { // --------------------------------------------------------------------------- type bufferedFuncCall struct { - OutputIndex int - CallID string - Name string - Args strings.Builder + OutputIndex int + CallID string + Name string + Namespace string + EncryptedFunctionArgs json.RawMessage + Args strings.Builder } // BufferedResponseAccumulator collects content from Responses SSE delta events @@ -540,9 +542,11 @@ func (a *BufferedResponseAccumulator) ProcessEvent(event *ResponsesStreamEvent) idx := len(a.funcCalls) a.outputIndexToFuncIdx[event.OutputIndex] = idx a.funcCalls = append(a.funcCalls, bufferedFuncCall{ - OutputIndex: event.OutputIndex, - CallID: event.Item.CallID, - Name: event.Item.Name, + OutputIndex: event.OutputIndex, + CallID: event.Item.CallID, + Name: event.Item.Name, + Namespace: event.Item.Namespace, + EncryptedFunctionArgs: event.Item.EncryptedFunctionArgs, }) } case "response.function_call_arguments.delta", "response.custom_tool_call_input.delta": @@ -607,10 +611,12 @@ func (a *BufferedResponseAccumulator) BuildOutput() []ResponsesOutput { for i := range a.funcCalls { out = append(out, ResponsesOutput{ - Type: "function_call", - CallID: a.funcCalls[i].CallID, - Name: a.funcCalls[i].Name, - Arguments: a.funcCalls[i].Args.String(), + Type: "function_call", + CallID: a.funcCalls[i].CallID, + Name: a.funcCalls[i].Name, + Namespace: a.funcCalls[i].Namespace, + EncryptedFunctionArgs: a.funcCalls[i].EncryptedFunctionArgs, + Arguments: a.funcCalls[i].Args.String(), }) } diff --git a/backend/internal/pkg/apicompat/types.go b/backend/internal/pkg/apicompat/types.go index ffa8960cb9..130f0ff63b 100644 --- a/backend/internal/pkg/apicompat/types.go +++ b/backend/internal/pkg/apicompat/types.go @@ -417,6 +417,9 @@ type ResponsesOutput struct { Arguments string `json:"arguments,omitempty"` // 来源为 namespace 子工具时的归属命名空间(codex 按 namespace+name 路由该调用)。 Namespace string `json:"namespace,omitempty"` + // Preserve the upstream encryption marker, including explicit null/[]; + // omitting it can make sealed arguments appear to be plaintext. + EncryptedFunctionArgs json.RawMessage `json:"encrypted_function_args,omitempty"` // type=custom_tool_call(custom/freeform 工具,input 为自由文本) Input string `json:"input,omitempty"` diff --git a/backend/internal/pkg/claude/effort_catalog.go b/backend/internal/pkg/claude/effort_catalog.go index 5676622f59..66efeab976 100644 --- a/backend/internal/pkg/claude/effort_catalog.go +++ b/backend/internal/pkg/claude/effort_catalog.go @@ -57,12 +57,12 @@ func IsHaiku55(model string) bool { return normalizeEffortModelID(model) == "claude-haiku-5-5" } -// IsFable52 identifies the Fable 5.2 model after provider/suffix normalization. +// IsFable52 identifies Fable 5.2 after provider/local suffix normalization. func IsFable52(model string) bool { return normalizeEffortModelID(model) == "claude-fable-5-2" } -// IsMythos52 identifies the restricted-access Mythos 5.2 model. +// IsMythos52 identifies Mythos 5.2 after provider/local suffix normalization. func IsMythos52(model string) bool { return normalizeEffortModelID(model) == "claude-mythos-5-2" } diff --git a/backend/internal/repository/migrations_runner.go b/backend/internal/repository/migrations_runner.go index 8c69eb50dd..5ec51a0e99 100644 --- a/backend/internal/repository/migrations_runner.go +++ b/backend/internal/repository/migrations_runner.go @@ -64,6 +64,8 @@ const usageLogsEffectiveRequestedModelIndex = "idx_usage_logs_effective_requeste const usageLogsEffectiveUpstreamModelIndex = "idx_usage_logs_effective_upstream_model_created" const usageLogsUpstreamRequestIDIndexMigration = "233_add_usage_log_upstream_request_id_index_notx.sql" const usageLogsUpstreamRequestIDIndex = "idx_usage_logs_upstream_request_id" +const usageLogsAPIKeyCostIndexMigration = "249_add_usage_logs_api_key_cost_index_notx.sql" +const usageLogsAPIKeyCostIndex = "idx_usage_logs_api_key_created_cost" type migrationChecksumCompatibilityRule struct { fileChecksum string @@ -309,6 +311,8 @@ func prepareNonTransactionalMigration(ctx context.Context, db migrationConnectio return nil case usageLogsUpstreamRequestIDIndexMigration: return dropInvalidIndexIfPresent(ctx, db, usageLogsUpstreamRequestIDIndex) + case usageLogsAPIKeyCostIndexMigration: + return dropInvalidIndexIfPresent(ctx, db, usageLogsAPIKeyCostIndex) default: return nil } diff --git a/backend/internal/repository/migrations_runner_api_key_cost_index_test.go b/backend/internal/repository/migrations_runner_api_key_cost_index_test.go new file mode 100644 index 0000000000..a9c6e1ee41 --- /dev/null +++ b/backend/internal/repository/migrations_runner_api_key_cost_index_test.go @@ -0,0 +1,49 @@ +package repository + +import ( + "context" + "database/sql" + "testing" + "testing/fstest" + + sqlmock "github.com/DATA-DOG/go-sqlmock" + "github.com/stretchr/testify/require" +) + +func TestApplyMigrationsFS_NonTransactionalMigration_APIKeyCostIndexDropsInvalidIndexBeforeRetry(t *testing.T) { + db, mock, err := sqlmock.New() + require.NoError(t, err) + defer func() { _ = db.Close() }() + + prepareMigrationsBootstrapExpectations(mock) + mock.ExpectQuery("SELECT checksum FROM schema_migrations WHERE filename = \\$1"). + WithArgs(usageLogsAPIKeyCostIndexMigration). + WillReturnError(sql.ErrNoRows) + mock.ExpectQuery("SELECT EXISTS \\("). + WithArgs(usageLogsAPIKeyCostIndex). + WillReturnRows(sqlmock.NewRows([]string{"exists"}).AddRow(true)) + mock.ExpectExec("DROP INDEX CONCURRENTLY IF EXISTS idx_usage_logs_api_key_created_cost"). + WillReturnResult(sqlmock.NewResult(0, 0)) + mock.ExpectExec("CREATE INDEX CONCURRENTLY IF NOT EXISTS idx_usage_logs_api_key_created_cost"). + WillReturnResult(sqlmock.NewResult(0, 0)) + mock.ExpectExec("INSERT INTO schema_migrations \\(filename, checksum\\) VALUES \\(\\$1, \\$2\\)"). + WithArgs(usageLogsAPIKeyCostIndexMigration, sqlmock.AnyArg()). + WillReturnResult(sqlmock.NewResult(1, 1)) + mock.ExpectExec("SELECT pg_advisory_unlock\\(\\$1\\)"). + WithArgs(migrationsAdvisoryLockID). + WillReturnResult(sqlmock.NewResult(0, 1)) + + fsys := fstest.MapFS{ + usageLogsAPIKeyCostIndexMigration: &fstest.MapFile{ + Data: []byte(` +CREATE INDEX CONCURRENTLY IF NOT EXISTS idx_usage_logs_api_key_created_cost + ON usage_logs (api_key_id, created_at) + INCLUDE (actual_cost); +`), + }, + } + + err = applyMigrationsFS(context.Background(), db, fsys) + require.NoError(t, err) + require.NoError(t, mock.ExpectationsWereMet()) +} diff --git a/backend/internal/repository/refresh_token_cache.go b/backend/internal/repository/refresh_token_cache.go index b01bd47697..2d131aecc0 100644 --- a/backend/internal/repository/refresh_token_cache.go +++ b/backend/internal/repository/refresh_token_cache.go @@ -3,6 +3,7 @@ package repository import ( "context" "encoding/json" + "errors" "fmt" "time" @@ -10,6 +11,18 @@ import ( "github.com/redis/go-redis/v9" ) +// consumeRefreshTokenScript atomically reads and deletes a refresh token. +// Rotation must only succeed for one concurrent caller, otherwise the same +// token can be exchanged twice (double-spend). +var consumeRefreshTokenScript = redis.NewScript(` + local value = redis.call('GET', KEYS[1]) + if not value then + return nil + end + redis.call('DEL', KEYS[1]) + return value +`) + const ( refreshTokenKeyPrefix = "refresh_token:" userRefreshTokensPrefix = "user_refresh_tokens:" @@ -70,6 +83,21 @@ func (c *refreshTokenCache) DeleteRefreshToken(ctx context.Context, tokenHash st return c.rdb.Del(ctx, key).Err() } +func (c *refreshTokenCache) ConsumeRefreshToken(ctx context.Context, tokenHash string) (*service.RefreshTokenData, error) { + val, err := consumeRefreshTokenScript.Run(ctx, c.rdb, []string{refreshTokenKey(tokenHash)}).Text() + if err != nil { + if errors.Is(err, redis.Nil) { + return nil, service.ErrRefreshTokenNotFound + } + return nil, err + } + var data service.RefreshTokenData + if err := json.Unmarshal([]byte(val), &data); err != nil { + return nil, fmt.Errorf("unmarshal refresh token data: %w", err) + } + return &data, nil +} + func (c *refreshTokenCache) DeleteUserRefreshTokens(ctx context.Context, userID int64) error { // Get all token hashes for this user tokenHashes, err := c.GetUserTokenHashes(ctx, userID) diff --git a/backend/internal/repository/refresh_token_cache_test.go b/backend/internal/repository/refresh_token_cache_test.go new file mode 100644 index 0000000000..c745a58c40 --- /dev/null +++ b/backend/internal/repository/refresh_token_cache_test.go @@ -0,0 +1,75 @@ +//go:build unit + +package repository + +import ( + "context" + "errors" + "sync" + "testing" + "time" + + "github.com/Wei-Shaw/sub2api/internal/service" + "github.com/alicebob/miniredis/v2" + "github.com/redis/go-redis/v9" + "github.com/stretchr/testify/require" +) + +func newRefreshTokenCacheForTest(t *testing.T) *refreshTokenCache { + t.Helper() + mr := miniredis.RunT(t) + rdb := redis.NewClient(&redis.Options{Addr: mr.Addr()}) + t.Cleanup(func() { _ = rdb.Close() }) + return &refreshTokenCache{rdb: rdb} +} + +type consumeResult struct { + data *service.RefreshTokenData + err error +} + +// 同一个 refresh token 被并发消费时,只能有一个调用成功。 +func TestRefreshTokenCacheConsumeIsAtomic(t *testing.T) { + cache := newRefreshTokenCacheForTest(t) + ctx := context.Background() + + require.NoError(t, cache.StoreRefreshToken(ctx, "hash-1", &service.RefreshTokenData{ + UserID: 7, + FamilyID: "family-1", + }, time.Minute)) + + const workers = 16 + results := make(chan consumeResult, workers) + start := make(chan struct{}) + var wg sync.WaitGroup + for i := 0; i < workers; i++ { + wg.Add(1) + go func() { + defer wg.Done() + <-start + data, err := cache.ConsumeRefreshToken(ctx, "hash-1") + results <- consumeResult{data: data, err: err} + }() + } + close(start) + wg.Wait() + close(results) + + successes, notFound := 0, 0 + for result := range results { + switch { + case result.err == nil: + successes++ + require.Equal(t, int64(7), result.data.UserID) + case errors.Is(result.err, service.ErrRefreshTokenNotFound): + notFound++ + default: + t.Fatalf("unexpected consume error: %v", result.err) + } + } + require.Equal(t, 1, successes) + require.Equal(t, workers-1, notFound) + + _, err := cache.GetRefreshToken(ctx, "hash-1") + require.ErrorIs(t, err, service.ErrRefreshTokenNotFound) +} diff --git a/backend/internal/repository/scheduler_cache_test.go b/backend/internal/repository/scheduler_cache_test.go index 0542842fdf..d6dfe7e01c 100644 --- a/backend/internal/repository/scheduler_cache_test.go +++ b/backend/internal/repository/scheduler_cache_test.go @@ -1,8 +1,10 @@ package repository import ( + "encoding/json" "strings" "testing" + "time" "github.com/Wei-Shaw/sub2api/internal/service" "github.com/stretchr/testify/require" @@ -54,6 +56,34 @@ func TestSchedulerMetadataAccountKeepsOpenAISubscriptionIdentity(t *testing.T) { require.Empty(t, metadata.GetCredential("access_token")) } +func TestSchedulerMetadataAccountKeepsProArgonQuotaIsolation(t *testing.T) { + account := service.Account{ + ID: 25, Platform: service.PlatformAntigravity, Type: service.AccountTypeOAuth, + Status: service.StatusActive, Schedulable: true, + Credentials: map[string]any{ + "plan_type": "Pro", "access_token": "secret-access-token", "refresh_token": "secret-refresh-token", + }, + Extra: map[string]any{ + "model_rate_limits": map[string]any{ + "antigravity:gemini:argon": map[string]any{ + "rate_limit_reset_at": time.Now().Add(time.Hour).Format(time.RFC3339), + }, + }, + }, + } + _, payload, err := marshalSchedulerCacheAccount(account) + require.NoError(t, err) + var metadata service.Account + require.NoError(t, json.Unmarshal([]byte(payload), &metadata)) + require.Equal(t, "Pro", metadata.GetCredential("plan_type")) + require.Empty(t, metadata.GetCredential("access_token")) + require.Empty(t, metadata.GetCredential("refresh_token")) + require.False(t, metadata.IsSchedulableForModel("gemini-4-argon-low")) + require.Positive(t, metadata.GetRateLimitRemainingTime("gemini-4-argon-low")) + require.True(t, metadata.IsSchedulableForModel("gemini-3.8-flash")) + require.Zero(t, metadata.GetRateLimitRemainingTime("gemini-3.8-flash")) +} + func TestSchedulerMetadataAccountProjectsUpstreamBillingProbe(t *testing.T) { lastError := strings.Repeat("upstream diagnostic ", 512) probe := map[string]any{ diff --git a/backend/internal/securityaudit/prompt_enqueue.go b/backend/internal/securityaudit/prompt_enqueue.go index 625636c90e..6336b477dd 100644 --- a/backend/internal/securityaudit/prompt_enqueue.go +++ b/backend/internal/securityaudit/prompt_enqueue.go @@ -10,6 +10,7 @@ type Enqueuer struct { repo JobRepository payload PayloadStore metrics Metrics + notify func() } func NewEnqueuer(config ConfigStore, repo JobRepository, payload PayloadStore, metrics ...Metrics) *Enqueuer { @@ -82,6 +83,9 @@ func (e *Enqueuer) Enqueue(ctx context.Context, req Request) error { e.recordDropped() return err } + if e.notify != nil { + e.notify() + } LogInfo(EventJobEnqueued, mergeLogFields(baseFields, map[string]any{ "job_id": job.ID, "queue_capacity": cfg.QueueCapacity, "status": "queued", diff --git a/backend/internal/securityaudit/prompt_service.go b/backend/internal/securityaudit/prompt_service.go index a8cefcd648..322d3c75e3 100644 --- a/backend/internal/securityaudit/prompt_service.go +++ b/backend/internal/securityaudit/prompt_service.go @@ -42,6 +42,7 @@ func NewPromptService( enqueuer := NewEnqueuer(config, repo, payload, metrics) evaluator := NewGuardEvaluator(scanner, repo, metrics) runner := NewRunner(config, repo, payload, scanner, metrics) + enqueuer.notify = runner.Notify return &PromptService{ config: config, repo: repo, payload: payload, scanner: scanner, metrics: metrics, enqueuer: enqueuer, evaluator: evaluator, runner: runner, clock: realClock{}, diff --git a/backend/internal/securityaudit/prompt_worker.go b/backend/internal/securityaudit/prompt_worker.go index 05ae828f05..89824299fb 100644 --- a/backend/internal/securityaudit/prompt_worker.go +++ b/backend/internal/securityaudit/prompt_worker.go @@ -8,6 +8,10 @@ import ( "time" ) +// workerIdlePoll is the fallback claim interval. Local enqueues also wake workers +// directly; polling still picks up retries that come due and jobs enqueued by other replicas. +const workerIdlePoll = 500 * time.Millisecond + type WorkerRuntime struct { active atomic.Int64 processed atomic.Int64 @@ -27,6 +31,7 @@ type Runner struct { metrics Metrics clock Clock runtime WorkerRuntime + wake []chan struct{} mu sync.Mutex cancel context.CancelFunc @@ -34,7 +39,27 @@ type Runner struct { } func NewRunner(config ConfigStore, repo JobRepository, payload PayloadStore, scanner PromptScanner, metrics Metrics) *Runner { - return &Runner{config: config, repo: repo, payload: payload, scanner: scanner, metrics: metrics, clock: realClock{}} + wake := make([]chan struct{}, MaxWorkerCount) + for i := range wake { + // Pre-filled so each worker drains jobs left over from a previous run at start. + wake[i] = make(chan struct{}, 1) + wake[i] <- struct{}{} + } + return &Runner{config: config, repo: repo, payload: payload, scanner: scanner, metrics: metrics, clock: realClock{}, wake: wake} +} + +// Notify wakes every worker to claim queued jobs. It never blocks; a worker that +// already has a pending wake-up keeps just one. +func (r *Runner) Notify() { + if r == nil { + return + } + for _, ch := range r.wake { + select { + case ch <- struct{}{}: + default: + } + } } func (r *Runner) Start(ctx context.Context) error { @@ -85,31 +110,36 @@ func (r *Runner) Shutdown(ctx context.Context) error { func (r *Runner) worker(ctx context.Context, workerID int) { defer r.wg.Done() - ticker := time.NewTicker(500 * time.Millisecond) + ticker := time.NewTicker(workerIdlePoll) defer ticker.Stop() + var wake <-chan struct{} + if workerID < len(r.wake) { + wake = r.wake[workerID] + } for { select { case <-ctx.Done(): return case <-ticker.C: - r.runtime.heartbeatNS.Store(r.clock.Now().UnixNano()) - cfg, ok := r.config.Active() - if !ok || !cfg.RiskControlEnabled || !cfg.Enabled || workerID >= cfg.WorkerCount { - continue + case <-wake: + } + r.runtime.heartbeatNS.Store(r.clock.Now().UnixNano()) + cfg, ok := r.config.Active() + if !ok || !cfg.RiskControlEnabled || !cfg.Enabled || workerID >= cfg.WorkerCount { + continue + } + for { + job, claimed, err := r.repo.ClaimNextJob(ctx, r.clock.Now()) + if err != nil { + r.setLastError("claim_job_failed", err.Error()) + break } - for { - job, claimed, err := r.repo.ClaimNextJob(ctx, r.clock.Now()) - if err != nil { - r.setLastError("claim_job_failed", err.Error()) - break - } - if !claimed { - break - } - r.runtime.active.Add(1) - r.processSafely(ctx, workerID, cfg, job) - r.runtime.active.Add(-1) + if !claimed { + break } + r.runtime.active.Add(1) + r.processSafely(ctx, workerID, cfg, job) + r.runtime.active.Add(-1) } } } @@ -273,6 +303,7 @@ func (r *Runner) reclaimer(ctx context.Context) { continue } if count > 0 { + r.Notify() LogWarn(EventProcessingReclaimed, map[string]any{"reclaimed_total": count, "status": "reclaimed"}) } } diff --git a/backend/internal/securityaudit/prompt_worker_test.go b/backend/internal/securityaudit/prompt_worker_test.go index a91569c2cf..a8de8833e8 100644 --- a/backend/internal/securityaudit/prompt_worker_test.go +++ b/backend/internal/securityaudit/prompt_worker_test.go @@ -84,6 +84,7 @@ type fakeJobRepository struct { refreshes int claimQueue []*Job + claims int recordBlockingCalls int recordBlockingSnapshot PromptSnapshot @@ -126,6 +127,7 @@ func (r *fakeJobRepository) MarkStagingFailed(_ context.Context, _ int64, code, func (r *fakeJobRepository) ClaimNextJob(context.Context, time.Time) (*Job, bool, error) { r.mu.Lock() defer r.mu.Unlock() + r.claims++ if len(r.claimQueue) == 0 { return nil, false, nil } diff --git a/backend/internal/securityaudit/prompt_worker_wake_test.go b/backend/internal/securityaudit/prompt_worker_wake_test.go new file mode 100644 index 0000000000..715aa43aa1 --- /dev/null +++ b/backend/internal/securityaudit/prompt_worker_wake_test.go @@ -0,0 +1,81 @@ +package securityaudit + +import ( + "context" + "errors" + "testing" + "time" + + "github.com/stretchr/testify/require" +) + +func TestEnqueuerNotifiesOnlyAfterPublish(t *testing.T) { + cases := []struct { + name string + publishErr error + want int + }{ + {name: "published", want: 1}, + {name: "publish failed", publishErr: errors.New("db down"), want: 0}, + } + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + repo := &fakeJobRepository{createJob: &Job{ID: 41}, publishErr: tc.publishErr} + enqueuer := NewEnqueuer(&fakeConfigStore{cfg: asyncConfig(), active: true}, repo, &fakePayloadStore{values: map[int64]string{}}) + notified := 0 + enqueuer.notify = func() { notified++ } + _ = enqueuer.Enqueue(context.Background(), asyncRequest()) + require.Equal(t, tc.want, notified) + }) + } +} + +// Both cases must finish before the first fallback tick (workerIdlePoll), so they +// exercise the start-up drain and the wake path rather than polling. +func TestWorkerClaimsWithoutWaitingForIdlePoll(t *testing.T) { + newRunner := func(repo *fakeJobRepository) *Runner { + payload := &fakePayloadStore{values: map[int64]string{51: "abc"}} + return NewRunner(&fakeConfigStore{cfg: asyncConfig(), active: true}, repo, payload, PromptScannerFunc(func(context.Context, ActiveEndpoint, string, []string) (*NormalizedResult, error) { + return integrationResult(EventPass), nil + }), NewAtomicMetrics()) + } + completed := func(repo *fakeJobRepository) func() bool { + return func() bool { repo.mu.Lock(); defer repo.mu.Unlock(); return repo.completeCount == 1 } + } + stop := func(t *testing.T, runner *Runner) { + ctx, cancel := context.WithTimeout(context.Background(), time.Second) + defer cancel() + require.NoError(t, runner.Shutdown(ctx)) + } + + t.Run("jobs left from a previous run are drained at start", func(t *testing.T) { + repo := &fakeJobRepository{claimQueue: []*Job{workerJob(1, 3)}} + runner := newRunner(repo) + require.NoError(t, runner.Start(context.Background())) + defer stop(t, runner) + require.Eventually(t, completed(repo), workerIdlePoll/2, 5*time.Millisecond) + }) + + t.Run("notify wakes an idle worker", func(t *testing.T) { + repo := &fakeJobRepository{} + runner := newRunner(repo) + require.NoError(t, runner.Start(context.Background())) + defer stop(t, runner) + // wait for the start-up drain to find an empty queue + require.Eventually(t, func() bool { repo.mu.Lock(); defer repo.mu.Unlock(); return repo.claims > 0 }, workerIdlePoll/2, time.Millisecond) + repo.mu.Lock() + repo.claimQueue = append(repo.claimQueue, workerJob(1, 3)) + repo.mu.Unlock() + runner.Notify() + require.Eventually(t, completed(repo), workerIdlePoll/2, 5*time.Millisecond) + }) + + t.Run("notify never blocks", func(t *testing.T) { + runner := newRunner(&fakeJobRepository{}) + for i := 0; i < 3; i++ { + runner.Notify() + } + var nilRunner *Runner + nilRunner.Notify() + }) +} diff --git a/backend/internal/service/antigravity_gateway_retry.go b/backend/internal/service/antigravity_gateway_retry.go index 2be464bbe5..70920eba04 100644 --- a/backend/internal/service/antigravity_gateway_retry.go +++ b/backend/internal/service/antigravity_gateway_retry.go @@ -882,7 +882,7 @@ func (s *AntigravityGatewayService) setAntigravityModelRateLimits(ctx context.Co if account == nil || repo == nil { return false } - keys := antigravityModelRateLimitKeys(modelName) + keys := antigravityModelRateLimitKeys(account, modelName) if len(keys) == 0 { return false } diff --git a/backend/internal/service/antigravity_pro_quota_rate_limit_test.go b/backend/internal/service/antigravity_pro_quota_rate_limit_test.go new file mode 100644 index 0000000000..34b2ab4199 --- /dev/null +++ b/backend/internal/service/antigravity_pro_quota_rate_limit_test.go @@ -0,0 +1,104 @@ +//go:build unit + +package service + +import ( + "context" + "encoding/json" + "net/http" + "testing" + "time" + + "github.com/stretchr/testify/require" +) + +func TestAntigravityModelRateLimits_ProArgonQuotaIsolation(t *testing.T) { + plans := []struct { + name string + value any + separate bool + }{ + {name: "Pro", value: "Pro", separate: true}, + {name: "normalized Pro", value: " pro ", separate: true}, + {name: "Pro tier ID", value: "g1-pro-tier", separate: true}, + {name: "Ultra", value: "Ultra"}, + {name: "Ultra tier ID", value: "g1-ultra-tier"}, + {name: "Ultra lite tier ID", value: "g1-ultra-lite-tier"}, + {name: "free", value: "Free"}, + {name: "unknown", value: "enterprise"}, + {name: "missing"}, + {name: "malformed", value: 42}, + } + pools := []struct { + name string + exhausted string + same []string + other []string + }{ + { + name: "Argon exhausted", + exhausted: "gemini-4-argon-high", + same: []string{"gemini-4-argon-high", "gemini-4-argon-low", "gemini-4-argon-medium", "client-argon"}, + other: []string{"gemini-3.8-flash", "gemini-2.5-pro"}, + }, + { + name: "other Gemini exhausted", + exhausted: "gemini-3.8-flash", + same: []string{"gemini-3.8-flash", "gemini-2.5-pro"}, + other: []string{"gemini-4-argon-high", "gemini-4-argon-low", "gemini-4-argon-medium", "client-argon"}, + }, + } + for _, plan := range plans { + for _, pool := range pools { + t.Run(plan.name+"/"+pool.name, func(t *testing.T) { + account := &Account{ + ID: 789, Platform: PlatformAntigravity, Status: StatusActive, Schedulable: true, + Credentials: map[string]any{ + "plan_type": plan.value, + "model_mapping": map[string]any{ + "gemini-4-argon-high": "gemini-4-argon-high", + "gemini-4-argon-low": "gemini-4-argon-low", + "gemini-4-argon-medium": "gemini-4-argon-medium", + "client-argon": "gemini-4-argon-high", + "gemini-3.8-flash": "gemini-3.8-flash", + "gemini-2.5-pro": "gemini-2.5-pro", + "gemini-3-pro-image": "gemini-3-pro-image", + "claude-sonnet-4-6": "claude-sonnet-4-6", + }, + }, + } + repo := &stubAntigravityAccountRepo{} + svc := &AntigravityGatewayService{} + resetAt := time.Now().Add(time.Hour) + require.True(t, svc.setAntigravityModelRateLimits(context.Background(), repo, account, + pool.exhausted, "[test]", http.StatusTooManyRequests, resetAt, false)) + + // Recreate the persisted limits, then read a fresh account through JSON, + // as the scheduler does instead of using the forwarding account object. + limits := make(map[string]any) + for _, call := range repo.modelRateLimitCalls { + require.Equal(t, account.ID, call.accountID) + limits[call.modelKey] = map[string]any{"rate_limit_reset_at": call.resetAt.Format(time.RFC3339)} + } + account.Extra = map[string]any{modelRateLimitsKey: limits} + data, err := json.Marshal(account) + require.NoError(t, err) + var snapshot Account + require.NoError(t, json.Unmarshal(data, &snapshot)) + + for _, model := range pool.same { + require.False(t, snapshot.IsSchedulableForModel(model), "exhausted pool: %s", model) + require.Positive(t, snapshot.GetRateLimitRemainingTime(model), "exhausted pool: %s", model) + } + for _, model := range pool.other { + require.Equal(t, plan.separate, snapshot.IsSchedulableForModel(model), "other pool: %s", model) + require.Equal(t, !plan.separate, snapshot.GetRateLimitRemainingTime(model) > 0, "other pool: %s", model) + } + for _, model := range []string{"gemini-3-pro-image", "claude-sonnet-4-6"} { + require.True(t, snapshot.IsSchedulableForModel(model), "unrelated model: %s", model) + require.Zero(t, snapshot.GetRateLimitRemainingTime(model)) + } + }) + } + } +} diff --git a/backend/internal/service/antigravity_tool_result_images_test.go b/backend/internal/service/antigravity_tool_result_images_test.go index b254c18da2..f555e0d0db 100644 --- a/backend/internal/service/antigravity_tool_result_images_test.go +++ b/backend/internal/service/antigravity_tool_result_images_test.go @@ -62,3 +62,26 @@ func toolImageCompatWire(t *testing.T, raw []byte, model string) []byte { require.NoError(t, err) return wire } + +func TestAntigravityResponsesParallelToolResultImagesKeepFunctionResponsesContiguous(t *testing.T) { + for _, model := range []string{"claude-opus-5-5-medium", "gemini-2.5-flash"} { + t.Run(model, func(t *testing.T) { + raw := []byte(`{"model":"client-alias","input":[ + {"type":"function_call","call_id":"call_img_1","name":"view_image","arguments":"{}"}, + {"type":"function_call","call_id":"call_img_2","name":"view_image","arguments":"{}"}, + {"type":"function_call","call_id":"call_cmd_3","name":"exec_command","arguments":"{}"}, + {"type":"function_call_output","call_id":"call_img_1","output":[{"type":"input_image","image_url":"data:image/png;base64,AQID"}]}, + {"type":"function_call_output","call_id":"call_img_2","output":[{"type":"input_text","text":"second image"},{"type":"input_image","image_url":"data:image/jpeg;base64,BAUG"}]}, + {"type":"function_call_output","call_id":"call_cmd_3","output":"done"} + ]}`) + wire := toolImageCompatWire(t, raw, model) + parts := gjson.GetBytes(wire, "request.contents.1.parts").Array() + require.Len(t, parts, 5) + require.Equal(t, "view_image", parts[0].Get("functionResponse.name").String()) + require.Equal(t, "view_image", parts[1].Get("functionResponse.name").String()) + require.Equal(t, "exec_command", parts[2].Get("functionResponse.name").String()) + require.Equal(t, "AQID", parts[3].Get("inlineData.data").String()) + require.Equal(t, "BAUG", parts[4].Get("inlineData.data").String()) + }) + } +} diff --git a/backend/internal/service/apicompat_config.go b/backend/internal/service/apicompat_config.go index e9605e0a5c..8d7680594c 100644 --- a/backend/internal/service/apicompat_config.go +++ b/backend/internal/service/apicompat_config.go @@ -16,10 +16,6 @@ func chatCompletionsToResponses(cfg *config.Config, req *apicompat.ChatCompletio return apicompat.ChatCompletionsToResponsesWithMinOutputTokens(req, configuredMinOutputTokens(cfg)) } -func anthropicToResponses(cfg *config.Config, req *apicompat.AnthropicRequest) (*apicompat.ResponsesRequest, error) { - return apicompat.AnthropicToResponsesWithMinOutputTokens(req, configuredMinOutputTokens(cfg)) -} - func settingServiceConfig(settingService *SettingService) *config.Config { if settingService == nil { return nil diff --git a/backend/internal/service/auth_service.go b/backend/internal/service/auth_service.go index ded56e1e13..5dbe3bca29 100644 --- a/backend/internal/service/auth_service.go +++ b/backend/internal/service/auth_service.go @@ -1869,10 +1869,15 @@ func (s *AuthService) RefreshTokenPair(ctx context.Context, refreshToken string) } } - // Token轮转:立即使旧Token失效 - if err := s.refreshTokenCache.DeleteRefreshToken(ctx, tokenHash); err != nil { - logger.LegacyPrintf("service.auth", "[Auth] Failed to delete old refresh token: %v", err) - // 继续处理,不影响主流程 + // Token轮转:原子消费旧Token。并发刷新时只有一个请求能成功, + // 其余请求拿到 ErrRefreshTokenNotFound,避免同一个 Refresh Token 被兑换两次。 + if _, err := s.refreshTokenCache.ConsumeRefreshToken(ctx, tokenHash); err != nil { + if errors.Is(err, ErrRefreshTokenNotFound) { + logger.LegacyPrintf("service.auth", "[Auth] Refresh token already consumed, possible reuse attack") + return nil, ErrRefreshTokenInvalid + } + logger.LegacyPrintf("service.auth", "[Auth] Failed to consume old refresh token: %v", err) + return nil, ErrServiceUnavailable } // 生成新的Token对,保持同一个家族ID diff --git a/backend/internal/service/auth_service_email_bind_test.go b/backend/internal/service/auth_service_email_bind_test.go index c41734c40b..a728b41077 100644 --- a/backend/internal/service/auth_service_email_bind_test.go +++ b/backend/internal/service/auth_service_email_bind_test.go @@ -919,6 +919,24 @@ func (s *emailBindRefreshTokenCacheStub) DeleteRefreshToken(_ context.Context, t return nil } +func (s *emailBindRefreshTokenCacheStub) ConsumeRefreshToken(_ context.Context, tokenHash string) (*service.RefreshTokenData, error) { + s.mu.Lock() + defer s.mu.Unlock() + data, ok := s.tokens[tokenHash] + if !ok { + return nil, service.ErrRefreshTokenNotFound + } + delete(s.tokens, tokenHash) + for _, tokenSet := range s.userSets { + delete(tokenSet, tokenHash) + } + for _, tokenSet := range s.families { + delete(tokenSet, tokenHash) + } + cloned := *data + return &cloned, nil +} + func (s *emailBindRefreshTokenCacheStub) DeleteUserRefreshTokens(_ context.Context, userID int64) error { s.mu.Lock() defer s.mu.Unlock() diff --git a/backend/internal/service/auth_service_refresh_race_test.go b/backend/internal/service/auth_service_refresh_race_test.go new file mode 100644 index 0000000000..c177fc2ff6 --- /dev/null +++ b/backend/internal/service/auth_service_refresh_race_test.go @@ -0,0 +1,104 @@ +//go:build unit + +package service_test + +import ( + "context" + "errors" + "sync" + "testing" + + "github.com/Wei-Shaw/sub2api/internal/config" + "github.com/Wei-Shaw/sub2api/internal/service" + "github.com/stretchr/testify/require" +) + +// barrierRefreshTokenCacheStub 让所有并发请求都先读到旧 token,再统一放行, +// 从而确定性地复现 "Get 之后、消费之前" 的 double-spend 窗口。 +type barrierRefreshTokenCacheStub struct { + *emailBindRefreshTokenCacheStub + + target int + barrier chan struct{} + mu sync.Mutex + reads int +} + +func newBarrierRefreshTokenCacheStub(target int) *barrierRefreshTokenCacheStub { + return &barrierRefreshTokenCacheStub{ + emailBindRefreshTokenCacheStub: newEmailBindRefreshTokenCacheStub(), + target: target, + barrier: make(chan struct{}), + } +} + +func (s *barrierRefreshTokenCacheStub) GetRefreshToken(ctx context.Context, tokenHash string) (*service.RefreshTokenData, error) { + data, err := s.emailBindRefreshTokenCacheStub.GetRefreshToken(ctx, tokenHash) + + s.mu.Lock() + s.reads++ + if s.reads == s.target { + close(s.barrier) + } + s.mu.Unlock() + <-s.barrier + return data, err +} + +// 同一个 refresh token 并发刷新时,只能有一个请求成功兑换,其余必须失败。 +func TestAuthServiceRefreshTokenPairConsumesTokenOnce(t *testing.T) { + ctx := context.Background() + const workers = 8 + cache := newBarrierRefreshTokenCacheStub(workers) + + user := &service.User{ + ID: 41, + Email: "refresh-race@example.com", + Username: "refresh-race", + Role: service.RoleUser, + Status: service.StatusActive, + TokenVersion: 1, + } + cfg := &config.Config{ + JWT: config.JWTConfig{ + Secret: "test-refresh-race-secret", + ExpireHour: 1, + AccessTokenExpireMinutes: 60, + RefreshTokenExpireDays: 7, + }, + } + svc := service.NewAuthService(nil, newEmailBindUserRepoStub(user), nil, cache, cfg, nil, nil, nil, nil, nil, nil, nil, nil) + + pair, err := svc.GenerateTokenPair(ctx, user, "") + require.NoError(t, err) + + start := make(chan struct{}) + errs := make(chan error, workers) + var wg sync.WaitGroup + for i := 0; i < workers; i++ { + wg.Add(1) + go func() { + defer wg.Done() + <-start + _, refreshErr := svc.RefreshTokenPair(ctx, pair.RefreshToken) + errs <- refreshErr + }() + } + close(start) + wg.Wait() + close(errs) + + successes, invalid := 0, 0 + for refreshErr := range errs { + switch { + case refreshErr == nil: + successes++ + case errors.Is(refreshErr, service.ErrRefreshTokenInvalid): + invalid++ + default: + t.Fatalf("unexpected refresh error: %v", refreshErr) + } + } + require.Equal(t, 1, successes) + require.Equal(t, workers-1, invalid) +} diff --git a/backend/internal/service/auth_service_register_test.go b/backend/internal/service/auth_service_register_test.go index 076cd025d3..a1e211bac8 100644 --- a/backend/internal/service/auth_service_register_test.go +++ b/backend/internal/service/auth_service_register_test.go @@ -149,6 +149,10 @@ func (s *refreshTokenCacheStub) DeleteTokenFamily(context.Context, string) error return nil } +func (s *refreshTokenCacheStub) ConsumeRefreshToken(context.Context, string) (*RefreshTokenData, error) { + return nil, ErrRefreshTokenNotFound +} + func (s *refreshTokenCacheStub) AddToUserTokenSet(context.Context, int64, string, time.Duration) error { return nil } diff --git a/backend/internal/service/billing_service.go b/backend/internal/service/billing_service.go index 0dc2752515..ca526bd8b6 100644 --- a/backend/internal/service/billing_service.go +++ b/backend/internal/service/billing_service.go @@ -426,7 +426,7 @@ func (s *BillingService) initFallbackPricing() { InputPricePerToken: 2e-6, OutputPricePerToken: 10e-6, CacheCreationPricePerToken: 2.5e-6, - CacheReadPricePerToken: 0.2e-6, + CacheReadPricePerToken: 0.1e-6, CacheCreation5mPrice: 2.5e-6, CacheCreation1hPrice: 4e-6, SupportsCacheBreakdown: true, @@ -445,7 +445,19 @@ func (s *BillingService) initFallbackPricing() { LongContextInputMultiplier: 5, LongContextOutputMultiplier: 5, } - // Claude Fable 5 and 5.1 use the same input/output and cache-write prices, while + for _, model := range []string{"claude-fable-5-2", "claude-mythos-5-2"} { + p := claude52FallbackPricing + s.fallbackPrices[model] = &ModelPricing{ + InputPricePerToken: p.InputCostPerToken, + OutputPricePerToken: p.OutputCostPerToken, + CacheCreationPricePerToken: p.CacheCreationInputTokenCost, + CacheCreation5mPrice: p.CacheCreationInputTokenCost, + CacheCreation1hPrice: p.CacheCreationInputTokenCostAbove1hr, + CacheReadPricePerToken: p.CacheReadInputTokenCost, + SupportsCacheBreakdown: true, + } + } + // Claude Fable 5.0 and 5.1 use the same input/output and cache-write prices, while // Fable 5.1 reduces cache reads from $1 to $0.25 per MTok. s.fallbackPrices["claude-fable-5"] = &ModelPricing{ InputPricePerToken: 10e-6, @@ -466,20 +478,6 @@ func (s *BillingService) initFallbackPricing() { SupportsCacheBreakdown: true, } - // Fable/Mythos 5.2: https://platform.claude.com/docs/en/about-claude/pricing - // No long-context surcharge. Fast mode uses the standard 2x tier multiplier. - for _, model := range []string{"claude-fable-5-2", "claude-mythos-5-2"} { - s.fallbackPrices[model] = &ModelPricing{ - InputPricePerToken: 8e-6, - OutputPricePerToken: 40e-6, - CacheCreationPricePerToken: 10e-6, - CacheCreation5mPrice: 10e-6, - CacheCreation1hPrice: 16e-6, - CacheReadPricePerToken: 0.2e-6, - SupportsCacheBreakdown: true, - } - } - // Gemini 3.1 Pro s.fallbackPrices["gemini-3.1-pro"] = &ModelPricing{ InputPricePerToken: 2e-6, // $2 per MTok @@ -1078,15 +1076,13 @@ func (s *BillingService) getFallbackPricing(model string) *ModelPricing { return s.fallbackPrices["jev-latest"] } - // Match 5.2 before the older, more general Fable family fallback. + // 按模型系列匹配 if claude.IsFable52(modelLower) { return s.fallbackPrices["claude-fable-5-2"] } if claude.IsMythos52(modelLower) { return s.fallbackPrices["claude-mythos-5-2"] } - - // 按模型系列匹配 if isClaudeFable51Model(modelLower) { return s.fallbackPrices["claude-fable-5-1"] } diff --git a/backend/internal/service/billing_service_test.go b/backend/internal/service/billing_service_test.go index cb68489b49..52264f8058 100644 --- a/backend/internal/service/billing_service_test.go +++ b/backend/internal/service/billing_service_test.go @@ -2104,7 +2104,8 @@ func TestNewModelPricingCatalogFallbackAndContext(t *testing.T) { require.NoError(t, err) require.InDelta(t, 100_000*2e-6, cost.InputCost, 1e-10) require.InDelta(t, 400*2.5e-6+600*4e-6, cost.CacheCreationCost, 1e-10) - require.InDelta(t, 1000*0.2e-6, cost.CacheReadCost, 1e-10) + // Sonnet 5.5 cache hits cost 5% of the $2/MTok input price (#8378). + require.InDelta(t, 1000*0.1e-6, cost.CacheReadCost, 1e-10) require.InDelta(t, 500*10e-6, cost.OutputCost, 1e-10) require.False(t, cost.LongContextBillingApplied) }) diff --git a/backend/internal/service/claude52_pricing_test.go b/backend/internal/service/claude52_pricing_test.go new file mode 100644 index 0000000000..b1515904cf --- /dev/null +++ b/backend/internal/service/claude52_pricing_test.go @@ -0,0 +1,114 @@ +package service + +import ( + "context" + "os" + "testing" + + "github.com/Wei-Shaw/sub2api/internal/config" + "github.com/stretchr/testify/require" +) + +func TestClaude52Pricing(t *testing.T) { + embedded, err := os.ReadFile("../../resources/model-pricing/model_prices_and_context_window.json") + require.NoError(t, err) + + for _, family := range []string{"fable", "mythos"} { + model := "claude-" + family + "-5-2" + for _, source := range []string{"no_catalog", "older_catalog", "embedded_catalog", "fable_only_remote_catalog"} { + t.Run(family+"/"+source, func(t *testing.T) { + var catalog *PricingService + switch source { + case "older_catalog": + catalog = newStubPricingServiceFromJSON(t, `{ + "claude-fable-5-1": {"input_cost_per_token": 1e-5, "output_cost_per_token": 5e-5}, + "claude-sonnet-4-5": {"input_cost_per_token": 3e-6, "output_cost_per_token": 1.5e-5} + }`) + case "fable_only_remote_catalog": + // The default remote catalog already prices Fable 5.2 correctly. + catalog = newStubPricingServiceFromJSON(t, `{ + "claude-fable-5-2": {"input_cost_per_token": 8e-6, "output_cost_per_token": 40e-6, + "cache_creation_input_token_cost": 10e-6, "cache_creation_input_token_cost_above_1hr": 16e-6, + "cache_read_input_token_cost": 0.2e-6} + }`) + case "embedded_catalog": + catalog = newStubPricingServiceFromJSON(t, string(embedded)) + } + svc := NewBillingService(&config.Config{}, catalog) + for _, name := range []string{model, "models/" + model, "anthropic/" + model, "anthropic." + model, "global.anthropic." + model} { + t.Run(name, func(t *testing.T) { + pricing, err := svc.GetModelPricing(name) + require.NoError(t, err) + require.InDelta(t, 8e-6, pricing.InputPricePerToken, 1e-12) + require.InDelta(t, 40e-6, pricing.OutputPricePerToken, 1e-12) + require.InDelta(t, 10e-6, pricing.CacheCreationPricePerToken, 1e-12) + require.InDelta(t, 10e-6, pricing.CacheCreation5mPrice, 1e-12) + require.InDelta(t, 16e-6, pricing.CacheCreation1hPrice, 1e-12) + require.InDelta(t, 0.2e-6, pricing.CacheReadPricePerToken, 1e-12) + require.True(t, pricing.SupportsCacheBreakdown) + }) + } + + // Cache writes have distinct TTL rates and are counted only once. + tokens := UsageTokens{InputTokens: 250000, OutputTokens: 200, CacheCreationTokens: 1000, + CacheCreation5mTokens: 600, CacheCreation1hTokens: 400, CacheReadTokens: 3000} + for _, tier := range []string{"", "fast", "priority"} { + t.Run("cost/"+tier, func(t *testing.T) { + multiplier := 1.0 + if tier != "" { + multiplier = 2 + } + cost, err := svc.CalculateCostWithServiceTier(model, tokens, 1.5, tier) + require.NoError(t, err) + require.InDelta(t, 2*multiplier, cost.InputCost, 1e-12) + require.InDelta(t, 0.008*multiplier, cost.OutputCost, 1e-12) + require.InDelta(t, 0.0124*multiplier, cost.CacheCreationCost, 1e-12) + require.InDelta(t, 0.0006*multiplier, cost.CacheReadCost, 1e-12) + require.InDelta(t, 2.021*multiplier, cost.TotalCost, 1e-12) + require.InDelta(t, 3.0315*multiplier, cost.ActualCost, 1e-12) + require.False(t, cost.LongContextBillingApplied) + + unified, err := svc.CalculateCostUnified(CostInput{ + Ctx: context.Background(), Model: model, Tokens: tokens, RateMultiplier: 1.5, + ServiceTier: tier, Resolver: NewModelPricingResolver(nil, svc), + }) + require.NoError(t, err) + cost.BillingMode = string(BillingModeToken) + require.Equal(t, cost, unified) + }) + } + }) + } + } +} + +func TestClaude52CatalogOverridesAndVersionBoundaries(t *testing.T) { + for _, family := range []string{"fable", "mythos"} { + model := "claude-" + family + "-5-2" + t.Run(family+"/catalog_override", func(t *testing.T) { + catalog := newStubPricingServiceFromJSON(t, `{"`+model+`": { + "input_cost_per_token": 0, "output_cost_per_token": 7e-6, + "cache_creation_input_token_cost": 0, "cache_read_input_token_cost": 0 + }}`) + svc := NewBillingService(&config.Config{}, catalog) + pricing, err := svc.GetModelPricing(model) + require.NoError(t, err) + require.Zero(t, pricing.InputPricePerToken) + require.InDelta(t, 7e-6, pricing.OutputPricePerToken, 1e-12) + require.Zero(t, pricing.CacheCreationPricePerToken) + require.Zero(t, pricing.CacheReadPricePerToken) + for _, name := range []string{model, "anthropic/" + model, "global.anthropic." + model} { + require.Same(t, catalog.pricingData[model], catalog.GetModelPricing(name)) + } + }) + } + + svc := NewBillingService(&config.Config{}, nil) + for _, model := range []string{"claude-fable-5", "claude-fable-5-1", "claude-fable-5-20", "claude-fable-5-2-preview", "claude-mythos-5-20"} { + t.Run(model, func(t *testing.T) { + pricing, err := svc.GetModelPricing(model) + require.NoError(t, err) + require.NotEqual(t, 8e-6, pricing.InputPricePerToken) + }) + } +} diff --git a/backend/internal/service/gateway_compat_error_policy_test.go b/backend/internal/service/gateway_compat_error_policy_test.go new file mode 100644 index 0000000000..2c2d53d24f --- /dev/null +++ b/backend/internal/service/gateway_compat_error_policy_test.go @@ -0,0 +1,124 @@ +//go:build unit + +package service + +import ( + "context" + "io" + "net/http" + "net/http/httptest" + "strconv" + "strings" + "testing" + + "github.com/Wei-Shaw/sub2api/internal/config" + "github.com/gin-gonic/gin" + "github.com/stretchr/testify/require" +) + +func TestAnthropicCompatAccountErrorPolicy(t *testing.T) { + for _, tc := range []struct { + name string + status int + credentials map[string]any + wantError int + wantTemp int + wantFailover bool + }{ + { + name: "custom gone", status: http.StatusGone, + credentials: map[string]any{ + "custom_error_codes_enabled": true, + "custom_error_codes": []any{float64(http.StatusGone)}, + }, + wantError: 1, wantFailover: true, + }, + { + name: "pool custom gone", status: http.StatusGone, + credentials: map[string]any{ + "pool_mode": true, + "pool_mode_retry_status_codes": []any{float64(http.StatusGone)}, + "custom_error_codes_enabled": true, + "custom_error_codes": []any{float64(http.StatusGone)}, + }, + wantError: 1, wantFailover: true, + }, + { + name: "pool temporary gone", status: http.StatusGone, + credentials: map[string]any{ + "pool_mode": true, + "pool_mode_retry_status_codes": []any{float64(http.StatusGone)}, + "temp_unschedulable_enabled": true, + "temp_unschedulable_rules": []any{map[string]any{ + "scope": "account", + "error_code": float64(http.StatusGone), + "keywords": []any{"Service moved"}, + "duration_minutes": float64(10), + }}, + }, + wantTemp: 1, wantFailover: true, + }, + {name: "unconfigured gone", status: http.StatusGone}, + { + name: "excluded custom code", status: http.StatusGone, + credentials: map[string]any{ + "custom_error_codes_enabled": true, + "custom_error_codes": []any{float64(http.StatusNotFound)}, + }, + }, + {name: "request error", status: http.StatusBadRequest}, + {name: "default server failover", status: http.StatusInternalServerError, wantFailover: true}, + } { + for _, chat := range []bool{false, true} { + for _, stream := range []bool{false, true} { + name := tc.name + "/chat=" + strconv.FormatBool(chat) + "/stream=" + strconv.FormatBool(stream) + t.Run(name, func(t *testing.T) { + account := &Account{ID: 1, Platform: PlatformAnthropic, Type: AccountTypeAPIKey, + Credentials: map[string]any{"api_key": "fixture-key"}} + for key, value := range tc.credentials { + account.Credentials[key] = value + } + repo := &rateLimitAccountRepoStub{} + upstream := &anthropicHTTPUpstreamRecorder{resp: &http.Response{ + StatusCode: tc.status, Header: http.Header{}, + Body: io.NopCloser(strings.NewReader(`{"type":"error","error":{"type":"invalid_request_error","message":"Service moved"}}`)), + }} + svc := &GatewayService{ + cfg: &config.Config{}, httpUpstream: upstream, + rateLimitService: NewRateLimitService(repo, nil, &config.Config{}, nil, nil), + } + body := `{"model":"claude-sonnet-4-5","input":"hello","stream":` + strconv.FormatBool(stream) + `}` + path := "/v1/responses" + if chat { + body = `{"model":"claude-sonnet-4-5","messages":[{"role":"user","content":"hello"}],"stream":` + strconv.FormatBool(stream) + `}` + path = "/v1/chat/completions" + } + rec := httptest.NewRecorder() + c, _ := gin.CreateTestContext(rec) + c.Request = httptest.NewRequest(http.MethodPost, path, strings.NewReader(body)) + var err error + if chat { + _, err = svc.ForwardAsChatCompletions(context.Background(), c, account, []byte(body), nil) + } else { + _, err = svc.ForwardAsResponses(context.Background(), c, account, []byte(body), nil) + } + require.Error(t, err) + require.Equal(t, tc.wantError, repo.setErrorCalls) + require.Equal(t, tc.wantTemp, repo.tempCalls) + var failoverErr *UpstreamFailoverError + if tc.wantFailover { + require.ErrorAs(t, err, &failoverErr) + require.Equal(t, tc.status, failoverErr.StatusCode) + require.False(t, failoverErr.RetryableOnSameAccount) + require.False(t, c.Writer.Written(), "leave the response available for the handler to try another account") + require.Empty(t, rec.Body.String()) + } else { + require.NotErrorAs(t, err, &failoverErr) + require.Equal(t, tc.status, rec.Code) + require.Contains(t, rec.Body.String(), "Service moved") + } + }) + } + } + } +} diff --git a/backend/internal/service/gateway_forward_as_chat_completions.go b/backend/internal/service/gateway_forward_as_chat_completions.go index f2e3f0027e..a1f9786719 100644 --- a/backend/internal/service/gateway_forward_as_chat_completions.go +++ b/backend/internal/service/gateway_forward_as_chat_completions.go @@ -155,7 +155,12 @@ func (s *GatewayService) ForwardAsChatCompletions( upstreamMsg := strings.TrimSpace(extractUpstreamErrorMessage(respBody)) upstreamMsg = sanitizeUpstreamErrorMessage(upstreamMsg) - if s.shouldFailoverUpstreamError(resp.StatusCode) { + // Apply account policies even for statuses outside the default failover list. + shouldDisable := false + if s.rateLimitService != nil { + shouldDisable = s.rateLimitService.HandleUpstreamError(ctx, account, resp.StatusCode, resp.Header, respBody, mappedModel) + } + if shouldDisable || s.shouldFailoverUpstreamError(resp.StatusCode) { appendOpsUpstreamError(c, OpsUpstreamErrorEvent{ ProxyID: opsUpstreamProxyID(account), ProxyName: opsUpstreamProxyName(account), @@ -167,10 +172,6 @@ func (s *GatewayService) ForwardAsChatCompletions( Kind: "failover", Message: upstreamMsg, }) - shouldDisable := false - if s.rateLimitService != nil { - shouldDisable = s.rateLimitService.HandleUpstreamError(ctx, account, resp.StatusCode, resp.Header, respBody, mappedModel) - } return nil, &UpstreamFailoverError{ StatusCode: resp.StatusCode, ResponseBody: respBody, diff --git a/backend/internal/service/gateway_forward_as_responses.go b/backend/internal/service/gateway_forward_as_responses.go index 802d090457..db10be2568 100644 --- a/backend/internal/service/gateway_forward_as_responses.go +++ b/backend/internal/service/gateway_forward_as_responses.go @@ -166,7 +166,12 @@ func (s *GatewayService) ForwardAsResponses( upstreamMsg := strings.TrimSpace(extractUpstreamErrorMessage(respBody)) upstreamMsg = sanitizeUpstreamErrorMessage(upstreamMsg) - if s.shouldFailoverUpstreamError(resp.StatusCode) { + // Apply account policies even for statuses outside the default failover list. + shouldDisable := false + if s.rateLimitService != nil { + shouldDisable = s.rateLimitService.HandleUpstreamError(ctx, account, resp.StatusCode, resp.Header, respBody, mappedModel) + } + if shouldDisable || s.shouldFailoverUpstreamError(resp.StatusCode) { appendOpsUpstreamError(c, OpsUpstreamErrorEvent{ ProxyID: opsUpstreamProxyID(account), ProxyName: opsUpstreamProxyName(account), @@ -178,10 +183,6 @@ func (s *GatewayService) ForwardAsResponses( Kind: "failover", Message: upstreamMsg, }) - shouldDisable := false - if s.rateLimitService != nil { - shouldDisable = s.rateLimitService.HandleUpstreamError(ctx, account, resp.StatusCode, resp.Header, respBody, mappedModel) - } return nil, &UpstreamFailoverError{ StatusCode: resp.StatusCode, ResponseBody: respBody, diff --git a/backend/internal/service/gateway_scheduling.go b/backend/internal/service/gateway_scheduling.go index c370e2177e..b1219980e7 100644 --- a/backend/internal/service/gateway_scheduling.go +++ b/backend/internal/service/gateway_scheduling.go @@ -1587,6 +1587,11 @@ func (s *GatewayService) hydrateSelectedAccount(ctx context.Context, account *Ac func (s *GatewayService) newSelectionResult(ctx context.Context, account *Account, acquired bool, release func(), waitPlan *AccountWaitPlan) (*AccountSelectionResult, error) { hydrated, err := s.hydrateSelectedAccount(ctx, account) if err != nil { + // release 只在成功结果里返回给调用方;hydrate 失败时这里不释放的话, + // 已从 Redis 占用的槽位会一直泄漏到 TTL 到期。 + if release != nil { + release() + } return nil, err } return attachSelectionProfitGate(ctx, &AccountSelectionResult{ diff --git a/backend/internal/service/gateway_scheduling_slot_release_test.go b/backend/internal/service/gateway_scheduling_slot_release_test.go new file mode 100644 index 0000000000..8f1e4cb1c8 --- /dev/null +++ b/backend/internal/service/gateway_scheduling_slot_release_test.go @@ -0,0 +1,50 @@ +//go:build unit + +package service + +import ( + "context" + "testing" + + "github.com/stretchr/testify/require" +) + +// hydrate 失败时,已经占用的并发槽位必须在返回前释放,否则调用方拿不到 +// ReleaseFunc,槽位会一直泄漏到 TTL 到期。 +func TestGatewayServiceNewSelectionResultReleasesSlotOnHydrationError(t *testing.T) { + svc := &GatewayService{ + schedulerSnapshot: &SchedulerSnapshotService{}, + } + + ctx, cancel := context.WithCancel(context.Background()) + cancel() + + released := 0 + selection, err := svc.newSelectionResult(ctx, &Account{ID: 42}, true, func() { released++ }, nil) + + require.Error(t, err) + require.Nil(t, selection) + require.Equal(t, 1, released) +} + +// hydrate 成功时不能提前释放槽位,ReleaseFunc 应原样交给调用方。 +func TestGatewayServiceNewSelectionResultKeepsReleaseOnSuccess(t *testing.T) { + account := &Account{ID: 42, Platform: PlatformAnthropic} + cache := &snapshotHydrationCache{ + accounts: map[int64]*Account{account.ID: account}, + } + svc := &GatewayService{ + schedulerSnapshot: NewSchedulerSnapshotService(cache, nil, nil, nil, nil), + } + + released := 0 + selection, err := svc.newSelectionResult(context.Background(), account, true, func() { released++ }, nil) + + require.NoError(t, err) + require.NotNil(t, selection) + require.Zero(t, released) + require.NotNil(t, selection.ReleaseFunc) + + selection.ReleaseFunc() + require.Equal(t, 1, released) +} diff --git a/backend/internal/service/gemini_chat_completions_compat_service_test.go b/backend/internal/service/gemini_chat_completions_compat_service_test.go index e4ebf7a838..cf32b74e93 100644 --- a/backend/internal/service/gemini_chat_completions_compat_service_test.go +++ b/backend/internal/service/gemini_chat_completions_compat_service_test.go @@ -161,3 +161,65 @@ func TestGeminiResponseToChatCompletionsRetainsTextAndToolBehavior(t *testing.T) require.Equal(t, "get_weather", choice.Message.ToolCalls[0].Function.Name) require.JSONEq(t, `{"city":"Paris"}`, choice.Message.ToolCalls[0].Function.Arguments) } + +func TestGeminiResponseToChatCompletionsOmitsThoughtParts(t *testing.T) { + rawData := []byte(`{"candidates":[{"content":{"role":"model","parts":[` + + `{"text":"**Solving the puzzle**\n\nThe ball costs 0.05.\n\n\n","thought":true},` + + `{"text":"0.05","thoughtSignature":"sig_1"}]},"finishReason":"STOP","index":0}],` + + `"usageMetadata":{"promptTokenCount":36,"candidatesTokenCount":4,"thoughtsTokenCount":217,"totalTokenCount":257}}`) + var geminiResp map[string]any + require.NoError(t, json.Unmarshal(rawData, &geminiResp)) + + got, usage, err := geminiResponseToChatCompletions(geminiResp, "gemini-test", rawData, nil) + require.NoError(t, err) + require.Len(t, got.Choices, 1) + + var content string + require.NoError(t, json.Unmarshal(got.Choices[0].Message.Content, &content)) + require.Equal(t, "0.05", content) + require.Empty(t, got.Choices[0].Message.ReasoningContent) + require.Equal(t, "stop", got.Choices[0].FinishReason) + require.Equal(t, 221, usage.OutputTokens) +} + +func TestGeminiResponseToChatCompletionsThoughtOnlyResponse(t *testing.T) { + rawData := []byte(`{"candidates":[{"content":{"role":"model","parts":[` + + `{"text":"Still reasoning about","thought":true}]},"finishReason":"MAX_TOKENS","index":0}],` + + `"usageMetadata":{"promptTokenCount":36,"candidatesTokenCount":0,"thoughtsTokenCount":64,"totalTokenCount":100}}`) + var geminiResp map[string]any + require.NoError(t, json.Unmarshal(rawData, &geminiResp)) + + got, usage, err := geminiResponseToChatCompletions(geminiResp, "gemini-test", rawData, nil) + require.NoError(t, err) + require.Len(t, got.Choices, 1) + require.Empty(t, got.Choices[0].Message.Content) + require.Empty(t, got.Choices[0].Message.ReasoningContent) + require.Equal(t, "length", got.Choices[0].FinishReason) + require.Equal(t, 64, usage.OutputTokens) +} + +func TestConvertGeminiToClaudeMessageOmitsThoughtParts(t *testing.T) { + geminiResp := map[string]any{ + "candidates": []any{map[string]any{ + "content": map[string]any{"parts": []any{ + map[string]any{"text": "planning the call", "thought": true}, + map[string]any{"text": "checking", "thought": false}, + map[string]any{"functionCall": map[string]any{"name": "get_weather", "args": map[string]any{"city": "Paris"}}, "thoughtSignature": "sig_1"}, + }}, + "finishReason": "STOP", + }}, + } + rawData, err := json.Marshal(geminiResp) + require.NoError(t, err) + + got, _ := convertGeminiToClaudeMessage(geminiResp, "gemini-test", rawData, false) + content, ok := got["content"].([]any) + require.True(t, ok) + require.Len(t, content, 2) + require.Equal(t, map[string]any{"type": "text", "text": "checking"}, content[0]) + toolUse, ok := content[1].(map[string]any) + require.True(t, ok) + require.Equal(t, "tool_use", toolUse["type"]) + require.Equal(t, "get_weather", toolUse["name"]) + require.Equal(t, "tool_use", got["stop_reason"]) +} diff --git a/backend/internal/service/gemini_messages_compat_service.go b/backend/internal/service/gemini_messages_compat_service.go index 1e86598d8a..9d2ad1ae45 100644 --- a/backend/internal/service/gemini_messages_compat_service.go +++ b/backend/internal/service/gemini_messages_compat_service.go @@ -3027,7 +3027,8 @@ func convertGeminiToClaudeMessage(geminiResp map[string]any, originalModel strin if !ok { continue } - if text, ok := pm["text"].(string); ok && text != "" { + // 思考摘要不属于正文;非流式响应不输出思考内容。 + if text, ok := pm["text"].(string); ok && text != "" && !isGeminiThoughtPart(pm) { contentBlocks = append(contentBlocks, map[string]any{ "type": "text", "text": text, diff --git a/backend/internal/service/model_rate_limit.go b/backend/internal/service/model_rate_limit.go index 46e3419e03..fc181de078 100644 --- a/backend/internal/service/model_rate_limit.go +++ b/backend/internal/service/model_rate_limit.go @@ -6,12 +6,14 @@ import ( "strings" "time" + "github.com/Wei-Shaw/sub2api/internal/pkg/antigravity" "github.com/Wei-Shaw/sub2api/internal/pkg/ctxkey" ) const ( modelRateLimitsKey = "model_rate_limits" antigravityGeminiModelRateLimitKey = "antigravity:gemini" + antigravityArgonModelRateLimitKey = "antigravity:gemini:argon" openAIImageGenerationRateLimitKey = "openai:image_generation" openAICodexSparkRateLimitReason = "openai_codex_spark_rate_limit" // anthropicFableRateLimitKey 是 Anthropic 7d_oi(Fable 专属 7d 窗口)限流的 @@ -80,9 +82,7 @@ func (a *Account) modelRateLimitKeysForRequest(ctx context.Context, requestedMod keys := []string{modelKey} switch a.Platform { case PlatformAntigravity: - if isAntigravityGeminiModel(modelKey) && !isAntigravityGeminiImageModel(modelKey) && modelKey != antigravityGeminiModelRateLimitKey { - keys = append(keys, antigravityGeminiModelRateLimitKey) - } + return antigravityModelRateLimitKeys(a, modelKey) case PlatformOpenAI: if openAIImageGenerationRateLimitApplies(ctx, requestedModel, modelKey) && modelKey != openAIImageGenerationRateLimitKey { keys = append(keys, openAIImageGenerationRateLimitKey) @@ -159,14 +159,23 @@ func isAntigravityGeminiModel(model string) bool { return strings.HasPrefix(normalizeAntigravityModelName(model), "gemini-") } -func antigravityModelRateLimitKeys(model string) []string { +func antigravityModelRateLimitKeys(account *Account, model string) []string { model = strings.TrimSpace(model) if model == "" { return nil } keys := []string{model} if isAntigravityGeminiModel(model) && !isAntigravityGeminiImageModel(model) && model != antigravityGeminiModelRateLimitKey { - keys = append(keys, antigravityGeminiModelRateLimitKey) + familyKey := antigravityGeminiModelRateLimitKey + // Pro has a separate Argon quota pool. Ultra and unknown plans retain + // the shared Gemini scope; Argon variants still cool down together. + if account != nil && strings.EqualFold(strings.TrimSpace(antigravity.TierIDToPlanType(account.GetCredential("plan_type"))), "Pro") { + normalized := normalizeAntigravityModelName(model) + if normalized == "gemini-4-argon" || strings.HasPrefix(normalized, "gemini-4-argon-") { + familyKey = antigravityArgonModelRateLimitKey + } + } + keys = append(keys, familyKey) } return keys } diff --git a/backend/internal/service/openai_account_runtime_block_fastpath.go b/backend/internal/service/openai_account_runtime_block_fastpath.go index 942ea07bcb..50ebf955eb 100644 --- a/backend/internal/service/openai_account_runtime_block_fastpath.go +++ b/backend/internal/service/openai_account_runtime_block_fastpath.go @@ -104,6 +104,18 @@ func (s *OpenAIGatewayService) handleOpenAIAccountUpstreamError(ctx context.Cont // 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) { + // An explicit model-scoped rule overrides the default retry policy without + // turning a request-level overload into an account-wide health failure. + model := firstRequestedModel(canonicalModel) + if s != nil && s.rateLimitService != nil && model != "" && account.IsTempUnschedulableEnabled() { + ruleBody := openAICapacityShedRuleBody(responseBody) + matches := matchTempUnschedulableRules(account, statusCode, ruleBody) + if len(matches) > 0 && matches[0].rule.Scope == TempUnschedScopeModel { + stateCtx, cancel := openAIAccountStateContext(ctx) + defer cancel() + return s.rateLimitService.HandleTempUnschedulable(stateCtx, account, statusCode, ruleBody, model) + } + } return false } stateCtx, cancel := openAIAccountStateContext(ctx) diff --git a/backend/internal/service/openai_capacity_shed_model_rule_test.go b/backend/internal/service/openai_capacity_shed_model_rule_test.go new file mode 100644 index 0000000000..8e5848633e --- /dev/null +++ b/backend/internal/service/openai_capacity_shed_model_rule_test.go @@ -0,0 +1,217 @@ +//go:build unit + +package service + +import ( + "context" + "encoding/json" + "errors" + "io" + "net/http" + "net/http/httptest" + "strings" + "testing" + "time" + + "github.com/gin-gonic/gin" + "github.com/stretchr/testify/require" +) + +func openAICapacityShedModelRuleAccount(accountType string) *Account { + return &Account{ + ID: 101, Platform: PlatformOpenAI, Type: accountType, Status: StatusActive, Schedulable: true, + Credentials: map[string]any{ + "temp_unschedulable_enabled": true, + "temp_unschedulable_rules": []any{map[string]any{ + "error_code": http.StatusServiceUnavailable, "keywords": []any{"overloaded"}, + "duration_minutes": 5, "scope": TempUnschedScopeModel, + }}, + "model_mapping": map[string]any{"alias": "gpt-6.1-sol", "gpt-6.1-sol": "must-not-remap"}, + }, + } +} + +func TestOpenAICapacityShedModelRule_StreamReaders(t *testing.T) { + gin.SetMode(gin.TestMode) + readers := []struct { + name string + run func(*OpenAIGatewayService, *gin.Context, *http.Response, *Account, []byte) error + }{ + {"stream", func(s *OpenAIGatewayService, c *gin.Context, r *http.Response, a *Account, _ []byte) error { + _, err := s.handleStreamingResponse(c.Request.Context(), r, c, a, time.Now(), "alias", "gpt-6.1-sol") + return err + }}, + {"passthrough", func(s *OpenAIGatewayService, c *gin.Context, r *http.Response, a *Account, _ []byte) error { + _, err := s.handleStreamingResponsePassthrough(c.Request.Context(), r, c, a, time.Now(), "alias", "gpt-6.1-sol") + return err + }}, + {"buffered", func(s *OpenAIGatewayService, c *gin.Context, r *http.Response, a *Account, body []byte) error { + _, err := s.handleSSEToJSON(r, c, a, body, "alias", "gpt-6.1-sol") + return err + }}, + {"buffered_passthrough", func(s *OpenAIGatewayService, c *gin.Context, r *http.Response, a *Account, body []byte) error { + _, err := s.handlePassthroughSSEToJSON(r, c, a, body, "alias", "gpt-6.1-sol") + return err + }}, + } + for _, accountType := range []string{AccountTypeOAuth, AccountTypeSetupToken, AccountTypeAPIKey} { + for _, reader := range readers { + for _, frame := range []struct{ name, payload string }{ + {"error", `{"type":"error","error":{"code":"server_is_overloaded","type":"service_unavailable_error","message":"Our servers are currently overloaded. Please try again later."}}`}, + {"response.failed", `{"type":"response.failed","response":{"error":{"code":"slow_down","message":"overloaded"}}}`}, + } { + t.Run(accountType+"/"+reader.name+"/"+frame.name, func(t *testing.T) { + repo := &modelNotFoundAccountRepoStub{} + svc := &OpenAIGatewayService{rateLimitService: &RateLimitService{accountRepo: repo}} + account := openAICapacityShedModelRuleAccount(accountType) + rec := httptest.NewRecorder() + c, _ := gin.CreateTestContext(rec) + c.Request = httptest.NewRequest(http.MethodPost, "/v1/responses", nil) + body := "data: " + frame.payload + "\n\n" + resp := &http.Response{StatusCode: http.StatusOK, Header: http.Header{"Content-Type": {"text/event-stream"}}, + Body: io.NopCloser(strings.NewReader(body))} + + err := reader.run(svc, c, resp, account, []byte(body)) + + var failover *UpstreamFailoverError + require.ErrorAs(t, err, &failover) + require.Len(t, repo.modelRateLimitCalls, 1) + require.False(t, failover.RetryableOnSameAccount, "a matching model cooldown must stop same-account replay") + require.True(t, failover.RequestScopedTransient, "do not enable generic account-wide cooldowns") + require.Equal(t, http.StatusServiceUnavailable, failover.ClientStatusCode) + call := repo.modelRateLimitCalls[0] + require.Equal(t, "gpt-6.1-sol", call.scope, "use the already mapped scheduling model") + require.WithinDuration(t, time.Now().Add(5*time.Minute), call.resetAt, time.Second) + var state TempUnschedState + require.NoError(t, json.Unmarshal([]byte(call.reason), &state)) + require.Equal(t, TempUnschedScopeModel, state.Scope) + require.Equal(t, http.StatusServiceUnavailable, state.StatusCode) + require.Zero(t, repo.tempCalls) + require.False(t, svc.isOpenAIAccountRuntimeBlocked(account)) + require.False(t, c.Writer.Written()) + require.Empty(t, rec.Body.String()) + }) + } + } + } +} + +func TestOpenAICapacityShedModelRule_HTTP(t *testing.T) { + account := openAICapacityShedModelRuleAccount(AccountTypeOAuth) + repo := &modelNotFoundAccountRepoStub{} + svc := &OpenAIGatewayService{rateLimitService: &RateLimitService{accountRepo: repo}} + c, _ := gin.CreateTestContext(httptest.NewRecorder()) + c.Request = httptest.NewRequest(http.MethodPost, "/v1/responses", nil) + body := []byte(`{"error":{"code":"server_is_overloaded","message":"overloaded"}}`) + err := svc.handleFailoverErrorResponsePassthrough(context.Background(), + &http.Response{StatusCode: http.StatusServiceUnavailable, Header: http.Header{}}, c, account, + []byte(`{"model":"alias"}`), body) + var failover *UpstreamFailoverError + require.ErrorAs(t, err, &failover) + require.False(t, failover.RetryableOnSameAccount) + require.True(t, failover.RequestScopedTransient) + require.Len(t, repo.modelRateLimitCalls, 1) + require.Equal(t, "gpt-6.1-sol", repo.modelRateLimitCalls[0].scope) + require.Zero(t, repo.tempCalls) + require.False(t, c.Writer.Written()) +} + +func TestOpenAICapacityShedModelRule_ProtectionBoundaries(t *testing.T) { + for _, tt := range []struct { + name string + change func(*Account, map[string]any) + model string + }{ + {"disabled", func(a *Account, _ map[string]any) { a.Credentials["temp_unschedulable_enabled"] = false }, "gpt-6.1-sol"}, + {"no_rules", func(a *Account, _ map[string]any) { delete(a.Credentials, "temp_unschedulable_rules") }, "gpt-6.1-sol"}, + {"unknown_model", func(*Account, map[string]any) {}, ""}, + {"account_scope", func(_ *Account, r map[string]any) { r["scope"] = TempUnschedScopeAccount }, "gpt-6.1-sol"}, + {"legacy_scope", func(_ *Account, r map[string]any) { delete(r, "scope") }, "gpt-6.1-sol"}, + {"keyword_mismatch", func(_ *Account, r map[string]any) { r["keywords"] = []any{"other error"} }, "gpt-6.1-sol"}, + {"status_mismatch", func(_ *Account, r map[string]any) { r["error_code"] = http.StatusBadGateway }, "gpt-6.1-sol"}, + {"pool_mode", func(a *Account, _ map[string]any) { a.Credentials["pool_mode"] = true }, "gpt-6.1-sol"}, + {"excluded_status", func(a *Account, _ map[string]any) { + a.Credentials["custom_error_codes_enabled"] = true + a.Credentials["custom_error_codes"] = []any{float64(http.StatusTooManyRequests)} + }, "gpt-6.1-sol"}, + } { + t.Run(tt.name, func(t *testing.T) { + account := openAICapacityShedModelRuleAccount(AccountTypeAPIKey) + rule := account.Credentials["temp_unschedulable_rules"].([]any)[0].(map[string]any) + tt.change(account, rule) + repo := &modelNotFoundAccountRepoStub{} + svc := &OpenAIGatewayService{rateLimitService: &RateLimitService{accountRepo: repo}} + payload := []byte(`{"type":"error","error":{"code":"server_is_overloaded","message":"overloaded"}}`) + failover := svc.newOpenAIStreamFailoverErrorWithModel(nil, account, false, "", payload, "overloaded", tt.model) + require.True(t, failover.RetryableOnSameAccount) + require.True(t, failover.RequestScopedTransient) + require.Empty(t, repo.modelRateLimitCalls) + require.Zero(t, repo.tempCalls) + require.False(t, svc.isOpenAIAccountRuntimeBlocked(account)) + }) + } +} + +func TestOpenAICapacityShedModelRule_WriteFailureDoesNotBlockAccount(t *testing.T) { + repo := &modelNotFoundAccountRepoStub{modelRateLimitErr: errors.New("write failed")} + svc := &OpenAIGatewayService{rateLimitService: &RateLimitService{accountRepo: repo}} + account := openAICapacityShedModelRuleAccount(AccountTypeOAuth) + payload := []byte(`{"type":"error","error":{"code":"server_is_overloaded","message":"overloaded"}}`) + failover := svc.newOpenAIStreamFailoverErrorWithModel(nil, account, false, "", payload, "overloaded", "gpt-6.1-sol") + require.False(t, failover.RetryableOnSameAccount) + require.True(t, failover.RequestScopedTransient) + require.Len(t, repo.modelRateLimitCalls, 1) + require.Zero(t, repo.tempCalls) + require.False(t, svc.isOpenAIAccountRuntimeBlocked(account)) +} + +func TestOpenAICapacityShedModelRule_ErrorFieldsOnly(t *testing.T) { + for _, tt := range []struct { + name, payload, keyword string + matched bool + }{ + {"output_is_not_an_error", `{"type":"response.failed","response":{"output":[{"text":"overloaded"}],"error":{"code":"slow_down","message":"try again"}}}`, "", false}, + {"metadata_is_not_an_error", `{"type":"error","metadata":{"prompt":"overloaded"},"error":{"code":"slow_down","message":"try again"}}`, "", false}, + {"model_is_not_an_error", `{"type":"response.failed","response":{"model":"overloaded-model","error":{"code":"slow_down","message":"try again"}}}`, "", false}, + {"flat_metadata_is_not_an_error", `{"type":"error","message":"Our servers are currently overloaded. Please try again later.","metadata":{"prompt":"cooldown-marker"}}`, "cooldown-marker", false}, + {"root_error_code_matches", `{"type":"error","error":{"code":"server_is_overloaded","message":"try again"},"metadata":{"prompt":"private-output-marker"}}`, "", true}, + {"nested_error_code_matches", `{"type":"response.failed","response":{"output":[{"text":"private-output-marker"}],"error":{"code":"server_is_overloaded"}}}`, "", true}, + {"flat_error_message_matches", `{"type":"error","message":"Our servers are currently overloaded. Please try again later.","metadata":{"prompt":"private-output-marker"}}`, "", true}, + {"error_message_matches", `{"type":"response.failed","response":{"error":{"code":"slow_down","message":"overloaded"}}}`, "", true}, + } { + t.Run(tt.name, func(t *testing.T) { + repo := &modelNotFoundAccountRepoStub{} + svc := &OpenAIGatewayService{rateLimitService: &RateLimitService{accountRepo: repo}} + account := openAICapacityShedModelRuleAccount(AccountTypeOAuth) + if tt.keyword != "" { + rule := account.Credentials["temp_unschedulable_rules"].([]any)[0].(map[string]any) + rule["keywords"] = []any{tt.keyword} + } + payload := []byte(tt.payload) + failover := svc.newOpenAIStreamFailoverErrorWithModel(nil, account, false, "", payload, + extractOpenAISSEErrorMessage(payload), "gpt-6.1-sol") + require.Equal(t, !tt.matched, failover.RetryableOnSameAccount) + require.True(t, failover.RequestScopedTransient) + if tt.matched { + require.Len(t, repo.modelRateLimitCalls, 1) + require.NotContains(t, repo.modelRateLimitCalls[0].reason, "private-output-marker") + } else { + require.Empty(t, repo.modelRateLimitCalls) + } + require.Zero(t, repo.tempCalls) + }) + } +} + +func TestOpenAICapacityShedModelRule_OtherPlatformKeepsDefault(t *testing.T) { + repo := &modelNotFoundAccountRepoStub{} + svc := &OpenAIGatewayService{rateLimitService: &RateLimitService{accountRepo: repo}} + account := openAICapacityShedModelRuleAccount(AccountTypeOAuth) + account.Platform = PlatformGrok + payload := []byte(`{"type":"error","error":{"code":"server_is_overloaded","message":"overloaded"}}`) + failover := svc.newOpenAIStreamFailoverErrorWithModel(nil, account, false, "", payload, "overloaded", "grok-4") + require.Empty(t, repo.modelRateLimitCalls) + require.Zero(t, repo.tempCalls) + require.True(t, failover.RetryableOnSameAccount) + require.True(t, failover.RequestScopedTransient) +} diff --git a/backend/internal/service/openai_codex_metadata_events_test.go b/backend/internal/service/openai_codex_metadata_events_test.go new file mode 100644 index 0000000000..6cb2e2393c --- /dev/null +++ b/backend/internal/service/openai_codex_metadata_events_test.go @@ -0,0 +1,51 @@ +package service + +import ( + "io" + "net/http" + "net/http/httptest" + "strings" + "testing" + "time" + + "github.com/Wei-Shaw/sub2api/internal/config" + "github.com/gin-gonic/gin" + "github.com/stretchr/testify/require" +) + +func TestRelayStallsMetadataBeforeCapacityFailure(t *testing.T) { + gin.SetMode(gin.TestMode) + for _, metadata := range []string{ + `{"type":"response.metadata","response_id":"r","metadata":{"route":"test"}}`, + `{"type":"codex.rate_limits","rate_limits":{}}`, + `{"type":"codex.response.metadata","response_id":"r","metadata":{}}`, + } { + for _, passthrough := range []bool{false, true} { + name := metadata + if passthrough { + name += "/passthrough" + } + t.Run(name, func(t *testing.T) { + svc := &OpenAIGatewayService{cfg: &config.Config{Gateway: config.GatewayConfig{MaxLineSize: defaultMaxLineSize}}} + rec := httptest.NewRecorder() + c, _ := gin.CreateTestContext(rec) + c.Request = httptest.NewRequest(http.MethodPost, "/v1/responses", nil) + stream := "data: {\"type\":\"response.created\",\"response\":{\"id\":\"r\"}}\n\n" + + "data: " + metadata + "\n\n" + + "data: {\"type\":\"response.failed\",\"response\":{\"error\":{\"code\":\"server_is_overloaded\",\"message\":\"Our servers are currently overloaded. Please try again later.\"}}}\n\n" + resp := &http.Response{StatusCode: http.StatusOK, Header: http.Header{}, Body: io.NopCloser(strings.NewReader(stream))} + account := &Account{ID: 1, Platform: PlatformOpenAI, Type: AccountTypeOAuth} + var err error + if passthrough { + _, err = svc.handleStreamingResponsePassthrough(c.Request.Context(), resp, c, account, time.Now(), "model", "model") + } else { + _, err = svc.handleStreamingResponse(c.Request.Context(), resp, c, account, time.Now(), "model", "model") + } + var failover *UpstreamFailoverError + require.ErrorAs(t, err, &failover) + require.Empty(t, rec.Body.String(), "metadata must stay attempt-local until real output") + require.True(t, failover.RequestScopedTransient) + }) + } + } +} diff --git a/backend/internal/service/openai_content_session_seed.go b/backend/internal/service/openai_content_session_seed.go index 2acf298721..8524f6d669 100644 --- a/backend/internal/service/openai_content_session_seed.go +++ b/backend/internal/service/openai_content_session_seed.go @@ -19,8 +19,7 @@ const contentStablePrefixSessionSeedPrefix = "compat_csp_" // deriveOpenAIContentSessionSeed builds a stable session seed from an // OpenAI-format request body. Only fields constant across conversation turns // are included: model, tools/functions definitions, the leading system/developer -// prompt prefix in Chat messages, instructions (Responses API), and the first -// user message. +// prompt prefix, instructions (Responses API), and the first user message. // Supports both Chat Completions (messages) and Responses API (input). func deriveOpenAIContentSessionSeed(body []byte) string { if len(body) == 0 { @@ -148,15 +147,19 @@ scanRoot: _, _ = b.WriteString("|input=") _, _ = b.WriteString(inp.String()) } else if inp.IsArray() { + systemPrefixOpen := true inp.ForEach(func(_, item gjson.Result) bool { role := item.Get("role").String() switch role { case "system", "developer": - _, _ = b.WriteString("|system=") - if c := item.Get("content"); c.Exists() { - _, _ = b.WriteString(normalizeCompatSeedJSON(json.RawMessage(c.Raw))) + if systemPrefixOpen { + _, _ = b.WriteString("|system=") + if c := item.Get("content"); c.Exists() { + _, _ = b.WriteString(normalizeCompatSeedJSON(json.RawMessage(c.Raw))) + } } case "user": + systemPrefixOpen = false if !firstUserCaptured { _, _ = b.WriteString("|first_user=") if c := item.Get("content"); c.Exists() { @@ -164,6 +167,10 @@ scanRoot: } firstUserCaptured = true } + default: + // Match Chat: reminders appended after conversation/tool items + // must not change the identity of an existing session. + systemPrefixOpen = false } if !firstUserCaptured && item.Get("type").String() == "input_text" { _, _ = b.WriteString("|first_user=") diff --git a/backend/internal/service/openai_content_session_seed_responses_test.go b/backend/internal/service/openai_content_session_seed_responses_test.go new file mode 100644 index 0000000000..13a4e6fd66 --- /dev/null +++ b/backend/internal/service/openai_content_session_seed_responses_test.go @@ -0,0 +1,118 @@ +package service + +import ( + "context" + "encoding/json" + "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/sjson" +) + +func TestDeriveOpenAIContentSessionSeed_ResponsesLeadingPrefix(t *testing.T) { + makeBody := func(items ...string) []byte { + return []byte(`{"model":"gpt-5.4","instructions":"Be concise.","tools":[{"type":"function","name":"lookup","parameters":{"type":"object"}}],"input":[` + strings.Join(items, ",") + `]}`) + } + prefix := []string{ + `{"role":"system","content":"System A"}`, + `{"role":"developer","content":[{"type":"input_text","text":"Developer B"}]}`, + } + boundaries := []struct { + name string + item string + }{ + {"user", `{"role":"user","content":"First question"}`}, + {"assistant", `{"role":"assistant","content":"Earlier answer"}`}, + {"function_call", `{"type":"function_call","call_id":"call_1","name":"lookup","arguments":"{}"}`}, + {"function_call_output", `{"type":"function_call_output","call_id":"call_1","output":"Result"}`}, + {"input_text", `{"type":"input_text","text":"First question"}`}, + } + for _, boundary := range boundaries { + for _, role := range []string{"system", "developer"} { + t.Run(boundary.name+"/"+role, func(t *testing.T) { + items := append(append([]string(nil), prefix...), boundary.item) + baseline := makeBody(append(items, `{"role":"user","content":"First question"}`)...) + reminder := `{"role":"` + role + `","content":[{"type":"input_text","text":"Dynamic reminder"}]}` + continued := makeBody(append(items, reminder, `{"role":"user","content":"First question"}`, `{"role":"user","content":"Follow-up"}`)...) + seed := deriveOpenAIContentSessionSeed(baseline) + require.Contains(t, seed, "System A") + require.Contains(t, seed, "Developer B") + require.Contains(t, seed, "First question") + require.Equal(t, seed, deriveOpenAIContentSessionSeed(continued), "later reminders must not change the session identity") + }) + } + } + + t.Run("stable fields still distinguish sessions", func(t *testing.T) { + body := makeBody(append(prefix, `{"role":"user","content":"First question"}`)...) + seed := deriveOpenAIContentSessionSeed(body) + for _, change := range [][2]string{ + {"gpt-5.4", "gpt-5.5"}, + {"Be concise.", "Be detailed."}, + {"lookup", "search"}, + {"System A", "System C"}, + {"Developer B", "Developer C"}, + {"First question", "Compacted question"}, + } { + t.Run(change[0], func(t *testing.T) { + require.NotEqual(t, seed, deriveOpenAIContentSessionSeed([]byte(strings.ReplaceAll(string(body), change[0], change[1])))) + }) + } + }) +} + +func TestOpenAIGatewayService_ResponsesToolLoopKeepsStickyAccount(t *testing.T) { + gin.SetMode(gin.TestMode) + first := []byte(`{"model":"gpt-5.4","input":[{"role":"system","content":"Be helpful."},{"role":"user","content":"Look up the weather"}]}`) + continued := []byte(`{"model":"gpt-5.4","input":[{"role":"system","content":"Be helpful."},{"role":"user","content":"Look up the weather"},{"type":"function_call","call_id":"call_1","name":"lookup","arguments":"{}"},{"type":"function_call_output","call_id":"call_1","output":"Sunny"},{"role":"developer","content":"Answer using the tool result."},{"role":"user","content":"And tomorrow?"}]}`) + for _, mode := range []string{"false", "true"} { + for _, identity := range []string{"content", "header", "prompt_cache_key"} { + t.Run("advanced="+mode+"/"+identity, func(t *testing.T) { + t.Cleanup(resetOpenAIAdvancedSchedulerSettingCacheForTest) + c, _ := gin.CreateTestContext(httptest.NewRecorder()) + c.Request = httptest.NewRequest(http.MethodPost, "/v1/responses", nil) + firstBody, nextBody := first, continued + switch identity { + case "header": + c.Request.Header.Set("session-id", "stable-conversation") + case "prompt_cache_key": + var err error + firstBody, err = sjson.SetBytes(first, "prompt_cache_key", "stable-conversation") + require.NoError(t, err) + nextBody, err = sjson.SetBytes(continued, "prompt_cache_key", "stable-conversation") + require.NoError(t, err) + } + require.True(t, json.Valid(firstBody)) + require.True(t, json.Valid(nextBody)) + groupID := int64(10) + cfg := &config.Config{} + cfg.Gateway.OpenAIWS.LBTopK = 1 + svc := &OpenAIGatewayService{ + accountRepo: schedulerTestOpenAIAccountRepo{accounts: []Account{ + {ID: 1, Platform: PlatformOpenAI, Type: AccountTypeOAuth, Status: StatusActive, Schedulable: true, Concurrency: 1, Priority: 100, GroupIDs: []int64{groupID}}, + {ID: 2, Platform: PlatformOpenAI, Type: AccountTypeOAuth, Status: StatusActive, Schedulable: true, Concurrency: 1, Priority: 0, GroupIDs: []int64{groupID}}, + }}, + cfg: cfg, + rateLimitService: newOpenAIAdvancedSchedulerRateLimitService(mode), + concurrencyService: NewConcurrencyService(schedulerTestConcurrencyCache{}), + } + firstHash := svc.GenerateSessionHash(c, firstBody) + require.NotEmpty(t, firstHash) + svc.cache = &schedulerTestGatewayCache{sessionBindings: map[string]int64{"openai:" + firstHash: 1}} + selection, decision, err := svc.SelectAccountWithScheduler(context.Background(), &groupID, "", svc.GenerateSessionHash(c, nextBody), "gpt-5.4", nil, OpenAIUpstreamTransportAny, false) + require.NoError(t, err) + require.NotNil(t, selection) + if selection.ReleaseFunc != nil { + defer selection.ReleaseFunc() + } + require.Equal(t, int64(1), selection.Account.ID, "a reminder must not lose a healthy existing binding to the higher-priority account") + require.True(t, decision.StickySessionHit) + }) + } + } +} diff --git a/backend/internal/service/openai_gateway_converted_reasoning_pricing_test.go b/backend/internal/service/openai_gateway_converted_reasoning_pricing_test.go index 4a001d4f0d..c9b20c93cb 100644 --- a/backend/internal/service/openai_gateway_converted_reasoning_pricing_test.go +++ b/backend/internal/service/openai_gateway_converted_reasoning_pricing_test.go @@ -82,31 +82,48 @@ func TestOpenAIMessagesGLMReasoningPricingUsesForwardedEffort(t *testing.T) { {"medium", "", "high", 2}, {"xhigh", "", "max", 3}, {"xhigh", "medium", "medium", 1.5}, + {"low", "medium", "medium", 1.5}, } { t.Run(fmt.Sprintf("stream=%t/effort=%s/policy=%s", stream, tc.effort, tc.maxPolicy), func(t *testing.T) { - body := []byte(fmt.Sprintf(`{"model":"glm-5.2","stream":%t,"max_tokens":32,"output_config":{"effort":%q},"messages":[{"role":"user","content":"hello"}]}`, stream, tc.effort)) - responseBody := `{"id":"chatcmpl_glm","object":"chat.completion","model":"glm-5.2","choices":[{"index":0,"message":{"role":"assistant","content":"ok"},"finish_reason":"stop"}],"usage":{"prompt_tokens":1000000,"completion_tokens":2,"total_tokens":1000002}}` - contentType := "application/json" - if stream { - contentType = "text/event-stream" - responseBody = "data: " + `{"id":"chatcmpl_glm","object":"chat.completion.chunk","model":"glm-5.2","choices":[{"index":0,"delta":{"role":"assistant","content":"ok"},"finish_reason":"stop"}],"usage":{"prompt_tokens":1000000,"completion_tokens":2,"total_tokens":1000002}}` + "\n\ndata: [DONE]\n\n" + for _, overLimit := range []string{"", ReasoningEffortOverLimitDowngrade, ReasoningEffortOverLimitDeny} { + t.Run("overLimit="+overLimit, func(t *testing.T) { + body := []byte(fmt.Sprintf(`{"model":"glm-5.2","stream":%t,"max_tokens":32,"output_config":{"effort":%q},"messages":[{"role":"user","content":"hello"}]}`, stream, tc.effort)) + responseBody := `{"id":"chatcmpl_glm","object":"chat.completion","model":"glm-5.2","choices":[{"index":0,"message":{"role":"assistant","content":"ok"},"finish_reason":"stop"}],"usage":{"prompt_tokens":1000000,"completion_tokens":2,"total_tokens":1000002}}` + contentType := "application/json" + if stream { + contentType = "text/event-stream" + responseBody = "data: " + `{"id":"chatcmpl_glm","object":"chat.completion.chunk","model":"glm-5.2","choices":[{"index":0,"delta":{"role":"assistant","content":"ok"},"finish_reason":"stop"}],"usage":{"prompt_tokens":1000000,"completion_tokens":2,"total_tokens":1000002}}` + "\n\ndata: [DONE]\n\n" + } + upstream := &httpUpstreamRecorder{resp: &http.Response{ + StatusCode: http.StatusOK, + Header: http.Header{"Content-Type": []string{contentType}}, + Body: io.NopCloser(strings.NewReader(responseBody)), + }} + svc := &OpenAIGatewayService{cfg: rawChatCompletionsTestConfig(), httpUpstream: upstream} + ctx := context.Background() + if tc.maxPolicy != "" { + ctx = WithOpenAIReasoningEffortPolicyForMessages(ctx, body, tc.maxPolicy, nil, overLimit) + } + requestContext := adaptiveProtocolTestContext("/v1/messages", body) + account := forceChatMessagesFallbackAccount() + require.Equal(t, PlatformOpenAI, account.Platform) + result, err := svc.ForwardAsAnthropic(ctx, requestContext, account, body, "", "") + if tc.maxPolicy != "" && overLimit == ReasoningEffortOverLimitDeny { + require.True(t, IsReasoningEffortPolicyDenied(err), "expected policy denial, got %v", err) + require.Equal(t, http.StatusForbidden, requestContext.Writer.Status()) + require.Empty(t, upstream.requests) + require.Nil(t, result) + return + } + require.NoError(t, err) + require.Equal(t, http.StatusOK, requestContext.Writer.Status()) + require.Len(t, upstream.requests, 1) + require.Equal(t, "/v1/chat/completions", upstream.lastReq.URL.Path) + require.Equal(t, tc.wantEffort, gjson.GetBytes(upstream.lastBody, "reasoning_effort").String()) + require.Equal(t, tc.wantEffort, optionalStringValue(result.ReasoningEffort)) + assertConvertedReasoningPrice(t, result, tc.wantCost) + }) } - upstream := &httpUpstreamRecorder{resp: &http.Response{ - StatusCode: http.StatusOK, - Header: http.Header{"Content-Type": []string{contentType}}, - Body: io.NopCloser(strings.NewReader(responseBody)), - }} - svc := &OpenAIGatewayService{cfg: rawChatCompletionsTestConfig(), httpUpstream: upstream} - ctx := context.Background() - if tc.maxPolicy != "" { - ctx = WithOpenAIReasoningEffortPolicy(ctx, tc.maxPolicy, nil, "") - } - result, err := svc.ForwardAsAnthropic(ctx, adaptiveProtocolTestContext("/v1/messages", body), forceChatMessagesFallbackAccount(), body, "", "") - require.NoError(t, err) - require.Equal(t, "/v1/chat/completions", upstream.lastReq.URL.Path) - require.Equal(t, tc.wantEffort, gjson.GetBytes(upstream.lastBody, "reasoning_effort").String()) - require.Equal(t, tc.wantEffort, optionalStringValue(result.ReasoningEffort)) - assertConvertedReasoningPrice(t, result, tc.wantCost) }) } } diff --git a/backend/internal/service/openai_gateway_count_tokens.go b/backend/internal/service/openai_gateway_count_tokens.go index 60bed92f8e..94361a456f 100644 --- a/backend/internal/service/openai_gateway_count_tokens.go +++ b/backend/internal/service/openai_gateway_count_tokens.go @@ -406,7 +406,9 @@ func prepareOpenAIInputTokensCountRequest( billingModel := resolveOpenAIForwardModel(account, normalizedModel, strings.TrimSpace(defaultMappedModel)) upstreamModel := normalizeOpenAIModelForUpstream(account, billingModel) - responsesReq, err := apicompat.AnthropicToResponses(&anthropicReq) + responsesReq, err := apicompat.AnthropicToResponsesWithOptions(&anthropicReq, apicompat.AnthropicToResponsesOptions{ + DeferReasoningEffortValidation: true, + }) if err != nil { return nil, fmt.Errorf("convert anthropic request to responses: %w", err) } diff --git a/backend/internal/service/openai_gateway_count_tokens_test.go b/backend/internal/service/openai_gateway_count_tokens_test.go index 37bfa91e00..db18583631 100644 --- a/backend/internal/service/openai_gateway_count_tokens_test.go +++ b/backend/internal/service/openai_gateway_count_tokens_test.go @@ -29,6 +29,28 @@ type countTokensRuntimeStateRepo struct { setErrorCalls int } +func TestPrepareOpenAIInputTokensCountRequestIgnoresOutputEffort(t *testing.T) { + account := &Account{Platform: PlatformOpenAI, Type: AccountTypeAPIKey} + for _, preference := range []string{ + `"thinking":{"type":"disabled"}`, + `"output_config":{"effort":"none"}`, + `"output_config":{"effort":"minimal"}`, + } { + t.Run(preference, func(t *testing.T) { + body := []byte(`{"model":"gpt-6.1-sol","messages":[{"role":"user","content":"hello"}],` + preference + `}`) + prepared, err := prepareOpenAIInputTokensCountRequest(body, account, "") + require.NoError(t, err) + encoded, err := json.Marshal(prepared.Request) + require.NoError(t, err) + require.Equal(t, "gpt-6.1-sol", prepared.Request.Model) + require.Contains(t, string(prepared.Request.Input), "hello") + for _, field := range []string{"reasoning", "reasoning_effort", "output_config", "thinking"} { + require.False(t, gjson.GetBytes(encoded, field).Exists(), field) + } + }) + } +} + func (r *countTokensRuntimeStateRepo) SetTempUnschedulable(_ context.Context, _ int64, _ time.Time, _ string) error { r.tempUnschedCalls++ return nil diff --git a/backend/internal/service/openai_gateway_messages.go b/backend/internal/service/openai_gateway_messages.go index 3e3c622aaf..4756d83383 100644 --- a/backend/internal/service/openai_gateway_messages.go +++ b/backend/internal/service/openai_gateway_messages.go @@ -98,7 +98,7 @@ func (s *OpenAIGatewayService) ForwardAsAnthropic( // 2. Model mapping billingModel := resolveOpenAIForwardModel(account, normalizedModel, defaultMappedModel) upstreamModel := normalizeOpenAIModelForUpstream(account, billingModel) - if err := validateGPT61CompatRequest(body, upstreamModel); err != nil { + if err := validateGPT61RawEffort(body, upstreamModel); err != nil { writeAnthropicError(c, http.StatusBadRequest, "invalid_request_error", err.Error()) return nil, err } @@ -154,7 +154,10 @@ func (s *OpenAIGatewayService) ForwardAsAnthropic( // 3. Convert Anthropic → Responses after compatibility-only replay guard. anthropicReq.Model = upstreamModel - responsesReq, err := anthropicToResponses(s.cfg, &anthropicReq) + responsesReq, err := apicompat.AnthropicToResponsesWithOptions(&anthropicReq, apicompat.AnthropicToResponsesOptions{ + MinOutputTokens: configuredMinOutputTokens(s.cfg), + DeferReasoningEffortValidation: true, + }) if err != nil { return nil, fmt.Errorf("convert anthropic to responses: %w", err) } @@ -315,6 +318,11 @@ func (s *OpenAIGatewayService) ForwardAsAnthropic( } } + if err := validateGPT61CompatRequest(responsesBody, upstreamModel); err != nil { + writeAnthropicError(c, http.StatusBadRequest, "invalid_request_error", err.Error()) + return nil, err + } + // 4c. Apply OpenAI fast policy (may filter service_tier or block the request). // Mirrors the Claude anthropic-beta "fast-mode-2026-02-01" filter, but keyed // on the body-level service_tier field (priority/flex). diff --git a/backend/internal/service/openai_gateway_messages_chat_fallback.go b/backend/internal/service/openai_gateway_messages_chat_fallback.go index ebfab5679b..0a92e5963a 100644 --- a/backend/internal/service/openai_gateway_messages_chat_fallback.go +++ b/backend/internal/service/openai_gateway_messages_chat_fallback.go @@ -63,7 +63,7 @@ func (s *OpenAIGatewayService) forwardAnthropicViaRawChatCompletions( billingModel := resolveOpenAIForwardModel(account, anthropicReq.Model, defaultMappedModel) upstreamModel := normalizeOpenAIModelForUpstream(account, billingModel) - if err := validateGPT61CompatRequest(body, upstreamModel); err != nil { + if err := validateGPT61RawEffort(body, upstreamModel); err != nil { writeAnthropicError(c, http.StatusBadRequest, "invalid_request_error", err.Error()) return nil, err } @@ -73,6 +73,10 @@ func (s *OpenAIGatewayService) forwardAnthropicViaRawChatCompletions( return nil, err } chatReq.Model = upstreamModel + if openai.IsGPT61SolModelSpelling(upstreamModel) { + chatReq.Temperature = nil + chatReq.TopP = nil + } chatReq.ReasoningEffort = openAICompatAnthropicReasoningEffort(&anthropicReq, upstreamModel, chatReq.ReasoningEffort) chatReq.Stream = clientStream if clientStream { @@ -101,6 +105,10 @@ func (s *OpenAIGatewayService) forwardAnthropicViaRawChatCompletions( chatBody = policyBody } } + if err := validateGPT61CompatRequest(chatBody, upstreamModel); err != nil { + writeAnthropicError(c, http.StatusBadRequest, "invalid_request_error", err.Error()) + return nil, err + } // Provider normalization and policy caps can both change the converted effort. // Use the final outbound value for usage logs and billing. reasoningEffort := extractOpenAIReasoningEffortFromBody(chatBody, upstreamModel, billingModel, originalModel) diff --git a/backend/internal/service/openai_gateway_passthrough.go b/backend/internal/service/openai_gateway_passthrough.go index af55cc0900..bf3debe638 100644 --- a/backend/internal/service/openai_gateway_passthrough.go +++ b/backend/internal/service/openai_gateway_passthrough.go @@ -1052,7 +1052,8 @@ func openAIStreamEventIsMetadata(eventType string) bool { switch strings.TrimSpace(eventType) { // Queuing and moderation metadata do not commit model output or disarm the // first-output timeout; a following overload must remain safe to retry. - case "response.created", "response.queued", "response.in_progress", "response.metadata", "keepalive": + case "response.created", "response.queued", "response.in_progress", "response.metadata", + "codex.rate_limits", "codex.response.metadata", "keepalive": return true default: return false @@ -1454,6 +1455,36 @@ func openAIStream403AccountFailure(payload []byte, message string) bool { return isOpenAIUpstreamAccessStateError(message, payload) || openAIStreamCredentialAuthFailure(payload) } +// openAICapacityShedRuleBody excludes response output and metadata from custom +// cooldown keyword matching and from the persisted rule reason. +func openAICapacityShedRuleBody(payload []byte) []byte { + if !gjson.ValidBytes(payload) { + return payload + } + errorFields := gjson.GetBytes(payload, "response.error") + if !errorFields.IsObject() { + errorFields = gjson.GetBytes(payload, "error") + } + var errorValue any + if errorFields.IsObject() { + errorValue = json.RawMessage(errorFields.Raw) + } else { + // Some compatible providers send flat errors instead of an error object. + flat := make(map[string]json.RawMessage) + for _, key := range []string{"code", "type", "message", "param", "headers"} { + if value := gjson.GetBytes(payload, key); value.Exists() { + flat[key] = json.RawMessage(value.Raw) + } + } + errorValue = flat + } + body, err := marshalOpenAIUpstreamJSON(gin.H{"error": errorValue}) + if err != nil { + return nil + } + return body +} + func openAIStreamFailedEventPassthroughBody(payload []byte, failedMessage string) []byte { if len(payload) == 0 || !gjson.ValidBytes(payload) { return payload @@ -1614,13 +1645,16 @@ func (s *OpenAIGatewayService) handleOpenAIStreamTerminalAccountSideEffects( canonicalModel ...string, ) (int, bool) { statusCode := openAIStreamFailureStatus(payload, message) + if statusCode == http.StatusServiceUnavailable && (account == nil || account.Platform != PlatformOpenAI) { + return statusCode, false + } switch statusCode { case http.StatusForbidden: if !openAIStream403AccountFailure(payload, message) { return statusCode, false } fallthrough - case http.StatusUnauthorized, http.StatusTooManyRequests, 529: + case http.StatusUnauthorized, http.StatusTooManyRequests, http.StatusServiceUnavailable, 529: ctx := context.Background() if c != nil && c.Request != nil { ctx = c.Request.Context() diff --git a/backend/internal/service/openai_gateway_request_body.go b/backend/internal/service/openai_gateway_request_body.go index 76e9d66489..b7e4514405 100644 --- a/backend/internal/service/openai_gateway_request_body.go +++ b/backend/internal/service/openai_gateway_request_body.go @@ -2748,9 +2748,19 @@ func supportsOpenAIReasoningEffortMax(model string) bool { } } -// validateGPT61CompatRequest runs after model mapping, before conversion can -// discard unsupported explicit effort selections or disabled thinking. +// validateGPT61CompatRequest validates the converted request after model +// mapping and reasoning effort policy application. func validateGPT61CompatRequest(body []byte, model string) error { + if err := validateGPT61RawEffort(body, model); err != nil { + return err + } + if gjson.GetBytes(body, "thinking.type").String() == "disabled" { + return openai.ValidateGPT61ReasoningEffort(model, "none") + } + return nil +} + +func validateGPT61RawEffort(body []byte, model string) error { if !openai.IsGPT61SolModelSpelling(model) && !openai.IsGPT61TerraModelSpelling(model) { return nil } @@ -2759,10 +2769,7 @@ func validateGPT61CompatRequest(body []byte, model string) error { return err } } - if gjson.GetBytes(body, "thinking.type").String() == "disabled" { - return openai.ValidateGPT61ReasoningEffort(model, "none") - } - requestedModel := gjson.GetBytes(body, "model").String() + requestedModel := openai.CanonicalizeOpenAIModelAliasSpelling(gjson.GetBytes(body, "model").String()) for _, effort := range []string{"none", "minimal"} { if strings.HasSuffix(strings.ToLower(requestedModel), "-"+effort) { return openai.ValidateGPT61ReasoningEffort(model, effort) diff --git a/backend/internal/service/openai_gateway_upstream_errors.go b/backend/internal/service/openai_gateway_upstream_errors.go index 69d10bb238..db13c916e0 100644 --- a/backend/internal/service/openai_gateway_upstream_errors.go +++ b/backend/internal/service/openai_gateway_upstream_errors.go @@ -455,6 +455,10 @@ func (s *OpenAIGatewayService) newOpenAIAccountFailoverErrorWithClassificationHe upstreamMsg, retryableOnSameAccount || oauth429Retry, ) + if shouldDisable && account != nil && account.Platform == PlatformOpenAI && failoverErr.RequestScopedTransient { + // A configured model cooldown takes precedence over capacity-shed replay. + failoverErr.RetryableOnSameAccount = false + } if oauth429Retry { failoverErr.SameAccountRetryDeadline = s.openAIOAuth429RetryDeadline(account) failoverErr.SameAccountRetryDelay = openAIOAuth429SameAccountRetryDelay(responseHeaders, failoverErr.SameAccountRetryDeadline) diff --git a/backend/internal/service/openai_images_json_keepalive.go b/backend/internal/service/openai_images_json_keepalive.go index 6ad79b1ae5..a47856444f 100644 --- a/backend/internal/service/openai_images_json_keepalive.go +++ b/backend/internal/service/openai_images_json_keepalive.go @@ -32,10 +32,17 @@ type openAIImagesJSONKeepalive struct { // StartOpenAIImagesJSONKeepalive starts whitespace heartbeats for a // non-streaming Images request. A non-positive interval disables the feature. +// Codex's native Images client relies on the HTTP status to distinguish errors +// from ImageResponse JSON. Keep its status uncommitted until the result exists; +// otherwise a late error becomes HTTP 200 and is misreported as missing image +// fields (for example, "created") instead of the upstream error. func StartOpenAIImagesJSONKeepalive(c *gin.Context, interval time.Duration) func() { if c == nil || c.Writer == nil || interval <= 0 { return func() {} } + if c.GetHeader("X-Codex-Image-Turn-Id") != "" { + return func() {} + } originalWriter := c.Writer k := &openAIImagesJSONKeepalive{ writer: originalWriter, diff --git a/backend/internal/service/openai_images_json_keepalive_test.go b/backend/internal/service/openai_images_json_keepalive_test.go index 780f47a1c3..0ee407cd80 100644 --- a/backend/internal/service/openai_images_json_keepalive_test.go +++ b/backend/internal/service/openai_images_json_keepalive_test.go @@ -76,6 +76,35 @@ func TestOpenAIImagesJSONKeepalive_FastErrorPreservesStatus(t *testing.T) { require.Equal(t, "invalid size", gjson.Get(rec.Body.String(), "error.message").String()) } +func TestOpenAIImagesJSONKeepalive_CodexLateErrorPreservesStatus(t *testing.T) { + gin.SetMode(gin.TestMode) + for _, path := range []string{"/v1/images/generations", "/v1/images/edits"} { + t.Run(path, func(t *testing.T) { + rec := httptest.NewRecorder() + c, _ := gin.CreateTestContext(rec) + c.Request = httptest.NewRequest(http.MethodPost, path, nil) + c.Request.Header.Set("X-Codex-Image-Turn-Id", "native-image-turn") + stop := StartOpenAIImagesJSONKeepalive(c, 5*time.Millisecond) + defer stop() + + // Reproduce an error arriving after a normal heartbeat would have + // committed HTTP 200. Native Codex must see the real error status. + time.Sleep(20 * time.Millisecond) + wrote := writeOpenAIImagesUpstreamErrorResponse(c, &OpenAIImagesUpstreamError{ + StatusCode: http.StatusTooManyRequests, + ErrorType: "rate_limit_error", + Code: "image_rate_limit", + Message: "image quota exceeded", + }) + require.True(t, wrote) + require.Equal(t, http.StatusTooManyRequests, rec.Code) + require.False(t, rec.Flushed) + require.Equal(t, "image_rate_limit", gjson.Get(rec.Body.String(), "error.code").String()) + require.Equal(t, "image quota exceeded", gjson.Get(rec.Body.String(), "error.message").String()) + }) + } +} + func TestOpenAIImagesJSONKeepalive_LateErrorRemainsJSON(t *testing.T) { gin.SetMode(gin.TestMode) rec := httptest.NewRecorder() diff --git a/backend/internal/service/openai_messages_effort_policy_test.go b/backend/internal/service/openai_messages_effort_policy_test.go new file mode 100644 index 0000000000..a6f7013de0 --- /dev/null +++ b/backend/internal/service/openai_messages_effort_policy_test.go @@ -0,0 +1,271 @@ +//go:build unit + +package service + +import ( + "fmt" + "io" + "net/http" + "net/http/httptest" + "strings" + "testing" + + "github.com/Wei-Shaw/sub2api/internal/pkg/openai_compat" + "github.com/gin-gonic/gin" + "github.com/stretchr/testify/require" + "github.com/tidwall/gjson" +) + +func TestMessagesEffortPolicyHTTP(t *testing.T) { + gin.SetMode(gin.TestMode) + noneToLow := []ReasoningEffortMapping{{From: "none", To: "low"}} + for _, chat := range []bool{false, true} { + for _, auth := range []string{AccountTypeAPIKey, AccountTypeOAuth} { + for _, stream := range []bool{false, true} { + for _, test := range []struct { + name string + preference string + mappings []ReasoningEffortMapping + ceiling string + overLimit string + model string + terminal bool + want string + status int + }{ + {name: "omitted unchanged", want: "medium"}, + {name: "omitted unrelated mapping unchanged", mappings: []ReasoningEffortMapping{{From: "medium", To: "low"}}, want: "medium"}, + {name: "omitted ceiling unchanged", ceiling: "low", want: "medium"}, + {name: "omitted deny ceiling unchanged", ceiling: "low", overLimit: ReasoningEffortOverLimitDeny, want: "medium"}, + {name: "omitted none mapping and ceiling unchanged", mappings: noneToLow, ceiling: "low", want: "medium"}, + {name: "omitted above ceiling none mapping leaves default", mappings: []ReasoningEffortMapping{{From: "none", To: "xhigh"}}, ceiling: "low", overLimit: ReasoningEffortOverLimitDeny, want: "medium"}, + {name: "omitted none mapping leaves default", mappings: noneToLow, want: "medium"}, + {name: "disabled omitted mapped", preference: `,"thinking":{"type":"disabled"}`, mappings: noneToLow, want: "low"}, + {name: "disabled synthesized ceiling downgrade", preference: `,"thinking":{"type":"disabled"}`, mappings: []ReasoningEffortMapping{{From: "none", To: "high"}}, ceiling: "low", want: "low"}, + {name: "disabled synthesized ceiling deny", preference: `,"thinking":{"type":"disabled"}`, mappings: []ReasoningEffortMapping{{From: "none", To: "high"}}, ceiling: "low", overLimit: ReasoningEffortOverLimitDeny, status: 403}, + {name: "disabled synthesized xhigh capped", preference: `,"thinking":{"type":"disabled"}`, mappings: []ReasoningEffortMapping{{From: "none", To: "xhigh"}}, ceiling: "low", want: "low"}, + {name: "disabled synthesized xhigh denied", preference: `,"thinking":{"type":"disabled"}`, mappings: []ReasoningEffortMapping{{From: "none", To: "xhigh"}}, ceiling: "low", overLimit: ReasoningEffortOverLimitDeny, status: 403}, + {name: "mapped claude sampling removed", model: "claude-sonnet-4-5", preference: `,"thinking":{"type":"disabled"},"temperature":0.5,"top_p":0.9`, mappings: noneToLow, want: "low"}, + {name: "disabled low mapped", preference: `,"thinking":{"type":"disabled"},"output_config":{"effort":"low"}`, mappings: noneToLow, want: "low"}, + {name: "disabled high mapped", preference: `,"thinking":{"type":"disabled"},"output_config":{"effort":"high"}`, mappings: noneToLow, want: "low"}, + {name: "disabled max mapped", preference: `,"thinking":{"type":"disabled"},"output_config":{"effort":"max"}`, mappings: noneToLow, want: "low"}, + {name: "disabled no mapping rejected", preference: `,"thinking":{"type":"disabled"},"output_config":{"effort":"high"}`, status: 400}, + {name: "disabled omitted no mapping rejected", preference: `,"thinking":{"type":"disabled"}`, status: 400}, + {name: "disabled unrelated mapping rejected", preference: `,"thinking":{"type":"disabled"},"output_config":{"effort":"high"}`, mappings: []ReasoningEffortMapping{{From: "high", To: "low"}}, status: 400}, + {name: "disabled wrong model scope rejected", preference: `,"thinking":{"type":"disabled"}`, mappings: []ReasoningEffortMapping{{From: "none", To: "low", Model: "gpt-6-sol", MatchType: "exact"}}, status: 400}, + {name: "raw none cannot be mapped away", preference: `,"output_config":{"effort":"none"}`, mappings: noneToLow, status: 400}, + {name: "raw none disabled cannot be hidden", preference: `,"thinking":{"type":"disabled"},"output_config":{"effort":"none"}`, mappings: noneToLow, status: 400}, + {name: "raw minimal disabled cannot be hidden", preference: `,"thinking":{"type":"disabled"},"output_config":{"effort":"minimal"}`, mappings: append(append([]ReasoningEffortMapping{}, noneToLow...), ReasoningEffortMapping{From: "minimal", To: "low"}), status: 400}, + {name: "raw minimal cannot be mapped away", preference: `,"output_config":{"effort":"minimal"}`, mappings: []ReasoningEffortMapping{{From: "minimal", To: "low"}}, status: 400}, + {name: "raw reasoning none cannot be hidden", preference: `,"thinking":{"type":"disabled"},"output_config":{"effort":"high"},"reasoning":{"effort":"none"}`, mappings: noneToLow, status: 400}, + {name: "raw chat minimal cannot be hidden", preference: `,"thinking":{"type":"disabled"},"output_config":{"effort":"high"},"reasoning_effort":"minimal"`, mappings: noneToLow, status: 400}, + {name: "raw alias cannot be hidden", model: "gpt-6.1-sol-minimal", preference: `,"thinking":{"type":"disabled"}`, mappings: noneToLow, status: 400}, + {name: "underscore minimal cannot be hidden", model: "gpt-6.1-sol_minimal", preference: `,"thinking":{"type":"disabled"}`, mappings: noneToLow, status: 400}, + {name: "underscore none cannot be hidden", model: "gpt-6.1-sol_none", preference: `,"thinking":{"type":"disabled"}`, mappings: noneToLow, status: 400}, + {name: "one hop mapping", preference: `,"thinking":{"type":"disabled"},"output_config":{"effort":"high"}`, mappings: []ReasoningEffortMapping{{From: "none", To: "low"}, {From: "low", To: "high"}}, want: "low"}, + {name: "mapping final unsupported rejected", preference: `,"thinking":{"type":"disabled"}`, mappings: []ReasoningEffortMapping{{From: "none", To: "minimal"}}, status: 400}, + {name: "mapping deny preserved", preference: `,"thinking":{"type":"disabled"}`, mappings: []ReasoningEffortMapping{{From: "none", To: "deny"}}, status: 403}, + {name: "adaptive explicit unchanged", preference: `,"thinking":{"type":"adaptive"},"output_config":{"effort":"high"}`, mappings: noneToLow, want: "high"}, + {name: "canonical explicit low preserved", preference: `,"output_config":{"effort":"low"}`, mappings: noneToLow, want: "low"}, + {name: "canonical explicit high preserved", preference: `,"output_config":{"effort":"high"}`, mappings: noneToLow, want: "high"}, + {name: "adaptive explicit mapped", preference: `,"thinking":{"type":"adaptive"},"output_config":{"effort":"high"}`, mappings: []ReasoningEffortMapping{{From: "high", To: "low"}, {From: "low", To: "medium"}}, want: "low"}, + {name: "explicit ceiling preserved", preference: `,"output_config":{"effort":"high"}`, ceiling: "medium", want: "medium"}, + {name: "terminal override not mapped twice", terminal: true, preference: `,"thinking":{"type":"disabled"},"output_config":{"effort":"high"}`, mappings: []ReasoningEffortMapping{{From: "none", To: "low", Model: "gpt-6.1-sol", MatchType: "exact"}}, want: "low"}, + {name: "terminal override raw rejected", terminal: true, preference: `,"thinking":{"type":"disabled"},"output_config":{"effort":"none"}`, mappings: noneToLow, status: 400}, + } { + t.Run(fmt.Sprintf("chat=%t/%s/stream=%t/%s", chat, auth, stream, test.name), func(t *testing.T) { + model := test.model + if model == "" { + model = "gpt-6.1-sol" + } + account := rawGPT56ResponsesAPIKeyAccount(model, "gpt-6.1-sol") + if auth == AccountTypeOAuth { + account = rawGPT56ResponsesOAuthAccount(model, "gpt-6.1-sol") + } + if chat { + account.Extra = map[string]any{openai_compat.ExtraKeyResponsesMode: string(openai_compat.ResponsesSupportModeForceChatCompletions)} + } + defaultMapped := "" + if test.terminal { + model = "public-alias" + defaultMapped = "gpt-6.1-sol" + account.Credentials["model_mapping"] = map[string]any{"gpt-6.1-sol": "gpt-6-sol"} + } + usesChat := chat && auth == AccountTypeAPIKey + response := openAICompatSSECompletedResponse("resp_effort", "gpt-6.1-sol") + if usesChat { + payload := `{"id":"chat_effort","model":"gpt-6.1-sol","choices":[{"index":0,"message":{"role":"assistant","content":"ok"},"finish_reason":"stop"}],"usage":{"prompt_tokens":5,"completion_tokens":2}}` + contentType := "application/json" + if stream { + payload = "data: " + `{"id":"chat_effort","model":"gpt-6.1-sol","choices":[{"index":0,"delta":{"role":"assistant","content":"ok"},"finish_reason":"stop"}],"usage":{"prompt_tokens":5,"completion_tokens":2}}` + "\n\ndata: [DONE]\n\n" + contentType = "text/event-stream" + } + response = &http.Response{StatusCode: 200, Header: http.Header{"Content-Type": []string{contentType}}, Body: io.NopCloser(strings.NewReader(payload))} + } + upstream := &httpUpstreamRecorder{resp: response} + svc := &OpenAIGatewayService{cfg: rawChatCompletionsTestConfig(), httpUpstream: upstream} + body := fmt.Sprintf(`{"model":%q,"max_tokens":1024,"messages":[{"role":"user","content":"Hello"}],"stream":%t%s}`, model, stream, test.preference) + var forwardErr error + var result *OpenAIForwardResult + router := gin.New() + router.POST("/v1/messages", func(c *gin.Context) { + ctx := WithOpenAIReasoningEffortPolicyForMessages(c.Request.Context(), []byte(body), test.ceiling, test.mappings, test.overLimit) + result, forwardErr = svc.ForwardAsAnthropic(ctx, c, account, []byte(body), "", defaultMapped) + }) + recorder := httptest.NewRecorder() + router.ServeHTTP(recorder, httptest.NewRequest(http.MethodPost, "/v1/messages", strings.NewReader(body))) + if test.status != 0 { + require.Error(t, forwardErr) + require.Equal(t, test.status, recorder.Code, recorder.Body.String()) + require.Empty(t, upstream.requests) + return + } + preferredEffortPath := "reasoning.effort" + endpoint := "/responses" + if usesChat { + preferredEffortPath = "reasoning_effort" + endpoint = "/chat/completions" + } + require.NoError(t, forwardErr) + require.Equal(t, http.StatusOK, recorder.Code, recorder.Body.String()) + require.Len(t, upstream.requests, 1) + require.True(t, strings.HasSuffix(upstream.lastReq.URL.Path, endpoint), upstream.lastReq.URL.String()) + require.Equal(t, "gpt-6.1-sol", gjson.GetBytes(upstream.lastBody, "model").String()) + require.Equal(t, test.want, gjson.GetBytes(upstream.lastBody, preferredEffortPath).String()) + require.False(t, gjson.GetBytes(upstream.lastBody, "temperature").Exists()) + require.False(t, gjson.GetBytes(upstream.lastBody, "top_p").Exists()) + require.NotNil(t, result) + require.NotNil(t, result.ReasoningEffort) + require.Equal(t, test.want, *result.ReasoningEffort) + require.Equal(t, stream, result.Stream) + require.Equal(t, stream || !usesChat, gjson.GetBytes(upstream.lastBody, "stream").Bool()) + if stream { + require.Contains(t, recorder.Header().Get("Content-Type"), "text/event-stream") + require.Contains(t, recorder.Body.String(), "message_stop") + } else { + require.Contains(t, recorder.Header().Get("Content-Type"), "application/json") + require.Equal(t, "ok", gjson.GetBytes(recorder.Body.Bytes(), "content.0.text").String()) + } + }) + } + } + } + } +} + +func TestMessagesRawEffortValidation(t *testing.T) { + for _, test := range []struct { + body string + deny bool + }{ + {body: `{"output_config":{"effort":"high"},"thinking":{"type":"disabled"}}`}, + {body: `{"output_config":{"effort":"none"},"thinking":{"type":"disabled"}}`, deny: true}, + {body: `{"reasoning_effort":"none"}`, deny: true}, + {body: `{"reasoning":{"effort":"minimal"}}`, deny: true}, + {body: `{"model":"gpt-6.1-sol-none"}`, deny: true}, + {body: `{"model":"gpt-6.1-sol_none"}`, deny: true}, + {body: `{"model":"gpt-6.1-sol_minimal"}`, deny: true}, + {body: `{"model":"gpt-6.1-sol_low","output_config":{"effort":"low"}}`}, + {body: `{"model":"gpt-6.1-sol","output_config":{"effort":"high"}}`}, + } { + require.Equal(t, test.deny, validateGPT61RawEffort([]byte(test.body), "gpt-6.1-sol") != nil, test.body) + require.NoError(t, validateGPT61RawEffort([]byte(test.body), "gpt-6-sol")) + } +} + +func TestMessagesGLMMappedEffortPolicyHTTP(t *testing.T) { + gin.SetMode(gin.TestMode) + for _, test := range []struct { + name string + model string + target string + ceiling string + overLimit string + want string + status int + explicit bool + }{ + {name: "mapped low preserved after normalization", target: "low", want: "low"}, + {name: "unmapped none below low ceiling", ceiling: "low", overLimit: ReasoningEffortOverLimitDeny, want: "none"}, + {name: "unmapped none below minimal ceiling", ceiling: "minimal", overLimit: ReasoningEffortOverLimitDeny, want: "none"}, + {name: "glm53 unmapped none below low ceiling", model: "glm-5.3", ceiling: "low", overLimit: ReasoningEffortOverLimitDeny, want: "none"}, + {name: "mapped minimal preserved", target: "minimal", want: "minimal"}, + {name: "mapped max preserved", target: "max", want: "max"}, + {name: "mapped low meets low ceiling", target: "low", ceiling: "low", want: "low"}, + {name: "mapped minimal below low ceiling", target: "minimal", ceiling: "low", want: "minimal"}, + {name: "mapped minimal meets minimal ceiling", target: "minimal", ceiling: "minimal", want: "minimal"}, + {name: "mapped low below medium ceiling", target: "low", ceiling: "medium", want: "low"}, + {name: "max capped to xhigh", target: "max", ceiling: "xhigh", want: "xhigh"}, + {name: "glm53 low preserved", model: "glm-5.3", target: "low", ceiling: "low", want: "low"}, + {name: "glm53 minimal preserved", model: "glm-5.3", target: "minimal", want: "minimal"}, + {name: "glm53 minimal below low ceiling", model: "glm-5.3", target: "minimal", ceiling: "low", want: "minimal"}, + {name: "glm53 max capped to medium", model: "glm-5.3", target: "max", ceiling: "medium", want: "medium"}, + {name: "glm53 minimal meets minimal ceiling", model: "glm-5.3", target: "minimal", ceiling: "minimal", want: "minimal"}, + {name: "mapped effort denied", target: "high", ceiling: "low", overLimit: ReasoningEffortOverLimitDeny, status: 403}, + {name: "mapping denied", target: "deny", status: 403}, + {name: "mapping applied once", target: "low", ceiling: "high", want: "low", explicit: true}, + } { + t.Run(test.name, func(t *testing.T) { + model := test.model + if model == "" { + model = "glm-5.2" + } + account := rawGPT56ResponsesAPIKeyAccount("claude-sonnet-4-5", model) + account.Extra = map[string]any{openai_compat.ExtraKeyResponsesMode: string(openai_compat.ResponsesSupportModeForceChatCompletions)} + upstream := &httpUpstreamRecorder{resp: &http.Response{ + StatusCode: http.StatusOK, + Header: http.Header{"Content-Type": []string{"application/json"}}, + Body: io.NopCloser(strings.NewReader(`{"id":"chat_glm","model":"` + model + `","choices":[{"index":0,"message":{"role":"assistant","content":"ok"},"finish_reason":"stop"}],"usage":{"prompt_tokens":5,"completion_tokens":2}}`)), + }} + svc := &OpenAIGatewayService{cfg: rawChatCompletionsTestConfig(), httpUpstream: upstream} + body := []byte(`{"model":"claude-sonnet-4-5","max_tokens":1024,"thinking":{"type":"disabled"},"messages":[{"role":"user","content":"Hello"}]}`) + if test.explicit { + body = []byte(`{"model":"claude-sonnet-4-5","max_tokens":1024,"thinking":{"type":"disabled"},"output_config":{"effort":"high"},"messages":[{"role":"user","content":"Hello"}]}`) + } + recorder := httptest.NewRecorder() + requestContext, _ := gin.CreateTestContext(recorder) + requestContext.Request = httptest.NewRequest(http.MethodPost, "/v1/messages", strings.NewReader(string(body))) + mappings := []ReasoningEffortMapping{{From: "high", To: "max"}} + if test.target != "" { + mappings = append(mappings, ReasoningEffortMapping{From: "none", To: test.target}) + } + ctx := WithOpenAIReasoningEffortPolicyForMessages(requestContext.Request.Context(), body, test.ceiling, mappings, test.overLimit) + result, err := svc.ForwardAsAnthropic(ctx, requestContext, account, body, "", "") + if test.status != 0 { + require.Error(t, err) + require.Equal(t, test.status, recorder.Code) + require.Empty(t, upstream.requests) + return + } + require.NoError(t, err) + require.Len(t, upstream.requests, 1) + require.Equal(t, model, gjson.GetBytes(upstream.lastBody, "model").String()) + require.Equal(t, test.want, gjson.GetBytes(upstream.lastBody, "reasoning_effort").String()) + require.NotNil(t, result.ReasoningEffort) + require.Equal(t, test.want, *result.ReasoningEffort) + }) + } +} + +func TestMessagesDisabledThinkingCountTokensHTTP(t *testing.T) { + gin.SetMode(gin.TestMode) + body := []byte(`{"model":"gpt-6.1-sol","thinking":{"type":"disabled"},"messages":[{"role":"user","content":"hello"}]}`) + recorder := httptest.NewRecorder() + requestContext, _ := gin.CreateTestContext(recorder) + requestContext.Request = httptest.NewRequest(http.MethodPost, "/v1/messages/count_tokens", strings.NewReader(string(body))) + upstream := &httpUpstreamRecorder{resp: &http.Response{ + StatusCode: http.StatusOK, + Header: http.Header{"Content-Type": []string{"application/json"}}, + Body: io.NopCloser(strings.NewReader(`{"object":"response.input_tokens","input_tokens":42}`)), + }} + svc := &OpenAIGatewayService{cfg: rawChatCompletionsTestConfig(), httpUpstream: upstream} + account := rawGPT56ResponsesAPIKeyAccount("gpt-6.1-sol", "gpt-6.1-sol") + ctx := WithOpenAIReasoningEffortPolicyForMessages(requestContext.Request.Context(), body, "", []ReasoningEffortMapping{{From: "none", To: "low"}}, "") + require.NoError(t, svc.ForwardCountTokensAsAnthropic(ctx, requestContext, account, body, "")) + require.Equal(t, http.StatusOK, recorder.Code) + require.Equal(t, int64(42), gjson.GetBytes(recorder.Body.Bytes(), "input_tokens").Int()) + require.Len(t, upstream.requests, 1) + require.True(t, strings.HasSuffix(upstream.lastReq.URL.Path, "/responses/input_tokens")) + require.False(t, gjson.GetBytes(upstream.lastBody, "reasoning").Exists()) + require.False(t, gjson.GetBytes(upstream.lastBody, "reasoning_effort").Exists()) +} diff --git a/backend/internal/service/openai_reasoning_effort_policy.go b/backend/internal/service/openai_reasoning_effort_policy.go index 907025597b..b8f7f3b409 100644 --- a/backend/internal/service/openai_reasoning_effort_policy.go +++ b/backend/internal/service/openai_reasoning_effort_policy.go @@ -445,6 +445,25 @@ func WithOpenAIReasoningEffortPolicy(ctx context.Context, maxEffort string, mapp return context.WithValue(ctx, openAIReasoningEffortPolicyContextKey{}, policy) } +// WithOpenAIReasoningEffortPolicyForMessages preserves ordinary bridge defaults, +// but retains ceilings and none mappings for explicitly disabled thinking. +func WithOpenAIReasoningEffortPolicyForMessages(ctx context.Context, body []byte, maxEffort string, mappings []ReasoningEffortMapping, overLimit string) context.Context { + effort := gjson.GetBytes(body, "output_config.effort") + if effort.Type != gjson.String || strings.TrimSpace(effort.String()) == "" { + if gjson.GetBytes(body, "thinking.type").String() != "disabled" { + maxEffort = "" + } + noneMappings := make([]ReasoningEffortMapping, 0, len(mappings)) + for _, mapping := range mappings { + if normalizeReasoningEffortMappingSource(mapping.From) == "none" { + noneMappings = append(noneMappings, mapping) + } + } + mappings = noneMappings + } + return WithOpenAIReasoningEffortPolicy(ctx, maxEffort, mappings, overLimit) +} + // ApplyOpenAIReasoningEffortPolicyFromContext applies a policy previously bound // to the request. An unbound request is returned byte-for-byte unchanged. func ApplyOpenAIReasoningEffortPolicyFromContext(ctx context.Context, body []byte) ([]byte, bool, error) { diff --git a/backend/internal/service/openai_reasoning_effort_policy_test.go b/backend/internal/service/openai_reasoning_effort_policy_test.go index 62cc394c3d..5de704e8fe 100644 --- a/backend/internal/service/openai_reasoning_effort_policy_test.go +++ b/backend/internal/service/openai_reasoning_effort_policy_test.go @@ -2,6 +2,7 @@ package service import ( "context" + "fmt" "testing" "github.com/Wei-Shaw/sub2api/internal/domain" @@ -9,6 +10,29 @@ import ( "github.com/tidwall/gjson" ) +func TestGLMReasoningEffortPolicyPreservesNoneAndMinimal(t *testing.T) { + for _, model := range []string{"glm-5.2", "glm-5.3"} { + for _, field := range []string{`"reasoning":{"effort":"%s"}`, `"reasoning_effort":"%s"`} { + for _, effort := range []string{"none", "minimal"} { + for _, ceiling := range []string{"minimal", "low"} { + for _, overLimit := range []string{ReasoningEffortOverLimitDowngrade, ReasoningEffortOverLimitDeny} { + t.Run(model+"/"+field+"/"+effort+"/"+ceiling+"/"+overLimit, func(t *testing.T) { + body := []byte(fmt.Sprintf(`{"model":%q,`+field+`}`, model, effort)) + ctx := WithOpenAIReasoningEffortPolicy(context.Background(), ceiling, nil, overLimit) + normalized, normalizationChanged := NormalizeGLMOpenAIReasoningEffort(body, model) + require.False(t, normalizationChanged) + got, changed, err := ApplyOpenAIReasoningEffortPolicyFromContext(ctx, normalized) + require.NoError(t, err) + require.False(t, changed) + require.Equal(t, body, got) + }) + } + } + } + } + } +} + func TestCanonicalRequestedReasoningEffort(t *testing.T) { t.Parallel() diff --git a/backend/internal/service/openai_responses_sealed_call_test.go b/backend/internal/service/openai_responses_sealed_call_test.go new file mode 100644 index 0000000000..31d1406c2d --- /dev/null +++ b/backend/internal/service/openai_responses_sealed_call_test.go @@ -0,0 +1,106 @@ +package service + +import ( + "context" + "encoding/json" + "io" + "net/http" + "net/http/httptest" + "strings" + "testing" + + "github.com/gin-gonic/gin" + "github.com/stretchr/testify/require" + "github.com/tidwall/gjson" +) + +func TestOpenAIResponsesSealedFunctionCallRoundTrip(t *testing.T) { + gin.SetMode(gin.TestMode) + const arguments = `{"message":"synthetic-sealed-message"}` + for _, marker := range []struct { + name string + raw string + }{ + {name: "encrypted", raw: `["message"]`}, + {name: "plaintext", raw: `[]`}, + {name: "null", raw: `null`}, + {name: "absent"}, + } { + for _, shape := range []string{"terminal_output", "item_done", "delta_fallback"} { + for _, passthrough := range []bool{false, true} { + mode := "normal" + if passthrough { + mode = "passthrough" + } + t.Run(marker.name+"/"+shape+"/"+mode, func(t *testing.T) { + item := map[string]any{ + "type": "function_call", "call_id": "call_sealed", "name": "send_message", + "namespace": "collaboration", "arguments": arguments, + } + if marker.raw != "" { + item["encrypted_function_args"] = json.RawMessage(marker.raw) + } + output := []any{} + var frames []string + addFrame := func(event map[string]any) { + encoded, err := json.Marshal(event) + require.NoError(t, err) + frames = append(frames, "data: "+string(encoded)+"\n\n") + } + switch shape { + case "terminal_output": + output = append(output, item) + case "item_done": + addFrame(map[string]any{"type": "response.output_item.done", "output_index": 0, "item": item}) + case "delta_fallback": + item["arguments"] = "" + addFrame(map[string]any{"type": "response.output_item.added", "output_index": 0, "item": item}) + addFrame(map[string]any{"type": "response.function_call_arguments.delta", "output_index": 0, "delta": arguments}) + } + addFrame(map[string]any{ + "type": "response.completed", + "response": map[string]any{ + "id": "resp_sealed", "model": "test-model", "status": "completed", "output": output, + "usage": map[string]int{"input_tokens": 7, "output_tokens": 3, "total_tokens": 10}, + }, + }) + + rec := httptest.NewRecorder() + c, _ := gin.CreateTestContext(rec) + c.Request = httptest.NewRequest(http.MethodPost, "/v1/responses", nil) + resp := &http.Response{ + StatusCode: http.StatusOK, + Header: http.Header{"Content-Type": []string{"text/event-stream"}}, + Body: io.NopCloser(strings.NewReader(strings.Join(frames, ""))), + } + account := &Account{ID: 1, Platform: PlatformOpenAI, Type: AccountTypeOAuth} + svc := newCompactBridgeTestService() + if passthrough { + result, err := svc.handleNonStreamingResponsePassthrough(context.Background(), resp, c, account, "test-model", "test-model") + require.NoError(t, err) + require.Equal(t, 7, result.usage.InputTokens) + } else { + result, err := svc.handleNonStreamingResponse(context.Background(), resp, c, account, "test-model", "test-model") + require.NoError(t, err) + require.Equal(t, 7, result.usage.InputTokens) + } + require.Equal(t, http.StatusOK, rec.Code) + require.Contains(t, rec.Header().Get("Content-Type"), "application/json") + body := rec.Body.Bytes() + require.Len(t, gjson.GetBytes(body, "output").Array(), 1) + call := gjson.GetBytes(body, "output.0") + require.Equal(t, "function_call", call.Get("type").String()) + require.Equal(t, "call_sealed", call.Get("call_id").String()) + require.Equal(t, "send_message", call.Get("name").String()) + require.Equal(t, arguments, call.Get("arguments").String()) + if marker.raw == "" { + require.False(t, call.Get("encrypted_function_args").Exists()) + } else { + require.Equal(t, marker.raw, call.Get("encrypted_function_args").Raw) + } + require.Equal(t, "collaboration", call.Get("namespace").String()) + }) + } + } + } +} diff --git a/backend/internal/service/openai_responses_tool_schema_test.go b/backend/internal/service/openai_responses_tool_schema_test.go index 7b1714e30d..06da6635d5 100644 --- a/backend/internal/service/openai_responses_tool_schema_test.go +++ b/backend/internal/service/openai_responses_tool_schema_test.go @@ -2,6 +2,8 @@ package service import ( "encoding/json" + "os" + "os/exec" "strconv" "testing" @@ -587,6 +589,17 @@ func buildToolSchemaNullTypeBody(t *testing.T, hits int) []byte { // 构造请求可以塞进百万级命中,会被放大成 TB 级 memcpy。这里用分配次数锁死该行为: // 命中数放大 500 倍,分配次数不得随之增长。 func TestSanitizeOpenAIResponsesToolParameterTypes_RewriteCountIndependentOfHits(t *testing.T) { + const isolatedAllocEnv = "SUB2API_TOOL_SCHEMA_ALLOC_ISOLATED" + if os.Getenv(isolatedAllocEnv) != "1" { + executable, err := os.Executable() + require.NoError(t, err) + command := exec.Command(executable, "-test.run=^"+t.Name()+"$", "-test.count=1", "-test.timeout=1m") + command.Env = append(os.Environ(), isolatedAllocEnv+"=1") + output, err := command.CombinedOutput() + require.NoError(t, err, "isolated allocation guard failed:\n%s", output) + return + } + small := buildToolSchemaNullTypeBody(t, 4) large := buildToolSchemaNullTypeBody(t, 2000) @@ -598,8 +611,6 @@ func TestSanitizeOpenAIResponsesToolParameterTypes_RewriteCountIndependentOfHits }) // 命中切片扩容是对数级,留出充裕余量;线性写法在这里会是 2000 量级。 - // 干净环境实测 large 约 17 allocs,200 是 10 倍余量,同时容忍 CI 慢 pod 上 - // 包内后台 goroutine(日志/ticker)对进程级 Mallocs 的噪声污染。 require.Less(t, largeAllocs, 200.0, "分配次数随命中数线性增长,说明退回了逐路径全量重写 (small=%v large=%v)", smallAllocs, largeAllocs) diff --git a/backend/internal/service/openai_ws_forwarder_ingress.go b/backend/internal/service/openai_ws_forwarder_ingress.go index 10bb77450d..5d8fffa62f 100644 --- a/backend/internal/service/openai_ws_forwarder_ingress.go +++ b/backend/internal/service/openai_ws_forwarder_ingress.go @@ -1255,7 +1255,12 @@ func (s *OpenAIGatewayService) ProxyResponsesWebSocketFromClient( Duration: time.Since(turnStart), FirstTokenMs: firstTokenMs, } - if replayInput := replayCollector.Items(); len(replayInput) > 0 { + replayInput := replayCollector.Items() + if account.IsOpenAIOAuthLike() && lease.initializedWithoutWebSearch() { + // Keep complete output while search activation can require a new socket. + replayInput = replayCollector.AllItems() + } + if len(replayInput) > 0 { result.wsReplayInput = replayInput result.wsReplayInputExists = true } @@ -1337,6 +1342,15 @@ func (s *OpenAIGatewayService) ProxyResponsesWebSocketFromClient( defer releaseSessionLease() turn := 1 + defer func() { + var failoverErr *UpstreamFailoverError + if turn > 1 && errors.As(returnErr, &failoverErr) { + // Native ingress does not retain a complete conversation for account + // migration. A nil current-turn payload makes the handler close the + // client connection instead of replaying its original first message. + returnErr = newOpenAIWSCurrentTurnFailoverError(returnErr, nil) + } + }() rejectedFieldRetryState = newOpenAIResponsesRejectedFieldRetryState(currentPayload) turnRetry := 0 turnPrevRecoveryTried := false @@ -1347,6 +1361,7 @@ func (s *OpenAIGatewayService) ProxyResponsesWebSocketFromClient( var lastTurnStrictState *openAIWSIngressPreviousTurnStrictState lastTurnReplayInput := []json.RawMessage(nil) lastTurnReplayInputExists := false + lastTurnReplayInputComplete := false currentTurnReplayInput := []json.RawMessage(nil) currentTurnReplayInputExists := false skipBeforeTurn := false @@ -1562,6 +1577,8 @@ func (s *OpenAIGatewayService) ProxyResponsesWebSocketFromClient( currentPayload, currentPreviousResponseID != "", ) + currentTurnReplayInputComplete := replayInputErr == nil && (currentPreviousResponseID == "" || + (lastTurnReplayInputComplete && currentPreviousResponseID == lastTurnResponseID)) if replayInputErr != nil { logOpenAIWSModeInfo( "ingress_ws_replay_input_skip account_id=%d turn=%d conn_id=%s reason=build_error cause=%s", @@ -1678,6 +1695,28 @@ func (s *OpenAIGatewayService) ProxyResponsesWebSocketFromClient( unpinSessionConn(sessionConnID) } } + if account.IsOpenAIOAuthLike() && sessionLease.initializedWithoutWebSearch() && openAIWSWebSearchDeclared(currentPayload) { + fullPayload, safe, err := buildOpenAIWSCurrentTurnRetryPayload(currentPayload, currentTurnReplayInput, currentTurnReplayInputExists, "") + if err != nil { + return fmt.Errorf("rebuild websocket input for web search activation: %w", err) + } + if !safe || !currentTurnReplayInputComplete { + return NewOpenAIWSClientCloseError(coderws.StatusPolicyViolation, "web search activation requires complete input history; please reconnect with full input", nil) + } + logOpenAIWSModeInfo("ingress_ws_web_search_activation account_id=%d turn=%d action=reconnect", account.ID, turn) + resetSessionLease(true) + acquiredLease, acquireErr := acquireTurnLease(turn, "", false, true) + if acquireErr != nil { + return fmt.Errorf("acquire upstream websocket for web search activation: %w", acquireErr) + } + sessionLease = acquiredLease + sessionConnID = strings.TrimSpace(sessionLease.ConnID()) + pinSessionConn(sessionConnID) + currentPayload = fullPayload + currentPayloadBytes = len(fullPayload) + currentPreviousResponseID = "" + forcePreferredConn = false + } shouldPreflightPing := turn > 1 && sessionLease != nil && sessionLease.SupportsIdlePingWithoutReader() && turnRetry == 0 if shouldPreflightPing && openAIWSIngressPreflightPingIdle > 0 && !lastTurnFinishedAt.IsZero() { if time.Since(lastTurnFinishedAt) < openAIWSIngressPreflightPingIdle { @@ -1857,6 +1896,7 @@ func (s *OpenAIGatewayService) ProxyResponsesWebSocketFromClient( // collector 增量经 combine 合并(新头数组)。 lastTurnReplayInput = currentTurnReplayInput lastTurnReplayInputExists = currentTurnReplayInputExists + lastTurnReplayInputComplete = currentTurnReplayInputComplete if result.wsReplayInputExists { lastTurnReplayInput = combineOpenAIWSReplayItems(lastTurnReplayInput, result.wsReplayInput) lastTurnReplayInputExists = true diff --git a/backend/internal/service/openai_ws_pool.go b/backend/internal/service/openai_ws_pool.go index b632bba523..ae4e3fe2c7 100644 --- a/backend/internal/service/openai_ws_pool.go +++ b/backend/internal/service/openai_ws_pool.go @@ -292,6 +292,9 @@ type openAIWSConn struct { readMu sync.Mutex writeMu sync.Mutex + // The subscription backend fixes hosted-search support on the first create. + responseCreateSent bool // guarded by writeMu + initialWebSearch bool // guarded by writeMu // readerLoopResults 非 nil 表示池为该连接常驻了读循环:coder/websocket 只在 // 阻塞读期间应答上游 ping,空闲连接没有读循环会被上游按保活超时关闭。 @@ -600,6 +603,9 @@ func (c *openAIWSConn) writeJSON(value any, writeCtx context.Context) error { if err := c.ws.WriteJSON(writeCtx, value); err != nil { return err } + if !c.responseCreateSent { + c.recordInitialWebSearch(value) + } c.touch() return nil } diff --git a/backend/internal/service/openai_ws_search_activation.go b/backend/internal/service/openai_ws_search_activation.go new file mode 100644 index 0000000000..6d1e640c11 --- /dev/null +++ b/backend/internal/service/openai_ws_search_activation.go @@ -0,0 +1,60 @@ +package service + +import ( + "encoding/json" + + "github.com/tidwall/gjson" +) + +func openAIWSWebSearchDeclared(payload []byte) bool { + fields := gjson.GetMany(openAIWSPayloadStringView(payload), "tools", "input") + if gjsonToolsContainWebSearch(fields[0]) { + return true + } + for _, item := range fields[1].Array() { + if item.Get("type").String() == openAIAdditionalToolsItemType && gjsonToolsContainWebSearch(item.Get("tools")) { + return true + } + } + return false +} + +// Called under writeMu, only after the first response.create was written. +func (c *openAIWSConn) recordInitialWebSearch(value any) { + var body []byte + switch payload := value.(type) { + case json.RawMessage: + body = payload + case []byte: + body = payload + case map[string]any: + if payload["type"] != "response.create" { + return + } + c.responseCreateSent = true + c.initialWebSearch = openAIToolsContainWebSearch(payload["tools"]) + input, _ := payload["input"].([]any) + for _, raw := range input { + if item, ok := raw.(map[string]any); ok && item["type"] == openAIAdditionalToolsItemType && openAIToolsContainWebSearch(item["tools"]) { + c.initialWebSearch = true + } + } + return + default: + return + } + if gjson.GetBytes(body, "type").String() == "response.create" { + c.responseCreateSent = true + c.initialWebSearch = openAIWSWebSearchDeclared(body) + } +} + +func (l *openAIWSConnLease) initializedWithoutWebSearch() bool { + c, err := l.activeConn() + if err != nil { + return false + } + c.writeMu.Lock() + defer c.writeMu.Unlock() + return c.responseCreateSent && !c.initialWebSearch +} diff --git a/backend/internal/service/openai_ws_search_activation_test.go b/backend/internal/service/openai_ws_search_activation_test.go new file mode 100644 index 0000000000..30fe9f0326 --- /dev/null +++ b/backend/internal/service/openai_ws_search_activation_test.go @@ -0,0 +1,202 @@ +package service + +import ( + "context" + "encoding/json" + "fmt" + "net/http" + "net/http/httptest" + "strings" + "testing" + "time" + + "github.com/Wei-Shaw/sub2api/internal/config" + coderws "github.com/coder/websocket" + "github.com/gin-gonic/gin" + "github.com/stretchr/testify/require" + "github.com/tidwall/gjson" +) + +func TestOpenAIWSIngressWebSearchActivation(t *testing.T) { + const search = `,"tools":[{"type":"web_search","external_web_access":false}]` + const userInput = `[{"type":"message","role":"user","content":"continue"}]` + const toolOutput = `[{"type":"function_call_output","call_id":"fc_lookup","output":"42"}]` + const firstOutput = `[{"type":"reasoning","id":"rs_first","summary":[{"type":"summary_text","text":"Keep this reasoning"}]},{"type":"message","id":"msg_first","role":"assistant","content":[{"type":"output_text","text":"Keep this answer"}]},{"type":"function_call","id":"fc_lookup","call_id":"fc_lookup","name":"lookup","arguments":"{}"}]` + for _, tc := range []struct { + name string + accountType string + firstFields string + firstInput string + firstOutput string + nextFields string + nextInput string + nextPrevious string + wantReconnect bool + wantFailClose bool + wantTypes []string + }{ + {name: "empty OAuth prewarm", accountType: AccountTypeOAuth, firstFields: `,"generate":false`, nextFields: search, nextInput: userInput, wantReconnect: true, wantTypes: []string{"message"}}, + {name: "Lite search history injection", accountType: AccountTypeOAuth, firstFields: `,"generate":false`, nextFields: `,"client_metadata":{"ws_request_header_x_openai_internal_codex_responses_lite":"true"}`, nextInput: `[{"type":"web_search_call","id":"ws_history","status":"completed","action":{"type":"search","query":"example"}},{"type":"message","role":"user","content":"continue"}]`, wantReconnect: true, wantTypes: []string{"web_search_call", "message", "additional_tools"}}, + {name: "tool continuation preserves all output", accountType: AccountTypeOAuth, firstFields: `,"tools":[{"type":"function","name":"lookup","parameters":{"type":"object"}}]`, firstInput: `[{"type":"message","role":"user","content":"Run lookup for my original question"}]`, firstOutput: firstOutput, nextFields: search, nextInput: toolOutput, wantReconnect: true, wantTypes: []string{"message", "reasoning", "message", "function_call", "function_call_output"}}, + {name: "search initialized socket", accountType: AccountTypeOAuth, firstFields: search, nextFields: search, nextInput: userInput}, + {name: "API key provider", accountType: AccountTypeAPIKey, firstFields: `,"generate":false`, nextFields: search, nextInput: userInput}, + {name: "function called web_search", accountType: AccountTypeOAuth, nextFields: `,"tools":[{"type":"function","name":"web_search","parameters":{"type":"object"}}]`, nextInput: userInput}, + {name: "missing tool context fails closed", accountType: AccountTypeOAuth, nextFields: search, nextInput: toolOutput, wantFailClose: true}, + {name: "unknown response history fails closed", accountType: AccountTypeOAuth, nextFields: search, nextInput: userInput, nextPrevious: "resp_unknown", wantFailClose: true}, + } { + t.Run(tc.name, func(t *testing.T) { + gin.SetMode(gin.TestMode) + cfg := &config.Config{} + cfg.Security.URLAllowlist.Enabled = false + cfg.Gateway.OpenAIWS.Enabled = true + cfg.Gateway.OpenAIWS.OAuthEnabled = true + cfg.Gateway.OpenAIWS.APIKeyEnabled = true + cfg.Gateway.OpenAIWS.ResponsesWebsocketsV2 = true + cfg.Gateway.OpenAIWS.MaxConnsPerAccount = 2 + cfg.Gateway.OpenAIWS.MaxIdlePerAccount = 2 + cfg.Gateway.OpenAIWS.QueueLimitPerConn = 8 + cfg.Gateway.OpenAIWS.DialTimeoutSeconds = 3 + cfg.Gateway.OpenAIWS.ReadTimeoutSeconds = 3 + cfg.Gateway.OpenAIWS.WriteTimeoutSeconds = 3 + output := tc.firstOutput + if output == "" { + output = "[]" + } + events := [][]byte{ + []byte(fmt.Sprintf(`{"type":"response.completed","response":{"id":"resp_first","model":"gpt-6.1-sol","output":%s,"usage":{"input_tokens":1,"output_tokens":1}}}`, output)), + []byte(`{"type":"response.completed","response":{"id":"resp_second","model":"gpt-6.1-sol","output":[],"usage":{"input_tokens":1,"output_tokens":1}}}`), + []byte(`{"type":"response.completed","response":{"id":"resp_third","model":"gpt-6.1-sol","output":[],"usage":{"input_tokens":1,"output_tokens":1}}}`), + []byte(`{"type":"response.completed","response":{"id":"resp_fourth","model":"gpt-6.1-sol","output":[],"usage":{"input_tokens":1,"output_tokens":1}}}`), + } + first := &openAIWSCaptureConn{events: append([][]byte(nil), events...)} + second := &openAIWSCaptureConn{events: append([][]byte(nil), events[1:]...)} + dialer := &openAIWSQueueDialer{conns: []openAIWSClientConn{first, second}} + pool := newOpenAIWSConnPool(cfg) + pool.setClientDialerForTest(dialer) + t.Cleanup(pool.Close) + svc := &OpenAIGatewayService{cfg: cfg, httpUpstream: &httpUpstreamRecorder{}, cache: &stubGatewayCache{}, openaiWSResolver: NewOpenAIWSProtocolResolver(cfg), toolCorrector: NewCodexToolCorrector(), openaiWSPool: pool} + account := &Account{ID: 71, Platform: PlatformOpenAI, Type: tc.accountType, Status: StatusActive, Schedulable: true, Concurrency: 1, + Credentials: map[string]any{"access_token": "test-token", "api_key": "test-token"}, + Extra: map[string]any{"responses_websockets_v2_enabled": true}} + serverErr := make(chan error, 1) + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + conn, err := coderws.Accept(w, r, nil) + if err != nil { + serverErr <- err + return + } + defer func() { _ = conn.CloseNow() }() + c, _ := gin.CreateTestContext(httptest.NewRecorder()) + c.Request = r + ctx, cancel := context.WithTimeout(r.Context(), 10*time.Second) + defer cancel() + _, payload, err := conn.Read(ctx) + if err == nil { + err = svc.ProxyResponsesWebSocketFromClient(ctx, c, conn, account, "test-token", payload, nil) + } + serverErr <- err + })) + defer server.Close() + ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) + defer cancel() + client, _, err := coderws.Dial(ctx, "ws"+strings.TrimPrefix(server.URL, "http"), nil) + require.NoError(t, err) + defer func() { _ = client.CloseNow() }() + write := func(fields, input string) { + payload := fmt.Sprintf(`{"type":"response.create","model":"gpt-6.1-sol","store":false,"input":%s%s}`, input, fields) + require.NoError(t, client.Write(ctx, coderws.MessageText, []byte(payload))) + } + read := func(id string) { + _, event, err := client.Read(ctx) + require.NoError(t, err) + require.Equal(t, id, gjson.GetBytes(event, "response.id").String()) + } + input := tc.firstInput + if input == "" { + input = "[]" + } + write(tc.firstFields, input) + read("resp_first") + previous := tc.nextPrevious + if previous == "" { + previous = "resp_first" + } + write(fmt.Sprintf(`,"previous_response_id":%q`, previous)+tc.nextFields, tc.nextInput) + if tc.wantFailClose { + _, _, err := client.Read(ctx) + require.Error(t, err) + require.Error(t, <-serverErr) + require.Len(t, first.writes, 1, "unsafe continuation must not reach upstream") + return + } + read("resp_second") + // Removing and restoring search must keep the search-initialized socket. + write(`,"previous_response_id":"resp_second"`, userInput) + read("resp_third") + write(`,"previous_response_id":"resp_third"`+tc.nextFields, userInput) + read("resp_fourth") + require.NoError(t, client.Close(coderws.StatusNormalClosure, "done")) + require.NoError(t, <-serverErr) + if !tc.wantReconnect { + require.Equal(t, 1, dialer.DialCount()) + require.Len(t, first.writes, 4) + return + } + require.Equal(t, 2, dialer.DialCount()) + require.Len(t, first.writes, 1, "search must never be sent on the incompatible socket") + require.Len(t, second.writes, 3) + forwarded, err := json.Marshal(second.writes[0]) + require.NoError(t, err) + require.False(t, gjson.GetBytes(forwarded, "previous_response_id").Exists()) + var types []string + for _, item := range gjson.GetBytes(forwarded, "input").Array() { + types = append(types, item.Get("type").String()) + } + require.Equal(t, tc.wantTypes, types) + if tc.firstOutput != "" { + require.Contains(t, string(forwarded), "Run lookup for my original question") + require.Contains(t, string(forwarded), "Keep this reasoning") + require.Contains(t, string(forwarded), "Keep this answer") + require.Contains(t, string(forwarded), `"output":"42"`) + } + }) + } +} + +func TestOpenAIWSConnWebSearchInitialization(t *testing.T) { + const search = `{"type":"response.create","tools":[{"type":"web_search"}]}` + for _, first := range []struct { + name string + body string + wantReconnect bool + }{ + {"empty prewarm", `{"type":"response.create","generate":false,"input":[]}`, true}, + {"hosted search", search, false}, + {"Lite hosted search", `{"type":"response.create","input":[{"type":"additional_tools","tools":[{"type":"web_search"}]}]}`, false}, + {"function lookalike", `{"type":"response.create","tools":[{"type":"function","name":"web_search"}]}`, true}, + } { + for _, format := range []string{"map", "raw", "bytes"} { + t.Run(first.name+"/"+format, func(t *testing.T) { + conn := newOpenAIWSConn("test", 1, &openAIWSCaptureConn{}, nil) + defer conn.close() + lease := &openAIWSConnLease{conn: conn} + require.False(t, lease.initializedWithoutWebSearch(), "an unused socket is compatible") + var payload any + switch format { + case "map": + require.NoError(t, json.Unmarshal([]byte(first.body), &payload)) + case "raw": + payload = json.RawMessage(first.body) + case "bytes": + payload = []byte(first.body) + } + require.NoError(t, lease.WriteJSON(payload, time.Second)) + // Capability belongs to the socket, even after it is leased again. + lease = &openAIWSConnLease{conn: conn} + require.Equal(t, first.wantReconnect, lease.initializedWithoutWebSearch()) + require.NoError(t, lease.WriteJSON(json.RawMessage(search), time.Second)) + require.Equal(t, first.wantReconnect, lease.initializedWithoutWebSearch(), "later writes cannot change initial capability") + }) + } + } +} diff --git a/backend/internal/service/openai_ws_v2/passthrough_relay.go b/backend/internal/service/openai_ws_v2/passthrough_relay.go index 78ec429d93..af3a57fcf0 100644 --- a/backend/internal/service/openai_ws_v2/passthrough_relay.go +++ b/backend/internal/service/openai_ws_v2/passthrough_relay.go @@ -87,7 +87,10 @@ type RelayOptions struct { BeforeRelayCancel func(exit RelayExit) ReadClientFrame func(ctx context.Context, clientConn FrameConn) (coderws.MessageType, []byte, error) OnTrace func(event RelayTraceEvent) - Now func() time.Time + // IsFirstTokenEvent decides which upstream event marks the first token. + // Nil keeps the built-in delta-based rule. + IsFirstTokenEvent func(eventType string, message []byte) bool + Now func() time.Time } type RelayTraceEvent struct { @@ -116,6 +119,7 @@ type relayState struct { turnTimingByID map[string]*relayTurnTiming activeTurn *relayTurnTiming pendingBareError *observedUpstreamEvent + isFirstTokenEvent func(eventType string, message []byte) bool } type relayExitSignal struct { @@ -181,7 +185,7 @@ func Relay( firstMessageType = coderws.MessageText } startAt := nowFn() - state := &relayState{requestModel: result.RequestModel} + state := &relayState{requestModel: result.RequestModel, isFirstTokenEvent: options.IsFirstTokenEvent} if isClientResponseCreateFrame(firstMessageType, firstClientMessage) { firstTurnStartedAt := options.FirstTurnStartedAt if firstTurnStartedAt.IsZero() { @@ -768,7 +772,7 @@ func observeUpstreamMessage( } now := nowFn() - if state.firstTokenMs == nil && isTokenEvent(eventType) { + if state.firstTokenMs == nil && state.startsFirstToken(eventType, message) { ms := int(now.Sub(startAt).Milliseconds()) if ms >= 0 { state.firstTokenMs = &ms @@ -788,7 +792,7 @@ func observeUpstreamMessage( turnTiming = state.activeTurn } // 每个 turn 独立记录首 token;连接级 firstTokenMs 只反映整条连接的第一个 token。 - if turnTiming != nil && turnTiming.firstTokenMs == nil && isTokenEvent(eventType) { + if turnTiming != nil && turnTiming.firstTokenMs == nil && state.startsFirstToken(eventType, message) { ms := int(now.Sub(turnTiming.startAt).Milliseconds()) if ms >= 0 { turnTiming.firstTokenMs = &ms @@ -1326,6 +1330,13 @@ func shouldParseUsage(eventType string) bool { return strings.HasPrefix(eventType, "response.") && !strings.HasSuffix(eventType, ".delta") } +func (s *relayState) startsFirstToken(eventType string, message []byte) bool { + if s.isFirstTokenEvent != nil { + return !isTerminalEvent(eventType) && s.isFirstTokenEvent(eventType, message) + } + return isTokenEvent(eventType) +} + func isTokenEvent(eventType string) bool { eventType = strings.TrimSpace(eventType) return strings.HasSuffix(eventType, ".delta") || 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 5ba49565df..8186025cec 100644 --- a/backend/internal/service/openai_ws_v2/passthrough_relay_test.go +++ b/backend/internal/service/openai_ws_v2/passthrough_relay_test.go @@ -1558,3 +1558,82 @@ func TestRelay_OnTurnComplete_FirstTokenMsRecordedForEveryTurn(t *testing.T) { t.Fatal("relay did not stop after cancellation") } } + +func TestRelay_IsFirstTokenEventDecidesEveryTurnFirstToken(t *testing.T) { + t.Parallel() + + clientConn := newPassthroughTestFrameConn(nil, false) + upstreamConn := newPassthroughTestFrameConn(nil, false) + firstTurnAt := time.Date(2026, time.November, 5, 9, 0, 0, 0, time.UTC) + secondTurnAt := firstTurnAt.Add(time.Minute) + var clock atomic.Int64 + clock.Store(firstTurnAt.UnixNano()) + + turns := make(chan RelayTurnResult, 2) + ctx, cancel := context.WithCancel(context.Background()) + defer cancel() + done := make(chan struct{}) + go func() { + defer close(done) + _, _ = Relay( + ctx, + clientConn, + upstreamConn, + []byte(`{"type":"response.create","model":"gpt-5.3-codex","input":[]}`), + RelayOptions{ + FirstTurnStartedAt: firstTurnAt, + Now: func() time.Time { return time.Unix(0, clock.Load()).UTC() }, + // Accept everything after response.created, including terminal events. + IsFirstTokenEvent: func(eventType string, _ []byte) bool { + return eventType != "response.created" + }, + OnTurnComplete: func(current RelayTurnResult) { + turns <- current + }, + }, + ) + }() + + sendUpstream := func(at time.Time, payload string) { + forwarded := len(clientConn.Writes()) + clock.Store(at.UnixNano()) + upstreamConn.readCh <- passthroughTestFrame{msgType: coderws.MessageText, payload: []byte(payload)} + require.Eventually(t, func() bool { return len(clientConn.Writes()) == forwarded+1 }, time.Second, time.Millisecond) + } + waitTurn := func(responseID string) RelayTurnResult { + select { + case turn := <-turns: + return turn + case <-time.After(time.Second): + t.Fatalf("turn %s did not complete", responseID) + return RelayTurnResult{} + } + } + + require.Eventually(t, func() bool { return len(upstreamConn.Writes()) == 1 }, time.Second, time.Millisecond) + sendUpstream(firstTurnAt.Add(100*time.Millisecond), `{"type":"response.created","response":{"id":"resp_first"}}`) + sendUpstream(firstTurnAt.Add(300*time.Millisecond), `{"type":"response.output_item.added","item":{"type":"reasoning"}}`) + sendUpstream(firstTurnAt.Add(900*time.Millisecond), `{"type":"response.output_text.delta","delta":"Hi"}`) + sendUpstream(firstTurnAt.Add(2*time.Second), `{"type":"response.completed","response":{"id":"resp_first","usage":{"input_tokens":1,"output_tokens":2}}}`) + firstTurn := waitTurn("resp_first") + require.NotNil(t, firstTurn.FirstTokenMs) + require.Equal(t, 300, *firstTurn.FirstTokenMs, "the injected rule picks the first-token event") + + clock.Store(secondTurnAt.UnixNano()) + clientConn.readCh <- passthroughTestFrame{ + msgType: coderws.MessageText, + payload: []byte(`{"type":"response.create","model":"gpt-5.3-codex","input":[]}`), + } + require.Eventually(t, func() bool { return len(upstreamConn.Writes()) == 2 }, time.Second, time.Millisecond) + sendUpstream(secondTurnAt.Add(100*time.Millisecond), `{"type":"response.created","response":{"id":"resp_second"}}`) + sendUpstream(secondTurnAt.Add(2*time.Second), `{"type":"response.completed","response":{"id":"resp_second","usage":{"input_tokens":1,"output_tokens":0}}}`) + secondTurn := waitTurn("resp_second") + require.Nil(t, secondTurn.FirstTokenMs, "terminal events never mark the first token") + + cancel() + select { + case <-done: + case <-time.After(time.Second): + t.Fatal("relay did not stop after cancellation") + } +} diff --git a/backend/internal/service/openai_ws_v2_passthrough_adapter.go b/backend/internal/service/openai_ws_v2_passthrough_adapter.go index e7d0a0d09b..71804511eb 100644 --- a/backend/internal/service/openai_ws_v2_passthrough_adapter.go +++ b/backend/internal/service/openai_ws_v2_passthrough_adapter.go @@ -1175,6 +1175,7 @@ func (s *OpenAIGatewayService) proxyResponsesWebSocketV2Passthrough( Options: openaiwsv2.RelayOptions{ WriteTimeout: s.openAIWSWriteTimeout(), FirstTurnStartedAt: firstTurnStartedAt, + IsFirstTokenEvent: openAIWSFirstTokenEventFunc(s.openAITTFTMode(ctx)), TakeNextTurnStartedAt: func() time.Time { startedAt := acceptedTurnStartedAt.Swap(nil) if startedAt == nil { @@ -1572,6 +1573,18 @@ func relayErrorText(err error) string { return err.Error() } +// openAIWSFirstTokenEventFunc applies the configured TTFT mode to WebSocket +// events so they report first-token time on the same basis as SSE streams. +// codex.* frames are WebSocket-only out-of-band events, not model output. +func openAIWSFirstTokenEventFunc(mode string) func(eventType string, message []byte) bool { + return func(eventType string, message []byte) bool { + if strings.HasPrefix(strings.TrimSpace(eventType), "codex.") { + return false + } + return openAIStreamDataStartsTTFT(string(message), eventType, false, mode) + } +} + func openAIWSFirstTokenMsForLog(firstTokenMs *int) int { if firstTokenMs == nil { return -1 diff --git a/backend/internal/service/openai_ws_v2_passthrough_ttft_mode_test.go b/backend/internal/service/openai_ws_v2_passthrough_ttft_mode_test.go new file mode 100644 index 0000000000..3201113969 --- /dev/null +++ b/backend/internal/service/openai_ws_v2_passthrough_ttft_mode_test.go @@ -0,0 +1,174 @@ +package service + +import ( + "context" + "net/http" + "net/http/httptest" + "strings" + "testing" + "time" + + "github.com/Wei-Shaw/sub2api/internal/config" + coderws "github.com/coder/websocket" + "github.com/gin-gonic/gin" + "github.com/stretchr/testify/require" + "github.com/tidwall/gjson" +) + +type openAIWSTTFTModeTestEvent struct { + delay time.Duration + payload string +} + +// openAIWSTTFTModeTestTurn replays a reasoning turn: the reasoning item is +// announced shortly after the out-of-band codex.* frame, the first delta only +// arrives after the reasoning ends. +func openAIWSTTFTModeTestTurn(responseID string, startDelay, reasoningDelay time.Duration) []openAIWSTTFTModeTestEvent { + return []openAIWSTTFTModeTestEvent{ + {startDelay, `{"type":"response.created","response":{"id":"` + responseID + `","model":"gpt-5.4"}}`}, + {0, `{"type":"codex.rate_limits","rate_limits":{"primary":{"used_percent":1}}}`}, + {0, `{"type":"response.in_progress","response":{"id":"` + responseID + `"}}`}, + {300 * time.Millisecond, `{"type":"response.output_item.added","output_index":0,"item":{"id":"rs_` + responseID + `","type":"reasoning","summary":[]}}`}, + {reasoningDelay, `{"type":"response.output_text.delta","output_index":1,"delta":"Hi"}`}, + {0, `{"type":"response.completed","response":{"id":"` + responseID + `","model":"gpt-5.4","usage":{"input_tokens":3,"output_tokens":2}}}`}, + } +} + +// openAIWSTTFTModeHTTPExpectedMs is the first-token time the SSE path would +// report for the same events: the delay up to the first event that +// openAIStreamDataStartsTTFT accepts. codex.* frames only exist on WebSocket. +func openAIWSTTFTModeHTTPExpectedMs(t *testing.T, events []openAIWSTTFTModeTestEvent, mode string) time.Duration { + t.Helper() + var elapsed time.Duration + for _, event := range events { + elapsed += event.delay + eventType := gjson.Get(event.payload, "type").String() + if strings.HasPrefix(eventType, "codex.") { + continue + } + if openAIStreamDataStartsTTFT(event.payload, eventType, false, mode) { + return elapsed + } + } + t.Fatalf("no first-token event for mode %s", mode) + return 0 +} + +func TestOpenAIWSPassthroughFirstTokenFollowsTTFTMode(t *testing.T) { + for _, mode := range []string{OpenAITTFTModeSemantic, OpenAITTFTModeVisible} { + t.Run(mode, func(t *testing.T) { + runOpenAIWSPassthroughTTFTModeCase(t, mode) + }) + } +} + +func runOpenAIWSPassthroughTTFTModeCase(t *testing.T, mode string) { + gin.SetMode(gin.TestMode) + gatewayForwardingCache.Store(&cachedGatewayForwardingSettings{openAITTFTMode: mode, expiresAt: time.Now().Add(time.Minute).UnixNano()}) + t.Cleanup(func() { + gatewayForwardingCache.Store(&cachedGatewayForwardingSettings{openAITTFTMode: OpenAITTFTModeSemantic, expiresAt: time.Now().Add(time.Minute).UnixNano()}) + }) + + const reasoningDelay = 600 * time.Millisecond + const tolerance = 250 * time.Millisecond + // The second turn's events wait so its response.create is accepted first. + turns := [][]openAIWSTTFTModeTestEvent{ + openAIWSTTFTModeTestTurn("resp_ttft_1", 0, reasoningDelay), + openAIWSTTFTModeTestTurn("resp_ttft_2", 200*time.Millisecond, reasoningDelay), + } + + upstreamConn := &openAIWSCaptureConn{} + for _, turn := range turns { + for _, event := range turn { + upstreamConn.events = append(upstreamConn.events, []byte(event.payload)) + upstreamConn.readDelays = append(upstreamConn.readDelays, event.delay) + } + } + + 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.ModeRouterV2Enabled = true + cfg.Gateway.OpenAIWS.IngressModeDefault = OpenAIWSIngressModeCtxPool + cfg.Gateway.OpenAIWS.DialTimeoutSeconds = 3 + cfg.Gateway.OpenAIWS.ReadTimeoutSeconds = 3 + cfg.Gateway.OpenAIWS.WriteTimeoutSeconds = 3 + svc := &OpenAIGatewayService{ + cfg: cfg, + httpUpstream: &httpUpstreamRecorder{}, + cache: &stubGatewayCache{}, + openaiWSResolver: NewOpenAIWSProtocolResolver(cfg), + toolCorrector: NewCodexToolCorrector(), + openaiWSPassthroughDialer: &openAIWSCaptureDialer{conn: upstreamConn}, + } + account := &Account{ + ID: 454, Name: "openai-ws-ttft-mode", Platform: PlatformOpenAI, Type: AccountTypeAPIKey, + Status: StatusActive, Schedulable: true, Concurrency: 1, + Credentials: map[string]any{"api_key": "sk-test"}, + Extra: map[string]any{"openai_apikey_responses_websockets_v2_mode": OpenAIWSIngressModePassthrough}, + } + + resultCh := make(chan *OpenAIForwardResult, len(turns)) + hooks := &OpenAIWSIngressHooks{ + AfterTurn: func(_ int, result *OpenAIForwardResult, turnErr error) { + if turnErr == nil && result != nil { + resultCh <- result + } + }, + } + wsServer := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + conn, err := coderws.Accept(w, r, nil) + if err != nil { + return + } + defer func() { _ = conn.CloseNow() }() + ginCtx, _ := gin.CreateTestContext(httptest.NewRecorder()) + ginCtx.Request = r.Clone(r.Context()) + readCtx, cancel := context.WithTimeout(r.Context(), 3*time.Second) + _, firstMessage, readErr := conn.Read(readCtx) + cancel() + if readErr != nil { + return + } + _ = svc.ProxyResponsesWebSocketFromClient(r.Context(), ginCtx, conn, account, "sk-test", firstMessage, hooks) + })) + defer wsServer.Close() + + dialCtx, cancelDial := context.WithTimeout(context.Background(), 3*time.Second) + clientConn, _, err := coderws.Dial(dialCtx, "ws"+strings.TrimPrefix(wsServer.URL, "http"), nil) + cancelDial() + require.NoError(t, err) + defer func() { _ = clientConn.CloseNow() }() + + request := []byte(`{"type":"response.create","model":"gpt-5.4","input":"hi"}`) + for i, turn := range turns { + writeCtx, cancelWrite := context.WithTimeout(context.Background(), 3*time.Second) + require.NoError(t, clientConn.Write(writeCtx, coderws.MessageText, request)) + cancelWrite() + for { + readCtx, cancelRead := context.WithTimeout(context.Background(), 5*time.Second) + _, message, readErr := clientConn.Read(readCtx) + cancelRead() + require.NoError(t, readErr) + if gjson.GetBytes(message, "type").String() == "response.completed" { + break + } + } + + var result *OpenAIForwardResult + select { + case result = <-resultCh: + case <-time.After(5 * time.Second): + t.Fatalf("turn %d result was not reported", i+1) + } + expected := openAIWSTTFTModeHTTPExpectedMs(t, turn, mode) + require.NotNil(t, result.FirstTokenMs, "turn %d must record first token", i+1) + got := time.Duration(*result.FirstTokenMs) * time.Millisecond + require.GreaterOrEqual(t, got, expected, "turn %d first token must not precede the SSE first-token event", i+1) + require.Less(t, got, expected+tolerance, "turn %d first token must match the SSE rule for mode %s", i+1, mode) + } + _ = clientConn.Close(coderws.StatusNormalClosure, "done") +} diff --git a/backend/internal/service/payment_config_service.go b/backend/internal/service/payment_config_service.go index ad5583da27..547bc95e23 100644 --- a/backend/internal/service/payment_config_service.go +++ b/backend/internal/service/payment_config_service.go @@ -337,9 +337,15 @@ func (s *PaymentConfigService) getStripePublishableKey(ctx context.Context) stri // and cannot be meaningfully decomposed without introducing unnecessary abstraction. func (s *PaymentConfigService) UpdatePaymentConfig(ctx context.Context, req UpdatePaymentConfigRequest) error { if req.BalanceRechargeMultiplier != nil { - if math.IsNaN(*req.BalanceRechargeMultiplier) || math.IsInf(*req.BalanceRechargeMultiplier, 0) || *req.BalanceRechargeMultiplier <= 0 { + v := *req.BalanceRechargeMultiplier + if math.IsNaN(v) || math.IsInf(v, 0) || v <= 0 { return infraerrors.BadRequest("INVALID_BALANCE_RECHARGE_MULTIPLIER", "balance recharge multiplier must be greater than 0") } + // 6 位小数可容纳实时汇率(如 1 USD = 7.100000 CNY → 0.140845), + // 到账金额仍按结算币种精度取整,余额不会被放大精度。 + if balanceRechargeMultiplierHasExcessPrecision(v) { + return infraerrors.BadRequest("INVALID_BALANCE_RECHARGE_MULTIPLIER", "balance recharge multiplier allows at most 6 decimal places") + } } if req.SubscriptionUSDToCNYRate != nil { v := *req.SubscriptionUSDToCNYRate @@ -392,7 +398,7 @@ func (s *PaymentConfigService) UpdatePaymentConfig(ctx context.Context, req Upda m[SettingBalancePayDisabled] = formatBoolOrEmpty(req.BalanceDisabled) } if req.BalanceRechargeMultiplier != nil { - m[SettingBalanceRechargeMult] = formatPositiveFloat(req.BalanceRechargeMultiplier) + m[SettingBalanceRechargeMult] = formatBalanceRechargeMultiplier(req.BalanceRechargeMultiplier) } if req.SubscriptionUSDToCNYRate != nil { m[SettingSubscriptionUSDToCNYRate] = formatPositiveFloatExact(req.SubscriptionUSDToCNYRate) @@ -474,6 +480,21 @@ func formatPositiveFloat(v *float64) string { return strconv.FormatFloat(*v, 'f', 2, 64) } +const balanceRechargeMultiplierMaxDecimals = 6 + +func balanceRechargeMultiplierHasExcessPrecision(v float64) bool { + scaled := v * math.Pow(10, balanceRechargeMultiplierMaxDecimals) + return math.Abs(scaled-math.Round(scaled)) > 1e-6 +} + +func formatBalanceRechargeMultiplier(v *float64) string { + if v == nil || *v <= 0 { + return "" // empty → parsePaymentConfig uses default + } + rounded := math.Round(*v*math.Pow(10, balanceRechargeMultiplierMaxDecimals)) / math.Pow(10, balanceRechargeMultiplierMaxDecimals) + return strconv.FormatFloat(rounded, 'f', -1, 64) +} + // formatPositiveFloatExact 保留完整精度,用于汇率等对小数位敏感的配置。 func formatPositiveFloatExact(v *float64) string { if v == nil || *v <= 0 { diff --git a/backend/internal/service/payment_config_service_test.go b/backend/internal/service/payment_config_service_test.go index 900866ef90..f914bf7e9f 100644 --- a/backend/internal/service/payment_config_service_test.go +++ b/backend/internal/service/payment_config_service_test.go @@ -554,3 +554,49 @@ func TestUpdatePaymentConfig_PersistsExplicitEmptyAndFalseValues(t *testing.T) { func paymentConfigStrPtr(value string) *string { return &value } + +func TestUpdatePaymentConfig_PersistsBalanceRechargeMultiplierWithUpToSixDecimals(t *testing.T) { + tests := []struct { + name string + multiplier float64 + want string + }{ + {"six decimals", 0.140845, "0.140845"}, + {"two decimals", 0.15, "0.15"}, + {"float artifact", 0.1 + 0.2, "0.3"}, + {"integer", 1, "1"}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + repo := &paymentConfigSettingRepoStub{} + svc := &PaymentConfigService{settingRepo: repo} + multiplier := tt.multiplier + + err := svc.UpdatePaymentConfig(context.Background(), UpdatePaymentConfigRequest{ + BalanceRechargeMultiplier: &multiplier, + }) + if err != nil { + t.Fatalf("UpdatePaymentConfig returned error: %v", err) + } + if got := repo.updates[SettingBalanceRechargeMult]; got != tt.want { + t.Fatalf("stored multiplier = %q, want %q", got, tt.want) + } + }) + } +} + +func TestUpdatePaymentConfig_RejectsBalanceRechargeMultiplierWithMoreThanSixDecimals(t *testing.T) { + repo := &paymentConfigSettingRepoStub{} + svc := &PaymentConfigService{settingRepo: repo} + multiplier := 0.1408454 + + err := svc.UpdatePaymentConfig(context.Background(), UpdatePaymentConfigRequest{ + BalanceRechargeMultiplier: &multiplier, + }) + if err == nil { + t.Fatal("expected UpdatePaymentConfig to reject more than 6 decimal places") + } + if _, ok := repo.updates[SettingBalanceRechargeMult]; ok { + t.Fatalf("multiplier was persisted despite validation error: %q", repo.updates[SettingBalanceRechargeMult]) + } +} diff --git a/backend/internal/service/payment_refund_test.go b/backend/internal/service/payment_refund_test.go index 834c7f4571..340e8eb4f2 100644 --- a/backend/internal/service/payment_refund_test.go +++ b/backend/internal/service/payment_refund_test.go @@ -6,7 +6,10 @@ import ( "context" "errors" "fmt" + "net/http" + "net/http/httptest" "strconv" + "sync/atomic" "testing" "time" @@ -208,6 +211,115 @@ func TestExecuteRefundUsesActualAvailableBalanceDeduction(t *testing.T) { require.Contains(t, audit.Detail, `"balanceDeducted":25`) } +func TestExecuteEasyPayRefundSuccessCode(t *testing.T) { + for _, tc := range []struct { + name, configuredCode, responseCode string + amount float64 + wantSuccess bool + }{ + {name: "zero success full", configuredCode: "0", responseCode: "0", amount: 100, wantSuccess: true}, + {name: "zero success partial", configuredCode: "0", responseCode: "0", amount: 40, wantSuccess: true}, + {name: "default one success", responseCode: "1", amount: 100, wantSuccess: true}, + {name: "default zero failure", responseCode: "0", amount: 100}, + {name: "zero protocol one failure", configuredCode: "0", responseCode: "1", amount: 100}, + {name: "zero protocol negative failure", configuredCode: "0", responseCode: "-1", amount: 100}, + } { + t.Run(tc.name, func(t *testing.T) { + ctx := context.Background() + client := newPaymentConfigServiceTestClient(t) + var calls atomic.Int32 + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + calls.Add(1) + if r.URL.Path != "/api.php" || r.URL.Query().Get("act") != "refund" || r.FormValue("out_trade_no") != "refund_protocol_order" { + t.Errorf("unexpected refund request: %s", r.URL) + w.WriteHeader(http.StatusBadRequest) + return + } + _, _ = fmt.Fprintf(w, `{"code":%s,"msg":"gateway result"}`, tc.responseCode) + })) + defer server.Close() + user, err := client.User.Create().SetEmail("refund-protocol@example.com"). + SetPasswordHash("hash").SetUsername("refund-protocol").Save(ctx) + require.NoError(t, err) + inst, err := client.PaymentProviderInstance.Create().SetProviderKey(payment.TypeEasyPay). + SetName("refund-protocol").SetConfig("{}").SetSupportedTypes("wxpay"). + SetEnabled(true).SetRefundEnabled(true).Save(ctx) + require.NoError(t, err) + order, err := client.PaymentOrder.Create(). + SetUserID(user.ID).SetUserEmail(user.Email).SetUserName(user.Username). + SetAmount(100).SetPayAmount(100).SetFeeRate(0). + SetRechargeCode("REFUND-PROTOCOL").SetOutTradeNo("refund_protocol_order"). + SetPaymentType(payment.TypeWxpay).SetPaymentTradeNo("trade-protocol"). + SetOrderType(payment.OrderTypeBalance).SetStatus(OrderStatusCompleted). + SetExpiresAt(time.Now().Add(time.Hour)).SetPaidAt(time.Now()). + SetClientIP("127.0.0.1").SetSrcHost("api.example.com"). + SetProviderInstanceID(strconv.FormatInt(inst.ID, 10)).Save(ctx) + require.NoError(t, err) + balance := 200.0 + repo := &mockUserRepo{ + getByIDUser: &User{Balance: balance}, + deductAvailableBalanceFn: func(_ context.Context, id int64, amount float64) (float64, error) { + require.Equal(t, user.ID, id) + balance -= amount + return amount, nil + }, + updateBalanceFn: func(_ context.Context, id int64, amount float64) error { + require.Equal(t, user.ID, id) + balance += amount + return nil + }, + } + svc := &PaymentService{entClient: client, userRepo: repo, loadBalancer: &easyPayRefundLoadBalancer{ + config: map[string]string{ + "pid": "1001", "pkey": "test-key", "apiBase": server.URL, + "notifyUrl": "https://site.example/notify", "returnUrl": "https://site.example/return", + "refundSuccessCode": tc.configuredCode, + }, + }} + plan, early, err := svc.PrepareRefund(ctx, order.ID, tc.amount, "protocol regression", false, true) + require.NoError(t, err) + require.Nil(t, early) + result, err := svc.ExecuteRefund(ctx, plan) + require.NoError(t, err) + require.NotNil(t, result) + require.Equal(t, tc.wantSuccess, result.Success) + require.Equal(t, int32(1), calls.Load(), "do not retry a refund based on a different success code") + stored, err := client.PaymentOrder.Get(ctx, order.ID) + require.NoError(t, err) + wantStatus := OrderStatusCompleted + if tc.wantSuccess { + wantStatus = OrderStatusRefunded + if tc.amount < order.Amount { + wantStatus = OrderStatusPartiallyRefunded + } + require.Equal(t, tc.amount, stored.RefundAmount) + require.NotNil(t, stored.RefundAt) + require.Equal(t, 200-tc.amount, balance) + } else { + require.Zero(t, stored.RefundAmount) + require.Nil(t, stored.RefundAt) + require.Equal(t, 200.0, balance) + } + require.Equal(t, wantStatus, stored.Status) + failed, err := client.PaymentAuditLog.Query().Where( + paymentauditlog.OrderIDEQ(strconv.FormatInt(order.ID, 10)), + paymentauditlog.ActionEQ("REFUND_GATEWAY_FAILED"), + ).Exist(ctx) + require.NoError(t, err) + require.Equal(t, !tc.wantSuccess, failed) + }) + } +} + +type easyPayRefundLoadBalancer struct { + captureLoadBalancer + config map[string]string +} + +func (lb *easyPayRefundLoadBalancer) GetInstanceConfig(context.Context, int64) (map[string]string, error) { + return lb.config, nil +} + func TestGwRefundRejectsAlipayMerchantIdentitySnapshotMismatch(t *testing.T) { ctx := context.Background() client := newPaymentConfigServiceTestClient(t) diff --git a/backend/internal/service/pricing_service.go b/backend/internal/service/pricing_service.go index a0a65d8bf1..f973b5abef 100644 --- a/backend/internal/service/pricing_service.go +++ b/backend/internal/service/pricing_service.go @@ -142,6 +142,14 @@ var ( Mode: "chat", SupportsPromptCaching: true, } + // Fable/Mythos 5.2 share the official price card, including both cache TTLs: + // https://platform.claude.com/docs/en/about-claude/pricing + claude52FallbackPricing = &LiteLLMModelPricing{ + InputCostPerToken: 8e-6, OutputCostPerToken: 40e-6, + CacheCreationInputTokenCost: 10e-6, CacheCreationInputTokenCostAbove1hr: 16e-6, + CacheReadInputTokenCost: 0.2e-6, + LiteLLMProvider: "anthropic", Mode: "chat", SupportsPromptCaching: true, + } claudeOpus55FallbackPricing = &LiteLLMModelPricing{ InputCostPerToken: 4e-6, OutputCostPerToken: 20e-6, CacheCreationInputTokenCost: 5e-6, CacheCreationInputTokenCostAbove1hr: 8e-6, @@ -153,7 +161,7 @@ var ( claudeSonnet55FallbackPricing = &LiteLLMModelPricing{ InputCostPerToken: 2e-6, OutputCostPerToken: 10e-6, CacheCreationInputTokenCost: 2.5e-6, CacheCreationInputTokenCostAbove1hr: 4e-6, - CacheReadInputTokenCost: 0.2e-6, + CacheReadInputTokenCost: 0.1e-6, LiteLLMProvider: "anthropic", Mode: "chat", SupportsPromptCaching: true, } claudeHaiku55FallbackPricing = &LiteLLMModelPricing{ @@ -647,10 +655,10 @@ func (s *PricingService) downloadPricingData() error { logger.LegacyPrintf("service.pricing", "[Pricing] Failed to save file: %v", err) } - // 使用远程哈希作为同步锚点,防止重复下载 - // 当远程哈希不可用时,回退到数据本身的哈希 + // 只有远程哈希与下载正文一致时才将其作为同步锚点。 + // 不匹配时保留正文哈希,让下一轮同步重试,避免旧数据被误标为最新。 syncHash := dataHashStr - if remoteHash != "" { + if strings.EqualFold(remoteHash, dataHashStr) { syncHash = remoteHash } hashFile := s.getHashFilePath() @@ -1451,6 +1459,19 @@ func (s *PricingService) extractBaseName(model string) string { // matchByModelFamily 基于模型系列匹配 func (s *PricingService) matchByModelFamily(model string) *LiteLLMModelPricing { model = normalizeAntigravityClaudeTierAlias(model) + var claude52Model string + switch { + case claude.IsFable52(model): + claude52Model = "claude-fable-5-2" + case claude.IsMythos52(model): + claude52Model = "claude-mythos-5-2" + } + if claude52Model != "" { + if pricing, ok := s.pricingData[claude52Model]; ok { + return pricing + } + return claude52FallbackPricing + } if claude.IsOpus55(model) { if pricing, ok := s.pricingData["claude-opus-5-5"]; ok { return pricing diff --git a/backend/internal/service/pricing_service_hot_reload_test.go b/backend/internal/service/pricing_service_hot_reload_test.go index 31a50ac145..f0d3975831 100644 --- a/backend/internal/service/pricing_service_hot_reload_test.go +++ b/backend/internal/service/pricing_service_hot_reload_test.go @@ -2,6 +2,8 @@ package service import ( "context" + "crypto/sha256" + "fmt" "os" "path/filepath" "strconv" @@ -160,21 +162,64 @@ func TestPricingHotReload_DeletedFileDropsItsLayer(t *testing.T) { require.NotNil(t, svc.pricingData["custom-a"], "文件重新出现即恢复") } -type stubPricingRemoteClient struct{ body string } +type stubPricingRemoteClient struct { + body string + hash string + downloads int +} -func (c stubPricingRemoteClient) FetchPricingJSON(context.Context, string) ([]byte, error) { +func (c *stubPricingRemoteClient) FetchPricingJSON(context.Context, string) ([]byte, error) { + c.downloads++ return []byte(c.body), nil } -func (c stubPricingRemoteClient) FetchHashText(context.Context, string) (string, error) { - return "", nil +func (c *stubPricingRemoteClient) FetchHashText(context.Context, string) (string, error) { + return c.hash, nil +} + +func TestPricingSyncRetriesMismatchedCatalogUntilDataCatchesUp(t *testing.T) { + oldBody := hotReloadCatalogJSON + newBody := `{` + hotReloadModelJSON("remote-model", 3e-6, 6e-6) + `}` + oldHash := fmt.Sprintf("%x", sha256.Sum256([]byte(oldBody))) + newHash := fmt.Sprintf("%x", sha256.Sum256([]byte(newBody))) + remote := &stubPricingRemoteClient{body: oldBody, hash: newHash} + svc := NewPricingService(&config.Config{Pricing: config.PricingConfig{ + DataDir: t.TempDir(), + RemoteURL: "https://example.com/pricing.json", + HashURL: "https://example.com/pricing.sha256", + }}, remote) + + // The hash endpoint has advanced, but the catalog endpoint still serves old prices. + require.NoError(t, svc.ForceUpdate()) + require.InDelta(t, 1e-6, svc.GetModelPricing("remote-model").InputCostPerToken, 1e-12) + require.Equal(t, oldHash, svc.localHash) + savedHash, err := os.ReadFile(svc.getHashFilePath()) + require.NoError(t, err) + require.Equal(t, oldHash+"\n", string(savedHash)) + + // An unchanged remote hash must not suppress the later catalog download. + remote.body = newBody + require.NoError(t, svc.syncWithRemote()) + require.Equal(t, 2, remote.downloads) + require.InDelta(t, 3e-6, svc.GetModelPricing("remote-model").InputCostPerToken, 1e-12) + require.Equal(t, newHash, svc.localHash) + savedBody, err := os.ReadFile(svc.getPricingFilePath()) + require.NoError(t, err) + require.Equal(t, newBody, string(savedBody)) + savedHash, err = os.ReadFile(svc.getHashFilePath()) + require.NoError(t, err) + require.Equal(t, newHash+"\n", string(savedHash)) + + // Once both endpoints agree, normal polling skips redundant downloads. + require.NoError(t, svc.syncWithRemote()) + require.Equal(t, 2, remote.downloads) } // 远程下载重建后指纹必须同步到当前文件内容,否则下一轮定时比对会多做一次无意义重载。 func TestPricingHotReload_DownloadRefreshesFingerprint(t *testing.T) { svc := newHotReloadPricingService(t, `{`+hotReloadModelJSON("custom-a", 4e-6, 8e-6)+`}`, "") svc.cfg.Pricing.RemoteURL = "https://example.com/pricing.json" - svc.remoteClient = stubPricingRemoteClient{body: hotReloadCatalogJSON} + svc.remoteClient = &stubPricingRemoteClient{body: hotReloadCatalogJSON} require.NoError(t, os.WriteFile(svc.cfg.Pricing.FallbackFile, []byte(`{`+hotReloadModelJSON("custom-b", 1e-6, 3e-6)+`}`), 0644)) require.NoError(t, svc.downloadPricingData()) diff --git a/backend/internal/service/refresh_token_cache.go b/backend/internal/service/refresh_token_cache.go index 9d49495ac9..179fe79d7b 100644 --- a/backend/internal/service/refresh_token_cache.go +++ b/backend/internal/service/refresh_token_cache.go @@ -44,6 +44,11 @@ type RefreshTokenCache interface { // 用于Token轮转时使旧Token失效 DeleteRefreshToken(ctx context.Context, tokenHash string) error + // ConsumeRefreshToken 原子地读取并删除 Refresh Token。 + // 并发轮转时只有一个调用能成功,其余返回 ErrRefreshTokenNotFound, + // 用于避免同一个 Refresh Token 被重复兑换(double-spend)。 + ConsumeRefreshToken(ctx context.Context, tokenHash string) (*RefreshTokenData, error) + // DeleteUserRefreshTokens 删除用户的所有Refresh Token // 用于密码更改或用户主动登出所有设备 DeleteUserRefreshTokens(ctx context.Context, userID int64) error diff --git a/backend/internal/service/token_refresh_pool_health_test.go b/backend/internal/service/token_refresh_pool_health_test.go index a9bd760d95..324e4ae012 100644 --- a/backend/internal/service/token_refresh_pool_health_test.go +++ b/backend/internal/service/token_refresh_pool_health_test.go @@ -105,17 +105,18 @@ func (r *poolHealthAccountRepo) snapshot() ([]OAuthRefreshPageOptions, []int64, } type poolHealthRefresher struct { - err error - delay time.Duration - startDelays []time.Duration - ignoreContext bool - cancel context.CancelFunc - newCredentials map[string]any - calls atomic.Int64 - active atomic.Int64 - maxActive atomic.Int64 - startMu sync.Mutex - startTimes []time.Time + err error + delay time.Duration + startDelays []time.Duration + ignoreContext bool + waitForContextDone bool + cancel context.CancelFunc + newCredentials map[string]any + calls atomic.Int64 + active atomic.Int64 + maxActive atomic.Int64 + startMu sync.Mutex + startTimes []time.Time } type countingRefreshAttemptGate struct { @@ -306,6 +307,9 @@ func (r *poolHealthRefresher) Refresh(ctx context.Context, _ *Account) (map[stri if r.cancel != nil { r.cancel() } + if r.waitForContextDone { + <-ctx.Done() + } if delay > 0 { if r.ignoreContext { time.Sleep(delay) @@ -936,8 +940,7 @@ func TestTokenRefreshService_ParentCancellationStopsRetryWithoutAccountMutation( func TestTokenRefreshService_LateSuccessPastAttemptDeadlineIsRejected(t *testing.T) { repo := &poolHealthAccountRepo{} refresher := &poolHealthRefresher{ - delay: 30 * time.Millisecond, - ignoreContext: true, + waitForContextDone: true, } svc := newPoolHealthService(repo, refresher, config.TokenRefreshConfig{MaxRetries: 1}) svc.attemptTimeoutOverride = 10 * time.Millisecond diff --git a/backend/migrations/249_add_usage_logs_api_key_cost_index_notx.sql b/backend/migrations/249_add_usage_logs_api_key_cost_index_notx.sql new file mode 100644 index 0000000000..740e1e516e --- /dev/null +++ b/backend/migrations/249_add_usage_logs_api_key_cost_index_notx.sql @@ -0,0 +1,5 @@ +-- Serve per-key 30-day / today cost sums (API key list usage column) from the index alone, +-- instead of fetching hundreds of thousands of usage_logs heap rows per page load. +CREATE INDEX CONCURRENTLY IF NOT EXISTS idx_usage_logs_api_key_created_cost + ON usage_logs (api_key_id, created_at) + INCLUDE (actual_cost); diff --git a/backend/migrations/usage_log_api_key_cost_index_test.go b/backend/migrations/usage_log_api_key_cost_index_test.go new file mode 100644 index 0000000000..5a68667517 --- /dev/null +++ b/backend/migrations/usage_log_api_key_cost_index_test.go @@ -0,0 +1,18 @@ +package migrations + +import ( + "strings" + "testing" + + "github.com/stretchr/testify/require" +) + +func TestUsageLogAPIKeyCostIndexMigration(t *testing.T) { + content, err := FS.ReadFile("249_add_usage_logs_api_key_cost_index_notx.sql") + require.NoError(t, err) + + sql := strings.Join(strings.Fields(string(content)), " ") + require.Contains(t, sql, "CREATE INDEX CONCURRENTLY IF NOT EXISTS idx_usage_logs_api_key_created_cost") + require.Contains(t, sql, "ON usage_logs (api_key_id, created_at)") + require.Contains(t, sql, "INCLUDE (actual_cost)") +} 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 bbe05a937c..0f48dc14f7 100644 --- a/backend/resources/model-pricing/model_prices_and_context_window.json +++ b/backend/resources/model-pricing/model_prices_and_context_window.json @@ -229,6 +229,26 @@ "cache_read_input_token_cost_batches": 5e-09, "context_window": 1050000 }, + "claude-fable-5-2": { + "cache_creation_input_token_cost": 1e-05, + "cache_creation_input_token_cost_above_1hr": 1.6e-05, + "cache_read_input_token_cost": 2e-07, + "input_cost_per_token": 8e-06, + "output_cost_per_token": 4e-05, + "litellm_provider": "anthropic", + "mode": "chat", + "supports_prompt_caching": true + }, + "claude-mythos-5-2": { + "cache_creation_input_token_cost": 1e-05, + "cache_creation_input_token_cost_above_1hr": 1.6e-05, + "cache_read_input_token_cost": 2e-07, + "input_cost_per_token": 8e-06, + "output_cost_per_token": 4e-05, + "litellm_provider": "anthropic", + "mode": "chat", + "supports_prompt_caching": true + }, "claude-opus-5-5": { "cache_creation_input_token_cost": 5e-06, "cache_creation_input_token_cost_above_1hr": 8e-06, @@ -1015,7 +1035,7 @@ "claude-sonnet-5-5": { "cache_creation_input_token_cost": 2.5e-06, "cache_creation_input_token_cost_above_1hr": 4e-06, - "cache_read_input_token_cost": 2e-07, + "cache_read_input_token_cost": 1e-07, "input_cost_per_token": 2e-06, "litellm_provider": "anthropic", "max_input_tokens": 1000000, diff --git a/docs/OPENAI_IMAGES_CODEX.md b/docs/OPENAI_IMAGES_CODEX.md new file mode 100644 index 0000000000..f1e70a0e9b --- /dev/null +++ b/docs/OPENAI_IMAGES_CODEX.md @@ -0,0 +1,39 @@ +# Native Codex Images HTTP status and proxy timeouts + +Non-streaming `/v1/images/generations` and `/v1/images/edits` requests carrying +`X-Codex-Image-Turn-Id` wait for the final response without whitespace heartbeats. +This preserves the actual HTTP error status. Otherwise an early heartbeat commits +HTTP 200, and Codex can mistake a delayed error for an incomplete image response +(for example, a missing `created` field). + +Other clients retain the configured `gateway.image_nonstream_keepalive_interval` +behavior. Streaming Images responses are unaffected. The header is a client +capability signal; it does not authenticate a request or grant image permissions. + +## Timeout budget + +A proxy in front of Sub2API must allow the entire image operation, including queue +waits, account selection and upstream processing, before the first response byte. +The proxy's upstream response-header deadline and idle-read timeout must exceed +that budget. A larger HTTP client total timeout alone does not override a short +proxy deadline. Configure the client, every intervening proxy and the upstream +HTTP transport consistently; use a finite deadline appropriate for the deployment. +For example, an nginx deployment with a 900-second image budget needs +`proxy_read_timeout 900s` or an appropriately larger value for scheduling overhead. +Check any outer CDN/load-balancer timeout as well: changing nginx does not change +that outer limit. + +Disabling heartbeats does not shorten image generation. A proxy timeout can occur +while the upstream is still generating and may still incur cost. Diagnose the +original request before retrying; a timeout is not proof that generation never +ran. This status-handling fix does not resolve upstream quota or permission errors. + +## Regression coverage + +The handler tests register both actual routes, parse JSON generation and multipart +edit requests, select an account and forward over HTTP to a delayed local upstream. +A local reverse proxy with a sufficient header deadline receives the final HTTP +400 error or successful image JSON after the usual heartbeat interval. A proxy +with a shorter header deadline times out for native requests; the same proxy +still receives heartbeats for ordinary clients. These are controlled fixtures, +not successful paid generation claims or a test of a particular deployed CDN. diff --git a/frontend/src/components/account/AccountUsageCell.vue b/frontend/src/components/account/AccountUsageCell.vue index d3bd7963c9..f6a7533838 100644 --- a/frontend/src/components/account/AccountUsageCell.vue +++ b/frontend/src/components/account/AccountUsageCell.vue @@ -1,5 +1,5 @@