diff --git a/.github/scripts/quality-live-red-compat.py b/.github/scripts/quality-live-red-compat.py index 196524aed0b3..6a2e73cfa680 100644 --- a/.github/scripts/quality-live-red-compat.py +++ b/.github/scripts/quality-live-red-compat.py @@ -13,3 +13,12 @@ if 'infraerrors "github.com/Wei-Shaw/sub2api/internal/pkg/errors"' not in original: original = original.replace('import (', 'import (\n\tinfraerrors "github.com/Wei-Shaw/sub2api/internal/pkg/errors"', 1) target.write_text(original) + +# The candidate's metadata resolver also fills an audio capability bit. The +# historical list implementation ignores it; retain storage for that caller. +descriptor = target.with_name('openai_codex_models_service.go') +source = descriptor.read_text() +anchor = 'type codexModelMetadataOverride struct {\n' +if source.count(anchor) != 1: + raise SystemExit('historical descriptor declaration missing or ambiguous') +descriptor.write_text(source.replace(anchor, anchor + '\taudioInput bool\n', 1)) diff --git a/.github/scripts/upstream-v0222-red-fixtures.txt b/.github/scripts/upstream-v0222-red-fixtures.txt index 64a3d6f43142..1ce6e1af0098 100644 --- a/.github/scripts/upstream-v0222-red-fixtures.txt +++ b/.github/scripts/upstream-v0222-red-fixtures.txt @@ -192,6 +192,11 @@ backend/internal/service/ciallo_test.go backend/internal/service/openai_409_controls_diagnostics_test.go backend/internal/handler/openai_owner_conflict_diagnostics_test.go +# v0.2.24 model listing and request-body diagnostics depend on newer handler APIs. +backend/internal/handler/gateway_models_test.go +backend/internal/handler/request_body_limit_test.go +backend/internal/handler/request_body_read_log_test.go + # Probe penalty tests use receipt types absent from historical WS sources. backend/internal/handler/probe_penalty_response_test.go backend/internal/service/account_probe_penalty_test.go diff --git a/.github/workflows/issue765-image-scheduler.yml b/.github/workflows/issue765-image-scheduler.yml index 32a07d574b67..1aa2db97220f 100644 --- a/.github/workflows/issue765-image-scheduler.yml +++ b/.github/workflows/issue765-image-scheduler.yml @@ -17,6 +17,29 @@ jobs: regression: runs-on: ubuntu-latest timeout-minutes: 35 + services: + postgres: + image: postgres:18.1-alpine3.23 + env: + POSTGRES_USER: postgres + POSTGRES_PASSWORD: postgres + POSTGRES_DB: sub2api_test + ports: + - 5432:5432 + options: >- + --health-cmd "pg_isready -U postgres -d sub2api_test" + --health-interval 5s + --health-timeout 5s + --health-retries 12 + redis: + image: redis:8.4-alpine + ports: + - 6379:6379 + options: >- + --health-cmd "redis-cli ping" + --health-interval 5s + --health-timeout 5s + --health-retries 12 env: CI: 'true' EXPECTED_HEAD: ${{ github.event.pull_request.head.sha || github.sha }} @@ -86,6 +109,9 @@ jobs: test -z "$(git -C candidate status --porcelain)" (cd candidate/backend && go test -race -json -tags=unit ./internal/repository ./internal/service -run '^(TestIssue765|TestExtraImageModels)' -count=1 -timeout=10m) > evidence/green-unit.jsonl 2> evidence/green-unit.stderr - name: GREEN - real Redis publication, memo refresh and revocation + env: + SUB2API_TEST_POSTGRES_DSN: 'postgres://postgres:postgres@127.0.0.1:5432/sub2api_test?sslmode=disable&TimeZone=UTC' + SUB2API_TEST_REDIS_URL: 'redis://127.0.0.1:6379/0' shell: bash run: | set -euo pipefail diff --git a/.github/workflows/issue817-grok-persistence.yml b/.github/workflows/issue817-grok-persistence.yml index e2c574ffe4eb..68147ad0caf3 100644 --- a/.github/workflows/issue817-grok-persistence.yml +++ b/.github/workflows/issue817-grok-persistence.yml @@ -113,6 +113,10 @@ jobs: path.write_bytes(historical.replace(anchor, anchor + field, 1)) PY else + # The pinned repository predates the OpenAI rotation CAS tests. + fixture=backend/internal/repository/account_repo_temp_unsched_test.go + git show "$original:$fixture" > "$fixture" + test "$(git hash-object "$fixture")" = "$(git rev-parse "$original:$fixture")" # These account repositories predate the compact-routing selector. # Apply only its import, struct field and constructor initialization. routing=2c69cefb93828e2bdefc413b4df058f3a342c7e1 diff --git a/backend/cmd/server/wire_gen.go b/backend/cmd/server/wire_gen.go index dfdb2469bef4..1dc51296aaac 100644 --- a/backend/cmd/server/wire_gen.go +++ b/backend/cmd/server/wire_gen.go @@ -276,7 +276,7 @@ func initializeApplication(buildInfo handler.BuildInfo) (*Application, error) { adminGroupRepository := repository.NewAdminGroupRepository(client, db) adminAccountRepository := repository.NewAdminAccountRepository(client, db, schedulerCache) proxyLatencyCache := repository.NewProxyLatencyCache(redisClient) - adminService := service.ProvideAdminService(configConfig, userRepository, adminGroupRepository, adminAccountRepository, proxyRepository, apiKeyRepository, redeemCodeRepository, userGroupRateRepository, userRPMCache, billingCacheService, proxyExitInfoProber, proxyLatencyCache, apiKeyAuthCacheInvalidator, client, settingService, subscriptionService, userSubscriptionRepository, privacyClientFactory, openAIGatewayService, affiliateService, compositeModelRouteRepository, compositeRouteResolver, channelService, lotteryService) + adminService := service.ProvideAdminService(configConfig, userRepository, adminGroupRepository, adminAccountRepository, proxyRepository, apiKeyRepository, redeemCodeRepository, userGroupRateRepository, userRPMCache, billingCacheService, proxyExitInfoProber, proxyLatencyCache, apiKeyAuthCacheInvalidator, client, settingService, subscriptionService, userSubscriptionRepository, privacyClientFactory, openAIGatewayService, affiliateService, compositeModelRouteRepository, compositeRouteResolver, channelService, lotteryService, serviceUserPlatformQuotaRepository) adminUserHandler := admin.NewUserHandler(adminService, concurrencyService, serviceUserPlatformQuotaRepository, billingCache, totpService, userService, settingService) groupCapacityService := service.NewGroupCapacityService(accountRepository, groupRepository, concurrencyService, sessionLimitCache, rpmCache) groupHandler := admin.ProvideGroupHandlerWithProtection(adminService, dashboardService, groupCapacityService, configConfig, groupAntiDistillationService) diff --git a/backend/internal/handler/gateway_compat_effort_policy_test.go b/backend/internal/handler/gateway_compat_effort_policy_test.go index 3f13c33da0d1..3ab2e60fa794 100644 --- a/backend/internal/handler/gateway_compat_effort_policy_test.go +++ b/backend/internal/handler/gateway_compat_effort_policy_test.go @@ -14,6 +14,7 @@ import ( "testing" "github.com/Wei-Shaw/sub2api/internal/config" + "github.com/Wei-Shaw/sub2api/internal/handler/dto" "github.com/Wei-Shaw/sub2api/internal/pkg/ctxkey" "github.com/Wei-Shaw/sub2api/internal/pkg/tlsfingerprint" middleware "github.com/Wei-Shaw/sub2api/internal/server/middleware" @@ -23,6 +24,43 @@ import ( "github.com/tidwall/gjson" ) +func TestOpenAIResponsesUsageReportsConfigurationUpdateEffort(t *testing.T) { + const input = `[{"role":"user","content":"hello"},{"type":"configuration_update","reasoning":{"effort":"high"}}]` + const body = `{"model":"gpt-6.1-sol","input":` + input + `,"reasoning":{"effort":"medium"}}` + upstream := newAstraProCapturedUpstream(&http.Response{ + StatusCode: http.StatusOK, + Header: http.Header{"Content-Type": []string{"application/json"}}, + Body: io.NopCloser(strings.NewReader(`{"id":"resp_effort","model":"gpt-6.1-sol","status":"completed","output":[],"usage":{"input_tokens":10,"output_tokens":1}}`)), + }) + account := service.Account{ + ID: 1, Platform: service.PlatformOpenAI, Type: service.AccountTypeAPIKey, + Status: service.StatusActive, Schedulable: true, Credentials: map[string]any{"api_key": "test-key"}, + } + usageRepo := &openAIWSUsageHandlerUsageLogRepoStub{created: make(chan *service.UsageLog, 1)} + cfg := &config.Config{RunMode: config.RunModeSimple} + billing := service.NewBillingCacheService(nil, nil, nil, nil, nil, nil, cfg, nil) + t.Cleanup(billing.Stop) + gateway := service.NewOpenAIGatewayService( + &openAIWSUsageHandlerAccountRepoStub{account: account}, nil, usageRepo, nil, nil, nil, nil, nil, cfg, + nil, nil, service.NewBillingService(cfg, nil), nil, billing, upstream, &service.DeferredService{}, + nil, nil, nil, nil, nil, nil, nil, + ) + h := NewOpenAIGatewayHandler(gateway, service.NewConcurrencyService(nil), billing, + service.NewAPIKeyService(nil, nil, nil, nil, nil, nil, cfg), nil, nil, nil, nil, cfg) + c, rec := newAstraProFailoverContext(t, body) + h.Responses(c) + + require.Equal(t, http.StatusOK, rec.Code, rec.Body.String()) + _, _, bodies := upstream.snapshot() + require.Len(t, bodies, 1) + require.Equal(t, "medium", gjson.GetBytes(bodies[0], "reasoning.effort").String()) + require.JSONEq(t, input, gjson.GetBytes(bodies[0], "input").Raw) + require.Len(t, usageRepo.created, 1) + log := dto.UsageLogFromService(<-usageRepo.created) + require.NotNil(t, log.ReasoningEffort) + require.Equal(t, "high", *log.ReasoningEffort) +} + type compatEffortPolicyUpstream struct { service.HTTPUpstream bodies [][]byte diff --git a/backend/internal/handler/gateway_handler.go b/backend/internal/handler/gateway_handler.go index c5f3f299b232..9c7ddd4b5100 100644 --- a/backend/internal/handler/gateway_handler.go +++ b/backend/internal/handler/gateway_handler.go @@ -150,11 +150,12 @@ func (h *GatewayHandler) Messages(c *gin.Context) { if middleware2.RejectRequestBodyReadError(c, err) { return } - if maxErr, ok := extractMaxBytesError(err); ok { - h.errorResponse(c, http.StatusRequestEntityTooLarge, "invalid_request_error", buildBodyTooLargeMessage(maxErr.Limit)) + status, message := requestBodyReadFailure(reqLog, c.Request, err) + if status == 499 { + c.Status(status) return } - h.errorResponse(c, http.StatusBadRequest, "invalid_request_error", "Failed to read request body") + h.errorResponse(c, status, "invalid_request_error", message) return } @@ -1271,6 +1272,22 @@ func (h *GatewayHandler) Models(c *gin.Context) { // Get available models from account configurations for the selected group platform. availableModels := h.gatewayService.GetAvailableModels(c.Request.Context(), groupID, platform) + if platform == service.PlatformAnthropic { + var group *service.Group + if apiKey != nil { + group = apiKey.Group + } + source := availableModels + if group != nil && group.ModelAllowlistEnabled() { + source = service.ModelListingSource(platform, availableModels, service.DefaultModelIDsForPlatform(platform)) + } else if len(source) == 0 { + source = service.DefaultModelIDsForPlatform(platform) + } + expanded := h.gatewayService.ExpandAnthropicLongContextModels(c.Request.Context(), group, source) + if len(availableModels) > 0 || len(expanded) > len(source) || (group != nil && group.ModelAllowlistEnabled()) { + availableModels = expanded + } + } if apiKey != nil && apiKey.Group != nil && apiKey.Group.ModelAllowlistEnabled() { source := service.ModelListingSource(platform, availableModels, service.DefaultModelIDsForPlatform(platform)) writeAllowlistedModelsList(c, platform, apiKey.Group.ModelAllowlist.FilterForListing(source)) @@ -2172,11 +2189,12 @@ func (h *GatewayHandler) CountTokens(c *gin.Context) { if middleware2.RejectRequestBodyReadError(c, err) { return } - if maxErr, ok := extractMaxBytesError(err); ok { - h.errorResponse(c, http.StatusRequestEntityTooLarge, "invalid_request_error", buildBodyTooLargeMessage(maxErr.Limit)) + status, message := requestBodyReadFailure(reqLog, c.Request, err) + if status == 499 { + c.Status(status) return } - h.errorResponse(c, http.StatusBadRequest, "invalid_request_error", "Failed to read request body") + h.errorResponse(c, status, "invalid_request_error", message) return } diff --git a/backend/internal/handler/gateway_handler_chat_completions.go b/backend/internal/handler/gateway_handler_chat_completions.go index 2b502d96ae1b..4cae559e8d90 100644 --- a/backend/internal/handler/gateway_handler_chat_completions.go +++ b/backend/internal/handler/gateway_handler_chat_completions.go @@ -180,8 +180,10 @@ func (h *GatewayHandler) ChatCompletions(c *gin.Context) { defer inflightRelease() // Parse request for session hash + // body 已在本函数开头用 gjson.ValidBytes 校验过,之后只经过 sjson 改写 + // (applyOpenAIReasoningEffortPolicyForRequest),合法性保持,因此跳过重复校验。 bodyRef := service.NewRequestBodyRef(body) - parsedReq, _ := service.ParseGatewayRequest(bodyRef, "chat_completions") + parsedReq, _ := service.ParseGatewayRequestValidated(bodyRef, "chat_completions") if parsedReq == nil { parsedReq = &service.ParsedRequest{Model: reqModel, Stream: reqStream, Body: bodyRef} } diff --git a/backend/internal/handler/gateway_handler_responses.go b/backend/internal/handler/gateway_handler_responses.go index bd6dcc1f347c..0bc735d84ac1 100644 --- a/backend/internal/handler/gateway_handler_responses.go +++ b/backend/internal/handler/gateway_handler_responses.go @@ -106,7 +106,10 @@ func (h *GatewayHandler) Responses(c *gin.Context) { // 里的任何工具声明(含 Codex 被动 image_gen namespace)而关闭。生图意图 // 仅用于能力路由与图片计费;独立图片/视频端点才在利润门范围之外。 requestCtx, pricingAt := service.WithGatewayTokenRequestPricing(requestCtx) - if service.IsImageGenerationIntentForPlatform("/v1/responses", reqModel, body, openAICompatibleRequestPlatform(c.Request.Context(), apiKey)) { + // body 已在本函数开头用 gjson.ValidBytes 校验过,之后只经过 sjson 改写 + // (applyOpenAIReasoningEffortPolicyForRequest),合法性保持,因此走跳过校验的 + // 变体,避免对同一份字节再全量校验一次。 + if service.IsImageGenerationIntentForPlatformValidated("/v1/responses", reqModel, body, openAICompatibleRequestPlatform(c.Request.Context(), apiKey)) { requestCtx = service.WithOpenAIImageGenerationIntent(requestCtx) } c.Request = c.Request.WithContext(requestCtx) @@ -181,8 +184,10 @@ func (h *GatewayHandler) Responses(c *gin.Context) { defer inflightRelease() // Parse request for session hash + // body 已在本函数开头用 gjson.ValidBytes 校验过,之后只经过 sjson 改写 + // (applyOpenAIReasoningEffortPolicyForRequest),合法性保持,因此跳过重复校验。 bodyRef := service.NewRequestBodyRef(body) - parsedReq, _ := service.ParseGatewayRequest(bodyRef, "responses") + parsedReq, _ := service.ParseGatewayRequestValidated(bodyRef, "responses") if parsedReq == nil { parsedReq = &service.ParsedRequest{Model: reqModel, Stream: reqStream, Body: bodyRef} } diff --git a/backend/internal/handler/gateway_models_test.go b/backend/internal/handler/gateway_models_test.go index 100166a022bb..fe6c24e2468f 100644 --- a/backend/internal/handler/gateway_models_test.go +++ b/backend/internal/handler/gateway_models_test.go @@ -23,6 +23,86 @@ type gatewayModelsAccountRepoStub struct { byGroup map[int64][]service.Account } +func TestGatewayModelsAnthropicLongContextVariants(t *testing.T) { + gin.SetMode(gin.TestMode) + const groupID int64 = 8880 + for _, test := range []struct { + name string + platform string + mapping map[string]any + metadata map[string]service.UpstreamModelMetadata + allowlist []string + routing map[string][]int64 + otherAccounts []service.Account + wantVariants []string + absent []string + }{ + {name: "mapped target and threshold", mapping: map[string]any{"public": "upstream", "short": "short", "max-only": "max-only"}, + metadata: map[string]service.UpstreamModelMetadata{"upstream": {ContextWindow: 900_000}, "short": {ContextWindow: 899_999}, "max-only": {MaxContextWindow: 1_000_000}, "hidden": {ContextWindow: 1_000_000}}, + wantVariants: []string{"public[1m]"}, absent: []string{"upstream", "upstream[1m]", "hidden", "hidden[1m]", "short[1m]", "max-only[1m]", claude.DefaultModels[0].ID}}, + {name: "wildcard mappings are not concrete variants", mapping: map[string]any{"public*": "upstream"}, + metadata: map[string]service.UpstreamModelMetadata{"upstream": {ContextWindow: 1_000_000}}, absent: []string{"public*[1m]"}}, + {name: "source metadata cannot override mapped target", mapping: map[string]any{"public": "short"}, + metadata: map[string]service.UpstreamModelMetadata{"public": {ContextWindow: 1_000_000}, "short": {ContextWindow: 200_000}}, absent: []string{"public[1m]"}}, + {name: "no duplicate suffix", mapping: map[string]any{"public": "upstream", "public[1m]": "upstream", "other[1M]": "upstream"}, + metadata: map[string]service.UpstreamModelMetadata{"upstream": {ContextWindow: 1_000_000}}, wantVariants: []string{"public[1m]", "other[1M]"}, absent: []string{"public[1m][1m]", "other[1M][1m]"}}, + {name: "allowlist filters variants", mapping: map[string]any{"public": "upstream", "private": "upstream"}, + metadata: map[string]service.UpstreamModelMetadata{"upstream": {ContextWindow: 1_000_000}}, allowlist: []string{"public"}, absent: []string{"public[1m]", "private", "private[1m]"}}, + {name: "allowlist can select variant", mapping: map[string]any{"public": "upstream"}, + metadata: map[string]service.UpstreamModelMetadata{"upstream": {ContextWindow: 1_000_000}}, allowlist: []string{"public[1m]"}, wantVariants: []string{"public[1m]"}, absent: []string{"public"}}, + {name: "routing excludes metadata account", mapping: map[string]any{"public": "upstream"}, + metadata: map[string]service.UpstreamModelMetadata{"upstream": {ContextWindow: 1_000_000}}, routing: map[string][]int64{"public": {2}}, absent: []string{"public[1m]"}}, + {name: "routing includes metadata account", mapping: map[string]any{"public": "upstream"}, + metadata: map[string]service.UpstreamModelMetadata{"upstream": {ContextWindow: 1_000_000}}, routing: map[string][]int64{"pub*": {1}}, wantVariants: []string{"public[1m]"}}, + {name: "non-Anthropic listing", platform: service.PlatformOpenAI, mapping: map[string]any{"public": "upstream"}, + metadata: map[string]service.UpstreamModelMetadata{"upstream": {ContextWindow: 1_000_000}}, absent: []string{"public[1m]"}}, + {name: "unmapped defaults", metadata: map[string]service.UpstreamModelMetadata{claude.DefaultModels[0].ID: {ContextWindow: 1_000_000}, "hidden": {ContextWindow: 1_000_000}}, + wantVariants: []string{claude.DefaultModels[0].ID + "[1m]"}, absent: []string{"hidden", "hidden[1m]"}}, + {name: "other platform account metadata", mapping: map[string]any{"public": "upstream"}, + otherAccounts: []service.Account{{ID: 2, Platform: service.PlatformOpenAI, Extra: map[string]any{service.UpstreamModelMetadataExtraKey: service.UpstreamModelMetadataSnapshot{Models: map[string]service.UpstreamModelMetadata{"upstream": {ContextWindow: 1_000_000}}}}}}, absent: []string{"public[1m]"}}, + {name: "unsupported model metadata", mapping: map[string]any{"public": "upstream"}, + otherAccounts: []service.Account{{ID: 2, Platform: service.PlatformAnthropic, Credentials: map[string]any{"model_mapping": map[string]any{"private": "private"}}, Extra: map[string]any{service.UpstreamModelMetadataExtraKey: service.UpstreamModelMetadataSnapshot{Models: map[string]service.UpstreamModelMetadata{"public": {ContextWindow: 1_000_000}}}}}}, absent: []string{"public[1m]"}}, + } { + t.Run(test.name, func(t *testing.T) { + platform := test.platform + if platform == "" { + platform = service.PlatformAnthropic + } + account := service.Account{ID: 1, Platform: platform, Type: service.AccountTypeOAuth, Credentials: map[string]any{"model_mapping": test.mapping}} + account.SetUpstreamModelMetadataSnapshot(service.UpstreamModelMetadataSnapshot{Models: test.metadata}) + outsideAccount := service.Account{ID: 3, Platform: service.PlatformAnthropic} + outsideAccount.SetUpstreamModelMetadataSnapshot(service.UpstreamModelMetadataSnapshot{Models: map[string]service.UpstreamModelMetadata{"upstream": {ContextWindow: 1_000_000}}}) + h := newGatewayModelsHandlerForTest(&gatewayModelsAccountRepoStub{byGroup: map[int64][]service.Account{ + groupID: append([]service.Account{account}, test.otherAccounts...), groupID + 1: {outsideAccount}, + }}) + rec := httptest.NewRecorder() + ctx, _ := gin.CreateTestContext(rec) + ctx.Request = httptest.NewRequest(http.MethodGet, "/v1/models", nil) + ctx.Set(string(middleware2.ContextKeyAPIKey), &service.APIKey{Group: &service.Group{ + ID: groupID, Platform: platform, + ModelAllowlist: service.GroupModelAllowlist{Enabled: test.allowlist != nil, Models: test.allowlist}, + ModelRoutingEnabled: test.routing != nil, ModelRouting: test.routing, + }}) + h.Models(ctx) + require.Equal(t, http.StatusOK, rec.Code) + var response gatewayModelsResponseForTest + require.NoError(t, json.Unmarshal(rec.Body.Bytes(), &response)) + ids := modelIDsForTest(response.Data) + for _, variant := range test.wantVariants { + require.Contains(t, ids, variant) + } + for _, absent := range test.absent { + require.NotContains(t, ids, absent) + } + seen := make(map[string]bool, len(ids)) + for _, id := range ids { + require.False(t, seen[id], "duplicate model ID: %s", id) + seen[id] = true + } + }) + } +} + type gatewayModelsRouteRepoStub struct { service.CompositeModelRouteRepository routes []service.CompositeModelRoute diff --git a/backend/internal/handler/gemini_cached_contents_handler.go b/backend/internal/handler/gemini_cached_contents_handler.go index 54a154c2448c..9d396bde19b8 100644 --- a/backend/internal/handler/gemini_cached_contents_handler.go +++ b/backend/internal/handler/gemini_cached_contents_handler.go @@ -68,11 +68,12 @@ func readGeminiCachedContentBody(c *gin.Context) ([]byte, bool) { if middleware.RejectRequestBodyReadError(c, err) { return nil, false } - if maxErr, ok := extractMaxBytesError(err); ok { - googleError(c, http.StatusRequestEntityTooLarge, buildBodyTooLargeMessage(maxErr.Limit)) - return nil, false + status, message := requestBodyReadFailure(nil, c.Request, err) + if status == pkghttputil.StatusClientClosedRequest { + c.Status(status) + } else { + googleError(c, status, message) } - googleError(c, http.StatusBadRequest, "Failed to read request body") return nil, false } if len(body) == 0 { diff --git a/backend/internal/handler/gemini_v1beta_handler.go b/backend/internal/handler/gemini_v1beta_handler.go index 8ec043d19ea8..72d1f24d30e6 100644 --- a/backend/internal/handler/gemini_v1beta_handler.go +++ b/backend/internal/handler/gemini_v1beta_handler.go @@ -992,7 +992,7 @@ func googleErrorWithType(c *gin.Context, status int, errType, code, message stri // googleClientErrorType 返回客户端请求类 4xx 状态码对应的 ops 错误类型;其余状态码返回空串。 func googleClientErrorType(status int) string { switch status { - case http.StatusBadRequest, http.StatusRequestEntityTooLarge: + case http.StatusBadRequest, http.StatusRequestTimeout, http.StatusRequestEntityTooLarge: return "invalid_request_error" case http.StatusUnauthorized: return "authentication_error" diff --git a/backend/internal/handler/grok_media.go b/backend/internal/handler/grok_media.go index 0c0b1b22d862..78cf025e2de2 100644 --- a/backend/internal/handler/grok_media.go +++ b/backend/internal/handler/grok_media.go @@ -490,6 +490,11 @@ func (h *OpenAIGatewayHandler) handleGrokMedia(c *gin.Context, endpoint service. service.SetOpsLatencyMs(c, service.OpsResponseLatencyMsKey, responseLatencyMs) if err != nil { + var validationErr *service.GrokMediaInputValidationError + if errors.As(err, &validationErr) { + h.errorResponse(c, http.StatusBadRequest, "invalid_request_error", validationErr.Error()) + return + } var failoverErr *service.UpstreamFailoverError if errors.As(err, &failoverErr) { if failoverClientGone(c) { diff --git a/backend/internal/handler/grok_media_errors_test.go b/backend/internal/handler/grok_media_errors_test.go index 234f37d5b8a4..9898119eb87b 100644 --- a/backend/internal/handler/grok_media_errors_test.go +++ b/backend/internal/handler/grok_media_errors_test.go @@ -3,12 +3,18 @@ package handler import ( + "bytes" "context" + "encoding/json" + "errors" + "fmt" "io" + "mime/multipart" "net/http" "net/http/httptest" "strings" "testing" + "testing/iotest" "time" "github.com/Wei-Shaw/sub2api/internal/service" @@ -17,6 +23,160 @@ import ( "github.com/tidwall/gjson" ) +func TestGrokImageEditLocalValidationSyncAndAsync(t *testing.T) { + enableGrokMediaValidationTestScheduler(t) + for _, oauth := range []bool{false, true} { + for _, async := range []bool{false, true} { + for _, format := range []string{"json", "multipart"} { + for _, count := range []int{3, 4, 5, 6} { + t.Run(fmt.Sprintf("oauth=%t/async=%t/%s/%d", oauth, async, format, count), func(t *testing.T) { + h, slots, _, upstream := newGrokMediaSlotHandler(t, oauth, false) + h.grokMediaEligibilityProber = grokMediaSlotProber(func(context.Context, int64) (bool, string, error) { + return true, "eligible", nil + }) + upstream.call = func(req *http.Request, _ int64) (*http.Response, error) { + assert.Equal(t, "/v1/images/edits", req.URL.Path) + body, err := io.ReadAll(req.Body) + assert.NoError(t, err) + assert.Len(t, gjson.GetBytes(body, "images").Array(), count) + assert.NotEmpty(t, gjson.GetBytes(body, "mask.url").String()) + return &http.Response{StatusCode: http.StatusBadRequest, Header: http.Header{"Content-Type": {"application/json"}}, + Body: io.NopCloser(strings.NewReader(`{"code":"invalid_image","error":"upstream image rejection"}`))}, nil + } + body, contentType := grokImageEditLimitBody(t, format, count) + c, recorder := grokMediaSlotContext(context.Background(), true) + path := "/v1/images/edits" + if async { + path += "/async" + } + c.Request = httptest.NewRequest(http.MethodPost, path, bytes.NewReader(body)) + c.Request.Header.Set("Content-Type", contentType) + responseBody := []byte(nil) + if async { + store := &asyncImageMemoryStore{tasks: make(map[string]*service.ImageTaskRecord)} + tasks := service.NewImageTaskServiceWithUploader(store, nil, time.Hour, time.Minute) + asyncHandler := NewAsyncImageHandler(tasks, h) + asyncHandler.Submit(c) + require.Equal(t, http.StatusAccepted, recorder.Code, recorder.Body.String()) + taskID := gjson.GetBytes(recorder.Body.Bytes(), "task_id").String() + owner := service.ImageTaskOwner{UserID: 10, APIKeyID: 20} + require.Eventually(t, func() bool { + task, err := tasks.Get(context.Background(), owner, taskID) + return err == nil && task.Status != service.ImageTaskStatusProcessing + }, time.Second, 10*time.Millisecond) + poll, pollRecorder := grokMediaSlotContext(context.Background(), false) + poll.Params[0].Key, poll.Params[0].Value = "task_id", taskID + asyncHandler.Get(poll) + require.Equal(t, http.StatusOK, pollRecorder.Code) + responseBody = pollRecorder.Body.Bytes() + require.Equal(t, service.ImageTaskStatusFailed, gjson.GetBytes(responseBody, "status").String()) + require.Equal(t, int64(http.StatusBadRequest), gjson.GetBytes(responseBody, "http_status").Int()) + } else { + h.GrokImages(c) + require.Equal(t, http.StatusBadRequest, recorder.Code, recorder.Body.String()) + responseBody = recorder.Body.Bytes() + } + require.Equal(t, "invalid_request_error", gjson.GetBytes(responseBody, "error.type").String()) + metrics := h.gatewayService.SnapshotOpenAIAccountSchedulerMetrics() + if count > 5 { + require.Equal(t, "a maximum of 5 source images is supported for image edits", gjson.GetBytes(responseBody, "error.message").String()) + require.Zero(t, upstream.calls) + require.Zero(t, metrics.RuntimeStatsAccountCount, "local rejection must report neither success nor failure") + } else { + require.Equal(t, "upstream image rejection", gjson.GetBytes(responseBody, "error.message").String()) + require.Equal(t, 1, upstream.calls) + require.Equal(t, 1, metrics.RuntimeStatsAccountCount, "real upstream failures still report failure") + } + require.Zero(t, metrics.AccountSwitchTotal) + slots.assertReleased(t) + }) + } + } + } + } +} + +func grokImageEditLimitBody(t *testing.T, format string, count int) ([]byte, string) { + t.Helper() + if format == "json" { + images := make([]string, count) + for index := range images { + images[index] = fmt.Sprintf("https://example.test/%d.png", index) + } + body, err := json.Marshal(map[string]any{"model": "grok-imagine-image-2.0", "prompt": "test", "images": images, "mask": "https://example.test/mask.png"}) + require.NoError(t, err) + return body, "application/json" + } + var buffer bytes.Buffer + writer := multipart.NewWriter(&buffer) + require.NoError(t, writer.WriteField("model", "grok-imagine-image-2.0")) + require.NoError(t, writer.WriteField("prompt", "test")) + for index := 0; index < count; index++ { + if index%2 == 0 { + require.NoError(t, writer.WriteField("image", fmt.Sprintf("https://example.test/%d.png", index))) + } else { + part, err := writer.CreateFormFile("image[]", fmt.Sprintf("%d.png", index)) + require.NoError(t, err) + _, err = part.Write([]byte("\x89PNG\r\n\x1a\nsynthetic")) + require.NoError(t, err) + } + } + part, err := writer.CreateFormFile("mask", "mask.png") + require.NoError(t, err) + _, err = part.Write([]byte("\x89PNG\r\n\x1a\nmask")) + require.NoError(t, err) + require.NoError(t, writer.Close()) + return buffer.Bytes(), writer.FormDataContentType() +} + +func TestGrokImageEditInternalAndRetryableErrorsRemainUpstreamErrors(t *testing.T) { + enableGrokMediaValidationTestScheduler(t) + for _, retryable := range []bool{false, true} { + t.Run(fmt.Sprintf("retryable=%t", retryable), func(t *testing.T) { + h, slots, _, upstream := newGrokMediaSlotHandler(t, false, false) + upstream.call = func(*http.Request, int64) (*http.Response, error) { + if !retryable { + return &http.Response{StatusCode: http.StatusOK, Header: http.Header{"Content-Type": {"application/json"}}, + Body: io.NopCloser(iotest.ErrReader(errors.New("internal response read failure")))}, nil + } + return &http.Response{StatusCode: http.StatusServiceUnavailable, Header: http.Header{"Content-Type": {"application/json"}}, + Body: io.NopCloser(strings.NewReader(`{"error":"temporarily unavailable"}`))}, nil + } + c, recorder := grokMediaSlotContext(context.Background(), true) + body, contentType := grokImageEditLimitBody(t, "json", 3) + c.Request = httptest.NewRequest(http.MethodPost, "/v1/images/edits", bytes.NewReader(body)) + c.Request.Header.Set("Content-Type", contentType) + h.GrokImages(c) + require.GreaterOrEqual(t, recorder.Code, http.StatusInternalServerError, recorder.Body.String()) + require.NotEqual(t, "invalid_request_error", gjson.GetBytes(recorder.Body.Bytes(), "error.type").String()) + metrics := h.gatewayService.SnapshotOpenAIAccountSchedulerMetrics() + require.Positive(t, metrics.RuntimeStatsAccountCount, "calls=%d response=%s", upstream.calls, recorder.Body.String()) + if retryable { + require.Greater(t, upstream.calls, 1) + require.Positive(t, metrics.AccountSwitchTotal) + } else { + require.Equal(t, http.StatusBadGateway, recorder.Code) + require.Equal(t, 1, upstream.calls) + require.Zero(t, metrics.AccountSwitchTotal) + } + slots.assertReleased(t) + }) + } +} + +func (grokMediaSlotRepo) SetTempUnschedulable(context.Context, int64, time.Time, string) error { + return nil +} + +func enableGrokMediaValidationTestScheduler(t *testing.T) { + t.Helper() + settings := service.NewSettingService(&contentModerationHandlerSettingRepo{}, nil) + require.NoError(t, settings.UpdateSettings(context.Background(), &service.SystemSettings{OpenAIAdvancedSchedulerEnabled: true})) + t.Cleanup(func() { + require.NoError(t, settings.UpdateSettings(context.Background(), &service.SystemSettings{})) + }) +} + func TestGrokImagesPreservesUpstreamErrorOnSyncAndAsyncRoutes(t *testing.T) { for _, oauth := range []bool{false, true} { accountType := "api-key" diff --git a/backend/internal/handler/openai_codex_page_context.go b/backend/internal/handler/openai_codex_page_context.go index 109bec4d23a6..cccfd984ccf5 100644 --- a/backend/internal/handler/openai_codex_page_context.go +++ b/backend/internal/handler/openai_codex_page_context.go @@ -20,7 +20,7 @@ func normalizeCodexPageContext(body []byte) ([]byte, bool) { } func normalizeCodexUntrustedContext(body []byte) ([]byte, bool) { - if !mayContainCodexCallOutputCandidate(body, "codex_apps_open_page", "codex_apps_selected_page_part_", "browser_info", "goal_objective", "untrusted_context") { + if !mayContainCodexCallOutputCandidate(body, "codex_apps_open_page", "codex_apps_selected_page_part_", "browser_info", "goal_objective", "untrusted_context", "ide_context", "untrusted_content", "proposed_plan") { return body, false } input := gjson.GetBytes(body, "input") @@ -44,7 +44,7 @@ func normalizeCodexUntrustedContext(body []byte) ([]byte, bool) { } name, output := item.Get("name").String(), item.Get("output").String() text := "\n" + output + "\n" - if name == "browser_info" || name == "goal_objective" || name == "untrusted_context" { + if codexStandaloneContextName(name) { text = "" + output + "" } message, err := json.Marshal(map[string]any{ @@ -89,7 +89,13 @@ func isCodexContext(item gjson.Result) bool { return false } name := item.Get("name").String() - if name == "browser_info" || name == "goal_objective" || name == "untrusted_context" { + if codexStandaloneContextName(name) { + if name == "untrusted_content" { + return true + } + if name == "proposed_plan" { + return output.String() != "" + } return strings.TrimSpace(output.String()) != "" } if name == "codex_apps_open_page" { @@ -135,3 +141,11 @@ func validCodexPageSnapshot(text string) bool { var value string return json.Unmarshal(id, &value) == nil && strings.TrimSpace(value) != "" } + +func codexStandaloneContextName(name string) bool { + switch name { + case "browser_info", "goal_objective", "untrusted_context", "ide_context", "untrusted_content", "proposed_plan": + return true + } + return false +} diff --git a/backend/internal/handler/openai_gateway_handler.go b/backend/internal/handler/openai_gateway_handler.go index e1788f518c61..d62f3a719510 100644 --- a/backend/internal/handler/openai_gateway_handler.go +++ b/backend/internal/handler/openai_gateway_handler.go @@ -1717,7 +1717,6 @@ func (h *OpenAIGatewayHandler) Messages(c *gin.Context) { } else { body = policyBody } - routingModel := service.NormalizeOpenAICompatRequestedModel(reqModel) preferredMappedModel := resolveOpenAIMessagesDispatchMappedModel(c, apiKey, reqModel) reqStream := gjson.GetBytes(body, "stream").Bool() @@ -1735,6 +1734,10 @@ func (h *OpenAIGatewayHandler) Messages(c *gin.Context) { // 解析渠道级模型映射 channelMappingMsg, _ := h.gatewayService.ResolveChannelMappingAndRestrict(c.Request.Context(), apiKey.GroupID, reqModel) mappedBodyForMessages := newOpenAIModelMappedBodyCache(body, h.gatewayService.ReplaceModelInBody) + // Schedule by the channel-mapped model, as the Responses and Chat Completions + // paths do: the forwarded body carries that model, so account model filters + // must judge it rather than the client's alias. + routingModel := service.NormalizeOpenAICompatRequestedModel(openAIChannelForwardModel(channelMappingMsg, reqModel)) // 绑定错误透传服务,允许 service 层在非 failover 错误场景复用规则。 if h.errorPassthroughService != nil { @@ -3189,6 +3192,16 @@ func (h *OpenAIGatewayHandler) ResponsesWebSocket(c *gin.Context) { closeOpenAIClientWS(wsConn, coderws.StatusPolicyViolation, fmt.Sprintf("Model %q is not available for your account in this group", denied)) return } + // 帧内重复字段(model、service_tier、reasoning.effort 等,含大小写变体与 + // 嵌套对象)会让计费/策略读到的首个值与上游实际绑定的值分叉;取值相同也不 + // 放行,因为网关的 sjson 改写只动首个(GHSA-p3r4-jcm3-2hph)。与 HTTP 入口 + // (RejectConflictingRequestFields)同一规则,对所有分组生效。放在白名单 + // 之后,白名单的拒绝原因保持不变。 + if field, conflict := requestmodel.ConflictingField("application/json", firstMessage); conflict { + middleware2.MarkIngressRejected(c, middleware2.IngressRejectConflictingRequestFields) + closeOpenAIClientWS(wsConn, coderws.StatusPolicyViolation, fmt.Sprintf("response.create payload declares field %.64q more than once", field)) + return + } // Keep the client model in the frame for admission, response identity and usage. // Apply the resolved upstream model through MapRequestModel on every turn. wsRouteModel := service.MapAPIKeyModel(apiKey, reqModel) @@ -3900,6 +3913,12 @@ func (h *OpenAIGatewayHandler) ResponsesWebSocket(c *gin.Context) { middleware2.MarkIngressRejected(c, middleware2.IngressRejectModelNotAllowed) return service.NewOpenAIWSClientCloseError(coderws.StatusPolicyViolation, fmt.Sprintf("Model %q is not available for your account in this group", denied), nil) } + // 后续 turn 同首帧:帧内有重复字段即关闭连接,避免计费/策略读到的 + // 值与上游实际绑定的值分叉。 + if field, conflict := requestmodel.ConflictingField("application/json", clientPayload); conflict { + middleware2.MarkIngressRejected(c, middleware2.IngressRejectConflictingRequestFields) + return service.NewOpenAIWSClientCloseError(coderws.StatusPolicyViolation, fmt.Sprintf("websocket request payload declares field %.64q more than once", field), nil) + } auditBody := clientPayload if rebuiltAuditBody != nil { auditBody = rebuiltAuditBody diff --git a/backend/internal/handler/openai_gateway_handler_test.go b/backend/internal/handler/openai_gateway_handler_test.go index 3e70e1e157cf..d3259b3b9106 100644 --- a/backend/internal/handler/openai_gateway_handler_test.go +++ b/backend/internal/handler/openai_gateway_handler_test.go @@ -2085,6 +2085,8 @@ type openAIResponsesWSUsageLogCase struct { firstFrameCloseExpected bool // secondTurnCloseExpected:第二个 turn 被拒(连接被 1008 关闭)。 secondTurnCloseExpected bool + // midFrameCloseExpected:midPayload 被拒(连接被 1008 关闭),帧不到达上游。 + midFrameCloseExpected bool } type openAIResponsesWSUsageLogResult struct { @@ -3512,6 +3514,19 @@ func runOpenAIResponsesWebSocketUsageLogCase(t *testing.T, tc openAIResponsesWSU err = clientConn.Write(writeCtx, coderws.MessageText, []byte(tc.midPayload)) cancelWrite() require.NoError(t, err) + if tc.midFrameCloseExpected { + readCtx, cancelRead := context.WithTimeout(context.Background(), 3*time.Second) + _, _, readErr := clientConn.Read(readCtx) + cancelRead() + require.Error(t, readErr, "mid frame should have been rejected with a close") + var closeErr coderws.CloseError + require.ErrorAs(t, readErr, &closeErr) + require.Equal(t, coderws.StatusPolicyViolation, closeErr.Code) + require.Contains(t, closeErr.Reason, tc.closeReason) + require.Len(t, upstreamPayloadCh, 1, "rejected mid frame must not reach upstream") + _ = clientConn.CloseNow() + return openAIResponsesWSUsageLogResult{} + } readCtx, cancelRead := context.WithTimeout(context.Background(), 3*time.Second) _, event, readErr := clientConn.Read(readCtx) cancelRead() diff --git a/backend/internal/handler/openai_gateway_ws_model_allowlist_test.go b/backend/internal/handler/openai_gateway_ws_model_allowlist_test.go index 43a7d61b20eb..96eccdc1cdc2 100644 --- a/backend/internal/handler/openai_gateway_ws_model_allowlist_test.go +++ b/backend/internal/handler/openai_gateway_ws_model_allowlist_test.go @@ -127,6 +127,8 @@ func TestOpenAIResponsesWebSocket_FirstFrameCaseVariantModelKeyRejected(t *testi // 后续 turn 含重复 model 键(首个在白名单、末个不在):拒绝并关闭连接。 func TestOpenAIResponsesWebSocket_SubsequentTurnDuplicateModelKeysRejected(t *testing.T) { for _, mode := range []string{service.OpenAIWSIngressModePassthrough, service.OpenAIWSIngressModeDedicated} { + // 两种模式都在读取任何字段之前先做字段歧义检查(帧必须在兼容归一化等 + // 重编码之前拦截),所以由歧义检查而不是白名单关闭连接,帧不到达上游。 t.Run(mode, func(t *testing.T) { runOpenAIResponsesWebSocketUsageLogCase(t, openAIResponsesWSUsageLogCase{ firstPayload: `{"type":"response.create","model":"gpt-5.4","stream":false}`, @@ -134,21 +136,21 @@ func TestOpenAIResponsesWebSocket_SubsequentTurnDuplicateModelKeysRejected(t *te group: wsAllowlistGroup(true, "gpt-5.4"), ingressMode: mode, secondTurnCloseExpected: true, + closeReason: `declares field "model" more than once`, }) }) } } -// 重复但同值的 model 键不误伤,连接正常完成两个 turn。 -func TestOpenAIResponsesWebSocket_DuplicateIdenticalModelKeysAllowed(t *testing.T) { - got := runOpenAIResponsesWebSocketUsageLogCase(t, openAIResponsesWSUsageLogCase{ - firstPayload: `{"type":"response.create","model":"gpt-5.4","model":"gpt-5.4","stream":false}`, - secondPayload: `{"type":"response.create","model":"gpt-5.4","stream":false}`, - group: wsAllowlistGroup(true, "gpt-5.4"), +// 重复但同值的 model 键:白名单本身放行(两个候选都在名单内),但字段歧义检查 +// 拒绝——网关的 sjson 模型改写只改首个,改写后两者就会分叉(GHSA-p3r4-jcm3-2hph)。 +func TestOpenAIResponsesWebSocket_DuplicateIdenticalModelKeysRejected(t *testing.T) { + runOpenAIResponsesWebSocketUsageLogCase(t, openAIResponsesWSUsageLogCase{ + firstPayload: `{"type":"response.create","model":"gpt-5.4","model":"gpt-5.4","stream":false}`, + group: wsAllowlistGroup(true, "gpt-5.4"), + firstFrameCloseExpected: true, + closeReason: `declares field "model" more than once`, }) - if len(got.clientEvents) != 2 { - t.Fatalf("expected two completed events, got %d", len(got.clientEvents)) - } } // session.update 轮换绕过:首帧用白名单内模型建立会话,session.update 把会话 diff --git a/backend/internal/handler/openai_gateway_ws_model_conflict_test.go b/backend/internal/handler/openai_gateway_ws_model_conflict_test.go new file mode 100644 index 000000000000..da824c24746b --- /dev/null +++ b/backend/internal/handler/openai_gateway_ws_model_conflict_test.go @@ -0,0 +1,128 @@ +package handler + +import ( + "testing" + + "github.com/Wei-Shaw/sub2api/internal/service" +) + +const wsModelConflictCloseReason = "more than once" + +// 没有开启白名单的分组:首帧里重复 model 键取值不一致(计费按第一个、上游可能 +// 按最后一个绑定)必须以 1008 关闭,帧不到达上游。 +func TestOpenAIResponsesWebSocket_FirstFrameConflictingModelKeysRejectedWithoutAllowlist(t *testing.T) { + for _, mode := range []string{service.OpenAIWSIngressModePassthrough, service.OpenAIWSIngressModeDedicated} { + t.Run(mode, func(t *testing.T) { + runOpenAIResponsesWebSocketUsageLogCase(t, openAIResponsesWSUsageLogCase{ + firstPayload: `{"type":"response.create","model":"gpt-5.4-nano","model":"gpt-5.4","stream":false}`, + group: wsAllowlistGroup(false), + ingressMode: mode, + firstFrameCloseExpected: true, + closeReason: wsModelConflictCloseReason, + }) + }) + } +} + +// 大小写变体键同样会被 encoding/json 绑定到同一个字段。 +func TestOpenAIResponsesWebSocket_FirstFrameConflictingCaseVariantModelKeyRejected(t *testing.T) { + runOpenAIResponsesWebSocketUsageLogCase(t, openAIResponsesWSUsageLogCase{ + firstPayload: `{"type":"response.create","model":"gpt-5.4-nano","Model":"gpt-5.4","stream":false}`, + group: wsAllowlistGroup(false), + ingressMode: service.OpenAIWSIngressModePassthrough, + firstFrameCloseExpected: true, + closeReason: wsModelConflictCloseReason, + }) +} + +// 白名单开启且两个模型都在名单内:白名单放行,模型歧义检查仍要拒绝。 +func TestOpenAIResponsesWebSocket_FirstFrameConflictingAllowlistedModelKeysRejected(t *testing.T) { + runOpenAIResponsesWebSocketUsageLogCase(t, openAIResponsesWSUsageLogCase{ + firstPayload: `{"type":"response.create","model":"gpt-5.4-nano","model":"gpt-5.4","stream":false}`, + group: wsAllowlistGroup(true, "gpt-5.4-nano", "gpt-5.4"), + ingressMode: service.OpenAIWSIngressModePassthrough, + firstFrameCloseExpected: true, + closeReason: wsModelConflictCloseReason, + }) +} + +// 后续 turn 的帧同样检查。 +func TestOpenAIResponsesWebSocket_SubsequentTurnConflictingModelKeysRejectedWithoutAllowlist(t *testing.T) { + for _, mode := range []string{service.OpenAIWSIngressModePassthrough, service.OpenAIWSIngressModeDedicated} { + t.Run(mode, func(t *testing.T) { + runOpenAIResponsesWebSocketUsageLogCase(t, openAIResponsesWSUsageLogCase{ + firstPayload: `{"type":"response.create","model":"gpt-5.4","stream":false}`, + secondPayload: `{"type":"response.create","model":"gpt-5.4-nano","model":"gpt-5.4","stream":false}`, + group: wsAllowlistGroup(false), + ingressMode: mode, + secondTurnCloseExpected: true, + closeReason: wsModelConflictCloseReason, + }) + }) + } +} + +// 取值相同的重复键同样拒绝:网关的 sjson 改写(模型映射、推理强度降级)只改 +// 首个,改写后两者就会分叉。首帧与后续 turn 都要关闭连接。 +func TestOpenAIResponsesWebSocket_IdenticalDuplicateKeysRejectedWithoutAllowlist(t *testing.T) { + for _, mode := range []string{service.OpenAIWSIngressModePassthrough, service.OpenAIWSIngressModeDedicated} { + t.Run(mode+"/first_frame", func(t *testing.T) { + runOpenAIResponsesWebSocketUsageLogCase(t, openAIResponsesWSUsageLogCase{ + firstPayload: `{"type":"response.create","model":"gpt-5.4","model":"gpt-5.4","stream":false}`, + group: wsAllowlistGroup(false), + ingressMode: mode, + firstFrameCloseExpected: true, + closeReason: `declares field "model" more than once`, + }) + }) + t.Run(mode+"/subsequent_turn", func(t *testing.T) { + runOpenAIResponsesWebSocketUsageLogCase(t, openAIResponsesWSUsageLogCase{ + firstPayload: `{"type":"response.create","model":"gpt-5.4","stream":false}`, + secondPayload: `{"type":"response.create","model":"gpt-5.4","reasoning":{"effort":"xhigh","effort":"xhigh"},"stream":false}`, + group: wsAllowlistGroup(false), + ingressMode: mode, + secondTurnCloseExpected: true, + closeReason: `declares field "reasoning.effort" more than once`, + }) + }) + } +} + +// 非 model 字段同样参与计费与策略:首帧 service_tier、后续 turn 嵌套的 +// reasoning.effort 取值不一致都必须关闭连接。 +func TestOpenAIResponsesWebSocket_ConflictingBillingFieldsRejected(t *testing.T) { + for _, mode := range []string{service.OpenAIWSIngressModePassthrough, service.OpenAIWSIngressModeDedicated} { + t.Run(mode+"/first_frame_service_tier", func(t *testing.T) { + runOpenAIResponsesWebSocketUsageLogCase(t, openAIResponsesWSUsageLogCase{ + firstPayload: `{"type":"response.create","model":"gpt-5.4","service_tier":"flex","stream":false,"service_tier":"priority"}`, + group: wsAllowlistGroup(false), + ingressMode: mode, + firstFrameCloseExpected: true, + closeReason: `declares field "service_tier" more than once`, + }) + }) + t.Run(mode+"/subsequent_turn_reasoning_effort", func(t *testing.T) { + runOpenAIResponsesWebSocketUsageLogCase(t, openAIResponsesWSUsageLogCase{ + firstPayload: `{"type":"response.create","model":"gpt-5.4","stream":false}`, + secondPayload: `{"type":"response.create","model":"gpt-5.4","reasoning":{"effort":"low","effort":"xhigh"},"stream":false}`, + group: wsAllowlistGroup(false), + ingressMode: mode, + secondTurnCloseExpected: true, + closeReason: `declares field "reasoning.effort" more than once`, + }) + }) + } +} + +// passthrough 原样转发 session.update 等非 response.create 事件:帧内重复字段 +// 同样必须关闭连接,不能到达上游。 +func TestOpenAIResponsesWebSocket_PassthroughSessionUpdateDuplicateRejected(t *testing.T) { + runOpenAIResponsesWebSocketUsageLogCase(t, openAIResponsesWSUsageLogCase{ + firstPayload: `{"type":"response.create","model":"gpt-5.4","stream":false}`, + midPayload: `{"type":"session.update","session":{"model":"gpt-5.4","model":"gpt-4.1"}}`, + group: wsAllowlistGroup(false), + ingressMode: service.OpenAIWSIngressModePassthrough, + midFrameCloseExpected: true, + closeReason: `declares field "session.model" more than once`, + }) +} diff --git a/backend/internal/handler/openai_page_context_test.go b/backend/internal/handler/openai_page_context_test.go index 2eb204ac901a..615ce687c27a 100644 --- a/backend/internal/handler/openai_page_context_test.go +++ b/backend/internal/handler/openai_page_context_test.go @@ -54,18 +54,24 @@ func TestNormalizeCodexPageContextFirstMessage(t *testing.T) { require.Equal(t, got, again) } +var codexTextContextNamesForTest = []string{"browser_info", "goal_objective", "untrusted_context", "untrusted_content", "ide_context", "proposed_plan"} + func TestNormalizeCodexAdditionalUntrustedContext(t *testing.T) { - // AdditionalContextToolOutput derives names from caller-provided context keys. - // Codex 0.169.0 enables this representation by default (openai/codex#60487). - for _, name := range []string{"browser_info", "goal_objective", "untrusted_context"} { + for _, name := range codexTextContextNamesForTest { t.Run(name, func(t *testing.T) { output := "external context\nline two" - body := pageContextRequest(t, pageContextItem(name, output), + if name == "ide_context" { + output = "# Context from my IDE setup:\n\n## Active file: main.go\n\n## Active selection of the file:\nfunc main() {}" + } + contextItem := map[string]any{"type": "function_call_output", "namespace": "agent", "name": name, "output": output} + body := pageContextRequest(t, contextItem, map[string]any{"role": "user", "content": "continue"}) 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 := normalizeCodexUntrustedContext(body) require.True(t, changed) @@ -87,7 +93,7 @@ func TestNormalizeCodexAdditionalUntrustedContext(t *testing.T) { } func TestNormalizeCodexAdditionalUntrustedContextPreservesRealAndMalformedOutputs(t *testing.T) { - for _, name := range []string{"browser_info", "goal_objective", "untrusted_context"} { + for _, name := range codexTextContextNamesForTest { for _, override := range []map[string]any{ {"call_id": "call_real"}, {"call_id": nil}, @@ -96,7 +102,6 @@ func TestNormalizeCodexAdditionalUntrustedContextPreservesRealAndMalformedOutput {"namespace": nil}, {"namespace": 42}, {"output": []any{map[string]any{"type": "encrypted_content", "encrypted_content": "sealed"}}}, - {"output": " "}, {"output": nil}, } { item := pageContextItem(name, "context") @@ -108,12 +113,14 @@ func TestNormalizeCodexAdditionalUntrustedContextPreservesRealAndMalformedOutput require.False(t, changed, "name=%s override=%v", name, override) require.Equal(t, body, got) } - item := pageContextItem(name, "context") - delete(item, "namespace") - body := pageContextRequest(t, item) - got, changed := normalizeCodexUntrustedContext(body) - require.False(t, changed) - require.Equal(t, body, got) + for _, field := range []string{"namespace", "output"} { + item := pageContextItem(name, "context") + delete(item, field) + body := pageContextRequest(t, item) + got, changed := normalizeCodexUntrustedContext(body) + require.False(t, changed) + require.Equal(t, body, got) + } } // Recognized external context cannot make an unrelated tool result valid. body := pageContextRequest(t, pageContextItem("browser_info", "tab"), @@ -138,7 +145,7 @@ func TestNormalizeCodexAdditionalUntrustedContextPreservesRealAndMalformedOutput } func TestNormalizeCodexAdditionalUntrustedContextBlankCallIDsAndMixedInput(t *testing.T) { - names := []string{"browser_info", "goal_objective", "untrusted_context"} + names := codexTextContextNamesForTest for _, callID := range []string{"", " \t\n"} { items := make([]any, 0, len(names)) for _, name := range names { @@ -158,7 +165,7 @@ func TestNormalizeCodexAdditionalUntrustedContextBlankCallIDsAndMixedInput(t *te } func TestNormalizeCodexAdditionalUntrustedContextRejectsDuplicateMembers(t *testing.T) { - for _, name := range []string{"browser_info", "goal_objective", "untrusted_context"} { + for _, name := range codexTextContextNamesForTest { for _, body := range []string{ `{"input":[{"type":"function_call_output","namespace":"agent","name":"` + name + `","call_id":"real","call_id":"","output":"context"}]}`, `{"input":[{"type":"function_call_output","namespace":"agent","name":"` + name + `","output":"first","output":"second"}]}`, @@ -170,6 +177,38 @@ func TestNormalizeCodexAdditionalUntrustedContextRejectsDuplicateMembers(t *test } } +func TestNormalizeCodexProposedPlanChunks(t *testing.T) { + chunks := []string{"# Plan\n", " \n\t", "1. Run tests."} + var items []any + for _, chunk := range chunks { + items = append(items, pageContextItem("proposed_plan", chunk)) + } + got, changed := normalizeCodexUntrustedContext(pageContextRequest(t, items...)) + require.True(t, changed) + messages := gjson.GetBytes(got, "input").Array() + require.Len(t, messages, len(chunks)) + for i, message := range messages { + require.Equal(t, "user", message.Get("role").String()) + require.Equal(t, ""+chunks[i]+"", message.Get("content.0.text").String()) + } +} + +func TestNormalizeCodexAdditionalUntrustedContextBlankOutput(t *testing.T) { + for _, name := range codexTextContextNamesForTest { + for _, output := range []string{"", " \t"} { + body := pageContextRequest(t, pageContextItem(name, output)) + got, changed := normalizeCodexUntrustedContext(body) + wantChange := name == "untrusted_content" || (name == "proposed_plan" && output != "") + require.Equal(t, wantChange, changed, "name=%s output=%q", name, output) + if wantChange { + require.Equal(t, ""+output+"", gjson.GetBytes(got, "input.0.content.0.text").String()) + } else { + require.Equal(t, body, got) + } + } + } +} + 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 := normalizeCodexUntrustedContext(body) diff --git a/backend/internal/handler/request_body_limit.go b/backend/internal/handler/request_body_limit.go index de24551ba947..0399542bca70 100644 --- a/backend/internal/handler/request_body_limit.go +++ b/backend/internal/handler/request_body_limit.go @@ -2,7 +2,6 @@ package handler import ( "errors" - "fmt" "net/http" "github.com/Wei-Shaw/sub2api/internal/config" @@ -17,18 +16,6 @@ func extractMaxBytesError(err error) (*http.MaxBytesError, bool) { return nil, false } -func formatBodyLimit(limit int64) string { - const mb = 1024 * 1024 - if limit >= mb { - return fmt.Sprintf("%dMB", limit/mb) - } - return fmt.Sprintf("%dB", limit) -} - -func buildBodyTooLargeMessage(limit int64) string { - return fmt.Sprintf("Request body too large, limit is %s", formatBodyLimit(limit)) -} - func readLenientJSONRequestBodyWithPrealloc(req *http.Request, cfg *config.Config) ([]byte, error) { return pkghttputil.ReadLenientJSONRequestBodyWithPrealloc(req, gatewayMaxBodySize(cfg)) } @@ -39,3 +26,5 @@ func gatewayMaxBodySize(cfg *config.Config) int64 { } return cfg.Gateway.MaxBodySize } + +func buildBodyTooLargeMessage(limit int64) string { return pkghttputil.BodyTooLargeMessage(limit) } diff --git a/backend/internal/handler/request_body_limit_test.go b/backend/internal/handler/request_body_limit_test.go index bd9b81779720..105995ea0be4 100644 --- a/backend/internal/handler/request_body_limit_test.go +++ b/backend/internal/handler/request_body_limit_test.go @@ -7,6 +7,7 @@ import ( "net/http/httptest" "testing" + pkghttputil "github.com/Wei-Shaw/sub2api/internal/pkg/httputil" "github.com/Wei-Shaw/sub2api/internal/server/middleware" "github.com/gin-gonic/gin" "github.com/stretchr/testify/require" @@ -41,5 +42,5 @@ func TestRequestBodyLimitTooLarge(t *testing.T) { router.ServeHTTP(recorder, req) require.Equal(t, http.StatusRequestEntityTooLarge, recorder.Code) - require.Contains(t, recorder.Body.String(), buildBodyTooLargeMessage(limit)) + require.Contains(t, recorder.Body.String(), pkghttputil.BodyTooLargeMessage(limit)) } diff --git a/backend/internal/handler/request_body_read_log.go b/backend/internal/handler/request_body_read_log.go index 5c6d73d93472..9483b6e6ebc4 100644 --- a/backend/internal/handler/request_body_read_log.go +++ b/backend/internal/handler/request_body_read_log.go @@ -9,6 +9,8 @@ import ( "strings" "syscall" + pkghttputil "github.com/Wei-Shaw/sub2api/internal/pkg/httputil" + "go.uber.org/zap" ) @@ -35,6 +37,21 @@ func logRequestBodyReadFailure(reqLog *zap.Logger, req *http.Request, err error) ) } +// requestBodyReadFailure maps a request body read error to the response status +// and message. Read timeouts (408) are no longer reported as malformed +// requests; other read failures keep the stable generic 400 message. Failures +// other than the configured size limit are logged with bounded, payload-free +// diagnostics (kind, declared length, bytes received and read duration) so +// operators can tell a stalled or slow upload from a broken client without +// logging request content. +func requestBodyReadFailure(reqLog *zap.Logger, req *http.Request, err error) (int, string) { + failure := pkghttputil.DescribeRequestBodyReadFailure(req, err) + if failure.Kind != pkghttputil.RequestBodyReadErrorMaxBytes { + logRequestBodyReadFailure(reqLog, req, err) + } + return failure.Status, failure.ClientMessage() +} + func requestContentEncodingCategory(value string) string { switch strings.ToLower(strings.TrimSpace(value)) { case "", "identity": diff --git a/backend/internal/handler/request_body_read_log_test.go b/backend/internal/handler/request_body_read_log_test.go index 8a8d21f10038..5707eaaa5d41 100644 --- a/backend/internal/handler/request_body_read_log_test.go +++ b/backend/internal/handler/request_body_read_log_test.go @@ -3,13 +3,23 @@ package handler import ( + "context" + "encoding/json" "errors" "fmt" "io" + "net" "net/http" + "net/http/httptest" + "os" "strings" "testing" + "testing/iotest" + pkghttputil "github.com/Wei-Shaw/sub2api/internal/pkg/httputil" + "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" ) @@ -38,3 +48,98 @@ func TestRequestBodyReadErrorKind(t *testing.T) { require.Equal(t, "max_bytes", requestBodyReadErrorKind(&http.MaxBytesError{Limit: 10})) require.Equal(t, "other", requestContentEncodingCategory("private-payload-marker")) } + +func TestRequestBodyReadFailureKeepsBodyLimitMessageWithoutLogging(t *testing.T) { + log, logs := newObservedLogger(t) + status, message := requestBodyReadFailure(log, nil, &http.MaxBytesError{Limit: 2 << 20}) + require.Equal(t, http.StatusRequestEntityTooLarge, status) + require.Equal(t, pkghttputil.BodyTooLargeMessage(2<<20), message) + require.Empty(t, logs.All()) +} + +// cancelOnReadErr models net/http on HTTP/1: a failed body read cancels the +// request context before the error reaches the handler. +type cancelOnReadErr struct { + err error + cancel context.CancelFunc +} + +func (r cancelOnReadErr) Read([]byte) (int, error) { + r.cancel() + return 0, r.err +} + +// The Anthropic /v1/messages handler reads the full body before it knows the +// model or account. A failed read must report why instead of a generic 400. +func TestGatewayMessagesClassifiesRequestBodyReadFailures(t *testing.T) { + gin.SetMode(gin.TestMode) + deadlineErr := &net.OpError{Op: "read", Net: "tcp", Err: os.ErrDeadlineExceeded} + + tests := []struct { + name string + readErr error + cancelCtx bool + wantStatus int + wantMessage string + }{ + {"h2 read timeout", deadlineErr, false, http.StatusRequestTimeout, "Timed out reading request body"}, + // net/http cancels the request context when an HTTP/1 read deadline + // fires; this is still a timeout, not a client that went away. + {"http1 read timeout", deadlineErr, true, http.StatusRequestTimeout, "Timed out reading request body"}, + // A client that went away gets no body, matching the failover path. + {"client disconnect", io.ErrUnexpectedEOF, true, 499, ""}, + {"truncated body", io.ErrUnexpectedEOF, false, http.StatusBadRequest, "Failed to read request body"}, + } + for _, tc := range tests { + t.Run(tc.name, func(t *testing.T) { + rec := httptest.NewRecorder() + c, _ := gin.CreateTestContext(rec) + ctx, cancel := context.WithCancel(context.Background()) + defer cancel() + failing := iotest.ErrReader(tc.readErr) + if tc.cancelCtx { + failing = cancelOnReadErr{err: tc.readErr, cancel: cancel} + } + body := io.MultiReader(strings.NewReader(`{"model":"claude-sonnet-4-5","messages":[`), failing) + req := httptest.NewRequest(http.MethodPost, "/v1/messages", body).WithContext(ctx) + req.ContentLength = 1 << 20 + c.Request = req + groupID := int64(1) + c.Set(string(middleware.ContextKeyAPIKey), &service.APIKey{ID: 1, UserID: 1, GroupID: &groupID}) + c.Set(string(middleware.ContextKeyUser), middleware.AuthSubject{UserID: 1, Concurrency: 1}) + + (&GatewayHandler{}).Messages(c) + + require.Equal(t, tc.wantStatus, c.Writer.Status()) + if tc.wantMessage == "" { + require.Empty(t, rec.Body.String()) + return + } + var resp struct { + Type string `json:"type"` + Error struct { + Type string `json:"type"` + Message string `json:"message"` + } `json:"error"` + } + require.NoError(t, json.Unmarshal(rec.Body.Bytes(), &resp)) + require.Equal(t, "error", resp.Type) + require.Equal(t, "invalid_request_error", resp.Error.Type) + require.Equal(t, tc.wantMessage, resp.Error.Message) + }) + } +} + +// Google-format errors carry no type field; body read failures must still be +// attributed to the client request rather than the platform. +func TestGeminiRequestBodyReadTimeoutClassifiedAsClient(t *testing.T) { + entry := recordGoogleFormatOpsError(t, func(c *gin.Context) { + c.Request.Body = io.NopCloser(iotest.ErrReader(&net.OpError{Op: "read", Net: "tcp", Err: os.ErrDeadlineExceeded})) + readGeminiCachedContentBody(c) + }) + require.Equal(t, http.StatusRequestTimeout, entry.StatusCode) + require.Equal(t, "invalid_request_error", entry.ErrorType) + require.Equal(t, "request", entry.ErrorPhase) + require.Equal(t, "client", entry.ErrorOwner) + require.Equal(t, "P3", entry.Severity) +} diff --git a/backend/internal/pkg/antigravity/quota_summary.go b/backend/internal/pkg/antigravity/quota_summary.go new file mode 100644 index 000000000000..7f168d4a3c31 --- /dev/null +++ b/backend/internal/pkg/antigravity/quota_summary.go @@ -0,0 +1,117 @@ +package antigravity + +import ( + "context" + "encoding/json" + "errors" + "fmt" + "io" + "net/http" + "strings" + + "github.com/Wei-Shaw/sub2api/internal/pkg/servertiming" +) + +// quotaSummaryBodyLimit bounds the retrieveUserQuotaSummary response (a few hundred bytes today). +const quotaSummaryBodyLimit = 1 << 20 + +// QuotaSummaryBucket is one quota window of a group, e.g. "gemini-5h" or "gemini-weekly". +type QuotaSummaryBucket struct { + BucketID string `json:"bucketId"` + DisplayName string `json:"displayName,omitempty"` + Window string `json:"window"` // "5h" or "weekly" + ResetTime string `json:"resetTime,omitempty"` + RemainingFraction float64 `json:"remainingFraction"` +} + +// QuotaSummaryGroup is a set of models that share their quota windows. +type QuotaSummaryGroup struct { + DisplayName string `json:"displayName"` + Description string `json:"description,omitempty"` + Buckets []QuotaSummaryBucket `json:"buckets"` +} + +// QuotaSummaryResponse is the retrieveUserQuotaSummary response. +// +// Unlike fetchAvailableModels, which reports one fraction per model (whichever window is +// tighter), this reports every window of every group, so the 5-hour and the weekly limit can +// be told apart. Within a group all models share both windows. +type QuotaSummaryResponse struct { + Groups []QuotaSummaryGroup `json:"groups"` + Description string `json:"description,omitempty"` +} + +// RetrieveUserQuotaSummary reads the account's per-group 5-hour and weekly quota windows, +// falling back across BaseURLs like FetchAvailableModels. +func (c *Client) RetrieveUserQuotaSummary(ctx context.Context, accessToken, projectID string) (*QuotaSummaryResponse, error) { + var lastErr error + for urlIdx, baseURL := range BaseURLs { + summary, status, err := c.retrieveUserQuotaSummary(ctx, baseURL, accessToken, projectID) + if err == nil { + DefaultURLAvailability.MarkSuccess(baseURL) + return summary, nil + } + lastErr = err + if urlIdx < len(BaseURLs)-1 && shouldFallbackToNextURL(nil, status) { + continue + } + return nil, err + } + return nil, lastErr +} + +// RetrieveUserQuotaSummaryFromURL reads the quota summary from one endpoint, without fallback. +func (c *Client) RetrieveUserQuotaSummaryFromURL(ctx context.Context, baseURL, accessToken, projectID string) (*QuotaSummaryResponse, error) { + baseURL = strings.TrimRight(strings.TrimSpace(baseURL), "/") + if baseURL == "" { + return nil, errors.New("retrieveUserQuotaSummary base URL is required") + } + summary, _, err := c.retrieveUserQuotaSummary(ctx, baseURL, accessToken, projectID) + return summary, err +} + +func (c *Client) retrieveUserQuotaSummary(ctx context.Context, baseURL, accessToken, projectID string) (*QuotaSummaryResponse, int, error) { + if c == nil || c.httpClient == nil { + return nil, 0, errors.New("antigravity client is not configured") + } + bodyBytes, err := json.Marshal(FetchAvailableModelsRequest{Project: projectID}) + if err != nil { + return nil, 0, fmt.Errorf("marshal retrieveUserQuotaSummary request: %w", err) + } + req, err := http.NewRequestWithContext(ctx, http.MethodPost, baseURL+"/v1internal:retrieveUserQuotaSummary", strings.NewReader(string(bodyBytes))) + if err != nil { + return nil, 0, fmt.Errorf("create retrieveUserQuotaSummary request: %w", err) + } + req.Header.Set("Authorization", "Bearer "+accessToken) + req.Header.Set("Content-Type", "application/json") + req.Header.Set("User-Agent", GetUserAgentForContext(ctx)) + + resp, err := servertiming.Do(c.httpClient, req) + if err != nil { + return nil, 0, fmt.Errorf("retrieveUserQuotaSummary request failed: %w", err) + } + respBody, err := io.ReadAll(io.LimitReader(resp.Body, quotaSummaryBodyLimit+1)) + _ = resp.Body.Close() + if err != nil { + return nil, resp.StatusCode, fmt.Errorf("read retrieveUserQuotaSummary response: %w", err) + } + if len(respBody) > quotaSummaryBodyLimit { + return nil, resp.StatusCode, fmt.Errorf("retrieveUserQuotaSummary response exceeds %d bytes", quotaSummaryBodyLimit) + } + if resp.StatusCode != http.StatusOK { + return nil, resp.StatusCode, fmt.Errorf("retrieveUserQuotaSummary failed (HTTP %d): %s", resp.StatusCode, truncateQuotaSummaryBody(respBody)) + } + var summary QuotaSummaryResponse + if err := json.Unmarshal(respBody, &summary); err != nil { + return nil, resp.StatusCode, fmt.Errorf("parse retrieveUserQuotaSummary response: %w", err) + } + return &summary, resp.StatusCode, nil +} + +func truncateQuotaSummaryBody(body []byte) string { + const max = 300 + if len(body) > max { + return string(body[:max]) + "..." + } + return string(body) +} diff --git a/backend/internal/pkg/antigravity/quota_summary_test.go b/backend/internal/pkg/antigravity/quota_summary_test.go new file mode 100644 index 000000000000..a35508ed2f32 --- /dev/null +++ b/backend/internal/pkg/antigravity/quota_summary_test.go @@ -0,0 +1,79 @@ +//go:build unit + +package antigravity + +import ( + "context" + "encoding/json" + "net/http" + "net/http/httptest" + "testing" +) + +// The shape Google returned for a consumer Ultra account on 2026-11-04. +const quotaSummaryBody = `{ + "groups": [ + {"buckets": [ + {"bucketId": "gemini-weekly", "displayName": "Weekly Limit Remaining", "window": "weekly", + "resetTime": "2026-11-11T15:52:48Z", "remainingFraction": 0.75}, + {"bucketId": "gemini-5h", "displayName": "Five Hour Limit Remaining", "window": "5h", + "resetTime": "2026-11-04T20:52:48Z", "remainingFraction": 0.4}], + "displayName": "Gemini Models", "description": "Models within this group: Gemini Flash, Gemini Pro"}, + {"buckets": [ + {"bucketId": "3p-weekly", "window": "weekly", "resetTime": "2026-11-11T15:52:48Z", "remainingFraction": 1}, + {"bucketId": "3p-5h", "window": "5h", "remainingFraction": 1}], + "displayName": "Claude and GPT models"} + ], + "description": "Within each group, models share a weekly limit and a 5-hour limit." +}` + +func TestClient_RetrieveUserQuotaSummaryFromURL(t *testing.T) { + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if r.URL.Path != "/v1internal:retrieveUserQuotaSummary" || r.Method != http.MethodPost { + t.Errorf("unexpected request: %s %s", r.Method, r.URL.Path) + } + if r.Header.Get("Authorization") != "Bearer tok" { + t.Errorf("unexpected authorization header") + } + var body FetchAvailableModelsRequest + if err := json.NewDecoder(r.Body).Decode(&body); err != nil || body.Project != "proj" { + t.Errorf("unexpected project: %+v, %v", body, err) + } + _, _ = w.Write([]byte(quotaSummaryBody)) + })) + defer server.Close() + + client := mustNewClient(t, "") + summary, err := client.RetrieveUserQuotaSummaryFromURL(context.Background(), server.URL, "tok", "proj") + if err != nil { + t.Fatalf("summary: %v", err) + } + if len(summary.Groups) != 2 || summary.Groups[0].DisplayName != "Gemini Models" { + t.Fatalf("groups: %+v", summary.Groups) + } + weekly := summary.Groups[0].Buckets[0] + if weekly.BucketID != "gemini-weekly" || weekly.Window != "weekly" || weekly.RemainingFraction != 0.75 || + weekly.ResetTime != "2026-11-11T15:52:48Z" { + t.Fatalf("weekly bucket: %+v", weekly) + } + if summary.Groups[1].Buckets[1].ResetTime != "" { + t.Fatalf("a bucket without resetTime keeps it empty") + } +} + +func TestClient_RetrieveUserQuotaSummaryFromURL_Errors(t *testing.T) { + for _, tc := range []struct { + status int + body string + }{{http.StatusForbidden, `{"error":{"code":403}}`}, {http.StatusInternalServerError, `{}`}, {http.StatusOK, `not json`}} { + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + w.WriteHeader(tc.status) + _, _ = w.Write([]byte(tc.body)) + })) + client := mustNewClient(t, "") + if _, err := client.RetrieveUserQuotaSummaryFromURL(context.Background(), server.URL, "tok", "proj"); err == nil { + t.Errorf("status %d body %q must be an error", tc.status, tc.body) + } + server.Close() + } +} diff --git a/backend/internal/pkg/apicompat/anthropic_tool_search.go b/backend/internal/pkg/apicompat/anthropic_tool_search.go new file mode 100644 index 000000000000..b21636d0b77b --- /dev/null +++ b/backend/internal/pkg/apicompat/anthropic_tool_search.go @@ -0,0 +1,271 @@ +package apicompat + +import ( + "encoding/json" + "strings" +) + +// ToolSearchToolName is Claude Code's client-executed tool-search tool. Under +// the native protocol it maps to the Responses `tool_search` tool, its +// tool_use to a `tool_search_call` and its tool_result to a +// `tool_search_output`; an upstream tool_search_call comes back under this name. +const ToolSearchToolName = "ToolSearch" + +// emptyToolResultOutput is what convertToolResultOutput emits for a +// tool_result without text. +const emptyToolResultOutput = "(empty)" + +// ApplyNativeToolSearch rewrites a Responses request produced by +// AnthropicToResponses so Claude Code's ToolSearch uses the native +// client-executed tool_search protocol of the ChatGPT/Codex backend. +// +// Deferred tools never reach the top-level tools: revealed definitions ride in +// the history's tool_search_output instead, so the top-level tools (the head of +// the prompt-cache prefix) stay identical before and after a reveal. +func ApplyNativeToolSearch(req *AnthropicRequest, out *ResponsesRequest) error { + declared := false + deferred := make(map[string]bool) + for _, t := range req.Tools { + if t.DeferLoading { + deferred[t.Name] = true + } else if t.Name == ToolSearchToolName { + declared = true + } + } + // The Responses API has no tool_choice value that forces tool_search or a + // tool declared only in tool_search_output, so a request forcing either + // keeps every tool and call as a plain function. + if !declared || forcesHiddenTool(req.ToolChoice, deferred) { + return nil + } + + schemas := make(map[string]AnthropicTool, len(req.Tools)) + kept := make([]AnthropicTool, 0, len(req.Tools)) + for _, t := range req.Tools { + schemas[t.Name] = t + if t.DeferLoading { + continue + } + kept = append(kept, t) + } + tools := convertAnthropicToolsToResponses(kept) + for i, t := range kept { + if t.Name == ToolSearchToolName { + // Codex declares this tool without a name or strict. + tools[i] = ResponsesTool{ + Type: "tool_search", + Execution: "client", + Description: t.Description, + Parameters: normalizeToolParameters(t.InputSchema), + } + } + } + out.Tools = tools + + revealed := toolSearchReveals(req.Messages) + if len(revealed) == 0 { + return nil + } + var items []json.RawMessage + if err := json.Unmarshal(out.Input, &items); err != nil { + return err + } + rewritten := make([]json.RawMessage, 0, len(items)) + var pendingText []string + flush := func(next json.RawMessage) (json.RawMessage, error) { + text := strings.Join(pendingText, "\n\n") + pendingText = nil + return userMessageWithLeadingText(next, text) + } + for _, raw := range items { + var item ResponsesInputItem + if err := json.Unmarshal(raw, &item); err != nil { + return err + } + if len(pendingText) > 0 && item.Type != "function_call_output" { + // A tool_search_output has no field for the result text, so it rides + // in the user message that follows the run of tool outputs. + merged, err := flush(raw) + if err != nil { + return err + } + if item.Type == "message" && item.Role == "user" { + raw = merged + } else { + rewritten = append(rewritten, merged) + } + } + names, isSearch := revealed[item.CallID] + if !isSearch { + rewritten = append(rewritten, raw) + continue + } + var native any + switch item.Type { + case "function_call": + native = map[string]any{ + "type": "tool_search_call", + "call_id": item.CallID, + "execution": "client", + "status": "completed", + "arguments": jsonObjectOrEmpty(item.Arguments), + } + case "function_call_output": + loaded := make([]any, 0, len(names)) + for _, name := range names { + t, ok := schemas[name] + if !ok { + continue + } + loaded = append(loaded, map[string]any{ + "type": "function", + "name": name, + "description": t.Description, + "defer_loading": true, + "strict": false, + "parameters": normalizeToolParameters(t.InputSchema), + }) + } + native = map[string]any{ + "type": "tool_search_output", + "call_id": item.CallID, + "execution": "client", + "status": "completed", + "tools": loaded, + } + if item.Output != "" && item.Output != emptyToolResultOutput { + pendingText = append(pendingText, item.Output) + } + default: + rewritten = append(rewritten, raw) + continue + } + encoded, err := json.Marshal(native) + if err != nil { + return err + } + rewritten = append(rewritten, encoded) + } + if len(pendingText) > 0 { + tail, err := flush(nil) + if err != nil { + return err + } + rewritten = append(rewritten, tail) + } + input, err := json.Marshal(rewritten) + if err != nil { + return err + } + out.Input = input + return nil +} + +// userMessageWithLeadingText returns next with a separate input_text part for +// text placed ahead of its existing parts when next is a user message, and +// otherwise a new user message holding text. Existing parts stay untouched. +func userMessageWithLeadingText(next json.RawMessage, text string) (json.RawMessage, error) { + lead, err := json.Marshal(ResponsesContentPart{Type: "input_text", Text: text}) + if err != nil { + return nil, err + } + var msg ResponsesInputItem + if len(next) > 0 && json.Unmarshal(next, &msg) == nil && msg.Type == "message" && msg.Role == "user" { + var parts []json.RawMessage + if json.Unmarshal(msg.Content, &parts) == nil { + content, err := json.Marshal(append([]json.RawMessage{lead}, parts...)) + if err != nil { + return nil, err + } + msg.Content = content + return json.Marshal(msg) + } + } + content, err := json.Marshal([]json.RawMessage{lead}) + if err != nil { + return nil, err + } + return json.Marshal(ResponsesInputItem{Type: "message", Role: "user", Content: content}) +} + +func forcesHiddenTool(raw json.RawMessage, deferred map[string]bool) bool { + var choice struct { + Type string `json:"type"` + Name string `json:"name"` + } + if len(raw) == 0 || json.Unmarshal(raw, &choice) != nil { + return false + } + return choice.Type == "tool" && (choice.Name == ToolSearchToolName || deferred[choice.Name]) +} + +// toolSearchReveals maps each ToolSearch tool_use id in the history to the +// tool names its tool_result referenced, first occurrence first. +func toolSearchReveals(msgs []AnthropicMessage) map[string][]string { + reveals := make(map[string][]string) + for _, m := range msgs { + var blocks []AnthropicContentBlock + if json.Unmarshal(m.Content, &blocks) != nil { + continue + } + for _, b := range blocks { + switch { + case b.Type == "tool_use" && b.Name == ToolSearchToolName && b.ID != "": + reveals[toResponsesCallID(b.ID)] = nil + case b.Type == "tool_result": + id := toResponsesCallID(b.ToolUseID) + if _, isSearch := reveals[id]; !isSearch { + continue + } + var inner []AnthropicContentBlock + _ = json.Unmarshal(b.Content, &inner) + seen := make(map[string]bool) + for _, ib := range inner { + if ib.Type == "tool_reference" && ib.ToolName != "" && !seen[ib.ToolName] { + seen[ib.ToolName] = true + reveals[id] = append(reveals[id], ib.ToolName) + } + } + } + } + } + return reveals +} + +// toolSearchCallToolUse turns an upstream tool_search_call back into the +// ToolSearch tool_use Claude Code executes; its call_id round-trips as the +// tool_use id that the next turn's tool_result answers. +func toolSearchCallToolUse(item ResponsesOutput) AnthropicContentBlock { + return AnthropicContentBlock{ + Type: "tool_use", + ID: fromResponsesCallID(item.CallID), + Name: ToolSearchToolName, + Input: jsonObjectOrEmpty(item.Arguments), + } +} + +// jsonObjectOrEmpty keeps raw when it is a JSON object; both tool_search_call +// arguments and tool_use input must be objects. +func jsonObjectOrEmpty(raw string) json.RawMessage { + var probe map[string]json.RawMessage + if json.Unmarshal([]byte(raw), &probe) != nil || probe == nil { + return json.RawMessage(`{}`) + } + return json.RawMessage(raw) +} + +func resToAnthHandleToolSearchDone(evt *ResponsesStreamEvent, state *ResponsesEventToAnthropicState) []AnthropicStreamEvent { + events := closeCurrentBlock(state) + block := toolSearchCallToolUse(*evt.Item) + input := block.Input + block.Input = json.RawMessage(`{}`) + idx := state.ContentBlockIndex + state.HasToolCall = true + events = append(events, + AnthropicStreamEvent{Type: "content_block_start", Index: &idx, ContentBlock: &block}, + AnthropicStreamEvent{Type: "content_block_delta", Index: &idx, Delta: &AnthropicDelta{Type: "input_json_delta", PartialJSON: string(input)}}, + AnthropicStreamEvent{Type: "content_block_stop", Index: &idx}, + ) + state.ContentBlockIndex++ + return events +} diff --git a/backend/internal/pkg/apicompat/anthropic_tool_search_test.go b/backend/internal/pkg/apicompat/anthropic_tool_search_test.go new file mode 100644 index 000000000000..76446588c6a3 --- /dev/null +++ b/backend/internal/pkg/apicompat/anthropic_tool_search_test.go @@ -0,0 +1,256 @@ +//go:build unit + +package apicompat + +import ( + "encoding/json" + "testing" + + "github.com/stretchr/testify/require" + "github.com/tidwall/gjson" +) + +const toolSearchTestSchema = `{"type":"object","properties":{"query":{"type":"string"},"max_results":{"type":"number"}},"required":["query","max_results"]}` + +func toolSearchTestRequest(t *testing.T, raw string) *AnthropicRequest { + t.Helper() + var req AnthropicRequest + require.NoError(t, json.Unmarshal([]byte(raw), &req)) + return &req +} + +func nativeToolSearchJSON(t *testing.T, req *AnthropicRequest) []byte { + t.Helper() + out, err := AnthropicToResponses(req) + require.NoError(t, err) + require.NoError(t, ApplyNativeToolSearch(req, out)) + body, err := json.Marshal(out) + require.NoError(t, err) + return body +} + +// Before the reveal Claude Code sends Bash + ToolSearch; after it, the revealed +// WebFetch schema joins tools[] with defer_loading:true and the history carries +// the ToolSearch call plus its tool_reference result. +const toolSearchBeforeReveal = `{"model":"gpt-6-astra","max_tokens":64, + "tools":[ + {"name":"Bash","description":"run","input_schema":{"type":"object","properties":{"command":{"type":"string"}}}}, + {"name":"ToolSearch","description":"search deferred tools","input_schema":` + toolSearchTestSchema + `}], + "messages":[{"role":"user","content":"fetch the page"}]}` + +const toolSearchAfterReveal = `{"model":"gpt-6-astra","max_tokens":64, + "tools":[ + {"name":"Bash","description":"run","input_schema":{"type":"object","properties":{"command":{"type":"string"}}}}, + {"name":"ToolSearch","description":"search deferred tools","input_schema":` + toolSearchTestSchema + `}, + {"name":"WebFetch","description":"fetch a url","input_schema":{"type":"object","properties":{"url":{"type":"string"}},"required":["url"]},"defer_loading":true}], + "messages":[ + {"role":"user","content":"fetch the page"}, + {"role":"assistant","content":[{"type":"tool_use","id":"toolu_search","name":"ToolSearch","input":{"query":"select:WebFetch","max_results":5}}]}, + {"role":"user","content":[{"type":"tool_result","tool_use_id":"toolu_search","content":[{"type":"tool_reference","tool_name":"WebFetch"},{"type":"tool_reference","tool_name":"WebFetch"},{"type":"tool_reference","tool_name":"Unknown"}]}]}]}` + +func TestApplyNativeToolSearch_TopLevelToolsStableAcrossReveal(t *testing.T) { + before := nativeToolSearchJSON(t, toolSearchTestRequest(t, toolSearchBeforeReveal)) + after := nativeToolSearchJSON(t, toolSearchTestRequest(t, toolSearchAfterReveal)) + + require.JSONEq(t, gjson.GetBytes(before, "tools").Raw, gjson.GetBytes(after, "tools").Raw, + "top-level tools must not change when a deferred tool is revealed (prompt cache prefix)") + + tools := gjson.GetBytes(after, "tools").Array() + require.Len(t, tools, 2) + require.Equal(t, "function", tools[0].Get("type").String()) + require.Equal(t, "Bash", tools[0].Get("name").String()) + + search := tools[1] + require.Equal(t, "tool_search", search.Get("type").String()) + require.Equal(t, "client", search.Get("execution").String()) + require.Equal(t, "search deferred tools", search.Get("description").String()) + require.JSONEq(t, toolSearchTestSchema, search.Get("parameters").Raw) + require.False(t, search.Get("name").Exists(), "tool_search carries no function name") + require.False(t, search.Get("strict").Exists(), "tool_search is declared without strict") +} + +func TestApplyNativeToolSearch_HistoryMapsToNativeItems(t *testing.T) { + body := nativeToolSearchJSON(t, toolSearchTestRequest(t, toolSearchAfterReveal)) + input := gjson.GetBytes(body, "input").Array() + require.Len(t, input, 3) + + call := input[1] + require.Equal(t, "tool_search_call", call.Get("type").String()) + require.Equal(t, "toolu_search", call.Get("call_id").String()) + require.Equal(t, "client", call.Get("execution").String()) + require.Equal(t, "completed", call.Get("status").String()) + require.True(t, call.Get("arguments").IsObject(), "tool_search_call arguments are a JSON object") + require.Equal(t, "select:WebFetch", call.Get("arguments.query").String()) + + output := input[2] + require.Equal(t, "tool_search_output", output.Get("type").String()) + require.Equal(t, "toolu_search", output.Get("call_id").String()) + require.Equal(t, "client", output.Get("execution").String()) + require.Equal(t, "completed", output.Get("status").String()) + revealed := output.Get("tools").Array() + require.Len(t, revealed, 1, "duplicate and unknown references are dropped") + require.Equal(t, "function", revealed[0].Get("type").String()) + require.Equal(t, "WebFetch", revealed[0].Get("name").String()) + require.Equal(t, "fetch a url", revealed[0].Get("description").String()) + require.True(t, revealed[0].Get("defer_loading").Bool()) + require.False(t, revealed[0].Get("strict").Bool()) + require.True(t, revealed[0].Get("strict").Exists()) + require.Equal(t, "url", revealed[0].Get("parameters.required.0").String()) +} + +func TestApplyNativeToolSearch_NoToolSearchDeclaredKeepsFunctionTools(t *testing.T) { + req := toolSearchTestRequest(t, toolSearchAfterReveal) + tools := req.Tools[:0:0] + for _, tool := range req.Tools { + if tool.Name != "ToolSearch" { + tools = append(tools, tool) + } + } + req.Tools = tools + + body := nativeToolSearchJSON(t, req) + var names []string + for _, tool := range gjson.GetBytes(body, "tools").Array() { + require.Equal(t, "function", tool.Get("type").String()) + names = append(names, tool.Get("name").String()) + } + require.Equal(t, []string{"Bash", "WebFetch"}, names) + require.NotContains(t, string(body), "tool_search_call") +} + +func TestApplyNativeToolSearch_ForcedHiddenToolLeavesRequestUntouched(t *testing.T) { + for _, name := range []string{"ToolSearch", "WebFetch"} { + for _, raw := range []string{toolSearchBeforeReveal, toolSearchAfterReveal} { + req := toolSearchTestRequest(t, raw) + if name == "WebFetch" { + req.Tools = append(req.Tools, AnthropicTool{Name: "WebFetch", InputSchema: json.RawMessage(`{"type":"object"}`), DeferLoading: true}) + } + req.ToolChoice = json.RawMessage(`{"type":"tool","name":"` + name + `"}`) + want, err := AnthropicToResponses(req) + require.NoError(t, err) + wantBody, err := json.Marshal(want) + require.NoError(t, err) + + require.Equal(t, string(wantBody), string(nativeToolSearchJSON(t, req)), name) + require.NotContains(t, string(wantBody), "tool_search", name) + } + } +} + +func TestApplyNativeToolSearch_OtherToolChoicesKeepNativeMapping(t *testing.T) { + for _, choice := range []string{ + `{"type":"tool","name":"Bash"}`, + `{"type":"auto"}`, + `{"type":"any"}`, + } { + req := toolSearchTestRequest(t, toolSearchAfterReveal) + req.ToolChoice = json.RawMessage(choice) + body := nativeToolSearchJSON(t, req) + require.Equal(t, "tool_search", gjson.GetBytes(body, "tools.1.type").String(), choice) + require.Contains(t, string(body), "tool_search_output", choice) + } +} + +func toolSearchResultRequest(t *testing.T, result string, trailing string) *AnthropicRequest { + t.Helper() + return toolSearchTestRequest(t, `{"model":"gpt-6-astra","max_tokens":64, + "tools":[ + {"name":"ToolSearch","description":"search deferred tools","input_schema":`+toolSearchTestSchema+`}, + {"name":"WebFetch","description":"fetch a url","input_schema":{"type":"object"},"defer_loading":true}], + "messages":[ + {"role":"user","content":"fetch the page"}, + {"role":"assistant","content":[{"type":"tool_use","id":"toolu_search","name":"ToolSearch","input":{"query":"x","max_results":5}}]}, + {"role":"user","content":[{"type":"tool_result","tool_use_id":"toolu_search",`+result+`}`+trailing+`]}]}`) +} + +func TestApplyNativeToolSearch_ResultTextRidesInFollowingUserMessage(t *testing.T) { + cases := []struct { + name, result, trailing, wantText, wantUser string + wantTools int + }{ + {"error", `"is_error":true,"content":"InputValidationError"`, "", "InputValidationError", "", 0}, + {"no match string", `"content":"No matching deferred tools found"`, "", "No matching deferred tools found", "", 0}, + {"text with reference", `"content":[{"type":"text","text":"found one"},{"type":"tool_reference","tool_name":"WebFetch"}]`, "", "found one", "", 1}, + {"separate part ahead of following text", `"content":"No matching deferred tools found"`, `,{"type":"text","text":"retry"}`, "No matching deferred tools found", "retry", 0}, + } + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + body := nativeToolSearchJSON(t, toolSearchResultRequest(t, tc.result, tc.trailing)) + input := gjson.GetBytes(body, "input").Array() + require.Len(t, input, 4) + require.Equal(t, "tool_search_call", input[1].Get("type").String()) + require.Equal(t, "tool_search_output", input[2].Get("type").String()) + require.Len(t, input[2].Get("tools").Array(), tc.wantTools) + require.Equal(t, "message", input[3].Get("type").String()) + require.Equal(t, "user", input[3].Get("role").String()) + parts := input[3].Get("content").Array() + require.Equal(t, tc.wantText, parts[0].Get("text").String()) + if tc.wantUser == "" { + require.Len(t, parts, 1) + return + } + require.Len(t, parts, 2) + require.Equal(t, `{"type":"input_text","text":"`+tc.wantUser+`"}`, parts[1].Raw) + }) + } + + t.Run("reference only adds no message", func(t *testing.T) { + body := nativeToolSearchJSON(t, toolSearchResultRequest(t, `"content":[{"type":"tool_reference","tool_name":"WebFetch"}]`, "")) + require.Len(t, gjson.GetBytes(body, "input").Array(), 3) + }) +} + +func TestResponsesToAnthropic_RestoresToolSearchCall(t *testing.T) { + var resp ResponsesResponse + require.NoError(t, json.Unmarshal([]byte(`{"id":"resp_1","status":"completed","output":[ + {"type":"tool_search_call","call_id":"call_search","execution":"client","status":"completed","arguments":{"query":"select:WebFetch","max_results":5}}]}`), &resp)) + + out := ResponsesToAnthropic(&resp, "gpt-6-astra") + require.Len(t, out.Content, 1) + block := out.Content[0] + require.Equal(t, "tool_use", block.Type) + require.Equal(t, "call_search", block.ID) + require.Equal(t, "ToolSearch", block.Name) + require.JSONEq(t, `{"query":"select:WebFetch","max_results":5}`, string(block.Input)) + require.Equal(t, "tool_use", AnthropicStopReasonString(out.StopReason)) +} + +func TestResponsesEventToAnthropic_RestoresToolSearchCall(t *testing.T) { + state := NewResponsesEventToAnthropicState() + var events []AnthropicStreamEvent + for _, raw := range []string{ + `{"type":"response.created","response":{"id":"resp_1","model":"gpt-6-astra"}}`, + `{"type":"response.output_item.added","output_index":0,"item":{"type":"tool_search_call","call_id":"call_search","execution":"client"}}`, + `{"type":"response.output_item.done","output_index":0,"item":{"type":"tool_search_call","call_id":"call_search","execution":"client","status":"completed","arguments":{"query":"docs","max_results":5}}}`, + `{"type":"response.completed","response":{"id":"resp_1","status":"completed","output":[]}}`, + } { + var evt ResponsesStreamEvent + require.NoError(t, json.Unmarshal([]byte(raw), &evt)) + events = append(events, ResponsesEventToAnthropicEvents(&evt, state)...) + } + + var start, delta, stop *AnthropicStreamEvent + for i := range events { + switch events[i].Type { + case "content_block_start": + start = &events[i] + case "content_block_delta": + delta = &events[i] + case "content_block_stop": + stop = &events[i] + } + } + require.NotNil(t, start) + require.Equal(t, "tool_use", start.ContentBlock.Type) + require.Equal(t, "call_search", start.ContentBlock.ID) + require.Equal(t, "ToolSearch", start.ContentBlock.Name) + require.NotNil(t, delta) + require.Equal(t, "input_json_delta", delta.Delta.Type) + require.JSONEq(t, `{"query":"docs","max_results":5}`, delta.Delta.PartialJSON) + require.NotNil(t, stop) + require.Equal(t, *start.Index, *stop.Index) + + last := events[len(events)-2] + require.Equal(t, "message_delta", last.Type) + require.Equal(t, "tool_use", last.Delta.StopReason) +} diff --git a/backend/internal/pkg/apicompat/chatcompletions_responses_bridge.go b/backend/internal/pkg/apicompat/chatcompletions_responses_bridge.go index c6f7b4ec06af..e99c40a231eb 100644 --- a/backend/internal/pkg/apicompat/chatcompletions_responses_bridge.go +++ b/backend/internal/pkg/apicompat/chatcompletions_responses_bridge.go @@ -61,6 +61,7 @@ func ResponsesToChatCompletionsRequestWithOptions(req *ResponsesRequest, opts *R Stream: req.Stream, ServiceTier: req.ServiceTier, ParallelToolCalls: req.ParallelToolCalls, + Stop: req.Stop, } if req.Reasoning != nil { out.ReasoningEffort = req.Reasoning.Effort diff --git a/backend/internal/pkg/apicompat/responses_to_anthropic.go b/backend/internal/pkg/apicompat/responses_to_anthropic.go index 0acb60aa84f1..43b64b9d02ef 100644 --- a/backend/internal/pkg/apicompat/responses_to_anthropic.go +++ b/backend/internal/pkg/apicompat/responses_to_anthropic.go @@ -53,9 +53,24 @@ func ResponsesToAnthropic(resp *ResponsesResponse, model string) *AnthropicRespo Type: "tool_use", ID: fromResponsesCallID(item.CallID), Name: item.Name, - Input: sanitizeAnthropicToolUseInput(item.Name, item.Arguments), + Input: anthropicToolUseInput(item.Type, item.Name, item.Arguments), }) + case "custom_tool_call": + if !resp.RenderCustomToolCalls || (resp.XAIServerSideSearch && IsServerSideSearchCall(item.Type, item.CallID)) { + continue + } + blocks = append(blocks, AnthropicContentBlock{ + Type: "tool_use", + ID: fromResponsesCallID(item.CallID), + Name: item.Name, + Input: anthropicToolUseInput(item.Type, item.Name, item.Input), + }) + case "tool_search_call": + blocks = append(blocks, toolSearchCallToolUse(item)) case "web_search_call": + if item.Status != "completed" { + continue + } toolUseID := "srvtoolu_" + item.ID query := "" if item.Action != nil { @@ -68,11 +83,10 @@ func ResponsesToAnthropic(resp *ResponsesResponse, model string) *AnthropicRespo Name: "web_search", Input: inputJSON, }) - emptyResults, _ := json.Marshal([]struct{}{}) blocks = append(blocks, AnthropicContentBlock{ Type: "web_search_tool_result", ToolUseID: toolUseID, - Content: emptyResults, + Content: webSearchCallResults(&item), }) } } @@ -142,6 +156,26 @@ func containsAnthropicToolUseBlock(blocks []AnthropicContentBlock) bool { return false } +// anthropicToolUseInput returns the input of a non-streaming tool_use block, +// which must be a JSON object. An object is kept as it is. A function_call whose +// arguments are not an object (truncated by max_output_tokens, or empty) gets {}; +// a custom_tool_call's free-form input is wrapped in the same {"input": ...} +// shape that downgrades a custom tool to a function tool, so that +// extractCustomToolCallInput gives the text back; an empty custom input is {} as +// it is in the streamed tool_use. +func anthropicToolUseInput(itemType, name, raw string) json.RawMessage { + if trimmed := strings.TrimSpace(raw); strings.HasPrefix(trimmed, "{") && json.Valid([]byte(trimmed)) { + return sanitizeAnthropicToolUseInput(name, raw) + } + if itemType == "custom_tool_call" && raw != "" { + wrapped, err := json.Marshal(map[string]string{"input": raw}) + if err == nil { + return wrapped + } + } + return json.RawMessage("{}") +} + func sanitizeAnthropicToolUseInput(name string, raw string) json.RawMessage { if name != "Read" || raw == "" { return json.RawMessage(raw) @@ -633,6 +667,10 @@ func resToAnthHandleOutputItemDone(evt *ResponsesStreamEvent, state *ResponsesEv if evt.Item.Type == "web_search_call" && evt.Item.Status == "completed" { return resToAnthHandleWebSearchDone(evt, state) } + // The native tool_search_call carries its arguments only on done. + if evt.Item.Type == "tool_search_call" { + return resToAnthHandleToolSearchDone(evt, state) + } // Capture encrypted_content on reasoning item done (often only present here). if evt.Item.Type == "reasoning" { @@ -680,9 +718,6 @@ func resToAnthHandleWebSearchDone(evt *ResponsesStreamEvent, state *ResponsesEve state.ContentBlockIndex++ // Emit web_search_tool_result block (start + stop). - // Content is empty because OpenAI does not expose individual search results; - // the model consumes them internally and produces text output. - emptyResults, _ := json.Marshal([]struct{}{}) idx2 := state.ContentBlockIndex events = append(events, AnthropicStreamEvent{ Type: "content_block_start", @@ -690,7 +725,7 @@ func resToAnthHandleWebSearchDone(evt *ResponsesStreamEvent, state *ResponsesEve ContentBlock: &AnthropicContentBlock{ Type: "web_search_tool_result", ToolUseID: toolUseID, - Content: emptyResults, + Content: webSearchCallResults(evt.Item), }, }) events = append(events, AnthropicStreamEvent{ diff --git a/backend/internal/pkg/apicompat/responses_to_anthropic_tool_input_test.go b/backend/internal/pkg/apicompat/responses_to_anthropic_tool_input_test.go new file mode 100644 index 000000000000..a0a99d3798cd --- /dev/null +++ b/backend/internal/pkg/apicompat/responses_to_anthropic_tool_input_test.go @@ -0,0 +1,80 @@ +package apicompat + +import ( + "encoding/json" + "testing" + + "github.com/stretchr/testify/require" +) + +func TestAnthropicToolUseInput(t *testing.T) { + tests := []struct { + name string + itemType string + raw string + want string + }{ + {"object kept", "function_call", "{\"a\":1}", "{\"a\":1}"}, + {"object with padding kept", "function_call", " {\"a\": 1}\n", " {\"a\": 1}\n"}, + {"truncated function arguments", "function_call", "{\"a\":1", "{}"}, + {"empty function arguments", "function_call", "", "{}"}, + {"non-object function arguments", "function_call", "[1]", "{}"}, + {"custom input wrapped", "custom_tool_call", "dir /b", "{\"input\":\"dir /b\"}"}, + {"empty custom input is an empty object", "custom_tool_call", "", "{}"}, + {"custom input that is an object kept", "custom_tool_call", "{\"a\":1}", "{\"a\":1}"}, + } + for _, tc := range tests { + t.Run(tc.name, func(t *testing.T) { + got := anthropicToolUseInput(tc.itemType, "exec", tc.raw) + require.Equal(t, tc.want, string(got)) + require.True(t, json.Valid(got)) + }) + } +} + +// The wrapper must round-trip through the helper that undoes the custom tool +// downgrade, including text that is itself valid JSON or has outer whitespace. +func TestAnthropicToolUseInputCustomRoundTrip(t *testing.T) { + for _, text := range []string{"dir", " padded text\n", "", "\"quoted\"", "[1,2]", "line1\nline2"} { + wrapped := anthropicToolUseInput("custom_tool_call", "exec", text) + require.Equal(t, text, extractCustomToolCallInput(string(wrapped)), text) + } +} + +func TestResponsesToAnthropicInvalidToolInputStillMarshals(t *testing.T) { + resp := &ResponsesResponse{ID: "resp_1", Status: "incomplete", IncompleteDetails: &ResponsesIncompleteDetails{Reason: "max_output_tokens"}, Output: []ResponsesOutput{ + {Type: "reasoning", Summary: []ResponsesSummary{{Type: "summary_text", Text: "plan"}}}, + {Type: "function_call", CallID: "call_1", Name: "get", Arguments: "{\"a\":1"}, + {Type: "custom_tool_call", CallID: "call_2", Name: "exec", Input: "dir"}, + }, RenderCustomToolCalls: true} + out := ResponsesToAnthropic(resp, "m") + body, err := json.Marshal(out) + require.NoError(t, err) + require.Len(t, out.Content, 3) + require.Equal(t, "thinking", out.Content[0].Type) + require.Equal(t, "{}", string(out.Content[1].Input)) + require.Equal(t, "{\"input\":\"dir\"}", string(out.Content[2].Input)) + require.Equal(t, "max_tokens", *out.StopReason, string(body)) +} + +func TestResponsesToChatCompletionsRendersCustomToolCall(t *testing.T) { + resp := &ResponsesResponse{ID: "resp_1", Status: "completed", Output: []ResponsesOutput{ + {Type: "custom_tool_call", CallID: "call_1", Name: "exec", Input: "dir"}, + }, RenderCustomToolCalls: true} + out := ResponsesToChatCompletions(resp, "m") + require.Len(t, out.Choices[0].Message.ToolCalls, 1) + require.Equal(t, "dir", out.Choices[0].Message.ToolCalls[0].Function.Arguments) + require.Equal(t, "tool_calls", out.Choices[0].FinishReason) +} + +// An output the upstream delivered keeps custom_tool_call items unrendered. +func TestResponsesToAnthropicAndChatSkipDeliveredCustomToolCall(t *testing.T) { + resp := &ResponsesResponse{ID: "resp_1", Status: "completed", Output: []ResponsesOutput{ + {Type: "custom_tool_call", CallID: "xs_123", Name: "x_keyword_search", Input: "{}"}, + }} + require.Len(t, ResponsesToAnthropic(resp, "m").Content, 1) + require.Equal(t, "text", ResponsesToAnthropic(resp, "m").Content[0].Type) + chat := ResponsesToChatCompletions(resp, "m") + require.Empty(t, chat.Choices[0].Message.ToolCalls) + require.Equal(t, "stop", chat.Choices[0].FinishReason) +} diff --git a/backend/internal/pkg/apicompat/responses_to_chatcompletions.go b/backend/internal/pkg/apicompat/responses_to_chatcompletions.go index e024a6f20392..5bd60f3f5f05 100644 --- a/backend/internal/pkg/apicompat/responses_to_chatcompletions.go +++ b/backend/internal/pkg/apicompat/responses_to_chatcompletions.go @@ -56,6 +56,18 @@ func ResponsesToChatCompletions(resp *ResponsesResponse, model string) *ChatComp Arguments: item.Arguments, }, }) + case "custom_tool_call": + if !resp.RenderCustomToolCalls || (resp.XAIServerSideSearch && IsServerSideSearchCall(item.Type, item.CallID)) { + continue + } + toolCalls = append(toolCalls, ChatToolCall{ + ID: item.CallID, + Type: "function", + Function: ChatFunctionCall{ + Name: item.Name, + Arguments: item.Input, + }, + }) case "reasoning": reasoningText += responsesReasoningText(item) case "web_search_call": @@ -520,6 +532,9 @@ type bufferedFuncCall struct { // so that non-streaming handlers can reconstruct output when the terminal event // (response.completed / response.done) carries an empty output array. type BufferedResponseAccumulator struct { + // tool_search_call items arrive complete on output_item.done. + toolSearchCalls []ResponsesOutput + text strings.Builder refusal strings.Builder reasoning strings.Builder @@ -583,6 +598,10 @@ func (a *BufferedResponseAccumulator) ProcessEvent(event *ResponsesStreamEvent) _, _ = a.funcCalls[idx].Args.WriteString(completed) } } + case "response.output_item.done": + if event.Item != nil && event.Item.Type == "tool_search_call" { + a.toolSearchCalls = append(a.toolSearchCalls, *event.Item) + } case "response.reasoning_summary_text.delta", "response.reasoning_text.delta": if event.Delta != "" { _, _ = a.reasoning.WriteString(event.Delta) @@ -592,7 +611,7 @@ func (a *BufferedResponseAccumulator) ProcessEvent(event *ResponsesStreamEvent) // HasContent reports whether any content has been accumulated. func (a *BufferedResponseAccumulator) HasContent() bool { - return a.text.Len() > 0 || a.refusal.Len() > 0 || len(a.funcCalls) > 0 || a.reasoning.Len() > 0 + return a.text.Len() > 0 || a.refusal.Len() > 0 || len(a.funcCalls) > 0 || len(a.toolSearchCalls) > 0 || a.reasoning.Len() > 0 } // BuildOutput constructs a []ResponsesOutput from the accumulated delta @@ -646,6 +665,7 @@ func (a *BufferedResponseAccumulator) BuildOutput() []ResponsesOutput { Arguments: a.funcCalls[i].Args.String(), }) } + out = append(out, a.toolSearchCalls...) return out } diff --git a/backend/internal/pkg/apicompat/responses_web_search_sources.go b/backend/internal/pkg/apicompat/responses_web_search_sources.go new file mode 100644 index 000000000000..f6f0bf16a7bb --- /dev/null +++ b/backend/internal/pkg/apicompat/responses_web_search_sources.go @@ -0,0 +1,60 @@ +package apicompat + +import ( + "encoding/json" + "slices" +) + +const webSearchSourcesInclude = "web_search_call.action.sources" + +// IncludeWebSearchSources asks a hosted web_search to report the pages it +// used; without it a web_search_call carries only its query. +func IncludeWebSearchSources(req *ResponsesRequest) { + for _, tool := range req.Tools { + if tool.Type == "web_search" { + if !slices.Contains(req.Include, webSearchSourcesInclude) { + req.Include = append(req.Include, webSearchSourcesInclude) + } + return + } + } +} + +type webSearchResult struct { + Type string `json:"type"` + URL string `json:"url"` + Title string `json:"title"` +} + +// webSearchCallResults is the web_search_tool_result content for one call: a +// search's action.sources, or the single page an open_page opened. Callers +// pass completed calls only. Sources and the page URL are decoded leniently, so +// a malformed value cannot fail the terminal event that carries the call. +func webSearchCallResults(item *ResponsesOutput) json.RawMessage { + results := []webSearchResult{} + if action := item.Action; action != nil { + var sources []json.RawMessage + if json.Unmarshal(action.Sources, &sources) == nil && sources != nil { + for _, raw := range sources { + var source map[string]any + _ = json.Unmarshal(raw, &source) + if rawURL, ok := source["url"].(string); ok && rawURL != "" { + results = append(results, newWebSearchResult(rawURL)) + } + } + } else if action.Type == "open_page" { + var pageURL string + if json.Unmarshal(action.URL, &pageURL) == nil && pageURL != "" { + results = append(results, newWebSearchResult(pageURL)) + } + } + } + out, _ := json.Marshal(results) + return out +} + +// newWebSearchResult uses the URL as the title because Responses sources carry +// no title and the Anthropic block requires one. +func newWebSearchResult(rawURL string) webSearchResult { + return webSearchResult{Type: "web_search_result", URL: rawURL, Title: rawURL} +} diff --git a/backend/internal/pkg/apicompat/responses_web_search_sources_test.go b/backend/internal/pkg/apicompat/responses_web_search_sources_test.go new file mode 100644 index 000000000000..3cf9c04f3e08 --- /dev/null +++ b/backend/internal/pkg/apicompat/responses_web_search_sources_test.go @@ -0,0 +1,130 @@ +//go:build unit + +package apicompat + +import ( + "encoding/json" + "testing" + + "github.com/stretchr/testify/require" +) + +const ( + webSearchCallWithTwoSources = `{"type":"web_search_call","id":"ws_1","status":"completed","action":{"type":"search","query":"q1","sources":[` + + `{"type":"url","url":"https://a.example/1"},{"type":"url","url":"https://a.example/2"}]}}` + webSearchCallWithOneSource = `{"type":"web_search_call","id":"ws_2","status":"completed","action":{"type":"search","query":"q2","sources":[` + + `{"type":"url","url":"https://b.example/1"}]}}` + webSearchSourcesWantWS1 = `[{"type":"web_search_result","url":"https://a.example/1","title":"https://a.example/1"},` + + `{"type":"web_search_result","url":"https://a.example/2","title":"https://a.example/2"}]` + webSearchSourcesWantWS2 = `[{"type":"web_search_result","url":"https://b.example/1","title":"https://b.example/1"}]` +) + +func decodeWebSearchItem(t *testing.T, raw string) ResponsesOutput { + t.Helper() + var item ResponsesOutput + require.NoError(t, json.Unmarshal([]byte(raw), &item)) + return item +} + +// webSearchResultContents returns each web_search_tool_result content keyed by +// the server_tool_use id it answers. +func webSearchResultContents(blocks []AnthropicContentBlock) map[string]string { + out := map[string]string{} + for _, block := range blocks { + if block.Type == "web_search_tool_result" { + out[block.ToolUseID] = string(block.Content) + } + } + return out +} + +func nonStreamingWebSearchResults(t *testing.T, items ...string) map[string]string { + t.Helper() + resp := &ResponsesResponse{ID: "resp_ws", Status: "completed"} + for _, raw := range items { + resp.Output = append(resp.Output, decodeWebSearchItem(t, raw)) + } + return webSearchResultContents(ResponsesToAnthropic(resp, "gpt-5.5").Content) +} + +func streamingWebSearchResults(t *testing.T, items ...string) map[string]string { + t.Helper() + state := NewResponsesEventToAnthropicState() + events := ResponsesEventToAnthropicEvents(&ResponsesStreamEvent{ + Type: "response.created", + Response: &ResponsesResponse{ID: "resp_ws", Model: "gpt-5.5"}, + }, state) + for i, raw := range items { + item := decodeWebSearchItem(t, raw) + events = append(events, ResponsesEventToAnthropicEvents(&ResponsesStreamEvent{ + Type: "response.output_item.done", + OutputIndex: i, + Item: &item, + }, state)...) + } + var blocks []AnthropicContentBlock + for _, evt := range events { + if evt.Type == "content_block_start" && evt.ContentBlock != nil { + blocks = append(blocks, *evt.ContentBlock) + } + } + return webSearchResultContents(blocks) +} + +func TestResponsesEventToAnthropic_WebSearchSources(t *testing.T) { + got := streamingWebSearchResults(t, webSearchCallWithTwoSources, webSearchCallWithOneSource) + require.Len(t, got, 2) + require.JSONEq(t, webSearchSourcesWantWS1, got["srvtoolu_ws_1"]) + require.JSONEq(t, webSearchSourcesWantWS2, got["srvtoolu_ws_2"]) +} + +func TestResponsesToAnthropic_WebSearchSources(t *testing.T) { + got := nonStreamingWebSearchResults(t, webSearchCallWithTwoSources, webSearchCallWithOneSource) + require.Len(t, got, 2) + require.JSONEq(t, webSearchSourcesWantWS1, got["srvtoolu_ws_1"]) + require.JSONEq(t, webSearchSourcesWantWS2, got["srvtoolu_ws_2"]) +} + +func TestWebSearchSourcesEntryRules(t *testing.T) { + got := nonStreamingWebSearchResults(t, `{"type":"web_search_call","id":"ws_1","status":"completed","action":{"type":"search","query":"q",`+ + `"sources":[{"url":"https://a"},{"url":""},{"url":1},"https://b",{"title":"x"}]}}`) + require.JSONEq(t, `[{"type":"web_search_result","url":"https://a","title":"https://a"}]`, got["srvtoolu_ws_1"]) +} + +func TestWebSearchOpenPageReturnsSinglePage(t *testing.T) { + got := nonStreamingWebSearchResults(t, `{"type":"web_search_call","id":"ws_1","status":"completed",`+ + `"action":{"type":"open_page","url":"https://docs.example/page?id=1#top"}}`) + require.JSONEq(t, `[{"type":"web_search_result","url":"https://docs.example/page?id=1#top","title":"https://docs.example/page?id=1#top"}]`, + got["srvtoolu_ws_1"]) +} + +func TestWebSearchOpenPageRequiresCompletedURL(t *testing.T) { + for name, item := range map[string]string{ + "empty url": `{"type":"web_search_call","id":"ws_1","status":"completed","action":{"type":"open_page","url":""}}`, + } { + t.Run(name, func(t *testing.T) { + require.JSONEq(t, `[]`, nonStreamingWebSearchResults(t, item)["srvtoolu_ws_1"]) + }) + } +} + +func TestWebSearchNonStringActionURLKeepsEvent(t *testing.T) { + for name, url := range map[string]string{"number": `123`, "object": `{"a":1}`, "array": `["a"]`} { + t.Run(name, func(t *testing.T) { + raw := `{"type":"web_search_call","id":"ws_1","status":"completed","action":{"type":"open_page","url":` + url + `}}` + got := nonStreamingWebSearchResults(t, raw) + require.JSONEq(t, `[]`, got["srvtoolu_ws_1"]) + require.JSONEq(t, `[]`, streamingWebSearchResults(t, raw)["srvtoolu_ws_1"]) + }) + } +} + +func TestWebSearchCallsThatDidNotCompleteProduceNoBlocks(t *testing.T) { + for _, status := range []string{"failed", "in_progress"} { + t.Run(status, func(t *testing.T) { + raw := `{"type":"web_search_call","id":"ws_1","status":"` + status + `","action":{"type":"search","query":"q","sources":[{"url":"https://a.example/1"}]}}` + require.Empty(t, nonStreamingWebSearchResults(t, raw)) + require.Empty(t, streamingWebSearchResults(t, raw)) + }) + } +} diff --git a/backend/internal/pkg/apicompat/types.go b/backend/internal/pkg/apicompat/types.go index 5b79f7d4ce92..348df8971dc1 100644 --- a/backend/internal/pkg/apicompat/types.go +++ b/backend/internal/pkg/apicompat/types.go @@ -81,6 +81,9 @@ type AnthropicContentBlock struct { ToolUseID string `json:"tool_use_id,omitempty"` Content json.RawMessage `json:"content,omitempty"` // string or []AnthropicContentBlock IsError bool `json:"is_error,omitempty"` + + // type=tool_reference (inside a ToolSearch tool_result) + ToolName string `json:"tool_name,omitempty"` } func (b AnthropicContentBlock) MarshalJSON() ([]byte, error) { @@ -123,6 +126,8 @@ type AnthropicTool struct { Description string `json:"description,omitempty"` InputSchema json.RawMessage `json:"input_schema,omitempty"` // JSON Schema object CacheControl *AnthropicCacheControl `json:"cache_control,omitempty"` + // DeferLoading marks a tool Claude Code reveals through ToolSearch. + DeferLoading bool `json:"defer_loading,omitempty"` } // AnthropicCacheControl 对应 Anthropic API 的 cache_control 字段。 @@ -343,6 +348,10 @@ type ResponsesRequest struct { ServiceTier string `json:"service_tier,omitempty"` PromptCacheKey string `json:"prompt_cache_key,omitempty"` PreviousResponseID string `json:"previous_response_id,omitempty"` + // Stop 在 Chat Completions 里是原生字段,Responses 协议本身没有。这里保留原样 + // (string 或 []string),仅在降级到 Chat Completions 时透传,避免客户端设的 + // 停止序列在转换层被静默丢弃。 + Stop json.RawMessage `json:"stop,omitempty"` } // ResponsesReasoning configures reasoning effort in the Responses API. @@ -428,6 +437,8 @@ type ResponsesTool struct { Description string `json:"description,omitempty"` Parameters json.RawMessage `json:"parameters,omitempty"` Strict *bool `json:"strict,omitempty"` + // type=tool_search: "client" means the caller executes the search. + Execution string `json:"execution,omitempty"` // type=namespace 的子工具列表(tools 与 children 二选一,语义相同)。 Tools []ResponsesTool `json:"tools,omitempty"` @@ -478,6 +489,16 @@ type ResponsesResponse struct { // Error is present when status="failed" Error *ResponsesError `json:"error,omitempty"` + + // RenderCustomToolCalls is set on an output rebuilt from stream events, where + // the accumulator has always handed custom_tool_call items to the converters + // as tool calls. An output the upstream delivered keeps them unrendered. + RenderCustomToolCalls bool `json:"-"` + + // XAIServerSideSearch is set with RenderCustomToolCalls when the upstream is + // xAI. A custom_tool_call that IsServerSideSearchCall then stays in the + // output but is not rendered as a tool call, because xAI runs it itself. + XAIServerSideSearch bool `json:"-"` } // ResponsesError describes an error in a failed response. @@ -612,6 +633,10 @@ func (o *ResponsesOutput) UnmarshalJSON(data []byte) error { type WebSearchAction struct { Type string `json:"type,omitempty"` // "search" Query string `json:"query,omitempty"` // primary search query + // URL and Sources stay raw: a strictly typed value of an unexpected shape + // would fail decoding the whole terminal event that carries this call. + URL json.RawMessage `json:"url,omitempty"` // open_page / find_in_page target + Sources json.RawMessage `json:"sources,omitempty"` } // ResponsesSummary is a summary text block inside a reasoning output. @@ -630,6 +655,10 @@ type ResponsesUsage struct { // Optional detailed breakdown InputTokensDetails *ResponsesInputTokensDetails `json:"input_tokens_details,omitempty"` OutputTokensDetails *ResponsesOutputTokensDetails `json:"output_tokens_details,omitempty"` + + // ServerSideToolUsageDetails is xAI's per-class success count object, + // kept raw so Grok search counting can read it from a decoded response. + ServerSideToolUsageDetails json.RawMessage `json:"server_side_tool_usage_details,omitempty"` } func (u *ResponsesUsage) UnmarshalJSON(data []byte) error { diff --git a/backend/internal/pkg/claude/sampling.go b/backend/internal/pkg/claude/sampling.go new file mode 100644 index 000000000000..a6016e7481e6 --- /dev/null +++ b/backend/internal/pkg/claude/sampling.go @@ -0,0 +1,21 @@ +package claude + +import "strings" + +var temperatureRejectingFamilies = []string{ + "claude-opus-4-7", + "claude-opus-4-8", +} + +func RejectsTemperature(model string) bool { + if IsOpus55(model) || IsFable52(model) || IsMythos52(model) { + return true + } + id := normalizeEffortModelID(model) + for _, family := range temperatureRejectingFamilies { + if id == family || strings.HasPrefix(id, family+"-") { + return true + } + } + return false +} diff --git a/backend/internal/pkg/claude/sampling_test.go b/backend/internal/pkg/claude/sampling_test.go new file mode 100644 index 000000000000..497d6d5dba36 --- /dev/null +++ b/backend/internal/pkg/claude/sampling_test.go @@ -0,0 +1,40 @@ +package claude + +import ( + "testing" + + "github.com/stretchr/testify/require" +) + +func TestRejectsTemperature(t *testing.T) { + t.Parallel() + + tests := []struct { + model string + want bool + }{ + {model: "claude-opus-4-8", want: true}, + {model: "claude-opus-4-8-20260529", want: true}, + {model: "claude-opus-4-7", want: true}, + {model: "anthropic/claude-opus-4-8", want: true}, + {model: "us.anthropic.claude-opus-4-8-v1", want: true}, + {model: "claude-opus-5-5", want: true}, + {model: "anthropic/claude-opus-5.5", want: true}, + {model: "claude-fable-5-2", want: true}, + {model: "claude-mythos-5-2", want: true}, + {model: "claude-opus-4-6", want: false}, + {model: "claude-opus-4-5-20251101", want: false}, + {model: "claude-sonnet-4-6", want: false}, + {model: "claude-sonnet-5-5", want: false}, + {model: "claude-haiku-5-5", want: false}, + {model: "claude-haiku-4-5-20251001", want: false}, + {model: "gpt-5.6", want: false}, + {model: "", want: false}, + } + for _, tt := range tests { + t.Run(tt.model, func(t *testing.T) { + t.Parallel() + require.Equal(t, tt.want, RejectsTemperature(tt.model)) + }) + } +} diff --git a/backend/internal/pkg/httputil/body.go b/backend/internal/pkg/httputil/body.go index 555656239f76..e7f0b40fd618 100644 --- a/backend/internal/pkg/httputil/body.go +++ b/backend/internal/pkg/httputil/body.go @@ -181,6 +181,10 @@ func readRequestBodyChunksWithBudget(ctx context.Context, reader io.Reader, init read, err = reader.Read(chunk[n:]) n += read } + // HTTP/1 can cancel the context as a side effect of the read deadline. + if IsRequestBodyReadTimeout(err) { + return requestBodyBuffer{}, err + } if err := ctx.Err(); err != nil { return requestBodyBuffer{}, err } diff --git a/backend/internal/pkg/httputil/body_read_error.go b/backend/internal/pkg/httputil/body_read_error.go new file mode 100644 index 000000000000..07b106faefc3 --- /dev/null +++ b/backend/internal/pkg/httputil/body_read_error.go @@ -0,0 +1,213 @@ +package httputil + +import ( + "context" + "errors" + "fmt" + "io" + "net" + "net/http" + "os" + "strings" + "syscall" + "time" + + "go.uber.org/zap" +) + +// Stable, payload-free labels for request body read failures. +const ( + RequestBodyReadErrorMaxBytes = "max_bytes" + RequestBodyReadErrorTimeout = "read_timeout" + RequestBodyReadErrorClientDisconnect = "client_disconnect" + RequestBodyReadErrorTruncated = "truncated_body" + RequestBodyReadErrorDecodeContentEncoding = "decode_content_encoding" + RequestBodyReadErrorUnsupportedContentEncoding = "unsupported_content_encoding" + RequestBodyReadErrorTransport = "transport" + RequestBodyReadErrorIO = "io_read" +) + +// StatusClientClosedRequest is the non-standard status recorded when the client +// goes away before the server responds. +const StatusClientClosedRequest = 499 + +// RequestBodyReadError annotates a failed request body read with progress +// counters. It never carries request content. +type RequestBodyReadError struct { + Err error + BytesRead int64 + Elapsed time.Duration +} + +func (e *RequestBodyReadError) Error() string { return e.Err.Error() } + +func (e *RequestBodyReadError) Unwrap() error { return e.Err } + +// RequestBodyReadFailure is the response and the payload-free diagnostics for a +// failed request body read. +type RequestBodyReadFailure struct { + Kind string + Status int + Message string + // MaxBytesLimit is set when Kind is RequestBodyReadErrorMaxBytes. + MaxBytesLimit int64 + + contentLength int64 + contentEncoding string + protocol string + chunked bool + bytesRead int64 + elapsed time.Duration +} + +// DescribeRequestBodyReadFailure classifies a request body read error. Timeouts +// and client disconnects get their own status codes so they are not reported +// as malformed requests; other failures keep the generic 400 response. +func DescribeRequestBodyReadFailure(req *http.Request, err error) RequestBodyReadFailure { + failure := RequestBodyReadFailure{ + Kind: classifyRequestBodyReadError(req, err), + contentLength: -1, + contentEncoding: "identity", + bytesRead: -1, + } + if req != nil { + failure.contentLength = req.ContentLength + failure.contentEncoding = RequestContentEncodingCategory(req.Header.Get("Content-Encoding")) + failure.protocol = req.Proto + failure.chunked = len(req.TransferEncoding) > 0 + } + var readErr *RequestBodyReadError + if errors.As(err, &readErr) { + failure.bytesRead = readErr.BytesRead + failure.elapsed = readErr.Elapsed + } + + switch failure.Kind { + case RequestBodyReadErrorMaxBytes: + var maxErr *http.MaxBytesError + if errors.As(err, &maxErr) { + failure.MaxBytesLimit = maxErr.Limit + } + failure.Status = http.StatusRequestEntityTooLarge + failure.Message = "Request body is too large" + case RequestBodyReadErrorTimeout: + failure.Status = http.StatusRequestTimeout + failure.Message = "Timed out reading request body" + case RequestBodyReadErrorClientDisconnect: + failure.Status = StatusClientClosedRequest + failure.Message = "Client closed the connection before the request body was received" + default: + failure.Status = http.StatusBadRequest + failure.Message = "Failed to read request body" + } + return failure +} + +// ClientMessage returns the message shown to the client. A size-limit failure +// names the limit so callers can tell which limit they hit. +func (f RequestBodyReadFailure) ClientMessage() string { + if f.Kind == RequestBodyReadErrorMaxBytes { + return BodyTooLargeMessage(f.MaxBytesLimit) + } + return f.Message +} + +// BodyTooLargeMessage formats the 413 message for a request body limit. +func BodyTooLargeMessage(limit int64) string { + const mb = 1024 * 1024 + if limit >= mb { + return fmt.Sprintf("Request body too large, limit is %dMB", limit/mb) + } + return fmt.Sprintf("Request body too large, limit is %dB", limit) +} + +// LogFields returns diagnostics that never include request content or error +// text, which may embed peer addresses or decoder input. +func (f RequestBodyReadFailure) LogFields() []zap.Field { + fields := []zap.Field{ + zap.String("error_kind", f.Kind), + zap.Int("status", f.Status), + zap.String("protocol", f.protocol), + zap.String("content_encoding", f.contentEncoding), + zap.Int64("content_length", f.contentLength), + zap.Bool("chunked", f.chunked), + } + if f.bytesRead >= 0 { + fields = append(fields, + zap.Int64("bytes_read", f.bytesRead), + zap.Int64("read_ms", f.elapsed.Milliseconds()), + ) + } + return fields +} + +func classifyRequestBodyReadError(req *http.Request, err error) string { + if err == nil { + return RequestBodyReadErrorIO + } + var maxErr *http.MaxBytesError + if errors.As(err, &maxErr) { + return RequestBodyReadErrorMaxBytes + } + lower := strings.ToLower(err.Error()) + if strings.Contains(lower, "decode content-encoding") { + if strings.Contains(lower, "unsupported content-encoding") { + return RequestBodyReadErrorUnsupportedContentEncoding + } + return RequestBodyReadErrorDecodeContentEncoding + } + // Check timeouts first: on HTTP/1 a read deadline also cancels the request + // context, which would otherwise look like a client disconnect. + if IsRequestBodyReadTimeout(err) { + return RequestBodyReadErrorTimeout + } + if requestBodyClientGone(req, err, lower) { + return RequestBodyReadErrorClientDisconnect + } + // HTTP/2 reports an END_STREAM that arrives before Content-Length bytes + // with "request declared a Content-Length of N but only wrote M bytes". + if errors.Is(err, io.ErrUnexpectedEOF) || strings.Contains(lower, "request declared a content-length") { + return RequestBodyReadErrorTruncated + } + var netErr net.Error + if errors.As(err, &netErr) { + return RequestBodyReadErrorTransport + } + return RequestBodyReadErrorIO +} + +// IsRequestBodyReadTimeout reports whether a body read failed because a read +// deadline expired (for example WithBodyReadTimeout's per-read deadline). +func IsRequestBodyReadTimeout(err error) bool { + var netErr net.Error + return errors.Is(err, os.ErrDeadlineExceeded) || (errors.As(err, &netErr) && netErr.Timeout()) +} + +func requestBodyClientGone(req *http.Request, err error, lowerErr string) bool { + if errors.Is(err, context.Canceled) || errors.Is(err, syscall.ECONNRESET) || errors.Is(err, syscall.EPIPE) { + return true + } + // HTTP/2 reports a closed client connection with this message. + if strings.Contains(lowerErr, "client disconnected") { + return true + } + // net/http cancels the request context when the connection fails, so an + // unexpected EOF with a canceled context is a disconnect, not a short body. + return req != nil && errors.Is(req.Context().Err(), context.Canceled) +} + +// RequestContentEncodingCategory maps Content-Encoding to a bounded label. +func RequestContentEncodingCategory(value string) string { + switch strings.ToLower(strings.TrimSpace(value)) { + case "", "identity": + return "identity" + case "gzip", "x-gzip": + return "gzip" + case "zstd": + return "zstd" + case "deflate": + return "deflate" + default: + return "other" + } +} diff --git a/backend/internal/pkg/requestmodel/conflict.go b/backend/internal/pkg/requestmodel/conflict.go new file mode 100644 index 000000000000..4aab752bed96 --- /dev/null +++ b/backend/internal/pkg/requestmodel/conflict.go @@ -0,0 +1,472 @@ +package requestmodel + +import ( + "bytes" + "hash/maphash" + "io" + "mime" + "mime/multipart" + "strconv" + "strings" + "unicode" + "unicode/utf16" + "unicode/utf8" +) + +// utf8BOM 是部分客户端写在 JSON 文档前的 UTF-8 字节序标记。网关 handler 的宽容 +// 读取(httputil.ReadLenientJSONRequestBodyWithPrealloc)会先剥掉它再解析, +// 准入与歧义检查必须看同一份字节。 +var utf8BOM = []byte{0xEF, 0xBB, 0xBF} + +// TrimUTF8BOM 去掉请求体开头的 UTF-8 BOM(与宽容读取的规则一致),否则原样返回。 +func TrimUTF8BOM(body []byte) []byte { + return bytes.TrimPrefix(body, utf8BOM) +} + +// LooksLikeJSON 判断(已去 BOM 的)请求体首个非空白字节是否为 JSON 对象或数组。 +// +// 是否按 JSON 检查只看内容、不看 Content-Type:JSON handler 从不校验请求头, +// 把 JSON 请求体标成 multipart/form-data 不能绕过检查。 +func LooksLikeJSON(body []byte) bool { + for _, c := range body { + // 与 gjson 一致:首个值之前所有 <= 0x20 的字节都当空白跳过。 + if c <= ' ' { + continue + } + return c == '{' || c == '[' + } + return false +} + +// ConflictingField 返回请求体中第一个重复声明的字段路径。 +// +// 网关读取 model、service_tier、reasoning.effort 等字段用的是 gjson(重复键取 +// 第一个、大小写敏感),sjson 改写(模型映射、推理强度降级、fast policy 删除 +// service_tier)也只改第一个;而改写并转发请求体的路径会经过 encoding/json +// (解码到 map 时重复键取最后一个,绑定到结构体时键名大小写不敏感、取最后一个), +// 上游解析器也可能取最后一个。同名字段一旦重复,准入、计费、策略看到的值和上游 +// 实际收到的值就可能分叉,例如 {"model":"便宜模型",...,"model":"贵模型"} 按便宜 +// 模型计费、转发贵模型。取值相同的重复同样拒绝:网关自己的 sjson 改写只动第一个, +// 改写后两者就不再相同。调用方应在任何解析器读取字段之前拒绝这类请求。 +// +// 判定范围: +// - JSON(按内容识别,见 LooksLikeJSON):任意深度的对象(含数组元素)内, +// 成员名经转义解码(无效 UTF-8 与孤立代理项按 encoding/json 替换为 U+FFFD) +// 后按 encoding/json 结构体绑定的大小写折叠规则相同。用户自定义键空间 +// (JSON Schema 的 properties/$defs、工具调用参数、模板变量等,见 +// isFreeformMember)内只比较精确名字,因为 id 与 ID 在那里是合法的不同键。 +// 字段路径形如 reasoning.effort、messages[1].role。 +// - multipart(按 Content-Type 声明):见 multipartConflictingField。 +// - 声明为 multipart、请求体又以 JSON 开头且解析出了表单 part:两种解读并存, +// 报告 Content-Type。 +// +// 扫描是一次线性遍历,键名以带随机种子的 64 位哈希判重,CPU 与内存都与请求体 +// 大小成线性关系;嵌套超过 maxConflictDepth 的部分只计括号不检查(encoding/json +// 本身拒绝这种深度),其后的同层成员仍继续检查。扫描在首个顶层值结束时停止, +// 与 gjson 读取的范围一致(其后的内容 encoding/json 会拒绝)。 +func ConflictingField(contentType string, body []byte) (string, bool) { + // 两种解读都要检查:JSON handler 不看请求头,按 JSON 读首个值;multipart + // handler 按 boundary 解析,并跳过首个 boundary 之前的前导内容(RFC 2046 + // preamble),前导内容可以是任意 JSON。 + looksJSON := LooksLikeJSON(TrimUTF8BOM(body)) + if looksJSON { + if field, conflict := scanDuplicateMember(TrimUTF8BOM(body)); conflict { + return field, true + } + } + if !isMultipartContentType(contentType) { + return "", false + } + field, conflict, parts := multipartConflictingField(contentType, body) + if conflict { + return field, true + } + if looksJSON && parts > 0 { + // 同一请求体既是 JSON 又含 multipart 字段:合成路由、白名单、JSON 与 + // multipart handler 会各取一种解读(例如前导 JSON 的 model 与表单的 + // model),整体视为歧义。 + return "Content-Type", true + } + return "", false +} + +// maxConflictDepth 与 encoding/json 的嵌套上限一致。 +const maxConflictDepth = 10000 + +// conflictLinearScanLimit 以内的对象线性比较哈希,超过后改用 map。 +const conflictLinearScanLimit = 32 + +// conflictHashSeed 每个进程随机生成:客户端无法构造哈希碰撞。碰撞只会让请求被 +// 误拒(fail closed),不会放过重复键。 +var conflictHashSeed = maphash.MakeSeed() + +type scanFrame struct { + object bool + fold bool // 是否按大小写折叠比较本对象的成员名 + wantKey bool // object:下一个字符串是成员名 + // 当前成员名在请求体中的原始范围(不含引号),用于路径与自由键判定。 + keyStart, keyEnd int + keyEscaped bool + index int // array:当前元素下标 + hashStart int // object:本对象成员哈希在 scanner.hashes 中的起点 + seen map[uint64]struct{} +} + +type duplicateScanner struct { + body []byte + stack []scanFrame + hashes []uint64 + hash maphash.Hash + runes []byte + names []byte +} + +func scanDuplicateMember(body []byte) (string, bool) { + s := duplicateScanner{body: body} + s.hash.SetSeed(conflictHashSeed) + overflow := 0 // 超过 maxConflictDepth 后未闭合的括号数 + for i := 0; i < len(body); { + switch c := body[i]; c { + case '{', '[': + if overflow > 0 || len(s.stack) >= maxConflictDepth { + overflow++ + } else { + s.push(c == '{') + } + i++ + case '}', ']': + if overflow > 0 { + overflow-- + } else if n := len(s.stack); n > 0 { + if top := s.stack[n-1]; top.object { + s.hashes = s.hashes[:top.hashStart] + } + s.stack = s.stack[:n-1] + if n == 1 { + return "", false + } + } + i++ + case ',': + if n := len(s.stack); overflow == 0 && n > 0 { + if top := &s.stack[n-1]; top.object { + top.wantKey = true + } else { + top.index++ + } + } + i++ + case '"': + end, escaped := scanJSONString(body, i+1) + if n := len(s.stack); overflow == 0 && n > 0 && s.stack[n-1].object && s.stack[n-1].wantKey { + top := &s.stack[n-1] + top.wantKey = false + top.keyStart, top.keyEnd, top.keyEscaped = i+1, end, escaped + if s.repeated(top) { + return s.path(), true + } + } + i = end + 1 + default: + i++ + } + } + return "", false +} + +func (s *duplicateScanner) push(object bool) { + fold := true + if n := len(s.stack); n > 0 { + parent := &s.stack[n-1] + fold = parent.fold + if fold && parent.object { + s.names = appendMemberName(s.names[:0], s.body[parent.keyStart:parent.keyEnd], parent.keyEscaped, false) + fold = !isFreeformMember(s.names, n > 1) + } + } + s.stack = append(s.stack, scanFrame{object: object, fold: fold, wantKey: object, hashStart: len(s.hashes)}) +} + +// repeated 登记 top 的当前成员名,返回它是否与本对象中更早的成员重名。 +func (s *duplicateScanner) repeated(top *scanFrame) bool { + s.hash.Reset() + s.runes = appendMemberName(s.runes[:0], s.body[top.keyStart:top.keyEnd], top.keyEscaped, top.fold) + _, _ = s.hash.Write(s.runes) + sum := s.hash.Sum64() + + if top.seen != nil { + if _, dup := top.seen[sum]; dup { + return true + } + top.seen[sum] = struct{}{} + return false + } + for _, seen := range s.hashes[top.hashStart:] { + if seen == sum { + return true + } + } + s.hashes = append(s.hashes, sum) + if len(s.hashes)-top.hashStart > conflictLinearScanLimit { + // 子对象的哈希总在其闭合时截掉,本对象的哈希在切片末尾连续。 + top.seen = make(map[uint64]struct{}, 4*conflictLinearScanLimit) + for _, seen := range s.hashes[top.hashStart:] { + top.seen[seen] = struct{}{} + } + s.hashes = s.hashes[:top.hashStart] + } + return false +} + +// path 把当前栈拼成 a.b[0].c;结果是新分配的字符串,不引用请求体。 +func (s *duplicateScanner) path() string { + var out []byte + for _, frame := range s.stack { + if !frame.object { + out = append(out, '[') + out = strconv.AppendInt(out, int64(frame.index), 10) + out = append(out, ']') + continue + } + if len(out) > 0 { + out = append(out, '.') + } + out = appendMemberName(out, s.body[frame.keyStart:frame.keyEnd], frame.keyEscaped, false) + } + return string(out) +} + +// freeformMembers 的值是用户自定义键空间:JSON Schema 的属性表与取值、工具调用 +// 参数、提示词模板变量、MCP 请求头、标签。这些子树内的成员名只做精确比较(成员名 +// 解码后不区分大小写地匹配本表)。它们都不在网关计费/策略读取、也不被结构体绑定 +// 的字段路径上;input / response 只在非顶层时算(顶层 input 是 Responses 的输入 +// 列表,顶层 response 是 realtime response.create 的参数)。metadata 不在表内: +// Antigravity 把 metadata.user_id 绑定到结构体(大小写不敏感),而网关的粘性会话 +// 用 gjson 读它。 +var freeformMembers = []string{ + "properties", "patternProperties", "$defs", "definitions", "dependentSchemas", + "dependentRequired", "dependencies", "default", "const", "examples", "enum", + "args", "arguments", "variables", "headers", "labels", +} + +func isFreeformMember(name []byte, nested bool) bool { + for _, candidate := range freeformMembers { + if bytes.EqualFold(name, []byte(candidate)) { + return true + } + } + return nested && (bytes.EqualFold(name, []byte("input")) || bytes.EqualFold(name, []byte("response"))) +} + +// scanJSONString 从字符串内容起点 i 找到闭合引号的下标(找不到返回 len(b)), +// 并报告内容中是否含转义。每个字节最多访问常数次:先找下一个引号,再看它前面 +// 连续反斜杠的个数,奇数说明引号被转义,从引号之后继续找。 +func scanJSONString(b []byte, i int) (int, bool) { + escaped := false + for i < len(b) { + quote := bytes.IndexByte(b[i:], '"') + if quote < 0 { + return len(b), escaped || bytes.IndexByte(b[i:], '\\') >= 0 + } + end := i + quote + if !escaped && bytes.IndexByte(b[i:end], '\\') >= 0 { + escaped = true + } + backslashes := 0 + for j := end - 1; j >= i && b[j] == '\\'; j-- { + backslashes++ + } + if backslashes%2 == 0 { + return end, escaped + } + i = end + 1 + } + return len(b), escaped +} + +// appendMemberName 把原始成员名按 encoding/json 的规则解码(转义、无效 UTF-8 与 +// 孤立代理项替换为 U+FFFD)后追加到 dst;fold 时逐字符做大小写折叠。 +func appendMemberName(dst, raw []byte, escaped, fold bool) []byte { + for i := 0; i < len(raw); { + var r rune + if raw[i] == '\\' && escaped && i+1 < len(raw) { + r, i = decodeJSONEscape(raw, i) + } else if raw[i] < utf8.RuneSelf { + r = rune(raw[i]) + i++ + } else { + var size int + r, size = utf8.DecodeRune(raw[i:]) + i += size + } + if fold { + r = foldRune(r) + } + dst = utf8.AppendRune(dst, r) + } + return dst +} + +// decodeJSONEscape 解码 raw[i] 处的转义序列,返回字符与下一个下标。 +func decodeJSONEscape(raw []byte, i int) (rune, int) { + switch raw[i+1] { + case 'b': + return '\b', i + 2 + case 'f': + return '\f', i + 2 + case 'n': + return '\n', i + 2 + case 'r': + return '\r', i + 2 + case 't': + return '\t', i + 2 + case 'u': + r, ok := hex4(raw, i+2) + if !ok { + return rune(raw[i+1]), i + 2 + } + if utf16.IsSurrogate(r) { + if i+11 < len(raw) && raw[i+6] == '\\' && raw[i+7] == 'u' { + if r2, ok := hex4(raw, i+8); ok { + if dec := utf16.DecodeRune(r, r2); dec != unicode.ReplacementChar { + return dec, i + 12 + } + } + } + return unicode.ReplacementChar, i + 6 + } + return r, i + 6 + default: + return rune(raw[i+1]), i + 2 + } +} + +func hex4(raw []byte, i int) (rune, bool) { + if i+4 > len(raw) { + return 0, false + } + var r rune + for _, c := range raw[i : i+4] { + switch { + case '0' <= c && c <= '9': + c -= '0' + case 'a' <= c && c <= 'f': + c = c - 'a' + 10 + case 'A' <= c && c <= 'F': + c = c - 'A' + 10 + default: + return 0, false + } + r = r*16 + rune(c) + } + return r, true +} + +// foldRune 返回 r 所在大小写折叠轨道上的固定代表,只有大小写不同的字符映射到 +// 同一个值(与 encoding/json 结构体字段的大小写不敏感匹配一致,覆盖 ſ、开尔文 +// 符号 K)。拉丁字母取小写。 +func foldRune(r rune) rune { + if r < utf8.RuneSelf { + // ASCII 字母的轨道代表就是其小写(k、s 的非 ASCII 成员都更大)。 + if 'A' <= r && r <= 'Z' { + return r + 'a' - 'A' + } + return r + } + folded := r + for next := unicode.SimpleFold(r); next != r; next = unicode.SimpleFold(next) { + if next < folded { + folded = next + } + } + if folded >= 'A' && folded <= 'Z' { + folded += 'a' - 'A' + } + return folded +} + +// hasExtendedNameParam 报告 Content-Disposition 是否带 RFC 2231 扩展形式的字段名 +// 参数(name*=、name*0=、name*0*=)。Go 以扩展值优先,忽略扩展参数的上游读的是 +// name=,同一 part 会被读成两个不同的字段。filename* 是非 ASCII 文件名的合法写法, +// 不在此列。 +func hasExtendedNameParam(disposition string) bool { + lower := strings.ToLower(disposition) + for i := 0; ; { + idx := strings.Index(lower[i:], "name*") + if idx < 0 { + return false + } + idx += i + start := idx + for start > 0 && (lower[start-1] == ' ' || lower[start-1] == '\t') { + start-- + } + if start == 0 || lower[start-1] == ';' { + return true + } + i = idx + len("name*") + } +} + +// isRepeatableMultipartField 报告表单字段是否按列表语义合法重复:以 [] 结尾的 +// 数组字段(如 timestamp_granularities[])、多图输入(image、image[...]、 +// Grok 媒体的 image_url)。其余文本字段(model、n、size、quality、duration 等 +// 计费/策略标量)出现多次即为歧义。 +func isRepeatableMultipartField(name string) bool { + return strings.HasSuffix(name, "[]") || name == "image" || name == "image_url" || strings.HasPrefix(name, "image[") +} + +// multipartConflictingField 检查 multipart 表单:同名标量字段出现多次(文件与 +// 文本 part 合并计数,列表字段见 isRepeatableMultipartField);名为 model / +// session 的文件 part(网关 handler 跳过文件 part,宽容的上游可能当字段读); +// 没有可解析名字、带多个 Content-Disposition 头或 RFC 2231 扩展字段名参数的 part +// (各解析器可能取不同的名字);session 字段的 JSON 值内部按 JSON 规则检查。 +// +// parts 返回成功解析出的 part 数,供调用方判断请求体是否同时含 multipart 内容。 +func multipartConflictingField(contentType string, body []byte) (field string, conflict bool, parts int) { + _, params, err := mime.ParseMediaType(strings.TrimSpace(contentType)) + if err != nil { + return "", false, 0 + } + boundary := strings.TrimSpace(params["boundary"]) + if boundary == "" { + return "", false, 0 + } + reader := multipart.NewReader(bytes.NewReader(body), boundary) + seen := make(map[string]struct{}) + for { + part, err := reader.NextPart() + if err != nil { + return "", false, parts + } + parts++ + name := strings.TrimSpace(part.FormName()) + dispositions := part.Header.Values("Content-Disposition") + if name == "" || len(dispositions) > 1 || hasExtendedNameParam(dispositions[0]) { + return "Content-Disposition", true, parts + } + isFile := part.FileName() != "" + if isFile && (name == "model" || name == "session") { + return name, true, parts + } + if isRepeatableMultipartField(name) { + continue + } + if _, dup := seen[name]; dup { + return name, true, parts + } + seen[name] = struct{}{} + if isFile || name != "session" { + continue + } + data, err := io.ReadAll(part) + if err != nil { + continue + } + if doc := TrimUTF8BOM(data); LooksLikeJSON(doc) { + if field, conflict := scanDuplicateMember(doc); conflict { + return "session." + field, true, parts + } + } + } +} diff --git a/backend/internal/pkg/requestmodel/conflict_test.go b/backend/internal/pkg/requestmodel/conflict_test.go new file mode 100644 index 000000000000..f343ab96d990 --- /dev/null +++ b/backend/internal/pkg/requestmodel/conflict_test.go @@ -0,0 +1,379 @@ +package requestmodel + +import ( + "bytes" + "encoding/json" + "fmt" + "mime/multipart" + "runtime" + "strings" + "testing" + "time" + + "github.com/stretchr/testify/require" + "github.com/tidwall/gjson" +) + +func TestConflictingFieldJSONReportsDuplicates(t *testing.T) { + tests := []struct { + name string + body string + want string + }{ + {name: "重复 model 取值不同", body: `{"model":"claude-3-5-haiku-20241022","max_tokens":64,"model":"claude-opus-4-8"}`, want: "model"}, + {name: "取值相同的重复 model", body: `{"model":"gpt-5.4","input":"hi","model":"gpt-5.4"}`, want: "model"}, + {name: "三个 model", body: `{"model":"a","model":"a","model":"b"}`, want: "model"}, + {name: "大小写变体", body: `{"model":"gpt-5.4-nano","MODEL":"gpt-5.4"}`, want: "MODEL"}, + {name: "取值相同的大小写变体", body: `{"model":"gpt-5.4","Model":"gpt-5.4"}`, want: "Model"}, + {name: "转义写法", body: `{"model":"cheap","\u006dodel":"expensive"}`, want: "model"}, + {name: "代理对转义", body: `{"\ud83d\ude00":1,"` + "\U0001F600" + `":2}`, want: "\U0001F600"}, + {name: "孤立代理项与无效 UTF-8 都解码为 U+FFFD", body: "{\"m\\ud800\":1,\"m\xff\":2}", want: "m\uFFFD"}, + {name: "长 s 折叠为 s", body: "{\"service_tier\":\"flex\",\"\u017Fervice_tier\":\"priority\"}", want: "\u017Fervice_tier"}, + {name: "开尔文符号折叠为 k", body: "{\"top_k\":1,\"top_\u212a\":2}", want: "top_\u212a"}, + {name: "service_tier 取值不同", body: `{"model":"gpt-5.4","service_tier":"default","input":"hi","service_tier":"priority"}`, want: "service_tier"}, + {name: "类型不同", body: `{"model":"cheap","model":null}`, want: "model"}, + {name: "内容字段", body: `{"messages":[],"model":"a","messages":[{"role":"user","content":"hi"}]}`, want: "messages"}, + {name: "session 内的 model", body: `{"sdp":"v=0","session":{"model":"gpt-live-a","model":"gpt-live-b"}}`, want: "session.model"}, + {name: "前导空白", body: " \n" + `{"model":"a","model":"b"}`, want: "model"}, + {name: "UTF-8 BOM", body: "\xef\xbb\xbf" + `{"model":"a","model":"b"}`, want: "model"}, + {name: "嵌套 reasoning.effort 取值不同", body: `{"model":"gpt-5.4","reasoning":{"effort":"low","effort":"xhigh"},"input":"hi"}`, want: "reasoning.effort"}, + {name: "嵌套 reasoning.effort 取值相同", body: `{"model":"gpt-5.4","reasoning":{"effort":"xhigh","effort":"xhigh"},"input":"hi"}`, want: "reasoning.effort"}, + {name: "嵌套大小写变体", body: `{"model":"gpt-5.4","input":"hi","reasoning":{"effort":"low","Effort":"xhigh"}}`, want: "reasoning.Effort"}, + {name: "output_config 大小写变体", body: `{"model":"m","output_config":{"effort":"low","EFFORT":"max"}}`, want: "output_config.EFFORT"}, + {name: "嵌套 thinking.type", body: `{"model":"m","thinking":{"type":"disabled","budget_tokens":1024,"type":"enabled"}}`, want: "thinking.type"}, + {name: "嵌套对象里的重复键", body: `{"model":"a","metadata":{"user_id":"1","user_id":"2"}}`, want: "metadata.user_id"}, + {name: "数组元素里的重复键", body: `{"messages":[{"role":"user","content":"a"},{"role":"user","role":"assistant"}]}`, want: "messages[1].role"}, + {name: "嵌套转义写法", body: `{"reasoning":{"effort":"low","\u0065ffort":"xhigh"}}`, want: "reasoning.effort"}, + {name: "深层嵌套", body: `{"a":[[{"b":{"c":1,"c":2}}]]}`, want: "a[0][0].b.c"}, + {name: "session 内嵌套", body: `{"session":{"audio":{"voice":"a","voice":"b"}}}`, want: "session.audio.voice"}, + {name: "自由键空间内的精确重复", body: `{"tools":[{"input_schema":{"properties":{"id":{},"id":{}}}}]}`, want: "tools[0].input_schema.properties.id"}, + {name: "metadata 大小写变体(Antigravity 结构体绑定)", body: `{"metadata":{"user_id":"A","USER_ID":"B"}}`, want: "metadata.USER_ID"}, + {name: "前导控制字节(gjson 当空白跳过)", body: "\x0b{\"model\":\"a\",\"model\":\"b\"}", want: "model"}, + {name: "顶层 input 仍做折叠", body: `{"input":[{"role":"user","Role":"system","content":"x"}]}`, want: "input[0].Role"}, + {name: "超深子树之后的同层重复", body: `{"model":"a","x":` + strings.Repeat("[", maxConflictDepth+5) + strings.Repeat("]", maxConflictDepth+5) + `,"model":"b"}`, want: "model"}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + got, conflict := ConflictingField("application/json", []byte(tt.body)) + require.True(t, conflict) + require.Equal(t, tt.want, got) + }) + } +} + +func TestConflictingFieldJSONAcceptsUnambiguousBodies(t *testing.T) { + tests := []struct { + name string + body string + }{ + {name: "空请求体", body: ""}, + {name: "空对象", body: `{}`}, + {name: "普通请求", body: `{"model":"a","max_tokens":1,"stream":true,"messages":[]}`}, + {name: "相近但不同的字段名", body: `{"model":"a","models":"b","model_id":"c"}`}, + {name: "兄弟对象里的同名键", body: `{"a":{"x":1},"b":{"x":2},"c":[{"x":1},{"x":2}]}`}, + {name: "父子对象同名键", body: `{"model":"m","metadata":{"model":"other"}}`}, + {name: "schema 属性大小写不同", body: `{"tools":[{"input_schema":{"type":"object","properties":{"id":{"type":"string"},"ID":{"type":"integer"}}}}]}`}, + {name: "tool_use 参数大小写不同", body: `{"messages":[{"role":"assistant","content":[{"type":"tool_use","id":"t","name":"f","input":{"path":"a","Path":"b"}}]}]}`}, + {name: "Gemini 函数参数与返回大小写不同", body: `{"contents":[{"parts":[{"functionCall":{"name":"f","args":{"k":1,"K":2}}},{"functionResponse":{"name":"f","response":{"v":1,"V":2}}}]}]}`}, + {name: "提示词模板变量大小写不同", body: `{"prompt":{"id":"p","variables":{"name":"a","Name":"b"}}}`}, + {name: "MCP 请求头大小写不同", body: `{"tools":[{"type":"mcp","headers":{"Authorization":"a","authorization":"b"}}]}`}, + {name: "dependentRequired 大小写不同", body: `{"s":{"dependentRequired":{"a":[],"A":[]}}}`}, + {name: "转义写法的自由键名", body: `{"tools":[{"input_schema":{"prop\u0065rties":{"id":{},"ID":{}}}}]}`}, + {name: "只读首个顶层值", body: `{"model":"a"}{"model":"a","model":"b"}`}, + {name: "字符串值里出现字段名", body: `{"model":"a","input":"{\"model\":\"b\",\"model\":\"c\"}"}`}, + {name: "字符串里的括号与逗号", body: `{"a":"{[,\"]}","b":"\\","c":1}`}, + {name: "顶层数组里的不同对象", body: `[{"model":"a"},{"model":"b"}]`}, + {name: "不是 JSON", body: `model=a&model=b`}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + got, conflict := ConflictingField("application/json", []byte(tt.body)) + require.False(t, conflict, got) + require.Empty(t, got) + }) + } +} + +// 回归:JSON handler 不看 Content-Type,把 JSON 请求体标成 multipart 不能绕过检查。 +func TestConflictingFieldIgnoresMultipartLabelOnJSONBody(t *testing.T) { + body := []byte(`{"model":"claude-3-5-haiku-20241022","messages":[],"model":"claude-opus-4-8"}`) + for _, contentType := range []string{"multipart/form-data", "multipart/form-data; boundary=zzz", `Multipart/Form-Data; boundary="a"`, "text/plain", ""} { + got, conflict := ConflictingField(contentType, body) + require.True(t, conflict, contentType) + require.Equal(t, "model", got) + } +} + +// 规则和它要防的解析器行为绑在一起:未报告冲突的请求体,gjson(首个、大小写 +// 敏感)和 encoding/json 结构体绑定(末值、大小写不敏感)读到的值必须一致。 +func TestConflictingFieldMatchesParserDisagreement(t *testing.T) { + tests := []struct { + body string + conflict bool + parsersDisagree bool + }{ + {body: `{"model":"first","model":"last"}`, conflict: true, parsersDisagree: true}, + {body: `{"model":"first","MODEL":"last"}`, conflict: true, parsersDisagree: true}, + {body: `{"MODEL":"first","model":"last"}`, conflict: true}, + {body: `{"model":"same","Model":"same"}`, conflict: true}, + {body: `{"model":"only","reasoning":{"effort":"low","Effort":"xhigh"}}`, conflict: true}, + {body: `{"model":"only","reasoning":{"effort":"low"}}`}, + } + for _, tt := range tests { + t.Run(tt.body, func(t *testing.T) { + var decoded struct { + Model string `json:"model"` + Reasoning struct { + Effort string `json:"effort"` + } `json:"reasoning"` + } + require.NoError(t, json.Unmarshal([]byte(tt.body), &decoded)) + first := gjson.Get(tt.body, "model").String() + require.Equal(t, tt.parsersDisagree, first != decoded.Model) + + _, conflict := ConflictingField("application/json", []byte(tt.body)) + require.Equal(t, tt.conflict, conflict) + if !conflict { + require.Equal(t, first, decoded.Model) + require.Equal(t, gjson.Get(tt.body, "reasoning.effort").String(), decoded.Reasoning.Effort) + } + }) + } +} + +func TestConflictingFieldReturnsIndependentCopy(t *testing.T) { + body := []byte(`{"outer":{"model":"a","model":"b"}}`) + got, conflict := ConflictingField("application/json", body) + require.True(t, conflict) + for i := range body { + body[i] = 'x' + } + require.Equal(t, "outer.model", got) +} + +func TestConflictingFieldManyMembersUsesIndex(t *testing.T) { + var b strings.Builder + _, _ = b.WriteString(`{"model":"m","tool":{`) + for i := 0; i < 100; i++ { + fmt.Fprintf(&b, `"k%d":%d,`, i, i) + } + body := b.String() + + got, conflict := ConflictingField("application/json", []byte(body+`"K3":3}}`)) + require.True(t, conflict, "duplicates past the linear-scan limit must be found") + require.Equal(t, "tool.K3", got) + + _, conflict = ConflictingField("application/json", []byte(body+`"k100":0}}`)) + require.False(t, conflict) +} + +// 回归:扫描是线性的,深嵌套不能放大 CPU(逐层递归时 1 MB、9990 层约 1.6 s)。 +func TestConflictingFieldDeepNestingIsLinear(t *testing.T) { + depth := maxConflictDepth - 10 + body := []byte(`{"input":` + strings.Repeat("[", depth) + `"` + strings.Repeat("a", 1<<20) + `"` + strings.Repeat("]", depth) + `}`) + start := time.Now() + _, conflict := ConflictingField("application/json", body) + require.False(t, conflict) + require.Less(t, time.Since(start), 200*time.Millisecond) + + objects := []byte(strings.Repeat(`{"a":`, maxConflictDepth+50) + "1" + strings.Repeat("}", maxConflictDepth+50)) + _, conflict = ConflictingField("application/json", objects) + require.False(t, conflict) +} + +// 回归:大对象的判重内存与请求体同一量级(逐键存字符串时峰值约为请求体的 16 倍)。 +// 64 位哈希 map 含扩容过程的累计分配约 6~7 倍,峰值约 2~3 倍。 +func TestConflictingFieldManyKeysMemoryIsBounded(t *testing.T) { + var b strings.Builder + _, _ = b.WriteString(`{"x":{`) + const keys = 1 << 20 + for i := 0; i < keys; i++ { + if i > 0 { + _ = b.WriteByte(',') + } + fmt.Fprintf(&b, `"%d":1`, i) + } + _, _ = b.WriteString(`}}`) + body := []byte(b.String()) + + var before, after runtime.MemStats + runtime.GC() + runtime.ReadMemStats(&before) + _, conflict := ConflictingField("application/json", body) + runtime.ReadMemStats(&after) + require.False(t, conflict) + require.Less(t, after.TotalAlloc-before.TotalAlloc, uint64(8*len(body))) +} + +// 回归:字符串扫描对转义数量是线性的(此前每个转义都会重扫到字符串末尾, +// 20 万个 \n 约 0.56 s)。 +func TestConflictingFieldManyEscapesIsLinear(t *testing.T) { + body := []byte(`{"model":"m","input":"` + strings.Repeat(`\n`, 1<<20) + `\\","model":"x"}`) + start := time.Now() + got, conflict := ConflictingField("application/json", body) + require.Less(t, time.Since(start), 100*time.Millisecond) + require.True(t, conflict) + require.Equal(t, "model", got) + + for _, tricky := range []string{ + `{"a":"\\","a":1}`, + `{"a":"x\\\"y","a":1}`, + `{"a":"\\\\\\\\","a":1}`, + `{"a":"\"","a":1}`, + } { + got, conflict := ConflictingField("application/json", []byte(tricky)) + require.True(t, conflict, tricky) + require.Equal(t, "a", got, tricky) + } +} + +func multipartBody(t *testing.T, fields ...[2]string) (string, []byte) { + t.Helper() + var body bytes.Buffer + writer := multipart.NewWriter(&body) + for _, field := range fields { + require.NoError(t, writer.WriteField(field[0], field[1])) + } + require.NoError(t, writer.Close()) + return writer.FormDataContentType(), body.Bytes() +} + +func TestConflictingFieldMultipart(t *testing.T) { + reject := []struct { + name string + fields [][2]string + want string + }{ + {name: "model 字段取值不同", fields: [][2]string{{"model", "gpt-image-1"}, {"prompt", "cat"}, {"model", "gpt-image-1.5"}}, want: "model"}, + {name: "model 字段取值相同", fields: [][2]string{{"model", "gpt-image-1"}, {"model", "gpt-image-1"}}, want: "model"}, + {name: "计费标量 size 重复", fields: [][2]string{{"model", "gpt-image-1"}, {"size", "1024x1024"}, {"size", "1536x1024"}}, want: "size"}, + {name: "计费标量 n 重复", fields: [][2]string{{"n", "1"}, {"n", "8"}}, want: "n"}, + {name: "session 字段重复", fields: [][2]string{{"sdp", "v=0"}, {"session", `{"model":"a"}`}, {"session", `{"model":"b"}`}}, want: "session"}, + {name: "session JSON 内的 model 重复", fields: [][2]string{{"sdp", "v=0"}, {"session", `{"model":"a","instructions":"hi","model":"b"}`}}, want: "session.model"}, + {name: "session JSON 内的嵌套重复", fields: [][2]string{{"sdp", "v=0"}, {"session", `{"model":"a","audio":{"voice":"x","voice":"y"}}`}}, want: "session.audio.voice"}, + } + for _, tt := range reject { + t.Run(tt.name, func(t *testing.T) { + contentType, body := multipartBody(t, tt.fields...) + got, conflict := ConflictingField(contentType, body) + require.True(t, conflict) + require.Equal(t, tt.want, got) + }) + } + + accept := []struct { + name string + fields [][2]string + }{ + {name: "普通表单", fields: [][2]string{{"model", "gpt-image-1"}, {"prompt", `{"model":"a","model":"b"}`}}}, + {name: "数组字段", fields: [][2]string{{"model", "whisper-1"}, {"timestamp_granularities[]", "word"}, {"timestamp_granularities[]", "segment"}}}, + {name: "多图输入", fields: [][2]string{{"model", "grok-imagine"}, {"image_url", "https://a"}, {"image_url", "https://b"}, {"image", "https://c"}, {"image", "https://d"}}}, + } + for _, tt := range accept { + t.Run(tt.name, func(t *testing.T) { + contentType, body := multipartBody(t, tt.fields...) + got, conflict := ConflictingField(contentType, body) + require.False(t, conflict, got) + }) + } +} + +func BenchmarkConflictingField(b *testing.B) { + var sb strings.Builder + _, _ = sb.WriteString(`{"model":"claude-sonnet-4-5","max_tokens":4096,"stream":true,"system":[{"type":"text","text":"sys"}],"tools":[`) + for i := 0; i < 40; i++ { + if i > 0 { + _, _ = sb.WriteString(",") + } + fmt.Fprintf(&sb, `{"name":"tool_%d","description":"%s","input_schema":{"type":"object","properties":{"path":{"type":"string"},"content":{"type":"string"}},"required":["path"]}}`, i, strings.Repeat("d", 200)) + } + _, _ = sb.WriteString(`],"messages":[`) + for i := 0; i < 200; i++ { + if i > 0 { + _, _ = sb.WriteString(",") + } + fmt.Fprintf(&sb, `{"role":"user","content":[{"type":"text","text":"%s"}]}`, strings.Repeat("t", 1000)) + } + _, _ = sb.WriteString(`]}`) + body := []byte(sb.String()) + b.SetBytes(int64(len(body))) + b.ReportAllocs() + b.ResetTimer() + for i := 0; i < b.N; i++ { + if _, conflict := ConflictingField("application/json", body); conflict { + b.Fatal("unexpected conflict") + } + } +} + +// rawMultipart 用固定 boundary 拼出原始 multipart 请求体,便于构造畸形 part。 +func rawMultipart(preamble string, parts ...string) (string, []byte) { + var b strings.Builder + _, _ = b.WriteString(preamble) + for _, part := range parts { + _, _ = b.WriteString("--BOUNDARY\r\n") + _, _ = b.WriteString(part) + _, _ = b.WriteString("\r\n") + } + _, _ = b.WriteString("--BOUNDARY--\r\n") + return "multipart/form-data; boundary=BOUNDARY", []byte(b.String()) +} + +func textPart(name, value string) string { + return "Content-Disposition: form-data; name=\"" + name + "\"\r\n\r\n" + value +} + +// 回归:multipart handler 跳过首个 boundary 之前的前导内容;前导内容是 JSON 时 +// 不能让请求体只被当成 JSON 检查,也不能让 JSON 与表单两种解读并存。 +func TestConflictingFieldMultipartPreambleAndMalformedParts(t *testing.T) { + cases := []struct { + name string + build func() (string, []byte) + want string + }{ + {name: "JSON 前导内容后的重复 n", want: "n", build: func() (string, []byte) { + return rawMultipart("{}\r\n", textPart("model", "gpt-image-2"), textPart("n", "8"), textPart("n", "1")) + }}, + {name: "JSON 前导内容与表单 model 并存", want: "Content-Type", build: func() (string, []byte) { + return rawMultipart(`{"model":"gpt-image-1-mini"}`+"\r\n", textPart("model", "gpt-image-2")) + }}, + {name: "数组前导内容", want: "Content-Type", build: func() (string, []byte) { + return rawMultipart("[]\r\n", textPart("model", "gpt-image-2")) + }}, + {name: "名为 model 的文件 part", want: "model", build: func() (string, []byte) { + return rawMultipart("", "Content-Disposition: form-data; name=\"model\"; filename=\"m.txt\"\r\n\r\ngpt-image-2") + }}, + {name: "文件与文本同名", want: "size", build: func() (string, []byte) { + return rawMultipart("", textPart("size", "1024x1024"), "Content-Disposition: form-data; name=\"size\"; filename=\"s\"\r\n\r\n1536x1024") + }}, + {name: "无法解析名字的 part", want: "Content-Disposition", build: func() (string, []byte) { + return rawMultipart("", "Content-Disposition: form-data; name=\"a\"; name=\"model\"\r\n\r\ngpt-image-2") + }}, + {name: "RFC 2231 扩展字段名", want: "Content-Disposition", build: func() (string, []byte) { + return rawMultipart("", "Content-Disposition: form-data; name=\"model\"; name*=UTF-8''prompt\r\n\r\ngpt-image-2") + }}, + {name: "分段的扩展字段名", want: "Content-Disposition", build: func() (string, []byte) { + return rawMultipart("", "Content-Disposition: form-data; name=\"model\";name*0=\"pro\"; name*1=\"mpt\"\r\n\r\ngpt-image-2") + }}, + {name: "两个 Content-Disposition 头", want: "Content-Disposition", build: func() (string, []byte) { + return rawMultipart("", "Content-Disposition: form-data; name=\"prompt\"\r\nContent-Disposition: form-data; name=\"model\"\r\n\r\ngpt-image-2") + }}, + } + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + contentType, body := tc.build() + got, conflict := ConflictingField(contentType, body) + require.True(t, conflict) + require.Equal(t, tc.want, got) + }) + } + + contentType, body := rawMultipart("", textPart("model", "gpt-image-2"), textPart("prompt", "cat")) + _, conflict := ConflictingField(contentType, body) + require.False(t, conflict, "a well-formed form must pass") + + // 非 ASCII 文件名的 filename* 写法是合法的,不能误拒。 + contentType, body = rawMultipart("", textPart("model", "gpt-image-2"), "Content-Disposition: form-data; name=\"image\"; filename=\"a.png\"; filename*=UTF-8''%E5%9B%BE.png\r\nContent-Type: image/png\r\n\r\nPNG") + _, conflict = ConflictingField(contentType, body) + require.False(t, conflict, "filename* must not be treated as an extended field name") +} diff --git a/backend/internal/pkg/requestmodel/requestmodel.go b/backend/internal/pkg/requestmodel/requestmodel.go index ead8e1e27429..a9ceab22c4a0 100644 --- a/backend/internal/pkg/requestmodel/requestmodel.go +++ b/backend/internal/pkg/requestmodel/requestmodel.go @@ -44,15 +44,19 @@ func IsLiveRequestRoute(routePath string) bool { // (为空回落 session 候选)。候选包含重复键、大小写变体的全部出现。 func FromBodyCandidates(routePath, contentType string, body []byte) []string { var topLevel, session []string + if doc := TrimUTF8BOM(body); LooksLikeJSON(doc) { + // 按内容识别 JSON,不看 Content-Type:JSON handler 不校验请求头,且宽容 + // 读取会剥掉 BOM,两者都不能成为绕过准入的手段。gjson 只读首个顶层值。 + topLevel = jsonModelCandidates(doc) + session = jsonSessionModelCandidates(doc) + } if isMultipartContentType(contentType) { - // 声明为 multipart 的请求体只做 multipart 解析——gjson 的部分扫描 - // 会在 multipart 字节流里误匹配 session JSON 内的 model 字段。 + // multipart handler 跳过首个 boundary 之前的前导内容(可以是任意 JSON), + // 所以两种解读的候选都要收集。只有声明为 multipart 时才按 multipart 解析, + // 不对非 multipart 字节流做 gjson 部分扫描。 models, sessions := multipartModelCandidates(contentType, body) - topLevel = models - session = sessionModelCandidates(sessions) - } else { - topLevel = jsonModelCandidates(body) - session = jsonSessionModelCandidates(body) + topLevel = append(topLevel, models...) + session = append(session, sessionModelCandidates(sessions)...) } if IsLiveRequestRoute(routePath) { diff --git a/backend/internal/pkg/requestmodel/requestmodel_test.go b/backend/internal/pkg/requestmodel/requestmodel_test.go index 5d59a0d34320..a1636c99d4d7 100644 --- a/backend/internal/pkg/requestmodel/requestmodel_test.go +++ b/backend/internal/pkg/requestmodel/requestmodel_test.go @@ -255,3 +255,40 @@ func TestFromBodyForRouteReturnsFirstCandidate(t *testing.T) { t.Fatalf("dispatch helper keeps gjson-first semantics, got %q", got) } } + +// 回归:JSON handler 不看 Content-Type、宽容读取会剥掉 BOM,准入候选必须与之 +// 一致,否则把请求体标成 multipart 或加 BOM 就能让白名单拿不到任何模型而放行。 +func TestFromBodyCandidatesFollowsWhatJSONHandlersParse(t *testing.T) { + body := []byte(`{"model":"claude-opus-4-8","messages":[]}`) + cases := []struct { + name string + contentType string + body []byte + }{ + {name: "multipart 标签", contentType: "multipart/form-data; boundary=zzz", body: body}, + {name: "无 boundary 的 multipart 标签", contentType: "multipart/form-data", body: body}, + {name: "UTF-8 BOM", contentType: "application/json", body: append([]byte{0xEF, 0xBB, 0xBF}, body...)}, + {name: "BOM 加 multipart 标签", contentType: "multipart/form-data", body: append([]byte{0xEF, 0xBB, 0xBF}, body...)}, + } + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + got := FromBodyCandidates("/v1/messages", tc.contentType, tc.body) + if len(got) != 1 || got[0] != "claude-opus-4-8" { + t.Fatalf("candidates = %v, want [claude-opus-4-8]", got) + } + if route := FromBodyForRoute("/v1/messages", tc.contentType, tc.body); route != "claude-opus-4-8" { + t.Fatalf("route model = %q", route) + } + }) + } +} + +// 回归:multipart handler 跳过首个 boundary 之前的前导内容,前导内容是 JSON 时 +// 白名单必须同时看到表单里的 model,不能只取 JSON 解读。 +func TestFromBodyCandidatesMultipartWithJSONPreamble(t *testing.T) { + body := []byte("{}\r\n--B\r\nContent-Disposition: form-data; name=\"model\"\r\n\r\ngpt-image-2\r\n--B--\r\n") + got := FromBodyCandidates("/v1/images/edits", "multipart/form-data; boundary=B", body) + if len(got) != 1 || got[0] != "gpt-image-2" { + t.Fatalf("candidates = %v, want [gpt-image-2]", got) + } +} diff --git a/backend/internal/pkg/websearch/exa.go b/backend/internal/pkg/websearch/exa.go new file mode 100644 index 000000000000..e5ed4f00b310 --- /dev/null +++ b/backend/internal/pkg/websearch/exa.go @@ -0,0 +1,112 @@ +package websearch + +import ( + "bytes" + "context" + "encoding/json" + "fmt" + "io" + "net/http" + "strings" +) + +const ( + exaSearchEndpoint = "https://api.exa.ai/search" + exaProviderName = "exa" +) + +// ExaProvider implements web search via the Exa Search API. +type ExaProvider struct { + apiKey string + httpClient *http.Client +} + +// NewExaProvider creates an Exa Search provider. +// The caller is responsible for configuring the http.Client with proxy/timeouts. +func NewExaProvider(apiKey string, httpClient *http.Client) *ExaProvider { + if httpClient == nil { + httpClient = http.DefaultClient + } + return &ExaProvider{apiKey: apiKey, httpClient: httpClient} +} + +func (e *ExaProvider) Name() string { return exaProviderName } + +func (e *ExaProvider) Search(ctx context.Context, req SearchRequest) (*SearchResponse, error) { + numResults := req.MaxResults + if numResults <= 0 { + numResults = defaultMaxResults + } + + // Search type and highlight length are left to Exa's defaults. + payload := exaRequest{ + Query: req.Query, + NumResults: numResults, + Contents: exaContents{Highlights: true}, + } + + bodyBytes, err := json.Marshal(payload) + if err != nil { + return nil, fmt.Errorf("exa: encode request: %w", err) + } + + httpReq, err := http.NewRequestWithContext(ctx, http.MethodPost, exaSearchEndpoint, bytes.NewReader(bodyBytes)) + if err != nil { + return nil, fmt.Errorf("exa: build request: %w", err) + } + httpReq.Header.Set("Content-Type", "application/json") + httpReq.Header.Set("x-api-key", e.apiKey) + + resp, err := e.httpClient.Do(httpReq) + if err != nil { + return nil, fmt.Errorf("exa: request failed: %w", err) + } + defer func() { _ = resp.Body.Close() }() + + body, err := io.ReadAll(io.LimitReader(resp.Body, maxResponseSize)) + if err != nil { + return nil, fmt.Errorf("exa: read body: %w", err) + } + + if resp.StatusCode != http.StatusOK { + return nil, fmt.Errorf("exa: status %d: %s", resp.StatusCode, truncateBody(body)) + } + + var raw exaResponse + if err := json.Unmarshal(body, &raw); err != nil { + return nil, fmt.Errorf("exa: decode response: %w", err) + } + + results := make([]SearchResult, 0, len(raw.Results)) + for _, r := range raw.Results { + results = append(results, SearchResult{ + URL: r.URL, + Title: r.Title, + Snippet: strings.Join(r.Highlights, "\n"), + PageAge: r.PublishedDate, + }) + } + + return &SearchResponse{Results: results, Query: req.Query}, nil +} + +type exaRequest struct { + Query string `json:"query"` + NumResults int `json:"numResults"` + Contents exaContents `json:"contents"` +} + +type exaContents struct { + Highlights bool `json:"highlights"` +} + +type exaResponse struct { + Results []exaResult `json:"results"` +} + +type exaResult struct { + URL string `json:"url"` + Title string `json:"title"` + PublishedDate string `json:"publishedDate"` + Highlights []string `json:"highlights"` +} diff --git a/backend/internal/pkg/websearch/exa_test.go b/backend/internal/pkg/websearch/exa_test.go new file mode 100644 index 000000000000..d18d8742b469 --- /dev/null +++ b/backend/internal/pkg/websearch/exa_test.go @@ -0,0 +1,91 @@ +package websearch + +import ( + "context" + "encoding/json" + "io" + "net/http" + "strings" + "testing" + + "github.com/stretchr/testify/require" +) + +type exaRoundTripFunc func(*http.Request) (*http.Response, error) + +func (f exaRoundTripFunc) RoundTrip(r *http.Request) (*http.Response, error) { return f(r) } + +func exaTestClient(status int, body string, seen *http.Request, seenBody *[]byte) *http.Client { + return &http.Client{Transport: exaRoundTripFunc(func(r *http.Request) (*http.Response, error) { + *seen = *r + b, _ := io.ReadAll(r.Body) + *seenBody = b + return &http.Response{ + StatusCode: status, + Body: io.NopCloser(strings.NewReader(body)), + Header: make(http.Header), + }, nil + })} +} + +func TestExaProvider_Name(t *testing.T) { + require.Equal(t, "exa", NewExaProvider("key", nil).Name()) +} + +func TestManagerBuildsExaProvider(t *testing.T) { + p := (&Manager{}).buildProvider(ProviderConfig{Type: ProviderTypeExa, APIKey: "k"}, nil) + require.IsType(t, &ExaProvider{}, p) +} + +func TestExaProvider_Search(t *testing.T) { + var seen http.Request + var seenBody []byte + resp := `{"requestId":"r1","results":[` + + `{"url":"https://go.dev","title":"Go","publishedDate":"2026-10-01T00:00:00.000Z","highlights":["Go is a language.","It compiles fast."]},` + + `{"url":"https://example.com","title":"Example","publishedDate":null,"highlights":[]}]}` + p := NewExaProvider("exa-key", exaTestClient(http.StatusOK, resp, &seen, &seenBody)) + + out, err := p.Search(context.Background(), SearchRequest{Query: "golang", MaxResults: 3}) + + require.NoError(t, err) + require.Equal(t, http.MethodPost, seen.Method) + require.Equal(t, "https://api.exa.ai/search", seen.URL.String()) + require.Equal(t, "exa-key", seen.Header.Get("x-api-key")) + require.Equal(t, "application/json", seen.Header.Get("Content-Type")) + var body map[string]any + require.NoError(t, json.Unmarshal(seenBody, &body)) + require.Equal(t, map[string]any{ + "query": "golang", + "numResults": float64(3), + "contents": map[string]any{"highlights": true}, + }, body) + + require.Equal(t, "golang", out.Query) + require.Equal(t, []SearchResult{ + {URL: "https://go.dev", Title: "Go", Snippet: "Go is a language.\nIt compiles fast.", PageAge: "2026-10-01T00:00:00.000Z"}, + {URL: "https://example.com", Title: "Example"}, + }, out.Results) +} + +func TestExaProvider_SearchDefaultsNumResults(t *testing.T) { + var seen http.Request + var seenBody []byte + p := NewExaProvider("k", exaTestClient(http.StatusOK, `{"results":[]}`, &seen, &seenBody)) + + _, err := p.Search(context.Background(), SearchRequest{Query: "q"}) + + require.NoError(t, err) + var body map[string]any + require.NoError(t, json.Unmarshal(seenBody, &body)) + require.Equal(t, float64(defaultMaxResults), body["numResults"]) +} + +func TestExaProvider_SearchHTTPError(t *testing.T) { + var seen http.Request + var seenBody []byte + p := NewExaProvider("bad", exaTestClient(http.StatusUnauthorized, `{"error":"invalid api key"}`, &seen, &seenBody)) + + _, err := p.Search(context.Background(), SearchRequest{Query: "q"}) + + require.ErrorContains(t, err, "exa: status 401") +} diff --git a/backend/internal/pkg/websearch/manager.go b/backend/internal/pkg/websearch/manager.go index f317c3909d59..1839308db146 100644 --- a/backend/internal/pkg/websearch/manager.go +++ b/backend/internal/pkg/websearch/manager.go @@ -21,7 +21,7 @@ import ( // ProviderConfig holds the configuration for a single search provider. type ProviderConfig struct { - Type string `json:"type"` // ProviderTypeBrave | ProviderTypeTavily | ProviderTypeDeepSeek + Type string `json:"type"` // ProviderTypeBrave | ProviderTypeTavily | ProviderTypeDeepSeek | ProviderTypeExa APIKey string `json:"api_key"` // secret QuotaLimit int64 `json:"quota_limit"` // 0 = unlimited SubscribedAt *int64 `json:"subscribed_at,omitempty"` // subscription start (unix seconds); quota resets monthly from this date @@ -466,6 +466,8 @@ func (m *Manager) buildProvider(cfg ProviderConfig, client *http.Client) Provide return NewDeepSeekProvider(cfg.APIKey, client) case tavilyProviderName: return NewTavilyProvider(cfg.APIKey, client) + case exaProviderName: + return NewExaProvider(cfg.APIKey, client) default: slog.Warn("websearch: unknown provider type, falling back to brave", "type", cfg.Type) diff --git a/backend/internal/pkg/websearch/provider.go b/backend/internal/pkg/websearch/provider.go index b9abd959c4ee..c75f7d460cc1 100644 --- a/backend/internal/pkg/websearch/provider.go +++ b/backend/internal/pkg/websearch/provider.go @@ -4,7 +4,7 @@ import "context" // Provider is the interface every search backend must implement. type Provider interface { - // Name returns the provider identifier ("brave", "tavily", or "deepseek"). + // Name returns the provider identifier ("brave", "tavily", "deepseek", or "exa"). Name() string // Search executes a web search and returns results. Search(ctx context.Context, req SearchRequest) (*SearchResponse, error) diff --git a/backend/internal/pkg/websearch/types.go b/backend/internal/pkg/websearch/types.go index ada68936731b..5dbeca8bda54 100644 --- a/backend/internal/pkg/websearch/types.go +++ b/backend/internal/pkg/websearch/types.go @@ -28,4 +28,5 @@ const ( ProviderTypeBrave = "brave" ProviderTypeDeepSeek = "deepseek" ProviderTypeTavily = "tavily" + ProviderTypeExa = "exa" ) diff --git a/backend/internal/repository/account_repo.go b/backend/internal/repository/account_repo.go index 3dbcdfdcd17f..6d7ed4644589 100644 --- a/backend/internal/repository/account_repo.go +++ b/backend/internal/repository/account_repo.go @@ -2049,6 +2049,29 @@ func (r *accountRepository) UpdateGrokOAuthCredentialsIfUnchanged( expectedCredentials map[string]any, expectedProxyID *int64, credentials map[string]any, +) (bool, error) { + return r.updateOAuthCredentialsIfUnchanged(ctx, id, service.PlatformGrok, expectedCredentials, expectedProxyID, credentials) +} + +// UpdateOpenAIOAuthCredentialsIfUnchanged preserves a completed token rotation +// without overwriting concurrent reauthorization or writing to a credential shadow. +func (r *accountRepository) UpdateOpenAIOAuthCredentialsIfUnchanged( + ctx context.Context, + id int64, + expectedCredentials map[string]any, + expectedProxyID *int64, + credentials map[string]any, +) (bool, error) { + return r.updateOAuthCredentialsIfUnchanged(ctx, id, service.PlatformOpenAI, expectedCredentials, expectedProxyID, credentials) +} + +func (r *accountRepository) updateOAuthCredentialsIfUnchanged( + ctx context.Context, + id int64, + platform string, + expectedCredentials map[string]any, + expectedProxyID *int64, + credentials map[string]any, ) (bool, error) { if r == nil || r.sql == nil { return false, errors.New("account repository SQL executor is not configured") @@ -2072,6 +2095,7 @@ func (r *accountRepository) UpdateGrokOAuthCredentialsIfUnchanged( AND a.type = $4 AND a.credentials = $5::jsonb AND a.proxy_id IS NOT DISTINCT FROM $6 + AND ($3 <> 'openai' OR a.parent_account_id IS NULL) RETURNING a.id ) INSERT INTO scheduler_outbox (event_type, account_id, group_id, payload) @@ -2079,7 +2103,7 @@ func (r *accountRepository) UpdateGrokOAuthCredentialsIfUnchanged( `, string(credentialsJSON), id, - service.PlatformGrok, + platform, service.AccountTypeOAuth, string(expectedJSON), expectedProxyID, diff --git a/backend/internal/repository/account_repo_temp_unsched_test.go b/backend/internal/repository/account_repo_temp_unsched_test.go index 9853e272ba1a..df226b1cb3c4 100644 --- a/backend/internal/repository/account_repo_temp_unsched_test.go +++ b/backend/internal/repository/account_repo_temp_unsched_test.go @@ -4,6 +4,7 @@ import ( "context" "database/sql" "database/sql/driver" + "errors" "regexp" "strings" "testing" @@ -258,9 +259,83 @@ func TestAccountRepository_UpdateGrokOAuthCredentialsIfUnchanged_UsesExactAttemp require.Contains(t, normalized, "proxy_id IS NOT DISTINCT FROM $6") require.Contains(t, normalized, "INSERT INTO scheduler_outbox") require.Len(t, exec.execArgs[0], 7) + require.Equal(t, service.PlatformGrok, exec.execArgs[0][2]) require.Equal(t, &proxyID, exec.execArgs[0][5]) } +func TestAccountRepository_UpdateOpenAIOAuthCredentialsIfUnchanged_UsesExactAttemptStateAndAtomicOutbox(t *testing.T) { + exec := &recordingSQLExecutor{result: rowsAffectedResult(1)} + repo := newAccountRepositoryWithSQL(nil, exec, nil) + proxyID := int64(29) + + applied, err := repo.UpdateOpenAIOAuthCredentialsIfUnchanged( + context.Background(), + 42, + map[string]any{"refresh_token": "attempted", "_token_version": int64(9)}, + &proxyID, + map[string]any{"refresh_token": "rotated", "_token_version": int64(10)}, + ) + + require.NoError(t, err) + require.True(t, applied) + require.Len(t, exec.execQueries, 1, "credential update and outbox insertion must share one SQL statement") + normalized := normalizeSQLWhitespace(exec.execQueries[0]) + require.Contains(t, normalized, "WITH updated AS ( UPDATE accounts AS a SET credentials = $1::jsonb") + require.Contains(t, normalized, "a.deleted_at IS NULL") + require.Contains(t, normalized, "a.platform = $3") + require.Contains(t, normalized, "a.type = $4") + require.Contains(t, normalized, "a.credentials = $5::jsonb") + require.Contains(t, normalized, "a.proxy_id IS NOT DISTINCT FROM $6") + require.Contains(t, normalized, "($3 <> 'openai' OR a.parent_account_id IS NULL)") + require.Contains(t, normalized, "RETURNING a.id ) INSERT INTO scheduler_outbox") + require.Contains(t, normalized, "SELECT $7, updated.id, NULL, NULL FROM updated") + require.Len(t, exec.execArgs[0], 7) + arg0, ok := exec.execArgs[0][0].(string) + require.True(t, ok) + require.JSONEq(t, `{"refresh_token":"rotated","_token_version":10}`, arg0) + require.Equal(t, int64(42), exec.execArgs[0][1]) + require.Equal(t, service.PlatformOpenAI, exec.execArgs[0][2]) + require.Equal(t, service.AccountTypeOAuth, exec.execArgs[0][3]) + arg4, ok := exec.execArgs[0][4].(string) + require.True(t, ok) + require.JSONEq(t, `{"refresh_token":"attempted","_token_version":9}`, arg4) + require.Equal(t, &proxyID, exec.execArgs[0][5]) + require.Equal(t, service.SchedulerOutboxEventAccountChanged, exec.execArgs[0][6]) +} + +func TestAccountRepository_UpdateOpenAIOAuthCredentialsIfUnchanged_NoMatchDoesNotApply(t *testing.T) { + exec := &recordingSQLExecutor{result: rowsAffectedResult(0)} + repo := newAccountRepositoryWithSQL(nil, exec, nil) + + applied, err := repo.UpdateOpenAIOAuthCredentialsIfUnchanged( + context.Background(), 42, map[string]any{"refresh_token": "attempted"}, nil, + map[string]any{"refresh_token": "rotated"}, + ) + + require.NoError(t, err) + require.False(t, applied) + require.Len(t, exec.execQueries, 1) + require.Nil(t, exec.execArgs[0][5], "a nil proxy must match only a database NULL proxy") + require.Contains(t, normalizeSQLWhitespace(exec.execQueries[0]), "SELECT $7, updated.id, NULL, NULL FROM updated", + "a CAS miss must not insert an independent invalidation event") +} + +func TestAccountRepository_UpdateOpenAIOAuthCredentialsIfUnchanged_OutboxFailureDoesNotReportSuccess(t *testing.T) { + outboxErr := errors.New("scheduler outbox insert failed") + exec := &recordingSQLExecutor{err: outboxErr} + repo := newAccountRepositoryWithSQL(nil, exec, nil) + + applied, err := repo.UpdateOpenAIOAuthCredentialsIfUnchanged( + context.Background(), 42, map[string]any{"refresh_token": "attempted"}, nil, + map[string]any{"refresh_token": "rotated"}, + ) + + require.ErrorIs(t, err, outboxErr) + require.False(t, applied) + require.Len(t, exec.execQueries, 1) + require.Contains(t, normalizeSQLWhitespace(exec.execQueries[0]), "INSERT INTO scheduler_outbox") +} + func TestAccountRepository_ListOAuthRefreshCandidatePage_SQLFilter(t *testing.T) { db, mock, err := sqlmock.New(sqlmock.QueryMatcherOption(sqlmock.QueryMatcherRegexp)) require.NoError(t, err) diff --git a/backend/internal/repository/custom_admin_key_review_test.go b/backend/internal/repository/custom_admin_key_review_test.go index e7a0057fdbd5..b14ad569344a 100644 --- a/backend/internal/repository/custom_admin_key_review_test.go +++ b/backend/internal/repository/custom_admin_key_review_test.go @@ -45,7 +45,7 @@ func TestScopedAdminReviewGroupPriorityAndStatus(t *testing.T) { cache := &scopedReviewSchedulerCache{accounts: make(map[int64]*service.Account)} repo := NewAdminAccountRepository(client, db, cache) groups := NewAdminGroupRepository(client, db) - admin := service.NewAdminService(nil, nil, groups, repo, nil, nil, nil, nil, nil, nil, nil, nil, nil, client, nil, nil, nil, nil, nil, nil, nil, nil, nil) + admin := service.NewAdminService(nil, nil, groups, repo, nil, nil, nil, nil, nil, nil, nil, nil, nil, client, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil) scoped := admin.(service.ScopedAdminAccounts) ctx := context.Background() a, err := client.Group.Create().SetName("授权组").Save(ctx) diff --git a/backend/internal/repository/ops_repo_openai_token_stats.go b/backend/internal/repository/ops_repo_openai_token_stats.go index d700c5af83aa..99dd338a3905 100644 --- a/backend/internal/repository/ops_repo_openai_token_stats.go +++ b/backend/internal/repository/ops_repo_openai_token_stats.go @@ -39,12 +39,8 @@ WITH stats AS ( ul.model AS model, COUNT(*)::bigint AS request_count, ROUND( - AVG( - CASE - WHEN ul.duration_ms > 0 AND ul.output_tokens > 0 - THEN ul.output_tokens * 1000.0 / ul.duration_ms - END - )::numeric, + 1000.0 * (SUM(ul.output_tokens) FILTER (WHERE ul.duration_ms > 0 AND ul.output_tokens > 0)) + / (SUM(ul.duration_ms) FILTER (WHERE ul.duration_ms > 0 AND ul.output_tokens > 0)), 2 )::float8 AS avg_tokens_per_sec, ROUND(AVG(ul.first_token_ms)::numeric, 2)::float8 AS avg_first_token_ms, diff --git a/backend/internal/repository/ops_repo_openai_token_stats_integration_test.go b/backend/internal/repository/ops_repo_openai_token_stats_integration_test.go new file mode 100644 index 000000000000..68483482f109 --- /dev/null +++ b/backend/internal/repository/ops_repo_openai_token_stats_integration_test.go @@ -0,0 +1,66 @@ +//go:build integration + +package repository + +import ( + "context" + "testing" + "time" + + "github.com/Wei-Shaw/sub2api/internal/service" + "github.com/stretchr/testify/require" +) + +func TestOpsRepositoryGetOpenAITokenStats_WeightsRateByDuration(t *testing.T) { + ctx := context.Background() + client := testEntClient(t) + user := mustCreateUser(t, client, &service.User{}) + group := mustCreateGroup(t, client, &service.Group{Name: "ops-token-stats"}) + account := mustCreateAccount(t, client, &service.Account{Name: "ops-token-stats"}) + key := mustCreateApiKey(t, client, &service.APIKey{UserID: user.ID}) + t.Cleanup(func() { + _, err := integrationDB.ExecContext(ctx, "DELETE FROM usage_logs WHERE group_id = $1", group.ID) + require.NoError(t, err) + _, err = integrationDB.ExecContext(ctx, "DELETE FROM api_keys WHERE id = $1", key.ID) + require.NoError(t, err) + _, err = integrationDB.ExecContext(ctx, "DELETE FROM accounts WHERE id = $1", account.ID) + require.NoError(t, err) + _, err = integrationDB.ExecContext(ctx, "DELETE FROM groups WHERE id = $1", group.ID) + require.NoError(t, err) + _, err = integrationDB.ExecContext(ctx, "DELETE FROM users WHERE id = $1", user.ID) + require.NoError(t, err) + }) + + now := time.Now().UTC() + _, err := integrationDB.ExecContext(ctx, ` +INSERT INTO usage_logs (user_id, api_key_id, account_id, group_id, created_at, model, output_tokens, duration_ms) +VALUES + ($1, $2, $3, $4, $5, 'gpt-mixed-durations', 100, 1000), + ($1, $2, $3, $4, $5, 'gpt-mixed-durations', 100, 4000), + ($1, $2, $3, $4, $5, 'gpt-mixed-durations', 0, 9000), + ($1, $2, $3, $4, $5, 'gpt-mixed-durations', 10, 0), + ($1, $2, $3, $4, $5, 'gpt-mixed-durations', 7, NULL), + ($1, $2, $3, $4, $5, 'gpt-no-valid-samples', 0, 1000) +`, user.ID, key.ID, account.ID, group.ID, now) + require.NoError(t, err) + + repo := NewOpsRepository(integrationDB) + stats, err := repo.GetOpenAITokenStats(ctx, &service.OpsOpenAITokenStatsFilter{ + StartTime: now.Add(-time.Minute), + EndTime: now.Add(time.Minute), + GroupID: &group.ID, + TopN: 10, + }) + require.NoError(t, err) + require.Len(t, stats.Items, 2) + + mixed := stats.Items[0] + require.Equal(t, "gpt-mixed-durations", mixed.Model) + require.NotNil(t, mixed.AvgTokensPerSec) + require.Equal(t, 40.0, *mixed.AvgTokensPerSec) + require.Equal(t, int64(5), mixed.RequestCount) + require.Equal(t, int64(217), mixed.TotalOutputTokens) + + require.Equal(t, "gpt-no-valid-samples", stats.Items[1].Model) + require.Nil(t, stats.Items[1].AvgTokensPerSec) +} diff --git a/backend/internal/repository/scheduler_cache.go b/backend/internal/repository/scheduler_cache.go index 38be882abc5c..7342c06931bf 100644 --- a/backend/internal/repository/scheduler_cache.go +++ b/backend/internal/repository/scheduler_cache.go @@ -1456,6 +1456,10 @@ func newSchedulerAccountMetaRevision() string { } func marshalSchedulerCacheAccount(account service.Account) ([]byte, []byte, error) { + // Hydration needs account configuration and group membership, not expanded + // group objects (also repeated in AccountGroups). Keep the caller's graph intact. + account.Groups = nil + account.AccountGroups = filterSchedulerAccountGroups(account.AccountGroups) fullPayload, err := json.Marshal(account) if err != nil { return nil, nil, fmt.Errorf("marshal account: %w", err) diff --git a/backend/internal/repository/scheduler_cache_integration_test.go b/backend/internal/repository/scheduler_cache_integration_test.go index 52673315c895..063521397ba2 100644 --- a/backend/internal/repository/scheduler_cache_integration_test.go +++ b/backend/internal/repository/scheduler_cache_integration_test.go @@ -57,6 +57,7 @@ func TestSchedulerCacheSnapshotUsesSlimMetadataButKeepsFullAccount(t *testing.T) SessionWindowEnd: &windowEnd, SessionWindowStatus: "active", GroupIDs: []int64{bucket.GroupID}, + Groups: []*service.Group{{ID: bucket.GroupID, Description: strings.Repeat("unused group configuration", 1024)}}, AccountGroups: []service.AccountGroup{ { AccountID: 101, @@ -101,8 +102,14 @@ func TestSchedulerCacheSnapshotUsesSlimMetadataButKeepsFullAccount(t *testing.T) require.NotNil(t, full) require.Equal(t, "secret-access-token", full.GetCredential("access_token")) require.Equal(t, strings.Repeat("x", 4096), full.GetCredential("huge_blob")) + require.Equal(t, account.GroupIDs, full.GroupIDs) + require.Empty(t, full.Groups) require.Len(t, full.AccountGroups, 1) - require.NotNil(t, full.AccountGroups[0].Group) + require.Equal(t, account.ID, full.AccountGroups[0].AccountID) + require.Equal(t, bucket.GroupID, full.AccountGroups[0].GroupID) + require.Equal(t, 5, full.AccountGroups[0].Priority) + require.Nil(t, full.AccountGroups[0].Group) + require.Nil(t, full.AccountGroups[0].Account) } func TestSchedulerCacheRetireAndReopenFencesOldEpochIntegration(t *testing.T) { diff --git a/backend/internal/repository/scheduler_cache_payload_unit_test.go b/backend/internal/repository/scheduler_cache_payload_unit_test.go new file mode 100644 index 000000000000..8802bccbafba --- /dev/null +++ b/backend/internal/repository/scheduler_cache_payload_unit_test.go @@ -0,0 +1,116 @@ +//go:build unit + +package repository + +import ( + "context" + "encoding/json" + "fmt" + "strconv" + "strings" + "testing" + "time" + + "github.com/Wei-Shaw/sub2api/internal/service" + "github.com/stretchr/testify/require" +) + +func TestSchedulerCacheAccountOmitsExpandedGroups(t *testing.T) { + for _, groupCount := range []int{1, 10, 100, 241} { + t.Run(strconv.Itoa(groupCount), func(t *testing.T) { + ctx := context.Background() + cache := newSchedulerCacheUnit(t) + now := time.Date(2026, time.November, 16, 12, 0, 0, 0, time.UTC) + resetAt := now.Add(time.Hour) + rate := 0.0 + proxyID := int64(5) + expected := service.Account{ + ID: 8842, Name: "multi-group", Platform: service.PlatformOpenAI, + Type: service.AccountTypeOAuth, Status: service.StatusActive, Schedulable: true, + Credentials: map[string]any{ + "access_token": "fixture-access", "refresh_token": "fixture-refresh", + "openai_capabilities": []any{"responses"}, + "model_mapping": map[string]any{"public-model": "upstream-model"}, + }, + Extra: map[string]any{"custom_account_setting": "keep", "openai_oauth_passthrough": true}, + ProxyID: &proxyID, Proxy: &service.Proxy{ID: proxyID, Protocol: "http", Host: "proxy.example", Port: 8080}, + Concurrency: 3, Priority: 7, RateMultiplier: &rate, + RateLimitResetAt: &resetAt, LastUsedAt: &now, + CreatedAt: now, UpdatedAt: now, + } + for i := 1; i <= groupCount; i++ { + expected.GroupIDs = append(expected.GroupIDs, int64(i)) + expected.AccountGroups = append(expected.AccountGroups, service.AccountGroup{ + AccountID: expected.ID, GroupID: int64(i), Priority: i, CreatedAt: now, + }) + } + account := expected + account.AccountGroups = append([]service.AccountGroup(nil), expected.AccountGroups...) + for i := range account.AccountGroups { + group := &service.Group{ + ID: int64(i + 1), Name: fmt.Sprintf("group-%d", i+1), + Description: strings.Repeat("unused group configuration ", 128), + } + account.Groups = append(account.Groups, group) + account.AccountGroups[i].Group = group + account.AccountGroups[i].Account = &service.Account{ID: account.ID, Name: "unused account edge"} + } + original, err := json.Marshal(account) + require.NoError(t, err) + + // Both account updates and bucket rebuilds write the same global record. + for _, write := range []string{"account", "snapshot"} { + t.Run(write, func(t *testing.T) { + if write == "account" { + require.NoError(t, cache.SetAccount(ctx, &account)) + } else { + bucket := service.SchedulerBucket{GroupID: 1, Platform: account.Platform, Mode: service.SchedulerModeSingle} + token, err := cache.CaptureBucketWriteToken(ctx, bucket) + require.NoError(t, err) + require.NoError(t, cache.SetSnapshot(ctx, bucket, token, []service.Account{account})) + snapshot, hit, err := cache.GetSnapshot(ctx, bucket) + require.NoError(t, err) + require.True(t, hit) + require.Len(t, snapshot, 1) + require.Equal(t, expected.GroupIDs, snapshot[0].GroupIDs) + require.Equal(t, expected.AccountGroups, snapshot[0].AccountGroups) + } + full, err := cache.GetAccount(ctx, account.ID) + require.NoError(t, err) + require.NotNil(t, full) + require.Zero(t, len(full.Groups), "full cache must omit expanded groups") + for _, membership := range full.AccountGroups { + require.True(t, membership.Group == nil && membership.Account == nil, "full cache must omit relationship objects") + } + require.Equal(t, &expected, full, "hydration must retain account configuration and membership") + payload, err := cache.rdb.Get(ctx, schedulerAccountKey(strconv.FormatInt(account.ID, 10))).Bytes() + require.NoError(t, err) + require.NotContains(t, string(payload), "unused group configuration") + require.NotContains(t, string(payload), "unused account edge") + require.Less(t, len(payload)*4, len(original)) + t.Logf("groups=%d expanded_bytes=%d cached_bytes=%d", groupCount, len(original), len(payload)) + }) + } + + // Serialization must not detach relationships from the repository's object. + after, err := json.Marshal(account) + require.NoError(t, err) + require.Equal(t, original, after) + }) + } +} + +func TestSchedulerCacheReadsLegacyExpandedGroups(t *testing.T) { + ctx := context.Background() + cache := newSchedulerCacheUnit(t) + account := service.Account{ + ID: 8843, GroupIDs: []int64{2}, Groups: []*service.Group{{ID: 2, Name: "legacy"}}, + AccountGroups: []service.AccountGroup{{AccountID: 8843, GroupID: 2, Priority: 4, Group: &service.Group{ID: 2}}}, + } + payload, err := json.Marshal(account) + require.NoError(t, err) + require.NoError(t, cache.rdb.Set(ctx, schedulerAccountKey("8843"), payload, 0).Err()) + full, err := cache.GetAccount(ctx, account.ID) + require.NoError(t, err) + require.Equal(t, &account, full, "rolling upgrades can still read records written by old instances") +} diff --git a/backend/internal/repository/scheduler_cache_unit_test.go b/backend/internal/repository/scheduler_cache_unit_test.go index b59164d1232d..46ed663ab6e4 100644 --- a/backend/internal/repository/scheduler_cache_unit_test.go +++ b/backend/internal/repository/scheduler_cache_unit_test.go @@ -315,7 +315,6 @@ func TestMarshalSchedulerCacheAccountKeepsEncodingJSONWireFormat(t *testing.T) { Credentials: map[string]any{}, Extra: map[string]any{}, GroupIDs: []int64{}, - Groups: []*service.Group{}, }}, {name: "nested maps and escaping", account: service.Account{ ID: 803, diff --git a/backend/internal/securityaudit/coordinator.go b/backend/internal/securityaudit/coordinator.go index ddca0e1c2257..7a1fe001f3a0 100644 --- a/backend/internal/securityaudit/coordinator.go +++ b/backend/internal/securityaudit/coordinator.go @@ -14,6 +14,8 @@ type LegacyEngine interface { type PromptEngine interface { EffectiveMode() Mode + // Enqueue borrows req read-only for this call; implementations must copy + // any request memory retained after returning. Enqueue(ctx context.Context, req Request) error Evaluate(ctx context.Context, req Request) (*PromptDecision, error) } @@ -82,7 +84,7 @@ func (c *Coordinator) Check(ctx context.Context, req Request) (decision Decision case ModeAsync: // Enqueue is deliberately best-effort. The implementation owns a bounded // context and copies request memory before it can outlive the Handler. - _ = c.prompt.Enqueue(ctx, req.Clone()) + _ = c.prompt.Enqueue(ctx, req) legacy, _ := c.checkLegacy(ctx, req) return prioritize(legacy, nil) case ModeBlocking: diff --git a/backend/internal/securityaudit/prompt_memory_optimization_test.go b/backend/internal/securityaudit/prompt_memory_optimization_test.go new file mode 100644 index 000000000000..5ed1178958d6 --- /dev/null +++ b/backend/internal/securityaudit/prompt_memory_optimization_test.go @@ -0,0 +1,225 @@ +package securityaudit + +import ( + "context" + "math/rand" + "runtime" + "strings" + "sync" + "sync/atomic" + "testing" + + "github.com/stretchr/testify/require" +) + +func memoryTestPromptService(cfg ActiveConfig, repo JobRepository) *PromptService { + store := &fakeConfigStore{cfg: cfg, active: true} + metrics := NewAtomicMetrics() + return &PromptService{config: store, metrics: metrics, background: context.Background(), enqueueSlots: make(chan struct{}, 128), + enqueuer: NewEnqueuer(store, repo, &fakePayloadStore{}, metrics)} +} + +func TestAsyncAuditOutOfScopeSkipsLargeBodyCopy(t *testing.T) { + cfg := asyncConfig() + cfg.AllGroups = false + cfg.GroupIDs = []int64{1} + groupID := int64(2) + svc := memoryTestPromptService(cfg, &fakeJobRepository{}) + req := Request{GroupID: &groupID, Protocol: "openai_responses", Body: []byte(`{"input":"` + strings.Repeat("x", 1<<20) + `"}`)} + runtime.GC() + var before, after runtime.MemStats + runtime.ReadMemStats(&before) + decision := NewCoordinator(nil, svc).Check(context.Background(), req) + svc.enqueueWG.Wait() + runtime.ReadMemStats(&after) + require.True(t, decision.AllowNextStage) + require.Less(t, after.TotalAlloc-before.TotalAlloc, uint64(len(req.Body)/2), "out-of-scope audit must not copy the body") + runtime.KeepAlive(req) +} + +func TestTrimRunesMatchesOriginalWithoutAllocatingTheWholePrompt(t *testing.T) { + for _, value := range []string{"", "abc", "中文😀suffix", "a\xff\xfebc", strings.Repeat("x", 1<<20)} { + for _, limit := range []int{0, 1, 3, 96} { + want := "" + if limit > 0 { + runes := []rune(value) + want = value + if len(runes) > limit { + want = string(runes[:limit]) + "…" + } + } + require.Equal(t, want, TrimRunes(value, limit)) + } + } + value := strings.Repeat("x", 1<<20) + var before, after runtime.MemStats + runtime.ReadMemStats(&before) + out := TrimRunes(value, 96) + runtime.ReadMemStats(&after) + require.Less(t, after.TotalAlloc-before.TotalAlloc, uint64(64<<10)) + runtime.KeepAlive(out) +} + +func TestSplitRunesPreservesChunksWithoutWholeTranscriptCopies(t *testing.T) { + for _, value := range []string{"", "abcdef", "中文😀suffix", "a\xff\xfebc", "abc" + promptAuditPrioritySeparator + "中文😀"} { + for _, limit := range []int{1, 3, 4000} { + want := []string{} + for _, segment := range strings.Split(value, promptAuditPrioritySeparator) { + runes := []rune(segment) + for start := 0; start < len(runes); start += limit { + want = append(want, string(runes[start:min(start+limit, len(runes))])) + } + } + require.Equal(t, want, SplitRunes(value, limit)) + } + } + value := strings.Repeat("x", 1<<20) + var before, after runtime.MemStats + runtime.ReadMemStats(&before) + chunks := SplitRunes(value, 4000) + runtime.ReadMemStats(&after) + require.Equal(t, value, strings.Join(chunks, "")) + require.Less(t, after.TotalAlloc-before.TotalAlloc, uint64(64<<10)) + runtime.KeepAlive(chunks) +} + +func TestRedactPreviewPreservesCompleteInputReplacementOrder(t *testing.T) { + for _, value := range []string{ + "Bearer abcdefghijklmnop token=abcdefghijkl USER_CANARY_example user@example.org +86 138 1234 5678", + strings.Repeat("x", 1<<20), + strings.Repeat("前缀😀", 40) + " Bearer abcdefghijklmnop", + "short password:abcdefghijkl suffix", + } { + want := bearerPattern.ReplaceAllString(value, "Bearer ***") + want = apiKeyPattern.ReplaceAllStringFunc(want, func(match string) string { + if index := strings.IndexAny(match, ":= \t"); index >= 0 { + return match[:index+1] + "***" + } + return "***" + }) + want = canaryPattern.ReplaceAllString(want, "${1}***") + want = emailPattern.ReplaceAllString(want, "***@***") + want = phonePattern.ReplaceAllString(want, "***PHONE***") + require.Equal(t, TrimRunes(want, 96), RedactPreview(value, 96)) + } + value := strings.Repeat("x", 1<<20) + var before, after runtime.MemStats + runtime.ReadMemStats(&before) + out := RedactPreview(value, 96) + runtime.ReadMemStats(&after) + require.Less(t, after.TotalAlloc-before.TotalAlloc, uint64(64<<10)) + runtime.KeepAlive(out) +} + +type memoryTestGatedConfig struct { + *fakeConfigStore + reads atomic.Int32 + resume <-chan struct{} +} + +func (c *memoryTestGatedConfig) Active() (ActiveConfig, bool) { + if c.reads.Add(1) >= 2 { + <-c.resume + } + return c.fakeConfigStore.Active() +} + +type memoryTestLegacyMutation struct{ mutate func(Request) } + +func (l memoryTestLegacyMutation) Check(_ context.Context, req Request) (*LegacyDecision, error) { + l.mutate(req) + return &LegacyDecision{Allowed: true}, nil +} + +func TestAsyncAuditOwnsCopyBeforeLegacyOrHandlerCanMutateInput(t *testing.T) { + cfg := asyncConfig() + cfg.AllGroups = false + cfg.GroupIDs = []int64{1} + resume := make(chan struct{}) + store := &memoryTestGatedConfig{fakeConfigStore: &fakeConfigStore{cfg: cfg, active: true}, resume: resume} + repo := &fakeJobRepository{} + svc := memoryTestPromptService(cfg, repo) + svc.config, svc.enqueuer.config = store, store + groupID := int64(1) + req := asyncRequest() + req.GroupID = &groupID + want, err := ExtractPromptSnapshot(req) + require.NoError(t, err) + legacy := memoryTestLegacyMutation{mutate: func(borrowed Request) { + borrowed.Body[0] = '!' + *borrowed.GroupID = 2 + close(resume) + }} + decision := NewCoordinator(legacy, svc).Check(context.Background(), req) + svc.enqueueWG.Wait() + require.True(t, decision.AllowNextStage) + require.Equal(t, AuditMetricsSnapshot{Enqueued: 1}, svc.metrics.AuditSnapshot()) + require.Equal(t, want.PromptHash, repo.createdSnapshot.PromptHash) + require.Equal(t, int64(1), *repo.createdSnapshot.GroupID) +} + +func TestAsyncAuditConcurrentRequestsStillEnqueueWithoutNewDrops(t *testing.T) { + svc := memoryTestPromptService(asyncConfig(), &fakeJobRepository{}) + coordinator := NewCoordinator(nil, svc) + req := asyncRequest() + var callers sync.WaitGroup + for i := 0; i < 8; i++ { + callers.Add(1) + go func() { defer callers.Done(); coordinator.Check(context.Background(), req) }() + } + callers.Wait() + svc.enqueueWG.Wait() + require.Equal(t, AuditMetricsSnapshot{Enqueued: 8}, svc.metrics.AuditSnapshot()) +} + +func originalTrimRunesForMemoryTest(value string, limit int) string { + if limit <= 0 { + return "" + } + runes := []rune(value) + if len(runes) <= limit { + return value + } + return string(runes[:limit]) + "…" +} + +func originalRedactForMemoryTest(value string, limit int) string { + value = bearerPattern.ReplaceAllString(value, "Bearer ***") + value = apiKeyPattern.ReplaceAllStringFunc(value, func(match string) string { + if index := strings.IndexAny(match, ":= \t"); index >= 0 { + return match[:index+1] + "***" + } + return "***" + }) + value = canaryPattern.ReplaceAllString(value, "${1}***") + value = emailPattern.ReplaceAllString(value, "***@***") + value = phonePattern.ReplaceAllString(value, "***PHONE***") + return originalTrimRunesForMemoryTest(value, limit) +} + +func TestAuditTextOptimizationsMatchOriginalOnDeterministicCorpus(t *testing.T) { + rng := rand.New(rand.NewSource(20261111)) + atoms := []string{"x", "中文", "😀", " ", "\xff\xfe", "\x00", "Bearer abcdefghijklmnop", " secret:abcdefghijkl ", " user@example.org ", " +86 138 1234 5678 ", promptAuditPrioritySeparator} + for sample := 0; sample < 100; sample++ { + var builder strings.Builder + for n := rng.Intn(128); n > 0; n-- { + _, _ = builder.WriteString(atoms[rng.Intn(len(atoms))]) + } + value := builder.String() + for _, limit := range []int{0, 1, 24, 96, 4000} { + require.Equal(t, originalTrimRunesForMemoryTest(value, limit), TrimRunes(value, limit)) + require.Equal(t, originalRedactForMemoryTest(value, limit), RedactPreview(value, limit)) + var want []string + if limit > 0 { + want = []string{} + for _, segment := range strings.Split(value, promptAuditPrioritySeparator) { + runes := []rune(segment) + for start := 0; start < len(runes); start += limit { + want = append(want, string(runes[start:min(start+limit, len(runes))])) + } + } + } + require.Equal(t, want, SplitRunes(value, limit)) + } + } +} diff --git a/backend/internal/securityaudit/prompt_scanner.go b/backend/internal/securityaudit/prompt_scanner.go index 103d10045429..232fcf422c11 100644 --- a/backend/internal/securityaudit/prompt_scanner.go +++ b/backend/internal/securityaudit/prompt_scanner.go @@ -5,6 +5,7 @@ import ( "sort" "strings" "time" + "unicode/utf8" ) func SplitRunes(value string, limit int) []string { @@ -14,18 +15,28 @@ func SplitRunes(value string, limit int) []string { segments := strings.Split(value, promptAuditPrioritySeparator) chunks := make([]string, 0, len(segments)) for _, segment := range segments { - runes := []rune(segment) - for start := 0; start < len(runes); start += limit { - end := start + limit - if end > len(runes) { - end = len(runes) + start, count := 0, 0 + for end := range segment { + if count == limit { + chunks = append(chunks, promptScanChunk(segment[start:end])) + start, count = end, 0 } - chunks = append(chunks, string(runes[start:end])) + count++ + } + if start < len(segment) { + chunks = append(chunks, promptScanChunk(segment[start:])) } } return chunks } +func promptScanChunk(value string) string { + if utf8.ValidString(value) { + return value // immutable substring; no full-transcript rune buffer/copy + } + return string([]rune(value)) // preserve the previous invalid-UTF-8 behavior +} + func AggregateResults(results []*NormalizedResult, latency time.Duration) (*NormalizedResult, error) { if len(results) == 0 { return nil, errors.New("prompt guard produced no complete result") diff --git a/backend/internal/securityaudit/prompt_service.go b/backend/internal/securityaudit/prompt_service.go index 211df6cdc4a0..f8bee73b9f82 100644 --- a/backend/internal/securityaudit/prompt_service.go +++ b/backend/internal/securityaudit/prompt_service.go @@ -120,6 +120,21 @@ func (s *PromptService) Enqueue(ctx context.Context, req Request) error { if req.NoBodyRetention { return s.enqueueRecovered(req) } + // Enqueuer rechecks configuration before persistence. Check it here too so + // requests outside the audit scope never copy their potentially large body. + cfg, ok := s.config.Active() + if !ok || cfg.EffectiveMode() != ModeAsync { + return nil + } + if !cfg.IncludesGroup(req.GroupID) { + LogInfo(EventEnqueueSkipped, mergeLogFields(requestLogFields(req), map[string]any{"config_version": cfg.ConfigVersion, "status": "skipped", "error_code": "group_out_of_scope"})) + return nil + } + if len(cfg.EnabledEndpoints()) == 0 { + s.enqueuer.recordDropped() + LogWarn(EventEnqueueDropped, mergeLogFields(requestLogFields(req), map[string]any{"config_version": cfg.ConfigVersion, "status": "dropped", "error_code": "no_enabled_endpoint"})) + return nil + } select { case s.enqueueSlots <- struct{}{}: default: diff --git a/backend/internal/securityaudit/prompt_snapshot.go b/backend/internal/securityaudit/prompt_snapshot.go index 202a33b5f569..3cd29bf6f593 100644 --- a/backend/internal/securityaudit/prompt_snapshot.go +++ b/backend/internal/securityaudit/prompt_snapshot.go @@ -636,16 +636,29 @@ func systemPromptSegments(texts []string) []promptSegment { } func RedactPreview(value string, maxRunes int) string { - value = bearerPattern.ReplaceAllString(value, "Bearer ***") - value = apiKeyPattern.ReplaceAllStringFunc(value, func(match string) string { - if index := strings.IndexAny(match, ":= \t"); index >= 0 { - return match[:index+1] + "***" - } - return "***" - }) - value = canaryPattern.ReplaceAllString(value, "${1}***") - value = emailPattern.ReplaceAllString(value, "***@***") - value = phonePattern.ReplaceAllString(value, "***PHONE***") + // ReplaceAllString copies even an unchanged input. Most prompts do not + // match these patterns, so avoid ten full-text allocations just to build a + // short preview. Preserve the replacement order and complete-input matching. + if bearerPattern.MatchString(value) { + value = bearerPattern.ReplaceAllString(value, "Bearer ***") + } + if apiKeyPattern.MatchString(value) { + value = apiKeyPattern.ReplaceAllStringFunc(value, func(match string) string { + if index := strings.IndexAny(match, ":= \t"); index >= 0 { + return match[:index+1] + "***" + } + return "***" + }) + } + if canaryPattern.MatchString(value) { + value = canaryPattern.ReplaceAllString(value, "${1}***") + } + if emailPattern.MatchString(value) { + value = emailPattern.ReplaceAllString(value, "***@***") + } + if phonePattern.MatchString(value) { + value = phonePattern.ReplaceAllString(value, "***PHONE***") + } return TrimRunes(value, maxRunes) } @@ -713,11 +726,21 @@ func TrimRunes(value string, limit int) string { if limit <= 0 { return "" } - runes := []rune(value) - if len(runes) <= limit { - return value + count := 0 + for index := range value { + if count == limit { + // Decode only the retained prefix. Converting the entire prompt to + // []rune just to keep 96/65536 runes allocates four bytes per rune. + // Keep the old replacement behavior for invalid UTF-8 prefixes. + prefix := value[:index] + if utf8.ValidString(prefix) { + return prefix + "…" + } + return string([]rune(prefix)) + "…" + } + count++ } - return string(runes[:limit]) + "…" + return value } func stringValue(value any) string { diff --git a/backend/internal/server/api_contract_test.go b/backend/internal/server/api_contract_test.go index 2b444a66eb30..5cae3b3f9c13 100644 --- a/backend/internal/server/api_contract_test.go +++ b/backend/internal/server/api_contract_test.go @@ -1621,7 +1621,7 @@ func newContractDeps(t *testing.T) *contractDeps { settingRepo := newStubSettingRepo() settingService := service.NewSettingService(settingRepo, cfg) - adminService := service.NewAdminService(nil, userRepo, groupRepo, &accountRepo, proxyRepo, apiKeyRepo, redeemRepo, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil) + adminService := service.NewAdminService(nil, userRepo, groupRepo, &accountRepo, proxyRepo, apiKeyRepo, redeemRepo, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil) authHandler := handler.NewAuthHandler(cfg, nil, userService, settingService, nil, redeemService, nil, nil) apiKeyHandler := handler.NewAPIKeyHandler(apiKeyService) usageHandler := handler.NewUsageHandler(usageService, apiKeyService, nil, nil) diff --git a/backend/internal/server/middleware/group_model_allowlist.go b/backend/internal/server/middleware/group_model_allowlist.go index 039f285ad5b4..5855ecee82c9 100644 --- a/backend/internal/server/middleware/group_model_allowlist.go +++ b/backend/internal/server/middleware/group_model_allowlist.go @@ -1,7 +1,6 @@ package middleware import ( - "errors" "fmt" "github.com/Wei-Shaw/sub2api/internal/pkg/requesttiming" "net/http" @@ -152,15 +151,7 @@ func readAdmissionRequestBody(c *gin.Context) ([]byte, bool) { if RejectRequestBodyReadError(c, err) { return nil, false } - status := http.StatusBadRequest - message := "Failed to read request body" - var maxErr *http.MaxBytesError - if errors.As(err, &maxErr) { - status = http.StatusRequestEntityTooLarge - message = "Request body is too large" - } - c.JSON(status, gin.H{"error": gin.H{"type": "invalid_request_error", "message": message}}) - c.Abort() + AbortWithRequestBodyReadFailure(c, "group_model_allowlist", err) return nil, false } requestmodel.ResetRequestBody(c.Request, body) diff --git a/backend/internal/server/middleware/group_model_allowlist_test.go b/backend/internal/server/middleware/group_model_allowlist_test.go index 161ebe85103c..1cdb75ddc3d7 100644 --- a/backend/internal/server/middleware/group_model_allowlist_test.go +++ b/backend/internal/server/middleware/group_model_allowlist_test.go @@ -176,8 +176,9 @@ func TestGroupModelAllowlistRequestBodyTooLargePassesThrough413(t *testing.T) { if w.Code != http.StatusRequestEntityTooLarge { t.Fatalf("expected 413, got %d: %s", w.Code, w.Body.String()) } - if !strings.Contains(w.Body.String(), "Request body is too large") { - t.Fatalf("expected too-large message, got %s", w.Body.String()) + // 与 handler 读取失败时一致:Messages 入口用 Anthropic 格式,文案带上限。 + if !strings.Contains(w.Body.String(), "Request body too large, limit is 64B") || !strings.Contains(w.Body.String(), `"type":"error"`) { + t.Fatalf("expected Anthropic-shaped too-large message, got %s", w.Body.String()) } if len(*calls) != 0 { t.Fatalf("expected handler not to run, got %v", *calls) diff --git a/backend/internal/server/middleware/ingress_reject.go b/backend/internal/server/middleware/ingress_reject.go index 3c5fcd5bdefb..ad7af4d6650d 100644 --- a/backend/internal/server/middleware/ingress_reject.go +++ b/backend/internal/server/middleware/ingress_reject.go @@ -35,6 +35,8 @@ const ( IngressRejectLongContextDisabled IngressRejectReason = "long_context_disabled" IngressRejectSubagentsBlocked IngressRejectReason = "subagents_blocked" IngressRejectCodexClientRequired IngressRejectReason = "codex_client_required" + // IngressRejectConflictingRequestFields:请求体同名字段重复声明(GHSA-p3r4-jcm3-2hph)。 + IngressRejectConflictingRequestFields IngressRejectReason = "conflicting_request_fields" ) const ingressRejectReasonContextKey = "ingress_reject_reason" diff --git a/backend/internal/server/middleware/request_body_memory.go b/backend/internal/server/middleware/request_body_memory.go index d66034f996f1..d6084fd7d296 100644 --- a/backend/internal/server/middleware/request_body_memory.go +++ b/backend/internal/server/middleware/request_body_memory.go @@ -12,7 +12,7 @@ import ( // handler runs. Cancelled clients have no response body and an uncommitted // response is marked 499, matching the gateway handler's cancellation path. func RejectRequestBodyReadError(c *gin.Context, err error) bool { - if err != nil && c != nil && c.Request != nil && c.Request.Context().Err() != nil { + if err != nil && c != nil && c.Request != nil && c.Request.Context().Err() != nil && !pkghttputil.IsRequestBodyReadTimeout(err) { if !c.Writer.Written() { c.Status(499) } diff --git a/backend/internal/server/middleware/request_body_read_failure.go b/backend/internal/server/middleware/request_body_read_failure.go new file mode 100644 index 000000000000..32adbdb2dee0 --- /dev/null +++ b/backend/internal/server/middleware/request_body_read_failure.go @@ -0,0 +1,27 @@ +package middleware + +import ( + "github.com/Wei-Shaw/sub2api/internal/pkg/httputil" + "github.com/Wei-Shaw/sub2api/internal/pkg/logger" + "github.com/gin-gonic/gin" + "go.uber.org/zap" +) + +// AbortWithRequestBodyReadFailure writes the shared response for a failed body +// read in middleware that inspects the body before the handler. It applies the +// same classification, client message, protocol-shaped error body and +// payload-free diagnostics as the gateway handlers, so a body read in +// middleware fails exactly as it would in the handler. +func AbortWithRequestBodyReadFailure(c *gin.Context, component string, err error) { + failure := httputil.DescribeRequestBodyReadFailure(c.Request, err) + if failure.Kind != httputil.RequestBodyReadErrorMaxBytes { + logRequestBodyReadFailure(c, component, failure) + } + writeGatewayInvalidRequest(c, failure.Status, failure.ClientMessage()) + c.Abort() +} + +func logRequestBodyReadFailure(c *gin.Context, component string, failure httputil.RequestBodyReadFailure) { + fields := append([]zap.Field{zap.String("component", component)}, failure.LogFields()...) + logger.FromContext(c.Request.Context()).Warn("read request body failed", fields...) +} diff --git a/backend/internal/server/middleware/request_field_conflict.go b/backend/internal/server/middleware/request_field_conflict.go new file mode 100644 index 000000000000..5655955e09f8 --- /dev/null +++ b/backend/internal/server/middleware/request_field_conflict.go @@ -0,0 +1,95 @@ +package middleware + +import ( + "fmt" + "net/http" + "strings" + + "github.com/Wei-Shaw/sub2api/internal/pkg/httputil" + "github.com/Wei-Shaw/sub2api/internal/pkg/requestmodel" + + "github.com/gin-gonic/gin" +) + +// RejectConflictingRequestFields 拒绝「同名字段重复声明」的网关请求。 +// +// 挂载位置:每条网关链的 GroupModelAllowlist 之后、compositeTarget 之前, +// 白名单对不在名单内的模型仍按原有格式拒绝。与白名单准入不同,这里对所有分组 +// 生效:重复 model 键让计费模型(gjson 取第一个)和实际转发的模型 +// (encoding/json 重新序列化后取最后一个)分叉,和分组是否开启白名单无关; +// service_tier、reasoning.effort 等按首个值做计费/策略判断、由 sjson 只改首个的 +// 字段也是如此(GHSA-p3r4-jcm3-2hph)。 +// +// 行为: +// - 只检查带请求体的方法(POST/PUT/PATCH)。 +// - JSON 按内容识别(不看 Content-Type),开头的 UTF-8 BOM 在这里剥掉后回填 +// (PrereadBody,下游零拷贝重读),与 handler 宽容读取的规则一致,保证 +// 合成路由、handler 与这里检查的是同一份字节。 +// - 判定规则见 requestmodel.ConflictingField;不是 JSON 也不是 multipart 的 +// 请求体放行,交给 handler 自己校验。 +// - 拒绝:按入口协议格式返回 400,标记 ingress 拒绝原因 +// conflicting_request_fields,请求不会进入合成路由、调度和计费。 +// +// Responses WebSocket 的帧不经过这里,由 ResponsesWebSocket 对每一帧执行同一规则。 +func RejectConflictingRequestFields() gin.HandlerFunc { + return func(c *gin.Context) { + if c.Request == nil || c.Request.Body == nil || c.Request.Body == http.NoBody { + c.Next() + return + } + switch c.Request.Method { + case http.MethodPost, http.MethodPut, http.MethodPatch: + default: + c.Next() + return + } + + body, err := httputil.ReadRequestBodyWithPrealloc(c.Request) + if err != nil { + if RejectRequestBodyReadError(c, err) { + return + } + AbortWithRequestBodyReadFailure(c, "middleware.request_field_conflict", err) + return + } + if doc := requestmodel.TrimUTF8BOM(body); len(doc) != len(body) && requestmodel.LooksLikeJSON(doc) { + body = doc + } + requestmodel.ResetRequestBody(c.Request, body) + + field, conflict := requestmodel.ConflictingField(c.GetHeader("Content-Type"), body) + if !conflict { + c.Next() + return + } + MarkIngressRejected(c, IngressRejectConflictingRequestFields) + // 字段名来自客户端请求体,回显时加引号并限制在 64 个字符以内。 + writeGatewayInvalidRequest(c, http.StatusBadRequest, fmt.Sprintf("Request body declares field %.64q more than once", field)) + c.Abort() + } +} + +// writeGatewayInvalidRequest 按入口协议输出 invalid_request_error: +// Gemini 原生(/v1beta、/antigravity/v1beta)用 Google 格式,Messages 入口用 +// Anthropic 格式,其余用 OpenAI 格式。协议划分与 groupModelAllowlistErrorWriter +// 相同;不复用它,是因为现有的 Anthropic / OpenAI 写入器把非 404/403 的状态写成 +// api_error / model_not_found。 +func writeGatewayInvalidRequest(c *gin.Context, status int, message string) { + path := "" + if c.Request != nil && c.Request.URL != nil { + path = c.Request.URL.Path + } + switch { + case strings.HasPrefix(path, "/v1beta") || strings.HasPrefix(path, "/antigravity/v1beta"): + GoogleErrorWriter(c, status, message) + case strings.Contains(path, "/messages"): + c.JSON(status, gin.H{ + "type": "error", + "error": gin.H{"type": "invalid_request_error", "message": message}, + }) + default: + c.JSON(status, gin.H{ + "error": gin.H{"type": "invalid_request_error", "message": message}, + }) + } +} diff --git a/backend/internal/server/middleware/request_field_conflict_test.go b/backend/internal/server/middleware/request_field_conflict_test.go new file mode 100644 index 000000000000..9dec9e247d34 --- /dev/null +++ b/backend/internal/server/middleware/request_field_conflict_test.go @@ -0,0 +1,282 @@ +package middleware + +import ( + "bytes" + "mime/multipart" + "net/http" + "net/http/httptest" + "strings" + "testing" + + "github.com/Wei-Shaw/sub2api/internal/pkg/httputil" + "github.com/Wei-Shaw/sub2api/internal/service" + + "github.com/gin-gonic/gin" +) + +// newRequestFieldConflictTestRouter 按网关链的顺序挂载:白名单准入在前, +// 字段歧义拒绝在后。handlerBodies 记录 handler 实际读到的请求体。 +func newRequestFieldConflictTestRouter(apiKey *service.APIKey) (*gin.Engine, *[]string) { + gin.SetMode(gin.TestMode) + router := gin.New() + var handlerBodies []string + router.Use(func(c *gin.Context) { + if apiKey != nil { + c.Set(string(ContextKeyAPIKey), apiKey) + } + c.Next() + }) + router.Use(GroupModelAllowlist()) + router.Use(RejectConflictingRequestFields()) + handler := func(c *gin.Context) { + body, _ := httputil.ReadRequestBodyWithPrealloc(c.Request) + handlerBodies = append(handlerBodies, string(body)) + c.Status(http.StatusOK) + } + for _, path := range []string{ + "/v1/messages", "/v1/responses", "/v1/chat/completions", "/v1/images/edits", "/v1/live", + "/v1beta/models/*modelAction", + } { + router.POST(path, handler) + } + router.GET("/v1/models", handler) + return router, &handlerBodies +} + +// 复现报告的请求体:第一个 model 是便宜模型,最后一个是贵模型。分组没有开启 +// 白名单时旧行为是放行并按第一个计费,现在必须在进入 handler 之前拒绝。 +func TestRejectConflictingRequestFieldsBlocksDisagreeingModelWithoutAllowlist(t *testing.T) { + for _, apiKey := range []*service.APIKey{nil, {}, allowlistAPIKey(false)} { + router, handlerBodies := newRequestFieldConflictTestRouter(apiKey) + + w := doJSON(t, router, http.MethodPost, "/v1/responses", + `{"model":"gpt-5.4-nano","stream":false,"input":"hi","model":"gpt-5.4"}`) + if w.Code != http.StatusBadRequest { + t.Fatalf("conflicting model keys must be rejected, got %d: %s", w.Code, w.Body.String()) + } + if !strings.Contains(w.Body.String(), `\"model\"`) || !strings.Contains(w.Body.String(), "invalid_request_error") { + t.Fatalf("expected the field name and invalid_request_error, got %s", w.Body.String()) + } + if len(*handlerBodies) != 0 { + t.Fatalf("expected handler not to run, got %v", *handlerBodies) + } + } +} + +// 白名单开启且两个模型都在名单内时,白名单会放行;字段歧义检查仍要拒绝, +// 否则计费模型和转发模型照样分叉。 +func TestRejectConflictingRequestFieldsBlocksEvenWhenAllCandidatesAllowlisted(t *testing.T) { + router, handlerBodies := newRequestFieldConflictTestRouter(allowlistAPIKey(true, "claude-3-5-haiku-20241022", "claude-opus-4-8")) + + w := doJSON(t, router, http.MethodPost, "/v1/messages", + `{"model":"claude-3-5-haiku-20241022","max_tokens":64,"messages":[{"role":"user","content":"hi"}],"model":"claude-opus-4-8"}`) + if w.Code != http.StatusBadRequest { + t.Fatalf("conflicting model keys must be rejected, got %d: %s", w.Code, w.Body.String()) + } + if len(*handlerBodies) != 0 { + t.Fatalf("expected handler not to run, got %v", *handlerBodies) + } +} + +func TestRejectConflictingRequestFieldsCoversOtherFields(t *testing.T) { + router, handlerBodies := newRequestFieldConflictTestRouter(allowlistAPIKey(false)) + + for _, body := range []string{ + `{"model":"gpt-5.4","service_tier":"default","input":"hi","service_tier":"priority"}`, + `{"model":"gpt-5.4","Model":"gpt-5.4-nano"}`, + `{"model":"gpt-5.4","messages":[],"messages":[{"role":"user","content":"hi"}]}`, + } { + w := doJSON(t, router, http.MethodPost, "/v1/chat/completions", body) + if w.Code != http.StatusBadRequest { + t.Fatalf("body %s must be rejected, got %d: %s", body, w.Code, w.Body.String()) + } + } + if len(*handlerBodies) != 0 { + t.Fatalf("expected handler not to run, got %v", *handlerBodies) + } +} + +func TestRejectConflictingRequestFieldsErrorFormats(t *testing.T) { + router, _ := newRequestFieldConflictTestRouter(allowlistAPIKey(false)) + body := `{"model":"a","contents":[],"model":"b"}` + + openai := doJSON(t, router, http.MethodPost, "/v1/responses", body) + if !strings.Contains(openai.Body.String(), `"error":{"message"`) || strings.Contains(openai.Body.String(), "model_not_found") { + t.Fatalf("unexpected OpenAI error format: %s", openai.Body.String()) + } + anthropic := doJSON(t, router, http.MethodPost, "/v1/messages", body) + if !strings.Contains(anthropic.Body.String(), `"type":"error"`) || !strings.Contains(anthropic.Body.String(), `"type":"invalid_request_error"`) { + t.Fatalf("unexpected Anthropic error format: %s", anthropic.Body.String()) + } + google := doJSON(t, router, http.MethodPost, "/v1beta/models/gemini-2.5-pro:generateContent", body) + if google.Code != http.StatusBadRequest || !strings.Contains(google.Body.String(), `"status":"INVALID_ARGUMENT"`) { + t.Fatalf("unexpected Google error format: %d %s", google.Code, google.Body.String()) + } +} + +// 普通请求体和非对象请求体都放行,handler 读到的请求体与客户端发送的完全一致。 +func TestRejectConflictingRequestFieldsPassesUnambiguousBodiesUnchanged(t *testing.T) { + for _, body := range []string{ + `{"model":"gpt-5.4","input":"hi"}`, + `{"model":"gpt-5.4","prompt":{"id":"p","variables":{"k":"1","K":"1"}}}`, + `not json`, + ``, + } { + router, handlerBodies := newRequestFieldConflictTestRouter(allowlistAPIKey(false)) + w := doJSON(t, router, http.MethodPost, "/v1/responses", body) + if w.Code != http.StatusOK { + t.Fatalf("body %q should pass, got %d: %s", body, w.Code, w.Body.String()) + } + if len(*handlerBodies) != 1 || (*handlerBodies)[0] != body { + t.Fatalf("handler must read the original body %q, got %v", body, *handlerBodies) + } + } +} + +func TestRejectConflictingRequestFieldsMultipart(t *testing.T) { + send := func(models ...string) *httptest.ResponseRecorder { + router, _ := newRequestFieldConflictTestRouter(allowlistAPIKey(false)) + var body bytes.Buffer + writer := multipart.NewWriter(&body) + for _, model := range models { + _ = writer.WriteField("model", model) + } + _ = writer.WriteField("prompt", "cat") + _ = writer.Close() + req := httptest.NewRequest(http.MethodPost, "/v1/images/edits", &body) + req.Header.Set("Content-Type", writer.FormDataContentType()) + w := httptest.NewRecorder() + router.ServeHTTP(w, req) + return w + } + + if w := send("gpt-image-1", "gpt-image-1.5"); w.Code != http.StatusBadRequest { + t.Fatalf("conflicting multipart model fields must be rejected, got %d: %s", w.Code, w.Body.String()) + } + if w := send("gpt-image-1", "gpt-image-1"); w.Code != http.StatusBadRequest { + t.Fatalf("repeated multipart model fields must be rejected even when identical, got %d: %s", w.Code, w.Body.String()) + } + if w := send("gpt-image-1"); w.Code != http.StatusOK { + t.Fatalf("single multipart model field should pass, got %d: %s", w.Code, w.Body.String()) + } +} + +func TestRejectConflictingRequestFieldsLiveSessionModel(t *testing.T) { + router, _ := newRequestFieldConflictTestRouter(allowlistAPIKey(false)) + + w := doJSON(t, router, http.MethodPost, "/v1/live", `{"sdp":"v=0","session":{"model":"gpt-live-a","model":"gpt-live-b"}}`) + if w.Code != http.StatusBadRequest || !strings.Contains(w.Body.String(), "session.model") { + t.Fatalf("conflicting session.model must be rejected, got %d: %s", w.Code, w.Body.String()) + } +} + +// GET/DELETE 不带需要检查的请求体:中间件不读取,直接放行。 +func TestRejectConflictingRequestFieldsDoesNotReadBodylessMethods(t *testing.T) { + gin.SetMode(gin.TestMode) + router := gin.New() + router.Use(RejectConflictingRequestFields()) + called := false + router.GET("/v1/models", func(c *gin.Context) { + called = true + c.Status(http.StatusOK) + }) + + body := &readTrackingBody{Reader: strings.NewReader(`{"model":"a","model":"b"}`)} + req := httptest.NewRequest(http.MethodGet, "/v1/models", body) + w := httptest.NewRecorder() + router.ServeHTTP(w, req) + + if w.Code != http.StatusOK || !called { + t.Fatalf("GET must reach the handler, got %d", w.Code) + } + if body.read { + t.Fatal("middleware must not read the body of a GET request") + } +} + +// 413 传递:请求体超过上限时保持现有的 413 响应,不被改写成 400。 +func TestRejectConflictingRequestFieldsRequestBodyTooLargePassesThrough413(t *testing.T) { + router, handlerBodies := newRequestFieldConflictTestRouter(allowlistAPIKey(false)) + + bigBody := `{"model":"a","padding":"` + strings.Repeat("x", 512) + `","model":"b"}` + req := httptest.NewRequest(http.MethodPost, "/v1/messages", strings.NewReader(bigBody)) + req.Header.Set("Content-Type", "application/json") + req.Body = http.MaxBytesReader(httptest.NewRecorder(), req.Body, 64) + w := httptest.NewRecorder() + router.ServeHTTP(w, req) + + if w.Code != http.StatusRequestEntityTooLarge { + t.Fatalf("expected 413, got %d: %s", w.Code, w.Body.String()) + } + // 与 handler 读取失败时一致:Messages 入口用 Anthropic 格式,文案带上限。 + if !strings.Contains(w.Body.String(), `"type":"error"`) || !strings.Contains(w.Body.String(), "Request body too large, limit is 64B") { + t.Fatalf("expected an Anthropic-shaped 413 naming the limit, got %s", w.Body.String()) + } + if len(*handlerBodies) != 0 { + t.Fatalf("expected handler not to run, got %v", *handlerBodies) + } +} + +// 取值相同的重复字段同样拒绝:网关的 sjson 改写(推理强度降级、模型映射、 +// fast policy 删除 service_tier)只改首个,改写后两者就会分叉。 +func TestRejectConflictingRequestFieldsRejectsIdenticalDuplicates(t *testing.T) { + for _, body := range []string{ + `{"model":"gpt-5.4","input":"hi","model":"gpt-5.4"}`, + `{"model":"gpt-5.4","input":"hi","reasoning":{"effort":"xhigh","effort":"xhigh"}}`, + `{"model":"gpt-5.4","service_tier":"priority","input":"hi","service_tier":"priority"}`, + } { + router, handlerBodies := newRequestFieldConflictTestRouter(allowlistAPIKey(false)) + w := doJSON(t, router, http.MethodPost, "/v1/responses", body) + if w.Code != http.StatusBadRequest || len(*handlerBodies) != 0 { + t.Fatalf("body %q must be rejected before the handler, got %d: %s", body, w.Code, w.Body.String()) + } + } +} + +// JSON handler 不看 Content-Type:把 JSON 请求体标成 multipart 不能绕过检查。 +func TestRejectConflictingRequestFieldsIgnoresMultipartLabelOnJSONBody(t *testing.T) { + for _, contentType := range []string{"multipart/form-data", "multipart/form-data; boundary=zzz", "text/plain"} { + router, handlerBodies := newRequestFieldConflictTestRouter(allowlistAPIKey(false)) + req := httptest.NewRequest(http.MethodPost, "/v1/messages", strings.NewReader(`{"model":"haiku","messages":[],"model":"opus"}`)) + req.Header.Set("Content-Type", contentType) + w := httptest.NewRecorder() + router.ServeHTTP(w, req) + if w.Code != http.StatusBadRequest || len(*handlerBodies) != 0 { + t.Fatalf("Content-Type %q must not bypass the check, got %d: %s", contentType, w.Code, w.Body.String()) + } + } +} + +// BOM 在这里剥掉后回填:合成路由与 handler 读到的是本层检查过的同一份字节。 +func TestRejectConflictingRequestFieldsStripsBOMForDownstream(t *testing.T) { + router, handlerBodies := newRequestFieldConflictTestRouter(allowlistAPIKey(false)) + w := doJSON(t, router, http.MethodPost, "/v1/responses", "\xef\xbb\xbf"+`{"model":"gpt-5.4","input":"hi"}`) + if w.Code != http.StatusOK { + t.Fatalf("expected 200, got %d: %s", w.Code, w.Body.String()) + } + if len(*handlerBodies) != 1 || (*handlerBodies)[0] != `{"model":"gpt-5.4","input":"hi"}` { + t.Fatalf("handler must read the BOM-free body, got %q", *handlerBodies) + } + + w = doJSON(t, router, http.MethodPost, "/v1/responses", "\xef\xbb\xbf"+`{"model":"a","input":"hi","model":"b"}`) + if w.Code != http.StatusBadRequest { + t.Fatalf("BOM-prefixed duplicate must be rejected, got %d: %s", w.Code, w.Body.String()) + } +} + +func TestRejectConflictingRequestFieldsMarksIngressReject(t *testing.T) { + gin.SetMode(gin.TestMode) + router := gin.New() + var reason any + router.Use(func(c *gin.Context) { + c.Next() + reason, _ = c.Get(ingressRejectReasonContextKey) + }) + router.Use(RejectConflictingRequestFields()) + router.POST("/v1/responses", func(c *gin.Context) { c.Status(http.StatusOK) }) + + w := doJSON(t, router, http.MethodPost, "/v1/responses", `{"model":"a","model":"b"}`) + if w.Code != http.StatusBadRequest || reason != IngressRejectConflictingRequestFields { + t.Fatalf("expected 400 with ingress reason %q, got %d reason=%v", IngressRejectConflictingRequestFields, w.Code, reason) + } +} diff --git a/backend/internal/server/routes/composite_platform_test.go b/backend/internal/server/routes/composite_platform_test.go index 7f61feecd4ab..6163c3ec0d22 100644 --- a/backend/internal/server/routes/composite_platform_test.go +++ b/backend/internal/server/routes/composite_platform_test.go @@ -466,3 +466,83 @@ func TestCompositeLiveRouteDispatchesBySessionModelNotTopLevelAlias(t *testing.T require.Equal(t, http.StatusNoContent, w.Code) } + +// A route that rewrites the model to a Claude 5.5 model also rewrites a +// thinking mode that model rejects into the nearest one it accepts; a route +// that keeps the client's model leaves thinking as the client sent it. +func TestCompositeTargetPlatformMiddlewareAdaptsThinkingToRewrittenModel(t *testing.T) { + cases := []struct { + name string + publicModel string + upstreamModel string + thinking string + wantThinking string + }{ + { + name: "enabled becomes adaptive on opus 5.5", + publicModel: "claude-sonnet-5", + upstreamModel: "claude-opus-5-5", + thinking: `{"type":"enabled","budget_tokens":4096}`, + wantThinking: `{"type":"adaptive"}`, + }, + { + name: "disabled becomes between_tools on sonnet 5.5", + publicModel: "claude-sonnet-5", + upstreamModel: "claude-sonnet-5-5", + thinking: `{"type":"disabled"}`, + wantThinking: `{"type":"between_tools"}`, + }, + { + name: "model not rewritten keeps enabled", + publicModel: "claude-opus-5-5", + upstreamModel: "claude-opus-5-5", + thinking: `{"type":"enabled","budget_tokens":4096}`, + wantThinking: `{"type":"enabled","budget_tokens":4096}`, + }, + } + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + gin.SetMode(gin.TestMode) + router := gin.New() + resolver := service.NewCompositeRouteResolver(compositeRouteRepoStub{ + routes: []service.CompositeModelRoute{{ + ID: 1, + GroupID: 1, + PublicModel: tc.publicModel, + MatchType: service.CompositeRouteMatchExact, + TargetPlatform: service.PlatformAnthropic, + UpstreamModel: tc.upstreamModel, + Endpoint: service.CompositeRouteEndpointAny, + Priority: 100, + Enabled: true, + }}, + }) + router.Use(gin.HandlerFunc(servermiddleware.APIKeyAuthMiddleware(func(c *gin.Context) { + groupID := int64(1) + c.Set(string(servermiddleware.ContextKeyAPIKey), &service.APIKey{ + GroupID: &groupID, + Group: &service.Group{ID: groupID, Platform: service.PlatformComposite}, + }) + c.Next() + }))) + router.Use(compositeTargetPlatformMiddleware(resolver)) + router.POST("/v1/messages", func(c *gin.Context) { + body, err := io.ReadAll(c.Request.Body) + require.NoError(t, err) + require.JSONEq(t, + `{"model":"`+tc.upstreamModel+`","max_tokens":64,"thinking":`+tc.wantThinking+`,"messages":[]}`, + string(body)) + c.Status(http.StatusNoContent) + }) + + req := httptest.NewRequest(http.MethodPost, "/v1/messages", strings.NewReader( + `{"model":"`+tc.publicModel+`","max_tokens":64,"thinking":`+tc.thinking+`,"messages":[]}`)) + req.Header.Set("Content-Type", "application/json") + w := httptest.NewRecorder() + + router.ServeHTTP(w, req) + + require.Equal(t, http.StatusNoContent, w.Code) + }) + } +} diff --git a/backend/internal/server/routes/custom_admin_key_group_models_test.go b/backend/internal/server/routes/custom_admin_key_group_models_test.go index 05657e6719c4..e930461c0da5 100644 --- a/backend/internal/server/routes/custom_admin_key_group_models_test.go +++ b/backend/internal/server/routes/custom_admin_key_group_models_test.go @@ -169,7 +169,7 @@ func (r *scopedRouteAllowlistRepository) ScopedAdminUpdateGroupModels(ctx contex func TestScopedAdminRegisteredGroupModelsUseUpstreamAllowlistSemantics(t *testing.T) { gin.SetMode(gin.TestMode) repo := &scopedRouteAllowlistRepository{} - api := service.NewAdminService(nil, nil, repo, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil) + api := service.NewAdminService(nil, nil, repo, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil) settings := service.NewSettingService(nil, nil) settings.SetScopedAdminKeyRepository(&scopedRouteKeys{}) key, _, err := settings.CreateScopedAdminKey(context.Background(), service.ScopedAdminKeyInput{Name: "白名单验证", Enabled: true, Policy: adminaccess.Policy{Rules: []adminaccess.Rule{{Permissions: []string{"groups.models.read", "groups.models.write"}, GroupIDs: []int64{2}, Platforms: []string{service.PlatformOpenAI}}}}}, 9) diff --git a/backend/internal/server/routes/gateway.go b/backend/internal/server/routes/gateway.go index 7d454a7f73d0..361319fc65c9 100644 --- a/backend/internal/server/routes/gateway.go +++ b/backend/internal/server/routes/gateway.go @@ -17,7 +17,6 @@ import ( "github.com/gin-gonic/gin" "github.com/tidwall/gjson" - "github.com/tidwall/sjson" ) // RegisterGatewayRoutes 注册 API 网关路由(Claude/OpenAI/Gemini 兼容) @@ -63,6 +62,21 @@ func RegisterGatewayRoutes( bodyLimit := middleware.RequestBodyLimit(cfg.Gateway.MaxBodySize, bodyBudget) textBodyLimit := middleware.RequestBodyLimit(cfg.Gateway.TextMaxBodySize, bodyBudget) imageAdmission := middleware.ExcelBPSImageAdmission() + // 分组链上的中间件(白名单、字段歧义检查、合成路由)会在 handler 之前读完 + // 请求体,路由级的上限来不及生效;纯文本入口的上限必须在分组层按路由选择。 + textBodyRoutes := map[string]bool{ + "/v1/systemone": true, + "/v1/alpha/search": true, + "/v1/embeddings": true, + "/backend-api/codex/alpha/search": true, + } + groupBodyLimit := func(c *gin.Context) { + if textBodyRoutes[c.FullPath()] { + textBodyLimit(c) + return + } + bodyLimit(c) + } clientRequestID := middleware.ClientRequestID() opsErrorLogger := handler.OpsErrorLoggerMiddleware(opsService) var captureTraffic gin.HandlerFunc @@ -105,6 +119,11 @@ func RegisterGatewayRoutes( groupCodexCLIOnly := middleware.GroupCodexCLIOnly(settingService) groupBlockSubagents := middleware.GroupBlockSubagents() + // 请求体字段歧义拒绝:同名字段重复且取值不一致(如两个不同的 model)时, + // 计费读到的值和实际转发的值会分叉。对所有分组生效,紧跟在白名单准入之后、 + // 合成路由改写之前,白名单的拒绝响应保持不变。 + rejectConflictingFields := middleware.RejectConflictingRequestFields() + isOpenAIResponsesCompatibleGatewayPlatform := func(c *gin.Context) bool { // openai、grok 与多协议 API Key 供应商经 OpenAI 网关转发(平台清单)。 return domain.UsesOpenAIGateway(getGroupPlatform(c)) @@ -266,7 +285,7 @@ func RegisterGatewayRoutes( // API网关(Claude API兼容) gateway := r.Group("/v1") - gateway.Use(traffic, bodyLimit) + gateway.Use(traffic, groupBodyLimit) gateway.Use(clientRequestID) gateway.Use(opsErrorLogger) gateway.Use(endpointNorm) @@ -274,7 +293,7 @@ func RegisterGatewayRoutes( gateway.Use(captureTraffic) gateway.Use(imageAdmission) gateway.GET("/sub2api/billing", h.Gateway.KeyBillingInfo) - gateway.Use(groupModelAllowlist, apiKeyModelPolicy) + gateway.Use(groupModelAllowlist, rejectConflictingFields, apiKeyModelPolicy) gateway.Use(groupCodexCLIOnly, groupBlockSubagents) gateway.Use(groupAntiDistillation, groupStreamOnly) // A serverless route may proxy to an older pod before local target resolution. @@ -293,8 +312,8 @@ func RegisterGatewayRoutes( } h.Gateway.Messages(c) }) - // System One carries only JSON text, so it uses the text body limit. - gateway.POST("/systemone", textBodyLimit, h.Gateway.SystemOne) + // System One carries only JSON text; groupBodyLimit applies the text body limit. + gateway.POST("/systemone", h.Gateway.SystemOne) // /v1/messages/count_tokens: OpenAI bridges upstream, Grok estimates // locally, and Anthropic-compatible platforms retain their existing path. gateway.POST("/messages/count_tokens", countTokensHandler) @@ -322,7 +341,7 @@ func RegisterGatewayRoutes( } h.Gateway.Responses(c) })) - gateway.POST("/alpha/search", textBodyLimit, h.OpenAIGateway.AlphaSearch) + gateway.POST("/alpha/search", h.OpenAIGateway.AlphaSearch) gateway.GET("/responses", func(c *gin.Context) { h.OpenAIGateway.ResponsesWebSocket(c) }) @@ -334,7 +353,7 @@ func RegisterGatewayRoutes( } h.Gateway.ChatCompletions(c) }) - gateway.POST("/embeddings", textBodyLimit, func(c *gin.Context) { + gateway.POST("/embeddings", func(c *gin.Context) { if !isOpenAIOnlyEndpointGatewayPlatform(c) { service.MarkOpsClientBusinessLimited(c, service.OpsClientBusinessLimitedReasonLocalFeatureGate) c.JSON(http.StatusNotFound, gin.H{ @@ -449,6 +468,7 @@ func RegisterGatewayRoutes( gemini.Use(middleware.APIKeyAuthWithSubscriptionGoogle(apiKeyService, subscriptionService, cfg)) gemini.Use(captureTraffic) gemini.Use(groupModelAllowlist) + gemini.Use(rejectConflictingFields) gemini.Use(groupCodexCLIOnly, groupBlockSubagents) gemini.Use(groupStreamOnly) gemini.Use(compositeGeminiTarget) @@ -486,7 +506,7 @@ func RegisterGatewayRoutes( // 根路径别名共用中间件链:白名单准入在 apiKeyAuth 之后、compositeTarget // 之前,避免逐条路由手工维护链导致漏挂。 rootRoute := func(method, path string, limit gin.HandlerFunc, handler gin.HandlerFunc) { - r.Handle(method, path, traffic, limit, clientRequestID, opsErrorLogger, endpointNorm, gin.HandlerFunc(apiKeyAuth), captureTraffic, imageAdmission, groupModelAllowlist, apiKeyModelPolicy, groupCodexCLIOnly, groupBlockSubagents, groupAntiDistillation, groupStreamOnly, apiKeyLongContext, podRoute, compositeTarget, apiKeyLongContext, requireGroupAnthropic, handler) + r.Handle(method, path, traffic, limit, clientRequestID, opsErrorLogger, endpointNorm, gin.HandlerFunc(apiKeyAuth), captureTraffic, imageAdmission, groupModelAllowlist, rejectConflictingFields, apiKeyModelPolicy, groupCodexCLIOnly, groupBlockSubagents, groupAntiDistillation, groupStreamOnly, apiKeyLongContext, podRoute, compositeTarget, apiKeyLongContext, requireGroupAnthropic, handler) } for _, prefix := range []string{"/api/v3", "/v3", "/v1", ""} { rootRoute(http.MethodPost, prefix+"/contents/generations/tasks", bodyLimit, h.OpenAIGateway.SeedanceTasks) @@ -503,13 +523,13 @@ func RegisterGatewayRoutes( rootRoute(http.MethodGet, "/models/:model", bodyLimit, h.Gateway.Models) rootRoute(http.MethodPost, "/messages/count_tokens", bodyLimit, countTokensHandler) codexDirect := r.Group("/backend-api/codex") - codexDirect.Use(traffic, bodyLimit, clientRequestID, opsErrorLogger, endpointNorm, gin.HandlerFunc(apiKeyAuth), captureTraffic, imageAdmission, groupModelAllowlist, apiKeyModelPolicy, groupCodexCLIOnly, groupBlockSubagents, groupAntiDistillation, groupStreamOnly, apiKeyLongContext, podRoute, compositeTarget, apiKeyLongContext, requireGroupAnthropic) + codexDirect.Use(traffic, groupBodyLimit, clientRequestID, opsErrorLogger, endpointNorm, gin.HandlerFunc(apiKeyAuth), captureTraffic, imageAdmission, groupModelAllowlist, rejectConflictingFields, apiKeyModelPolicy, groupCodexCLIOnly, groupBlockSubagents, groupAntiDistillation, groupStreamOnly, apiKeyLongContext, podRoute, compositeTarget, apiKeyLongContext, requireGroupAnthropic) { codexDirect.POST("/realtime/calls", h.OpenAIGateway.Live) codexDirect.GET("/:call_id", h.OpenAIGateway.LiveSideband) codexDirect.POST("/responses", responsesHandler) codexDirect.POST("/responses/*subpath", guardResponsesSubpath(responsesHandler)) - codexDirect.POST("/alpha/search", textBodyLimit, h.OpenAIGateway.AlphaSearch) + codexDirect.POST("/alpha/search", h.OpenAIGateway.AlphaSearch) codexDirect.GET("/responses", func(c *gin.Context) { h.OpenAIGateway.ResponsesWebSocket(c) }) @@ -625,7 +645,7 @@ func RegisterGatewayRoutes( antigravityV1.Use(middleware.ForcePlatform(service.PlatformAntigravity)) antigravityV1.Use(gin.HandlerFunc(apiKeyAuth)) antigravityV1.Use(captureTraffic) - antigravityV1.Use(groupModelAllowlist, apiKeyModelPolicy) + antigravityV1.Use(groupModelAllowlist, rejectConflictingFields, apiKeyModelPolicy) antigravityV1.Use(groupCodexCLIOnly, groupBlockSubagents) antigravityV1.Use(groupStreamOnly) antigravityV1.Use(apiKeyLongContext) @@ -646,6 +666,7 @@ func RegisterGatewayRoutes( antigravityV1Beta.Use(middleware.APIKeyAuthWithSubscriptionGoogle(apiKeyService, subscriptionService, cfg)) antigravityV1Beta.Use(captureTraffic) antigravityV1Beta.Use(groupModelAllowlist) + antigravityV1Beta.Use(rejectConflictingFields) antigravityV1Beta.Use(groupCodexCLIOnly, groupBlockSubagents) antigravityV1Beta.Use(groupStreamOnly) antigravityV1Beta.Use(apiKeyLongContext) @@ -739,9 +760,7 @@ func compositeTargetPlatformMiddleware(resolver *service.CompositeRouteResolver) c.Request = c.Request.WithContext(service.WithCompositeRouteDecision(c.Request.Context(), decision)) if upstreamModel := strings.TrimSpace(decision.UpstreamModel); upstreamModel != "" && upstreamModel != model && gjson.ValidBytes(body) { if _, modelPath := requestmodel.JSONModelPathForRoute(routePath, body); modelPath != "" { - if rewritten, rewriteErr := sjson.SetBytes(body, modelPath, upstreamModel); rewriteErr == nil { - body = rewritten - } + body = service.RewriteCompositeRequestModel(body, modelPath, upstreamModel) } } } diff --git a/backend/internal/server/routes/gateway_model_allowlist_test.go b/backend/internal/server/routes/gateway_model_allowlist_test.go index cb70aabd69ec..484d0031ae48 100644 --- a/backend/internal/server/routes/gateway_model_allowlist_test.go +++ b/backend/internal/server/routes/gateway_model_allowlist_test.go @@ -79,7 +79,7 @@ func TestGatewayRoutesGroupModelAllowlistMountedOnEveryGatewayRoute(t *testing.T source := string(routeSource) // rootRoute helper:apiKeyAuth 之后、compositeTarget 之前。 - rootHelper := regexp.MustCompile(regexp.QuoteMeta(`r.Handle(method, path, traffic, limit, clientRequestID, opsErrorLogger, endpointNorm, gin.HandlerFunc(apiKeyAuth), captureTraffic, imageAdmission, groupModelAllowlist, apiKeyModelPolicy, groupCodexCLIOnly, groupBlockSubagents, groupAntiDistillation, groupStreamOnly, apiKeyLongContext, podRoute, compositeTarget, apiKeyLongContext, requireGroupAnthropic, handler)`)) + rootHelper := regexp.MustCompile(regexp.QuoteMeta(`r.Handle(method, path, traffic, limit, clientRequestID, opsErrorLogger, endpointNorm, gin.HandlerFunc(apiKeyAuth), captureTraffic, imageAdmission, groupModelAllowlist, rejectConflictingFields, apiKeyModelPolicy, groupCodexCLIOnly, groupBlockSubagents, groupAntiDistillation, groupStreamOnly, apiKeyLongContext, podRoute, compositeTarget, apiKeyLongContext, requireGroupAnthropic, handler)`)) require.Regexp(t, rootHelper, source, "root alias helper must place the allowlist after apiKeyAuth, then protection and stream-only admission before compositeTarget") @@ -89,9 +89,9 @@ func TestGatewayRoutesGroupModelAllowlistMountedOnEveryGatewayRoute(t *testing.T marker string composite string }{ - {group: "gateway", auth: "gin.HandlerFunc(apiKeyAuth)", marker: "gateway.Use(groupModelAllowlist, apiKeyModelPolicy)", composite: "gateway.Use(compositeTarget)"}, + {group: "gateway", auth: "gin.HandlerFunc(apiKeyAuth)", marker: "gateway.Use(groupModelAllowlist, rejectConflictingFields, apiKeyModelPolicy)", composite: "gateway.Use(compositeTarget)"}, {group: "gemini", auth: "middleware.APIKeyAuthWithSubscriptionGoogle(apiKeyService, subscriptionService, cfg)", marker: "gemini.Use(groupModelAllowlist)", composite: "gemini.Use(compositeGeminiTarget)"}, - {group: "antigravityV1", auth: "gin.HandlerFunc(apiKeyAuth)", marker: "antigravityV1.Use(groupModelAllowlist, apiKeyModelPolicy)", composite: "antigravityV1.Use(requireGroupAnthropic)"}, + {group: "antigravityV1", auth: "gin.HandlerFunc(apiKeyAuth)", marker: "antigravityV1.Use(groupModelAllowlist, rejectConflictingFields, apiKeyModelPolicy)", composite: "antigravityV1.Use(requireGroupAnthropic)"}, {group: "antigravityV1Beta", auth: "middleware.APIKeyAuthWithSubscriptionGoogle(apiKeyService, subscriptionService, cfg)", marker: "antigravityV1Beta.Use(groupModelAllowlist)", composite: "antigravityV1Beta.Use(requireGroupGoogle)"}, } for _, chain := range chains { @@ -104,7 +104,7 @@ func TestGatewayRoutesGroupModelAllowlistMountedOnEveryGatewayRoute(t *testing.T } // codexDirect 链是一条 Use 调用,直接断言顺序。 - codexDirect := regexp.MustCompile(regexp.QuoteMeta(`codexDirect.Use(traffic, bodyLimit, clientRequestID, opsErrorLogger, endpointNorm, gin.HandlerFunc(apiKeyAuth), captureTraffic, imageAdmission, groupModelAllowlist, apiKeyModelPolicy, groupCodexCLIOnly, groupBlockSubagents, groupAntiDistillation, groupStreamOnly, apiKeyLongContext, podRoute, compositeTarget, apiKeyLongContext, requireGroupAnthropic)`)) + codexDirect := regexp.MustCompile(regexp.QuoteMeta(`codexDirect.Use(traffic, groupBodyLimit, clientRequestID, opsErrorLogger, endpointNorm, gin.HandlerFunc(apiKeyAuth), captureTraffic, imageAdmission, groupModelAllowlist, rejectConflictingFields, apiKeyModelPolicy, groupCodexCLIOnly, groupBlockSubagents, groupAntiDistillation, groupStreamOnly, apiKeyLongContext, podRoute, compositeTarget, apiKeyLongContext, requireGroupAnthropic)`)) require.Regexp(t, codexDirect, source, "codexDirect chain must mount the allowlist after auth, then protection and stream-only admission before compositeTarget") // 所有带 apiKeyAuth 的根路径路由必须收敛到 rootRoute,避免漏挂。 diff --git a/backend/internal/server/routes/gateway_request_field_conflict_test.go b/backend/internal/server/routes/gateway_request_field_conflict_test.go new file mode 100644 index 000000000000..c0c7a149997f --- /dev/null +++ b/backend/internal/server/routes/gateway_request_field_conflict_test.go @@ -0,0 +1,230 @@ +package routes + +import ( + "net/http" + "net/http/httptest" + "os" + "regexp" + "strings" + "testing" + + "github.com/Wei-Shaw/sub2api/internal/config" + "github.com/Wei-Shaw/sub2api/internal/handler" + servermiddleware "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" +) + +// TestGatewayRoutesRejectConflictingFieldsMountedOnEveryGatewayRoute 沿用 +// gateway_model_allowlist_test.go 的源码级断言:每条网关链都必须紧跟在白名单 +// 准入之后挂载 rejectConflictingFields,这样它也在合成路由改写之前。 +func TestGatewayRoutesRejectConflictingFieldsMountedOnEveryGatewayRoute(t *testing.T) { + routeSource, err := os.ReadFile("gateway.go") + require.NoError(t, err) + source := string(routeSource) + + // 每一处白名单挂载点后面都紧跟着字段歧义拒绝,两者数量一致。 + allowlistUses := regexp.MustCompile(`(?:\.Use\(|, )groupModelAllowlist\b`).FindAllStringIndex(source, -1) + followedByConflict := regexp.MustCompile(`\bgroupModelAllowlist(\)\s+\w+\.Use\(|, )rejectConflictingFields\b`).FindAllStringIndex(source, -1) + require.Len(t, followedByConflict, len(allowlistUses), + "every chain that mounts groupModelAllowlist must mount rejectConflictingFields right after it") + require.GreaterOrEqual(t, len(followedByConflict), 6, "gateway, gemini, root aliases, codexDirect and both antigravity chains") + + // TestGatewayRoutesGroupModelAllowlistMountedOnEveryGatewayRoute separately + // verifies the position of each admission chain before target rewriting. +} + +// TestGatewayRoutesRejectConflictingFieldsCoversGatewayRoutes 用没有开启白名单 +// 的分组请求各个入口:重复声明且取值不一致的 model 必须在进入 handler 之前 +// 得到 400。分组不需要任何额外配置,这正是计费绕过的前提条件。 +func TestGatewayRoutesRejectConflictingFieldsCoversGatewayRoutes(t *testing.T) { + router := newGatewayRoutesTestRouterWithGroup(allowlistGroup(service.PlatformOpenAI, false)) + + const duplicate = `"model":"gpt-5.4-nano","input":"hi","model":"gpt-5.4"` + paths := []struct { + path string + body string + }{ + {"/responses", `{` + duplicate + `}`}, + {"/responses/compact", `{` + duplicate + `}`}, + {"/chat/completions", `{` + duplicate + `}`}, + {"/embeddings", `{` + duplicate + `}`}, + {"/images/generations", `{` + duplicate + `}`}, + {"/videos/generations", `{` + duplicate + `}`}, + {"/messages/count_tokens", `{` + duplicate + `}`}, + {"/tts", `{` + duplicate + `}`}, + {"/alpha/search", `{` + duplicate + `}`}, + {"/v1/responses", `{` + duplicate + `}`}, + {"/v1/messages", `{` + duplicate + `}`}, + {"/v1/messages/count_tokens", `{` + duplicate + `}`}, + {"/v1/chat/completions", `{` + duplicate + `}`}, + {"/v1/embeddings", `{` + duplicate + `}`}, + {"/v1/images/generations", `{` + duplicate + `}`}, + {"/v1/videos/generations", `{` + duplicate + `}`}, + {"/v1/systemone", `{` + duplicate + `}`}, + {"/v1/contents/generations/tasks", `{` + duplicate + `}`}, + {"/api/v3/contents/generations/tasks", `{` + duplicate + `}`}, + {"/v1/live", `{"sdp":"v=0","session":{"model":"gpt-live-a","model":"gpt-live-b"}}`}, + {"/backend-api/codex/responses", `{` + duplicate + `}`}, + {"/backend-api/codex/realtime/calls", `{"sdp":"v=0","session":{"model":"gpt-live-a","model":"gpt-live-b"}}`}, + {"/antigravity/v1/messages", `{` + duplicate + `}`}, + } + + for _, tc := range paths { + req := httptest.NewRequest(http.MethodPost, tc.path, strings.NewReader(tc.body)) + req.Header.Set("Content-Type", "application/json") + w := httptest.NewRecorder() + router.ServeHTTP(w, req) + + require.Equal(t, http.StatusBadRequest, w.Code, "POST %s should be rejected, got body: %s", tc.path, w.Body.String()) + require.Contains(t, w.Body.String(), "more than once", "POST %s", tc.path) + } +} + +// 白名单开启时,不在名单内的模型仍由白名单按原有格式拒绝(404),不会被这层 +// 改写成 400;两个候选都在名单内但取值不同时,由这层拒绝。 +func TestGatewayRoutesRejectConflictingFieldsKeepsAllowlistResponse(t *testing.T) { + router := newGatewayRoutesTestRouterWithGroup(allowlistGroup(service.PlatformOpenAI, true, "gpt-5.4", "gpt-5.4-nano")) + + send := func(body string) *httptest.ResponseRecorder { + req := httptest.NewRequest(http.MethodPost, "/v1/responses", strings.NewReader(body)) + req.Header.Set("Content-Type", "application/json") + w := httptest.NewRecorder() + router.ServeHTTP(w, req) + return w + } + + blocked := send(`{"model":"gpt-5.4","input":"hi","model":"gpt-4.1"}`) + require.Equal(t, http.StatusNotFound, blocked.Code, blocked.Body.String()) + require.Contains(t, blocked.Body.String(), "not available for this group") + + bothAllowed := send(`{"model":"gpt-5.4-nano","input":"hi","model":"gpt-5.4"}`) + require.Equal(t, http.StatusBadRequest, bothAllowed.Code, bothAllowed.Body.String()) + require.Contains(t, bothAllowed.Body.String(), "more than once") +} + +// 取值相同的重复字段同样拒绝:网关的 sjson 改写只改首个,改写后两者就会分叉。 +func TestGatewayRoutesRejectConflictingFieldsRejectsIdenticalDuplicates(t *testing.T) { + router := newGatewayRoutesTestRouterWithGroup(allowlistGroup(service.PlatformOpenAI, false)) + + req := httptest.NewRequest(http.MethodPost, "/v1/responses", strings.NewReader(`{"model":"gpt-5.4","input":"hi","reasoning":{"effort":"xhigh","effort":"xhigh"}}`)) + req.Header.Set("Content-Type", "application/json") + w := httptest.NewRecorder() + router.ServeHTTP(w, req) + + require.Equal(t, http.StatusBadRequest, w.Code, w.Body.String()) + require.Contains(t, w.Body.String(), "reasoning.effort") +} + +// 回归:Content-Type 标成 multipart 的 JSON 请求体,既不能绕过歧义检查,也不能 +// 绕过分组白名单(此前白名单按请求头只做 multipart 解析,拿不到模型就放行)。 +func TestGatewayRoutesMultipartLabelDoesNotBypassChecks(t *testing.T) { + send := func(group *service.Group, contentType, body string) *httptest.ResponseRecorder { + router := newGatewayRoutesTestRouterWithGroup(group) + req := httptest.NewRequest(http.MethodPost, "/v1/messages", strings.NewReader(body)) + req.Header.Set("Content-Type", contentType) + w := httptest.NewRecorder() + router.ServeHTTP(w, req) + return w + } + for _, contentType := range []string{"multipart/form-data", "multipart/form-data; boundary=zzz"} { + w := send(allowlistGroup(service.PlatformAnthropic, false), contentType, `{"model":"claude-3-5-haiku-20241022","messages":[],"model":"claude-opus-4-8"}`) + require.Equal(t, http.StatusBadRequest, w.Code, w.Body.String()) + require.Contains(t, w.Body.String(), "more than once") + + w = send(allowlistGroup(service.PlatformAnthropic, true, "claude-3-5-haiku-20241022"), contentType, `{"model":"claude-opus-4-8","messages":[]}`) + require.Equal(t, http.StatusNotFound, w.Code, w.Body.String()) + require.Contains(t, w.Body.String(), "not available for this group") + } +} + +// 回归:带 UTF-8 BOM 的请求体(handler 宽容读取会剥掉 BOM)不能绕过分组白名单。 +func TestGatewayRoutesBOMDoesNotBypassAllowlist(t *testing.T) { + router := newGatewayRoutesTestRouterWithGroup(allowlistGroup(service.PlatformAnthropic, true, "claude-3-5-haiku-20241022")) + req := httptest.NewRequest(http.MethodPost, "/v1/messages", strings.NewReader("\xef\xbb\xbf"+`{"model":"claude-opus-4-8","messages":[]}`)) + req.Header.Set("Content-Type", "application/json") + w := httptest.NewRecorder() + router.ServeHTTP(w, req) + require.Equal(t, http.StatusNotFound, w.Code, w.Body.String()) + require.Contains(t, w.Body.String(), "not available for this group") +} + +// 回归:纯文本入口的上限必须在分组中间件读体之前生效,否则中间件会先按通用 +// 上限把请求体整体读入并解析。超出文本上限的请求体直接 413,不会走到歧义检查。 +func TestGatewayRoutesTextBodyLimitAppliesBeforeGroupMiddleware(t *testing.T) { + gin.SetMode(gin.TestMode) + router := gin.New() + RegisterGatewayRoutes( + router, + &handler.Handlers{Gateway: &handler.GatewayHandler{}, OpenAIGateway: &handler.OpenAIGatewayHandler{}, AsyncImage: handler.NewAsyncImageHandler(nil, nil)}, + servermiddleware.APIKeyAuthMiddleware(func(c *gin.Context) { + groupID := int64(1) + c.Set(string(servermiddleware.ContextKeyAPIKey), &service.APIKey{GroupID: &groupID, Group: allowlistGroup(service.PlatformOpenAI, false)}) + c.Next() + }), + nil, nil, nil, nil, nil, + &config.Config{Gateway: config.GatewayConfig{MaxBodySize: 1 << 20, TextMaxBodySize: 256}}, + ) + body := `{"model":"a","input":"` + strings.Repeat("x", 1024) + `","model":"b"}` + for _, path := range []string{"/v1/embeddings", "/v1/alpha/search", "/v1/systemone", "/backend-api/codex/alpha/search", "/embeddings", "/alpha/search"} { + req := httptest.NewRequest(http.MethodPost, path, strings.NewReader(body)) + req.Header.Set("Content-Type", "application/json") + w := httptest.NewRecorder() + router.ServeHTTP(w, req) + require.Equal(t, http.StatusRequestEntityTooLarge, w.Code, "POST %s: %s", path, w.Body.String()) + require.Contains(t, w.Body.String(), "limit is 256B", "POST %s", path) + } +} + +// 嵌套字段取值不一致(reasoning.effort 参与计费倍率与分组推理强度上限、 +// thinking.type 决定是否清洗 thinking 块)同样在进入 handler 之前拒绝。 +func TestGatewayRoutesRejectConflictingNestedFields(t *testing.T) { + cases := []struct { + platform string + path string + body string + field string + }{ + {service.PlatformOpenAI, "/v1/responses", `{"model":"gpt-5.4","reasoning":{"effort":"low","effort":"xhigh"},"input":"hi"}`, `reasoning.effort`}, + {service.PlatformOpenAI, "/backend-api/codex/responses", `{"model":"gpt-5.4","input":[{"role":"user","content":"a","role":"system"}]}`, `input[0].role`}, + {service.PlatformAnthropic, "/v1/messages", `{"model":"claude-sonnet-4-5","thinking":{"type":"disabled","type":"enabled","budget_tokens":1024},"messages":[]}`, `thinking.type`}, + } + for _, tc := range cases { + t.Run(tc.path, func(t *testing.T) { + router := newGatewayRoutesTestRouterWithGroup(allowlistGroup(tc.platform, false)) + req := httptest.NewRequest(http.MethodPost, tc.path, strings.NewReader(tc.body)) + req.Header.Set("Content-Type", "application/json") + w := httptest.NewRecorder() + router.ServeHTTP(w, req) + + require.Equal(t, http.StatusBadRequest, w.Code, w.Body.String()) + require.Contains(t, w.Body.String(), "invalid_request_error") + require.Contains(t, w.Body.String(), tc.field) + }) + } +} + +// 回归:multipart handler 跳过首个 boundary 之前的前导内容。前导内容是 JSON 时, +// 白名单必须看到表单里的 model,表单里的重复标量字段也必须被拒绝。 +func TestGatewayRoutesMultipartJSONPreambleDoesNotBypassChecks(t *testing.T) { + part := func(name, value string) string { + return "--B\r\nContent-Disposition: form-data; name=\"" + name + "\"\r\n\r\n" + value + "\r\n" + } + send := func(group *service.Group, body string) *httptest.ResponseRecorder { + router := newGatewayRoutesTestRouterWithGroup(group) + req := httptest.NewRequest(http.MethodPost, "/v1/images/edits", strings.NewReader(body)) + req.Header.Set("Content-Type", "multipart/form-data; boundary=B") + w := httptest.NewRecorder() + router.ServeHTTP(w, req) + return w + } + + blocked := send(allowlistGroup(service.PlatformOpenAI, true, "gpt-image-1-mini"), "{}\r\n"+part("model", "gpt-image-2")+part("prompt", "cat")+"--B--\r\n") + require.Equal(t, http.StatusNotFound, blocked.Code, blocked.Body.String()) + require.Contains(t, blocked.Body.String(), "gpt-image-2") + + repeated := send(allowlistGroup(service.PlatformOpenAI, false), "{}\r\n"+part("model", "gpt-image-2")+part("n", "8")+part("n", "1")+"--B--\r\n") + require.Equal(t, http.StatusBadRequest, repeated.Code, repeated.Body.String()) + require.Contains(t, repeated.Body.String(), `\"n\"`) +} diff --git a/backend/internal/server/routes/gateway_stream_only_test.go b/backend/internal/server/routes/gateway_stream_only_test.go index d8bd38a1c4fd..83a781fc227b 100644 --- a/backend/internal/server/routes/gateway_stream_only_test.go +++ b/backend/internal/server/routes/gateway_stream_only_test.go @@ -26,9 +26,9 @@ func TestGatewayRoutesGroupStreamOnlyMountedOnEveryGatewayChain(t *testing.T) { {group: "antigravityV1", next: "antigravityV1.Use(requireGroupAnthropic)"}, {group: "antigravityV1Beta", next: "antigravityV1Beta.Use(requireGroupGoogle)"}, } { - allowlistChain := chain.group + ".Use(groupModelAllowlist)" + allowlistChain := chain.group + ".Use(groupModelAllowlist)\n\t" + chain.group + ".Use(rejectConflictingFields)" if chain.group == "gateway" || chain.group == "antigravityV1" { - allowlistChain = chain.group + ".Use(groupModelAllowlist, apiKeyModelPolicy)" + allowlistChain = chain.group + ".Use(groupModelAllowlist, rejectConflictingFields, apiKeyModelPolicy)" } streamOnlyChain := chain.group + ".Use(groupStreamOnly)" if chain.group == "gateway" { @@ -60,7 +60,7 @@ func TestGatewayRoutesGroupStreamOnlyRejectsNonStreamRequests(t *testing.T) { {"/chat/completions", `{"model":"gpt-5.4","messages":[]}`, "stream_required"}, {"/v1/responses", `{"model":"gpt-5.4","input":"hi"}`, "stream_required"}, {"/responses", `{"model":"gpt-5.4","stream":"true"}`, "stream_required"}, - {"/backend-api/codex/responses", `{"model":"gpt-5.4","stream":true,"stream":false}`, "stream_required"}, + {"/backend-api/codex/responses", `{"model":"gpt-5.4","stream":false}`, "stream_required"}, } { req := httptest.NewRequest(http.MethodPost, tc.path, strings.NewReader(tc.body)) req.Header.Set("Content-Type", "application/json") diff --git a/backend/internal/service/account.go b/backend/internal/service/account.go index b26c19da0592..d25a19a8dc49 100644 --- a/backend/internal/service/account.go +++ b/backend/internal/service/account.go @@ -1124,8 +1124,8 @@ func resolveRequestedModelInMapping(mapping map[string]string, requestedModel st // IsModelSupported 检查模型是否在 model_mapping 中(支持通配符) // 如果未配置 mapping,返回 true(允许所有模型)。 // -// 例外:OpenAI OAuth 账号(Codex 上游)的空映射会排除明确属于其他厂商 -// 家族的模型(deepseek-*/glm-* 等)——转发阶段 normalizeOpenAIModelForUpstream +// 例外:OpenAI OAuth 账号(Codex 上游)的空映射与透传模式都会排除明确属于 +// 其他厂商家族的模型(claude-*/deepseek-*/glm-* 等)——转发阶段 normalizeOpenAIModelForUpstream // 会把未知模型原样透传,Codex 上游对这类模型必然返回不可重试的 400,导致 // 请求卡死在该账号上、无法 failover 到真正支持该模型的 API Key 账号(#3662)。 // 未知/自定义别名仍保持允许(兼容渠道级映射),见 isOpenAIOAuthServableModel。 @@ -1174,6 +1174,12 @@ func (a *Account) isModelMappingSupported(requestedModel string) bool { // credentials 里常残留旧的非空 model_mapping,若不在此放行,透传账号会被 // model_mapping 白名单错误排除出候选集,导致 no available accounts / 404(issue #4936)。 if a.IsOpenAIPassthroughEnabled() { + // OAuth 与 Setup Token 透传的出口恒为 chatgpt.com/backend-api/codex(见 + // buildUpstreamRequestOpenAIPassthrough),异族厂商模型在那里必然是不可重试的 400, + // 因此透传也要在调度阶段跳过它们;API Key 透传的上游由 base_url 决定,不受此限。 + if a.IsOpenAIOAuthLike() && !isOpenAIOAuthServableModel(requestedModel) { + return false + } if !a.IsOpenAIPassthroughModelFilterEnabled() { return true } diff --git a/backend/internal/service/account_test_service.go b/backend/internal/service/account_test_service.go index 2ca70ee2d1b3..e025b5d1f6a0 100644 --- a/backend/internal/service/account_test_service.go +++ b/backend/internal/service/account_test_service.go @@ -336,7 +336,7 @@ func createTestPayload(modelID string) (map[string]any, error) { return nil, err } - return map[string]any{ + payload := map[string]any{ "model": modelID, "messages": []map[string]any{ { @@ -364,10 +364,13 @@ func createTestPayload(modelID string) (map[string]any, error) { "metadata": map[string]string{ "user_id": sessionID, }, - "max_tokens": 1024, - "temperature": 1, - "stream": true, - }, nil + "max_tokens": 1024, + "stream": true, + } + if !claude.RejectsTemperature(modelID) { + payload["temperature"] = 1 + } + return payload, nil } // TestAccountConnection tests an account's connection by sending a test request @@ -815,6 +818,28 @@ func (s *AccountTestService) testClaudeVertexServiceAccountConnection(c *gin.Con return s.processClaudeStream(accountTestResponseContext(c, resp), resp.Body) } +func buildBedrockTestPayload(modelID string) map[string]any { + payload := map[string]any{ + "anthropic_version": "bedrock-2023-05-31", + "messages": []map[string]any{ + { + "role": "user", + "content": []map[string]any{ + { + "type": "text", + "text": "hi", + }, + }, + }, + }, + "max_tokens": 256, + } + if !claude.RejectsTemperature(modelID) { + payload["temperature"] = 1 + } + return payload +} + // testBedrockAccountConnection tests a Bedrock (SigV4 or API Key) account using non-streaming invoke func (s *AccountTestService) testBedrockAccountConnection(c *gin.Context, ctx context.Context, account *Account, testModelID string) error { region := bedrockRuntimeRegion(account) @@ -832,23 +857,7 @@ func (s *AccountTestService) testBedrockAccountConnection(c *gin.Context, ctx co c.Writer.Flush() // Create a minimal Bedrock-compatible payload (no stream, no cache_control) - bedrockPayload := map[string]any{ - "anthropic_version": "bedrock-2023-05-31", - "messages": []map[string]any{ - { - "role": "user", - "content": []map[string]any{ - { - "type": "text", - "text": "hi", - }, - }, - }, - }, - "max_tokens": 256, - "temperature": 1, - } - bedrockBody, _ := json.Marshal(bedrockPayload) + bedrockBody, _ := json.Marshal(buildBedrockTestPayload(testModelID)) // Use non-streaming endpoint (response is standard Claude JSON) apiURL := BuildBedrockURL(region, testModelID, false) diff --git a/backend/internal/service/account_test_service_payload_test.go b/backend/internal/service/account_test_service_payload_test.go new file mode 100644 index 000000000000..865a9e4f01f0 --- /dev/null +++ b/backend/internal/service/account_test_service_payload_test.go @@ -0,0 +1,55 @@ +//go:build unit + +package service + +import ( + "testing" + + "github.com/stretchr/testify/require" +) + +func TestCreateTestPayload_Temperature(t *testing.T) { + tests := []struct { + model string + wantTemperature bool + }{ + {model: "claude-sonnet-4-6", wantTemperature: true}, + {model: "claude-opus-4-6", wantTemperature: true}, + {model: "claude-sonnet-5-5", wantTemperature: true}, + {model: "claude-haiku-5-5", wantTemperature: true}, + {model: "claude-opus-4-7", wantTemperature: false}, + {model: "claude-opus-4-8", wantTemperature: false}, + {model: "claude-opus-5-5", wantTemperature: false}, + {model: "claude-fable-5-2", wantTemperature: false}, + {model: "claude-mythos-5-2", wantTemperature: false}, + } + for _, tt := range tests { + t.Run(tt.model, func(t *testing.T) { + payload, err := createTestPayload(tt.model) + require.NoError(t, err) + + temperature, present := payload["temperature"] + require.Equal(t, tt.wantTemperature, present) + if tt.wantTemperature { + require.Equal(t, 1, temperature) + } + require.Equal(t, tt.model, payload["model"]) + }) + } +} + +func TestBuildBedrockTestPayload_Temperature(t *testing.T) { + tests := []struct { + model string + wantTemperature bool + }{ + {model: "us.anthropic.claude-sonnet-4-6", wantTemperature: true}, + {model: "us.anthropic.claude-opus-4-8-v1", wantTemperature: false}, + } + for _, tt := range tests { + t.Run(tt.model, func(t *testing.T) { + _, present := buildBedrockTestPayload(tt.model)["temperature"] + require.Equal(t, tt.wantTemperature, present) + }) + } +} diff --git a/backend/internal/service/account_test_service_typesafe.go b/backend/internal/service/account_test_service_typesafe.go index 2c7416dcf3a6..80edb86b9e3c 100644 --- a/backend/internal/service/account_test_service_typesafe.go +++ b/backend/internal/service/account_test_service_typesafe.go @@ -39,8 +39,9 @@ func (s *AccountTestService) testTypeSafeAccountConnection(c *gin.Context, accou if state == "" { state = typeSafeTestDefaultState } + model := firstNonEmpty(account.GetMappedModel(typesafe.JevLatestModel), typesafe.JevLatestModel) payload, err := json.Marshal(map[string]any{ - "model": typesafe.JevLatestModel, + "model": model, "state": state, "questions": map[string]any{ typeSafeTestQuestionID: map[string]any{ @@ -59,7 +60,7 @@ func (s *AccountTestService) testTypeSafeAccountConnection(c *gin.Context, accou c.Writer.Header().Set("X-Accel-Buffering", "no") c.Writer.Flush() - s.sendEvent(c, TestEvent{Type: "test_start", Model: typesafe.JevLatestModel}) + s.sendEvent(c, TestEvent{Type: "test_start", Model: model}) req, err := typesafe.NewSystemOneRequest(ctx, baseURL, apiKey, payload) if err != nil { diff --git a/backend/internal/service/account_test_service_typesafe_test.go b/backend/internal/service/account_test_service_typesafe_test.go index c60abf42c3c0..39444c84c115 100644 --- a/backend/internal/service/account_test_service_typesafe_test.go +++ b/backend/internal/service/account_test_service_typesafe_test.go @@ -60,6 +60,18 @@ func TestTypeSafeAccountTestSendsNativeSystemOneRequest(t *testing.T) { require.Zero(t, repo.errorCalls) } +func TestTypeSafeAccountTestAppliesAccountModelMapping(t *testing.T) { + svc, repo, requests, c, rec := newTypeSafeAccountTestFixture(t, http.StatusOK, `{"answers":{"connection_test":{"type":"noul"}}}`) + repo.account.Credentials["model_mapping"] = map[string]any{"jev-latest": "decision-model-preview"} + + require.NoError(t, svc.TestAccountConnection(c, 31, "ignored-client-model", "custom state", AccountTestModeDefault)) + require.Len(t, *requests, 1) + body, err := io.ReadAll((*requests)[0].Body) + require.NoError(t, err) + require.JSONEq(t, `{"model":"decision-model-preview","state":"custom state","questions":{"connection_test":{"type":"noul","instructions":"Is this text a connection test?"}}}`, string(body)) + require.Contains(t, rec.Body.String(), `"type":"test_start","model":"decision-model-preview"`) +} + func TestTypeSafeAccountTestMarksRejectedKey(t *testing.T) { for _, status := range []int{http.StatusUnauthorized, http.StatusForbidden} { t.Run(http.StatusText(status), func(t *testing.T) { diff --git a/backend/internal/service/account_usage_service.go b/backend/internal/service/account_usage_service.go index 650eca0e1789..852e4d4bf821 100644 --- a/backend/internal/service/account_usage_service.go +++ b/backend/internal/service/account_usage_service.go @@ -96,6 +96,13 @@ type apiUsageCache struct { type windowStatsCache struct { stats *WindowStats timestamp time.Time + startTime time.Time +} + +// Separate quota windows while keeping at most two cached entries per account. +type windowStatsCacheKey struct { + accountID int64 + duration time.Duration } // antigravityUsageCache 缓存 Antigravity 额度数据 @@ -118,7 +125,7 @@ const ( // UsageCache 封装账户使用量相关的缓存 type UsageCache struct { apiCache sync.Map // accountID -> *apiUsageCache - windowStatsCache sync.Map // accountID -> *windowStatsCache + windowStatsCache sync.Map // windowStatsCacheKey -> *windowStatsCache antigravityCache sync.Map // accountID -> *antigravityUsageCache apiFlight singleflight.Group // 防止同一账号的并发请求击穿缓存(Anthropic) antigravityFlight singleflight.Group // 防止同一 Antigravity 账号的并发请求击穿缓存 @@ -199,7 +206,8 @@ type UsageInfo struct { GeminiFlashMinute *UsageProgress `json:"gemini_flash_minute,omitempty"` // Gemini Flash RPM // Antigravity 多模型配额 - AntigravityQuota map[string]*AntigravityModelQuota `json:"antigravity_quota,omitempty"` + AntigravityQuota map[string]*AntigravityModelQuota `json:"antigravity_quota,omitempty"` + AntigravityQuotaGroups []*AntigravityQuotaGroup `json:"antigravity_quota_groups,omitempty"` // Grok / xAI 被动额度快照 GrokRequestQuota *xai.QuotaWindow `json:"grok_request_quota,omitempty"` @@ -1411,50 +1419,61 @@ func enrichUsageWithAccountError(info *UsageInfo, account *Account) { // addWindowStats 为 usage 数据添加窗口期统计 // 使用独立缓存(1 分钟),与 API 缓存分离 func (s *AccountUsageService) addWindowStats(ctx context.Context, account *Account, usage *UsageInfo) { - // 修复:即使 FiveHour 为 nil,也要尝试获取统计数据 - // 因为 SevenDay/SevenDaySonnet/SevenDayFable 可能需要 - if usage.FiveHour == nil && usage.SevenDay == nil && usage.SevenDaySonnet == nil && usage.SevenDayFable == nil { + if s.usageLogRepo == nil || usage == nil { return } - // 检查窗口统计缓存(1 分钟) - var windowStats *WindowStats - if cached, ok := s.cache.windowStatsCache.Load(account.ID); ok { - if cache, ok := cached.(*windowStatsCache); ok && time.Since(cache.timestamp) < windowStatsCacheTTL { - windowStats = cache.stats + now := time.Now() + for _, window := range []struct { + progress *UsageProgress + duration time.Duration + }{ + {usage.FiveHour, 5 * time.Hour}, + {usage.SevenDay, 7 * 24 * time.Hour}, + } { + if window.progress == nil { + continue } - } - // 如果没有缓存,从数据库查询 - if windowStats == nil { - // 使用统一的窗口开始时间计算逻辑(考虑窗口过期情况) startTime := account.GetCurrentWindowStartTime() + if supportsAnthropicPassiveUsage(account) { + // Only pair local costs with a known, current upstream quota window. + // A rolling lookback or expired sample would produce a misleading estimate. + if window.progress.ResetsAt == nil || !now.Before(*window.progress.ResetsAt) { + continue + } + startTime = window.progress.ResetsAt.Add(-window.duration) + if startTime.After(now) { + continue + } + } else if window.duration != 5*time.Hour { + continue + } + + key := windowStatsCacheKey{accountID: account.ID, duration: window.duration} + if cached, ok := s.cache.windowStatsCache.Load(key); ok { + if cache, ok := cached.(*windowStatsCache); ok && cache.startTime.Equal(startTime) && now.Sub(cache.timestamp) < windowStatsCacheTTL { + window.progress.WindowStats = cache.stats + continue + } + } stats, err := s.usageLogRepo.GetAccountWindowStats(ctx, account.ID, startTime) if err != nil { log.Printf("Failed to get window stats for account %d: %v", account.ID, err) - return + continue } - - windowStats = &WindowStats{ - Requests: stats.Requests, - Tokens: stats.Tokens, - Cost: stats.Cost, - StandardCost: stats.StandardCost, - UserCost: stats.UserCost, + if stats == nil { + continue } - - // 缓存窗口统计(1 分钟) - s.cache.windowStatsCache.Store(account.ID, &windowStatsCache{ + windowStats := windowStatsFromAccountStats(stats) + window.progress.WindowStats = windowStats + s.cache.windowStatsCache.Store(key, &windowStatsCache{ stats: windowStats, - timestamp: time.Now(), + timestamp: now, + startTime: startTime, }) } - - // 为 FiveHour 添加 WindowStats(5h 窗口统计) - if usage.FiveHour != nil { - usage.FiveHour.WindowStats = windowStats - } } // GetTodayStats 获取账号今日统计,并附带账号累计 Token/费用。 @@ -1901,3 +1920,18 @@ func buildGeminiUsageProgress(used, limit int64, resetAt time.Time, tokens int64 func (s *AccountUsageService) GetAccountWindowStats(ctx context.Context, accountID int64, startTime time.Time) (*usagestats.AccountStats, error) { return s.usageLogRepo.GetAccountWindowStats(ctx, accountID, startTime) } + +// AntigravityQuotaGroup is a group of Antigravity models that share their quota windows. +type AntigravityQuotaGroup struct { + Key string `json:"key"` // bucket prefix, e.g. "gemini" or "3p" + Name string `json:"name"` + Description string `json:"description,omitempty"` + Windows []*AntigravityQuotaWindow `json:"windows"` +} + +// AntigravityQuotaWindow is one window ("5h" or "weekly") of an Antigravity quota group. +type AntigravityQuotaWindow struct { + Window string `json:"window"` + Utilization float64 `json:"utilization"` // used percentage, 0-100 + ResetsAt *time.Time `json:"resets_at"` +} diff --git a/backend/internal/service/account_usage_window_cost_test.go b/backend/internal/service/account_usage_window_cost_test.go new file mode 100644 index 000000000000..93c07291a789 --- /dev/null +++ b/backend/internal/service/account_usage_window_cost_test.go @@ -0,0 +1,98 @@ +package service + +import ( + "context" + "errors" + "testing" + "time" + + "github.com/Wei-Shaw/sub2api/internal/pkg/usagestats" + "github.com/stretchr/testify/require" +) + +type windowCostRepo struct { + usageBatchLogRepoStub + starts []time.Time + failStart time.Time +} + +func (r *windowCostRepo) GetAccountWindowStats(_ context.Context, _ int64, start time.Time) (*usagestats.AccountStats, error) { + r.starts = append(r.starts, start) + if start.Equal(r.failStart) { + return nil, errors.New("test query failure") + } + return &usagestats.AccountStats{Requests: 1, Tokens: 100, Cost: float64(len(r.starts)), UserCost: 99}, nil +} + +func TestAccountUsageService_ClaudeWindowCosts(t *testing.T) { + for _, accountType := range []string{AccountTypeOAuth, AccountTypeSetupToken} { + t.Run(accountType, func(t *testing.T) { + now := time.Now().UTC().Truncate(time.Second) + fiveReset, weeklyReset := now.Add(time.Hour), now.Add(48*time.Hour) + account := Account{ID: 8510, Platform: PlatformAnthropic, Type: accountType, + SessionWindowEnd: &fiveReset, + Extra: map[string]any{ + "session_window_utilization": 0.25, + "passive_usage_7d_utilization": 0.4, + "passive_usage_7d_reset": weeklyReset.Unix(), + }, + } + repo := &windowCostRepo{} + svc := &AccountUsageService{accountRepo: &stubOpenAIAccountRepo{accounts: []Account{account}}, usageLogRepo: repo, cache: NewUsageCache()} + usage, err := svc.GetPassiveUsage(t.Context(), account.ID) + require.NoError(t, err) + require.Len(t, repo.starts, 2) + require.True(t, fiveReset.Add(-5*time.Hour).Equal(repo.starts[0])) + require.True(t, weeklyReset.Add(-7*24*time.Hour).Equal(repo.starts[1])) + require.Equal(t, 1.0, usage.FiveHour.WindowStats.Cost) + require.Equal(t, 2.0, usage.SevenDay.WindowStats.Cost) + + // Cached costs remain separated, and a changed reset invalidates the weekly entry. + svc.addWindowStats(t.Context(), &account, usage) + require.Len(t, repo.starts, 2) + nextReset := weeklyReset.Add(time.Hour) + usage.SevenDay.ResetsAt = &nextReset + svc.addWindowStats(t.Context(), &account, usage) + require.Len(t, repo.starts, 3) + require.True(t, nextReset.Add(-7*24*time.Hour).Equal(repo.starts[2])) + require.Equal(t, 1.0, usage.FiveHour.WindowStats.Cost) + require.Equal(t, 3.0, usage.SevenDay.WindowStats.Cost) + entries := 0 + svc.cache.windowStatsCache.Range(func(_, _ any) bool { entries++; return true }) + require.Equal(t, 2, entries) + }) + } +} + +func TestAccountUsageService_ClaudeWindowCostsMissingOrExpired(t *testing.T) { + now := time.Now() + expired, futureStart := now.Add(-time.Hour), now.Add(8*24*time.Hour) + for name, reset := range map[string]*time.Time{"missing": nil, "expired": &expired, "future_start": &futureStart} { + t.Run(name, func(t *testing.T) { + repo := &windowCostRepo{} + svc := &AccountUsageService{usageLogRepo: repo, cache: NewUsageCache()} + usage := &UsageInfo{SevenDay: &UsageProgress{ResetsAt: reset}} + svc.addWindowStats(t.Context(), &Account{ID: 8511, Platform: PlatformAnthropic, Type: AccountTypeSetupToken}, usage) + require.Empty(t, repo.starts) + require.Nil(t, usage.SevenDay.WindowStats) + }) + } +} + +func TestAccountUsageService_ClaudeWindowCostsIndependentFailure(t *testing.T) { + now := time.Now().UTC().Truncate(time.Second) + fiveReset, weeklyReset := now.Add(time.Hour), now.Add(48*time.Hour) + repo := &windowCostRepo{failStart: fiveReset.Add(-5 * time.Hour)} + svc := &AccountUsageService{usageLogRepo: repo, cache: NewUsageCache()} + usage := &UsageInfo{ + FiveHour: &UsageProgress{ResetsAt: &fiveReset}, + SevenDay: &UsageProgress{ResetsAt: &weeklyReset}, + SevenDaySonnet: &UsageProgress{ResetsAt: &weeklyReset}, + SevenDayFable: &UsageProgress{ResetsAt: &weeklyReset}, + } + svc.addWindowStats(t.Context(), &Account{ID: 8512, Platform: PlatformAnthropic, Type: AccountTypeOAuth}, usage) + require.Nil(t, usage.FiveHour.WindowStats) + require.NotNil(t, usage.SevenDay.WindowStats) + require.Nil(t, usage.SevenDaySonnet.WindowStats) + require.Nil(t, usage.SevenDayFable.WindowStats) +} diff --git a/backend/internal/service/admin_service.go b/backend/internal/service/admin_service.go index e97d6d79d2b9..a2894a1b21af 100644 --- a/backend/internal/service/admin_service.go +++ b/backend/internal/service/admin_service.go @@ -766,6 +766,8 @@ type adminServiceImpl struct { affiliateService adminRechargeAffiliateAccruer compositeRouteRepo CompositeModelRouteRepository compositeResolver *CompositeRouteResolver + + userPlatformQuotaRepo UserPlatformQuotaRepository // 分组平台变更后用来失效渠道缓存;可为 nil(缓存会在 TTL 到期后自然重建) channelCacheInvalidator ChannelCacheInvalidator } @@ -809,7 +811,12 @@ func NewAdminService( compositeRouteRepo CompositeModelRouteRepository, compositeResolver *CompositeRouteResolver, channelCacheInvalidator ChannelCacheInvalidator, + quotaRepos ...UserPlatformQuotaRepository, ) AdminService { + var userPlatformQuotaRepo UserPlatformQuotaRepository + if len(quotaRepos) > 0 { + userPlatformQuotaRepo = quotaRepos[0] + } return &adminServiceImpl{ cfg: cfg, userRepo: userRepo, @@ -839,5 +846,6 @@ func NewAdminService( compositeResolver: compositeResolver, channelCacheInvalidator: channelCacheInvalidator, + userPlatformQuotaRepo: userPlatformQuotaRepo, } } diff --git a/backend/internal/service/admin_service_create_user_test.go b/backend/internal/service/admin_service_create_user_test.go index 5e9578abecca..8b82116bc111 100644 --- a/backend/internal/service/admin_service_create_user_test.go +++ b/backend/internal/service/admin_service_create_user_test.go @@ -108,7 +108,14 @@ func TestAdminService_CreateUser_EmailExists(t *testing.T) { func TestAdminService_CreateUser_CreateError(t *testing.T) { createErr := errors.New("db down") repo := &userRepoStub{createErr: createErr} - svc := &adminServiceImpl{userRepo: repo} + quotas := &userPlatformQuotaRepoStub{} + svc := &adminServiceImpl{ + userRepo: repo, + settingService: NewSettingService(&settingRepoStub{values: map[string]string{ + SettingKeyDefaultPlatformQuotas: `{"openai":{"daily":100}}`, + }}, &config.Config{}), + userPlatformQuotaRepo: quotas, + } _, err := svc.CreateUser(context.Background(), &CreateUserInput{ Email: "user@test.com", @@ -116,6 +123,7 @@ func TestAdminService_CreateUser_CreateError(t *testing.T) { }) require.ErrorIs(t, err, createErr) require.Empty(t, repo.created) + require.Empty(t, quotas.bulkInsertCalls, "failed user creation must not initialize platform quotas") } func TestAdminService_CreateUser_AssignsDefaultSubscriptions(t *testing.T) { @@ -146,3 +154,109 @@ func TestAdminService_CreateUser_AssignsDefaultSubscriptions(t *testing.T) { require.Equal(t, int64(5), assigner.calls[0].GroupID) require.Equal(t, 30, assigner.calls[0].ValidityDays) } + +func TestAdminService_CreateUser_SnapshotsDefaultPlatformQuotas(t *testing.T) { + users := &userRepoStub{nextID: 40} + quotas := &userPlatformQuotaRepoStub{} + settings := NewSettingService(&settingRepoStub{values: map[string]string{ + SettingKeyDefaultPlatformQuotas: `{ + "openai": {"daily": 100, "weekly": 700, "monthly": 3000}, + "anthropic": {"daily": 100}, + "gemini": {"daily": 500}, + "antigravity": {"daily": 500}, + "grok": {"daily": 0}, + "cline": {}, + "deepseek": null + }`, + SettingKeyAuthSourceDefaultEmailGrantOnSignup: "true", + SettingKeyAuthSourcePlatformQuotas("email"): `{"openai":{"daily":3}}`, + }}, &config.Config{}) + svc := NewAdminService(nil, users, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, settings, nil, nil, nil, nil, nil, nil, nil, nil, quotas) + + user, err := svc.CreateUser(context.Background(), &CreateUserInput{ + Email: "quota-defaults@example.test", + Password: "strong-pass", + }) + + require.NoError(t, err) + require.Equal(t, int64(40), user.ID) + require.Len(t, quotas.bulkInsertCalls, 1, "admin-created users must receive the configured platform quotas") + records := make(map[string]UserPlatformQuotaRecord) + for _, record := range quotas.bulkInsertCalls[0] { + require.Equal(t, user.ID, record.UserID) + records[record.Platform] = record + } + require.Len(t, records, 5, "unconfigured platforms must not receive quota rows") + require.Equal(t, 100.0, *records["openai"].DailyLimitUSD, "admin creation uses system defaults, not email signup overrides") + require.Equal(t, 700.0, *records["openai"].WeeklyLimitUSD) + require.Equal(t, 3000.0, *records["openai"].MonthlyLimitUSD) + require.Equal(t, 100.0, *records["anthropic"].DailyLimitUSD) + require.Equal(t, 500.0, *records["gemini"].DailyLimitUSD) + require.Equal(t, 500.0, *records["antigravity"].DailyLimitUSD) + require.NotNil(t, records["grok"].DailyLimitUSD, "zero is an explicit limit") + require.Zero(t, *records["grok"].DailyLimitUSD) + require.Nil(t, records["anthropic"].WeeklyLimitUSD) + require.Nil(t, records["anthropic"].MonthlyLimitUSD) +} + +func TestAdminService_CreateUser_UnlimitedDefaultsDoNotCreateQuotaRows(t *testing.T) { + quotas := &userPlatformQuotaRepoStub{} + svc := &adminServiceImpl{ + userRepo: &userRepoStub{nextID: 41}, + settingService: NewSettingService(&settingRepoStub{values: map[string]string{ + SettingKeyDefaultPlatformQuotas: `{"openai":{"daily":null,"weekly":null,"monthly":null}}`, + }}, &config.Config{}), + userPlatformQuotaRepo: quotas, + } + + _, err := svc.CreateUser(context.Background(), &CreateUserInput{ + Email: "unlimited@example.test", + Password: "strong-pass", + }) + + require.NoError(t, err) + require.Empty(t, quotas.bulkInsertCalls) +} + +func TestAdminService_CreateUser_AdminSkipsDefaultPlatformQuotas(t *testing.T) { + quotas := &userPlatformQuotaRepoStub{} + svc := &adminServiceImpl{ + userRepo: &userRepoStub{nextID: 42}, + settingService: NewSettingService(&settingRepoStub{values: map[string]string{ + SettingKeyDefaultPlatformQuotas: `{"openai":{"daily":100}}`, + }}, &config.Config{}), + userPlatformQuotaRepo: quotas, + } + + user, err := svc.CreateUser(context.Background(), &CreateUserInput{ + Email: "admin@example.test", + Password: "strong-pass", + Role: RoleAdmin, + }) + + require.NoError(t, err) + require.Equal(t, RoleAdmin, user.Role) + require.Empty(t, quotas.bulkInsertCalls) +} + +func TestAdminService_CreateUser_QuotaWriteFailureDoesNotFailCreation(t *testing.T) { + users := &userRepoStub{nextID: 43} + quotas := &userPlatformQuotaRepoStub{bulkInsertErr: errors.New("quota insert failed")} + svc := &adminServiceImpl{ + userRepo: users, + settingService: NewSettingService(&settingRepoStub{values: map[string]string{ + SettingKeyDefaultPlatformQuotas: `{"openai":{"daily":100}}`, + }}, &config.Config{}), + userPlatformQuotaRepo: quotas, + } + + user, err := svc.CreateUser(context.Background(), &CreateUserInput{ + Email: "quota-failure@example.test", + Password: "strong-pass", + }) + + require.NoError(t, err) + require.Equal(t, int64(43), user.ID) + require.Len(t, users.created, 1) + require.Len(t, quotas.bulkInsertCalls, 1) +} diff --git a/backend/internal/service/admin_user.go b/backend/internal/service/admin_user.go index d727dcd7d16c..22ba5a8cbfd4 100644 --- a/backend/internal/service/admin_user.go +++ b/backend/internal/service/admin_user.go @@ -195,9 +195,24 @@ func (s *adminServiceImpl) CreateUser(ctx context.Context, input *CreateUserInpu input.ActorAdminID, user.ID) } s.assignDefaultSubscriptions(ctx, user.ID) + s.assignDefaultPlatformQuotas(ctx, user) return user, nil } +func (s *adminServiceImpl) assignDefaultPlatformQuotas(ctx context.Context, user *User) { + if user == nil || user.Role != RoleUser || s.settingService == nil || s.userPlatformQuotaRepo == nil { + return + } + quotas, err := s.settingService.GetDefaultPlatformQuotas(ctx) + if err != nil { + logger.LegacyPrintf("service.admin", "failed to load default platform quotas: user_id=%d err=%v", user.ID, err) + return + } + if err := snapshotUserPlatformQuotaDefaults(ctx, s.userPlatformQuotaRepo, user.ID, quotas); err != nil { + logger.LegacyPrintf("service.admin", "failed to snapshot default platform quotas: user_id=%d err=%v (fail-open)", user.ID, err) + } +} + // ensureNotLastAdmin 降级管理员前确认系统中仍存在其他管理员,防止零 admin 锁死。 // 注:读取与写入之间存在竞态窗口,极端并发下仍可能双双降级;作为后台低频操作 // 的兜底保护足够,彻底防护需依赖数据库层约束。 diff --git a/backend/internal/service/anthropic_models_list.go b/backend/internal/service/anthropic_models_list.go new file mode 100644 index 000000000000..191a837a6e5c --- /dev/null +++ b/backend/internal/service/anthropic_models_list.go @@ -0,0 +1,47 @@ +package service + +import ( + "context" + "slices" + "strings" +) + +func (s *GatewayService) ExpandAnthropicLongContextModels(ctx context.Context, group *Group, models []string) []string { + var accounts []Account + var err error + if group != nil { + accounts, err = s.accountRepo.ListSchedulableByGroupID(ctx, group.ID) + } else { + accounts, err = s.accountRepo.ListSchedulable(ctx) + } + if err != nil { + return models + } + result := slices.Clone(models) + seen := make(map[string]bool, len(models)) + for _, model := range models { + seen[strings.ToLower(model)] = true + } + for _, model := range models { + if strings.HasSuffix(strings.ToLower(model), claudeCodeLongContextModelSuffix) || strings.Contains(model, "*") { + continue + } + var routedAccountIDs []int64 + if group != nil { + routedAccountIDs = group.GetRoutingAccountIDs(model) + } + for _, account := range accounts { + if !account.IsAnthropic() || !account.IsModelSupported(model) || + (len(routedAccountIDs) > 0 && !slices.Contains(routedAccountIDs, account.ID)) { + continue + } + metadata, ok := account.GetUpstreamModelMetadata(account.GetMappedModel(model)) + variant := model + claudeCodeLongContextModelSuffix + if ok && metadata.ContextWindow >= 900_000 && !seen[strings.ToLower(variant)] { + result = append(result, variant) + seen[strings.ToLower(variant)] = true + } + } + } + return result +} diff --git a/backend/internal/service/antigravity_bare429_after_loop_test.go b/backend/internal/service/antigravity_bare429_after_loop_test.go new file mode 100644 index 000000000000..7d2cdb2d5e1b --- /dev/null +++ b/backend/internal/service/antigravity_bare429_after_loop_test.go @@ -0,0 +1,80 @@ +//go:build unit + +package service + +import ( + "context" + "io" + "net/http" + "strings" + "testing" + + "github.com/gin-gonic/gin" + "github.com/stretchr/testify/require" +) + +// 2026-11-19 17:03 UTC: one Codex request (/v1/responses, 2 MB) got the bare 429 +// on #2, #7 and #6. The retry loop cooled #2 and logged bare_429_cooldown_skipped +// for #7 and #6, but the compat path then cooled #7 and #6 anyway when it turned +// the 429 into a failover, so the whole pool was down for a minute. +func compatBare429(t *testing.T, svc *AntigravityGatewayService, c *gin.Context, accountID int64) error { + t.Helper() + call := &antigravityCompatUpstreamCall{ + prefix: "[test]", + request: antigravityCompatRequest{originalModel: "gemini-4-argon-medium"}, + } + resp := &http.Response{ + StatusCode: http.StatusTooManyRequests, + Header: http.Header{}, + Body: io.NopCloser(strings.NewReader(bareAntigravity429Body)), + } + return svc.handleAntigravityCompatHTTPError(context.Background(), c, bare429Account(accountID), call, resp) +} + +func cooledAccounts(repo *stubAntigravityAccountRepo) map[int64]bool { + cooled := map[int64]bool{} + for _, call := range repo.modelRateLimitCalls { + cooled[call.accountID] = true + } + for _, call := range repo.rateCalls { + cooled[call.accountID] = true + } + return cooled +} + +func TestCompatHTTPError_Bare429_DoesNotCoolASecondAccount(t *testing.T) { + repo := &stubAntigravityAccountRepo{} + svc := &AntigravityGatewayService{accountRepo: repo} + c := newBare429TestContext() + + // The retry loop already cooled #2 for this request. + require.True(t, claimBare429Cooldown(c, 2)) + + for _, id := range []int64{7, 6} { + err := compatBare429(t, svc, c, id) + var failover *UpstreamFailoverError + require.ErrorAs(t, err, &failover, "the request still fails over from account %d", id) + } + require.Empty(t, cooledAccounts(repo), "accounts 7 and 6 must not be cooled by the request that cooled 2") +} + +func TestCompatHTTPError_Bare429_FirstAccountIsStillCooled(t *testing.T) { + repo := &stubAntigravityAccountRepo{} + svc := &AntigravityGatewayService{accountRepo: repo} + c := newBare429TestContext() + + require.Error(t, compatBare429(t, svc, c, 13)) + require.Equal(t, map[int64]bool{13: true}, cooledAccounts(repo)) +} + +func TestCompatHTTPError_429WithReason_CoolsEveryAccount(t *testing.T) { + repo := &stubAntigravityAccountRepo{} + svc := &AntigravityGatewayService{accountRepo: repo} + c := newBare429TestContext() + require.True(t, claimBare429Cooldown(c, 2)) + body := `{"error":{"code":429,"message":"Individual quota reached.","status":"RESOURCE_EXHAUSTED","details":[{"@type":"type.googleapis.com/google.rpc.ErrorInfo","reason":"QUOTA_EXHAUSTED","metadata":{"quotaResetDelay":"41m15s"}}]}}` + call := &antigravityCompatUpstreamCall{prefix: "[test]", request: antigravityCompatRequest{originalModel: "gemini-4-argon-medium"}} + resp := &http.Response{StatusCode: http.StatusTooManyRequests, Header: http.Header{}, Body: io.NopCloser(strings.NewReader(body))} + require.Error(t, svc.handleAntigravityCompatHTTPError(context.Background(), c, bare429Account(7), call, resp)) + require.True(t, cooledAccounts(repo)[7]) +} diff --git a/backend/internal/service/antigravity_bare429_request_scope_test.go b/backend/internal/service/antigravity_bare429_request_scope_test.go new file mode 100644 index 000000000000..915e723aa791 --- /dev/null +++ b/backend/internal/service/antigravity_bare429_request_scope_test.go @@ -0,0 +1,123 @@ +//go:build unit + +package service + +import ( + "context" + "io" + "net/http" + "net/http/httptest" + "strings" + "testing" + "time" + + "github.com/Wei-Shaw/sub2api/internal/pkg/antigravity" + "github.com/Wei-Shaw/sub2api/internal/pkg/tlsfingerprint" + "github.com/gin-gonic/gin" + "github.com/stretchr/testify/require" +) + +// fixed429Upstream answers every call with one 429 body. +type fixed429Upstream struct { + body string + calls int +} + +func (u *fixed429Upstream) Do(req *http.Request, proxyURL string, accountID int64, accountConcurrency int) (*http.Response, error) { + u.calls++ + return &http.Response{ + StatusCode: http.StatusTooManyRequests, + Header: http.Header{}, + Body: io.NopCloser(strings.NewReader(u.body)), + }, nil +} + +func (u *fixed429Upstream) DoWithTLS(req *http.Request, proxyURL string, accountID int64, accountConcurrency int, profile *tlsfingerprint.Profile) (*http.Response, error) { + return u.Do(req, proxyURL, accountID, accountConcurrency) +} + +// The body Google sent on 2026-11-16 for one 1.8 MB request on every account it +// reached, while the same accounts served other requests: no reason, no delay. +const bareAntigravity429Body = `{"error":{"code":429,"message":"Resource has been exhausted (e.g. check quota).","status":"RESOURCE_EXHAUSTED"}}` + +func runBare429Loop(t *testing.T, c *gin.Context, account *Account, body string) (cooled bool) { + t.Helper() + svc := &AntigravityGatewayService{} + result, err := svc.antigravityRetryLoop(antigravityRetryLoopParams{ + prefix: "[test]", + ctx: context.Background(), + account: account, + accessToken: "token", + action: "streamGenerateContent", + body: []byte(`{"input":"test"}`), + c: c, + httpUpstream: &fixed429Upstream{body: body}, + requestedModel: "gemini-4-argon-high", + handleError: func(ctx context.Context, prefix string, account *Account, statusCode int, headers http.Header, body []byte, requestedModel string, groupID int64, sessionHash string, isStickySession bool) *handleModelRateLimitResult { + cooled = true + return nil + }, + }) + require.NoError(t, err) + require.NotNil(t, result) + require.NotNil(t, result.resp) + _ = result.resp.Body.Close() + require.Equal(t, http.StatusTooManyRequests, result.resp.StatusCode) + return cooled +} + +func setupBare429Test(t *testing.T) { + t.Helper() + t.Setenv(antigravityForwardBaseURLEnv, "") + oldBaseURLs := append([]string(nil), antigravity.BaseURLs...) + oldAvailability := antigravity.DefaultURLAvailability + t.Cleanup(func() { + antigravity.BaseURLs = oldBaseURLs + antigravity.DefaultURLAvailability = oldAvailability + }) + antigravity.BaseURLs = []string{"https://ag-1.test"} + antigravity.DefaultURLAvailability = antigravity.NewURLAvailability(time.Minute) +} + +func newBare429TestContext() *gin.Context { + gin.SetMode(gin.TestMode) + c, _ := gin.CreateTestContext(httptest.NewRecorder()) + c.Request = httptest.NewRequest(http.MethodPost, "/v1/responses", nil) + return c +} + +func bare429Account(id int64) *Account { + return &Account{ID: id, Name: "acc", Platform: PlatformAntigravity, Schedulable: true, Status: StatusActive, Concurrency: 1} +} + +// One request that gets a bare 429 on every account it reaches must not cool +// them all: it cools the first, and the rest are only skipped for this request. +func TestAntigravityRetryLoop_Bare429_CoolsOnlyTheFirstAccountPerRequest(t *testing.T) { + setupBare429Test(t) + c := newBare429TestContext() + + require.True(t, runBare429Loop(t, c, bare429Account(13), bareAntigravity429Body), "first account is cooled") + require.False(t, runBare429Loop(t, c, bare429Account(6), bareAntigravity429Body), "same request on a second account: not cooled") + require.False(t, runBare429Loop(t, c, bare429Account(2), bareAntigravity429Body), "same request on a third account: not cooled") + require.True(t, runBare429Loop(t, c, bare429Account(13), bareAntigravity429Body), "the account it already cooled may be cooled again") +} + +// Another request that reaches the second account first still cools it, so an +// account that really is throttled for everyone is still taken out. +func TestAntigravityRetryLoop_Bare429_OtherRequestStillCools(t *testing.T) { + setupBare429Test(t) + + require.True(t, runBare429Loop(t, newBare429TestContext(), bare429Account(13), bareAntigravity429Body)) + require.True(t, runBare429Loop(t, newBare429TestContext(), bare429Account(6), bareAntigravity429Body)) +} + +// A 429 that says when it resets is Google's statement about the account and is +// applied on every account, as before. +func TestAntigravityRetryLoop_429WithResetDelay_CoolsEveryAccount(t *testing.T) { + setupBare429Test(t) + c := newBare429TestContext() + body := `{"error":{"code":429,"message":"You have exhausted your capacity on this model. Your quota will reset after 2h.","status":"RESOURCE_EXHAUSTED","details":[{"@type":"type.googleapis.com/google.rpc.ErrorInfo","reason":"QUOTA_EXHAUSTED","metadata":{"quotaResetDelay":"2h0m0s"}}]}}` + + require.True(t, runBare429Loop(t, c, bare429Account(13), body)) + require.True(t, runBare429Loop(t, c, bare429Account(6), body)) +} diff --git a/backend/internal/service/antigravity_bare429_scope.go b/backend/internal/service/antigravity_bare429_scope.go new file mode 100644 index 000000000000..b365be4b7373 --- /dev/null +++ b/backend/internal/service/antigravity_bare429_scope.go @@ -0,0 +1,67 @@ +package service + +import ( + "context" + "net/http" + + "github.com/Wei-Shaw/sub2api/internal/pkg/logger" + "github.com/gin-gonic/gin" + "github.com/tidwall/gjson" +) + +// antigravityBare429CooledAccountKey holds, on the request's gin context, the one +// account this request has cooled down for a bare 429. +const antigravityBare429CooledAccountKey = "antigravity_bare429_cooled_account_id" + +// isBareAntigravity429 reports a 429 with no reason and no reset time, only +// "Resource has been exhausted". Google sends it for an account that is +// throttled, but also for a single request it will not serve (2026-11-16: one +// 1.8 MB request got it on four accounts in a row while those accounts kept +// serving other requests). A 429 that names a reason or a reset time is +// Google's statement about the account and is not bare. +func isBareAntigravity429(statusCode int, body []byte) bool { + if statusCode != http.StatusTooManyRequests { + return false + } + if gjson.GetBytes(body, "error.details").Exists() { + return false + } + return ParseGeminiRateLimitResetTime(body) == nil +} + +// claimBare429Cooldown reports whether this request may cool accountID for a +// bare 429. A request cools at most one account this way: when the same bare +// 429 follows the request to another account, the request is the likely cause, +// and cooling every account it reaches takes a shared pool offline for everyone. +// The request still leaves that account and fails over. An account throttled +// for everyone is cooled by the next request that reaches it first. +func claimBare429Cooldown(c *gin.Context, accountID int64) bool { + if c == nil { + return true + } + if v, ok := c.Get(antigravityBare429CooledAccountKey); ok { + if id, ok := v.(int64); ok && id != accountID { + return false + } + } + c.Set(antigravityBare429CooledAccountKey, accountID) + return true +} + +// handleUpstreamErrorAfterRetryLoop applies an error the retry loop handed back +// as a response. A bare 429 there was already decided by the loop: the account +// this request cooled may be cooled again, any other is left alone. Without this +// the compat, Gemini and Claude paths cooled every account the loop had skipped +// (2026-11-19: one 2 MB Codex request cooled #2, #7 and #6 every few minutes). +func (s *AntigravityGatewayService) handleUpstreamErrorAfterRetryLoop( + ctx context.Context, c *gin.Context, prefix string, account *Account, + statusCode int, headers http.Header, body []byte, + requestedModel string, + groupID int64, sessionHash string, isStickySession bool, +) *handleModelRateLimitResult { + if isBareAntigravity429(statusCode, body) && !claimBare429Cooldown(c, account.ID) { + logger.LegacyPrintf("service.antigravity_gateway", "%s status=%d bare_429_cooldown_skipped account=%d (after retry loop)", prefix, statusCode, account.ID) + return nil + } + return s.handleUpstreamError(ctx, prefix, account, statusCode, headers, body, requestedModel, groupID, sessionHash, isStickySession) +} diff --git a/backend/internal/service/antigravity_gateway_claude.go b/backend/internal/service/antigravity_gateway_claude.go index 98232989097a..7e81156da05f 100644 --- a/backend/internal/service/antigravity_gateway_claude.go +++ b/backend/internal/service/antigravity_gateway_claude.go @@ -400,7 +400,7 @@ func (s *AntigravityGatewayService) Forward(ctx context.Context, c *gin.Context, } } - s.handleUpstreamError(ctx, prefix, account, resp.StatusCode, resp.Header, respBody, originalModel, 0, "", isStickySession) + s.handleUpstreamErrorAfterRetryLoop(ctx, c, prefix, account, resp.StatusCode, resp.Header, respBody, originalModel, 0, "", isStickySession) // 精确匹配服务端配置类 400 错误,触发同账号重试 + failover if resp.StatusCode == http.StatusBadRequest { diff --git a/backend/internal/service/antigravity_gateway_compat.go b/backend/internal/service/antigravity_gateway_compat.go index d5ba74e4ff92..462c6ddaa2fe 100644 --- a/backend/internal/service/antigravity_gateway_compat.go +++ b/backend/internal/service/antigravity_gateway_compat.go @@ -467,8 +467,9 @@ func (s *AntigravityGatewayService) handleAntigravityCompatHTTPError( resp *http.Response, ) error { body := s.readUpstreamErrorBody(resp) - s.handleUpstreamError( + s.handleUpstreamErrorAfterRetryLoop( ctx, + c, call.prefix, account, resp.StatusCode, diff --git a/backend/internal/service/antigravity_gateway_gemini.go b/backend/internal/service/antigravity_gateway_gemini.go index 3a4b2c5405c3..01d6aa55bfc0 100644 --- a/backend/internal/service/antigravity_gateway_gemini.go +++ b/backend/internal/service/antigravity_gateway_gemini.go @@ -360,7 +360,7 @@ func (s *AntigravityGatewayService) ForwardGemini(ctx context.Context, c *gin.Co if unwrapErr != nil || len(unwrappedForOps) == 0 { unwrappedForOps = respBody } - s.handleUpstreamError(ctx, prefix, account, resp.StatusCode, resp.Header, respBody, originalModel, forwardOpts.groupID, forwardOpts.sessionHash, isStickySession) + s.handleUpstreamErrorAfterRetryLoop(ctx, c, prefix, account, resp.StatusCode, resp.Header, respBody, originalModel, forwardOpts.groupID, forwardOpts.sessionHash, isStickySession) upstreamMsg := strings.TrimSpace(extractAntigravityErrorMessage(unwrappedForOps)) upstreamMsg = sanitizeUpstreamErrorMessage(upstreamMsg) upstreamDetail := s.getUpstreamErrorDetail(unwrappedForOps) diff --git a/backend/internal/service/antigravity_gateway_retry.go b/backend/internal/service/antigravity_gateway_retry.go index 0f7498bfe372..4ff1e313ea72 100644 --- a/backend/internal/service/antigravity_gateway_retry.go +++ b/backend/internal/service/antigravity_gateway_retry.go @@ -648,8 +648,12 @@ urlFallbackLoop: continue } - // 重试用尽,标记账户限流 - p.handleError(p.ctx, p.prefix, p.account, resp.StatusCode, resp.Header, respBody, p.requestedModel, p.groupID, p.sessionHash, p.isStickySession) + // 重试用尽,标记账户限流(无原因的 429 每个请求最多冷却一个账号) + if isBareAntigravity429(resp.StatusCode, respBody) && !claimBare429Cooldown(p.c, p.account.ID) { + logger.LegacyPrintf("service.antigravity_gateway", "%s status=%d bare_429_cooldown_skipped account=%d (this request already cooled another account; the request is the likely cause)", p.prefix, resp.StatusCode, p.account.ID) + } else { + p.handleError(p.ctx, p.prefix, p.account, resp.StatusCode, resp.Header, respBody, p.requestedModel, p.groupID, p.sessionHash, p.isStickySession) + } logger.LegacyPrintf("service.antigravity_gateway", "%s status=%d rate_limited base_url=%s body=%s", p.prefix, resp.StatusCode, baseURL, truncateForLog(respBody, 200)) resp = &http.Response{ StatusCode: resp.StatusCode, diff --git a/backend/internal/service/antigravity_gateway_service_test.go b/backend/internal/service/antigravity_gateway_service_test.go index c589eed3f93a..57ca2dd26f33 100644 --- a/backend/internal/service/antigravity_gateway_service_test.go +++ b/backend/internal/service/antigravity_gateway_service_test.go @@ -1430,6 +1430,37 @@ func TestHandleGeminiStreamingResponse_EventSeparatorIsExactlyOneBlankLine(t *te } } +func TestHandleGeminiStreamingResponse_ForwardedCommentFrames(t *testing.T) { + gin.SetMode(gin.TestMode) + svc := newAntigravityTestService(&config.Config{ + Gateway: config.GatewayConfig{MaxLineSize: defaultMaxLineSize}, + }) + const first = `data: {"candidates":[{"content":{"role":"model","parts":[{"text":"first"}]}}]}` + "\n\n" + const second = `data: {"candidates":[{"content":{"role":"model","parts":[{"text":"second"}]}}]}` + "\n\n" + const comment = ": upstream" + const stream = first + comment + "\r\n\r\n" + second + + for _, tc := range []struct { + name string + userAgent string + forwardedComment string + }{ + {"js-genai", "google-genai-sdk/3.6.0 gl-node/v26.13.1", comment + "\n\n"}, + {"go-genai", "google-genai-sdk/1.71.0 gl-go/go1.27.4", ""}, + {"python-genai", "google-genai-sdk/1.20.0 gl-python/3.12.4", ""}, + } { + t.Run(tc.name, func(t *testing.T) { + c, rec := newAntigravityCompatContext(http.MethodPost, "/v1beta/models/gemini-2.5-flash:streamGenerateContent", nil) + c.Request.Header.Set("User-Agent", tc.userAgent) + resp := &http.Response{StatusCode: http.StatusOK, Body: io.NopCloser(strings.NewReader(stream)), Header: http.Header{}} + + _, err := svc.handleGeminiStreamingResponse(c, resp, time.Now()) + require.NoError(t, err) + require.Equal(t, first+tc.forwardedComment+second, rec.Body.String()) + }) + } +} + func TestHandleGeminiStreamingResponse_ThoughtsTokenCount(t *testing.T) { gin.SetMode(gin.TestMode) svc := newAntigravityTestService(&config.Config{ diff --git a/backend/internal/service/antigravity_gateway_streaming.go b/backend/internal/service/antigravity_gateway_streaming.go index 8dcca68f320e..f6fe20c112e7 100644 --- a/backend/internal/service/antigravity_gateway_streaming.go +++ b/backend/internal/service/antigravity_gateway_streaming.go @@ -197,9 +197,9 @@ func (s *AntigravityGatewayService) handleGeminiStreamingResponse(c *gin.Context if s.settingService.cfg != nil && s.settingService.cfg.Gateway.StreamKeepaliveInterval > 0 { keepaliveInterval = time.Duration(s.settingService.cfg.Gateway.StreamKeepaliveInterval) * time.Second } - // go-genai / python-genai 不会忽略 SSE 注释行,收到 ":\n\n" 会直接把整个流判成 - // invalid stream chunk 而中断(Antigravity CLI 在用 go-genai)。对这类客户端宁可不发心跳。 - if keepaliveInterval > 0 && downstreamRejectsSSEComments(c) { + // go-genai / python-genai 收到 SSE 注释会中断流。 + rejectComments := downstreamRejectsSSEComments(c) + if rejectComments { keepaliveInterval = 0 } var keepaliveTicker *time.Ticker @@ -226,6 +226,7 @@ func (s *AntigravityGatewayService) handleGeminiStreamingResponse(c *gin.Context flusher.Flush() } + var needsEventSeparator bool for { select { case ev, ok := <-events: @@ -251,6 +252,7 @@ func (s *AntigravityGatewayService) handleGeminiStreamingResponse(c *gin.Context s.observeAntigravityGeminiSSELine(c, line) trimmed := strings.TrimRight(line, "\r\n") if strings.HasPrefix(trimmed, "data:") { + needsEventSeparator = false payload := strings.TrimSpace(strings.TrimPrefix(trimmed, "data:")) if payload == "" || payload == "[DONE]" { cw.Fprintf("%s\n", line) @@ -293,15 +295,20 @@ func (s *AntigravityGatewayService) handleGeminiStreamingResponse(c *gin.Context continue } - // 上游每个 data 事件后面跟一个空行作为事件分隔。上面已经把 data 行写成 - // "data: ...\n\n",若再把这个空行透传出去,事件之间就会变成 "\n\n\n"。 - // google-genai 的 Go SDK(Antigravity CLI 在用)按 "\n\n" 切事件,多出的 - // "\n" 会粘到下一个事件开头,前缀变成 "\ndata" 而被判成 invalid stream chunk。 + // 保留透传帧的空行。重写的 data 帧已带分隔符,重复空行会破坏部分客户端的解析。 if trimmed == "" { + if needsEventSeparator { + cw.Fprintf("\n") + needsEventSeparator = false + } + continue + } + if rejectComments && strings.HasPrefix(trimmed, ":") { continue } cw.Fprintf("%s\n", line) + needsEventSeparator = true case <-intervalCh: lastRead := time.Unix(0, atomic.LoadInt64(&lastReadAt)) @@ -328,6 +335,7 @@ func (s *AntigravityGatewayService) handleGeminiStreamingResponse(c *gin.Context logger.LegacyPrintf("service.antigravity_gateway", "Client disconnected during keepalive ping (antigravity gemini), continuing to drain upstream for billing") continue } + needsEventSeparator = false } } } diff --git a/backend/internal/service/antigravity_quota_fetcher.go b/backend/internal/service/antigravity_quota_fetcher.go index e296654e6dc8..12e47975166b 100644 --- a/backend/internal/service/antigravity_quota_fetcher.go +++ b/backend/internal/service/antigravity_quota_fetcher.go @@ -7,6 +7,7 @@ import ( "fmt" "log/slog" "regexp" + "sort" "strings" "time" @@ -56,8 +57,14 @@ func (f *AntigravityQuotaFetcher) FetchQuota(ctx context.Context, account *Accou return nil, fmt.Errorf("create antigravity client failed: %w", err) } - // 调用 API 获取配额 - modelsResp, modelsRaw, err := client.FetchAvailableModels(ctx, accessToken, projectID, resolveModelsListReadLimit(f.cfg)) + baseURL := resolveAntigravityForwardBaseURL(account) + if baseURL == "" { + return nil, errors.New("no antigravity base url configured") + } + + // Query the same endpoint that receives forwarded requests for this account (daily for + // paid tiers, prod otherwise), because Google accounts quota separately per endpoint. + modelsResp, modelsRaw, err := client.FetchAvailableModelsFromURL(ctx, baseURL, accessToken, projectID, resolveModelsListReadLimit(f.cfg)) if err != nil { // 403 Forbidden: 不报错,返回 is_forbidden 标记 var forbiddenErr *antigravity.ForbiddenError @@ -86,6 +93,14 @@ func (f *AntigravityQuotaFetcher) FetchQuota(ctx context.Context, account *Accou // 转换为 UsageInfo usageInfo := f.buildUsageInfo(modelsResp, tierRaw, tierNormalized, loadResp) + // The per-group 5-hour and weekly windows. Not on the critical path: without them the + // per-model figures above are shown as before. + if summary, err := client.RetrieveUserQuotaSummaryFromURL(ctx, baseURL, accessToken, projectID); err != nil { + slog.Warn("failed to fetch antigravity quota summary", "account_id", account.ID, "error", err) + } else { + usageInfo.AntigravityQuotaGroups = buildAntigravityQuotaGroups(summary) + } + return &QuotaResult{ UsageInfo: usageInfo, Raw: modelsRaw, @@ -272,3 +287,48 @@ func extractValidationURL(body string) string { } return "" } + +func buildAntigravityQuotaGroups(summary *antigravity.QuotaSummaryResponse) []*AntigravityQuotaGroup { + if summary == nil { + return nil + } + windowOrder := map[string]int{"5h": 0, "weekly": 1} + var groups []*AntigravityQuotaGroup + for _, group := range summary.Groups { + if len(group.Buckets) == 0 { + continue + } + out := &AntigravityQuotaGroup{Name: group.DisplayName, Description: group.Description} + for _, bucket := range group.Buckets { + if out.Key == "" { + if i := strings.LastIndex(bucket.BucketID, "-"); i > 0 { + out.Key = bucket.BucketID[:i] + } + } + used := (1.0 - bucket.RemainingFraction) * 100 + if used < 0 { + used = 0 + } + window := &AntigravityQuotaWindow{Window: bucket.Window, Utilization: used} + if bucket.ResetTime != "" { + if resetAt, err := time.Parse(time.RFC3339, bucket.ResetTime); err == nil { + window.ResetsAt = &resetAt + } + } + out.Windows = append(out.Windows, window) + } + sort.SliceStable(out.Windows, func(i, j int) bool { + oi, iok := windowOrder[out.Windows[i].Window] + oj, jok := windowOrder[out.Windows[j].Window] + if !iok { + oi = len(windowOrder) + } + if !jok { + oj = len(windowOrder) + } + return oi < oj + }) + groups = append(groups, out) + } + return groups +} diff --git a/backend/internal/service/antigravity_quota_fetcher_test.go b/backend/internal/service/antigravity_quota_fetcher_test.go index a5463ec007ee..61ce78a088fe 100644 --- a/backend/internal/service/antigravity_quota_fetcher_test.go +++ b/backend/internal/service/antigravity_quota_fetcher_test.go @@ -7,6 +7,7 @@ import ( "errors" "net/http" "net/http/httptest" + "strconv" "testing" "time" @@ -555,3 +556,156 @@ func TestExtractValidationURL(t *testing.T) { }) } } + +func TestFetchQuota_QueriesForwardEndpoint(t *testing.T) { + newQuotaServer := func(t *testing.T, remaining float64, hits *[]string) *httptest.Server { + t.Helper() + return httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + *hits = append(*hits, r.URL.Path) + w.Header().Set("Content-Type", "application/json") + remainingText := strconv.FormatFloat(remaining, 'f', -1, 64) + switch r.URL.Path { + case "/v1internal:fetchAvailableModels": + _, _ = w.Write([]byte(`{"models":{"gemini-3-flash":{"quotaInfo":{"remainingFraction":` + remainingText + `,"resetTime":"2026-11-20T09:00:00Z"}}}}`)) + case "/v1internal:retrieveUserQuotaSummary": + _, _ = w.Write([]byte(`{"groups":[{"displayName":"Gemini Models","buckets":[{"bucketId":"gemini-5h","window":"5h","remainingFraction":` + remainingText + `,"resetTime":"2026-11-20T09:00:00Z"}]}]}`)) + case "/v1internal:loadCodeAssist": + _, _ = w.Write([]byte(`{"paidTier":{"id":"g1-ultra-tier"}}`)) + default: + http.NotFound(w, r) + } + })) + } + + tests := []struct { + name string + planType string + envOverride string + wantDaily bool + wantUtilization int + wantGroupUtil float64 + }{ + { + name: "paid Ultra account queries daily endpoint", + planType: "Ultra", + wantDaily: true, + wantUtilization: 75, + wantGroupUtil: 75, + }, + { + name: "paid Pro account queries daily endpoint", + planType: "Pro", + wantDaily: true, + wantUtilization: 75, + wantGroupUtil: 75, + }, + { + name: "free account queries prod endpoint", + planType: "Free", + wantDaily: false, + wantUtilization: 25, + wantGroupUtil: 25, + }, + { + name: "env override daily routes free account to daily", + planType: "Free", + envOverride: "daily", + wantDaily: true, + wantUtilization: 75, + wantGroupUtil: 75, + }, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + t.Setenv(antigravityForwardBaseURLEnv, tt.envOverride) + + var prodHits, dailyHits []string + prodServer := newQuotaServer(t, 0.75, &prodHits) + defer prodServer.Close() + dailyServer := newQuotaServer(t, 0.25, &dailyHits) + defer dailyServer.Close() + + oldBaseURLs := append([]string(nil), antigravity.BaseURLs...) + oldAvailability := antigravity.DefaultURLAvailability + t.Cleanup(func() { + antigravity.BaseURLs = oldBaseURLs + antigravity.DefaultURLAvailability = oldAvailability + }) + antigravity.BaseURLs = []string{prodServer.URL, dailyServer.URL} + antigravity.DefaultURLAvailability = antigravity.NewURLAvailability(time.Minute) + + fetcher := NewAntigravityQuotaFetcher(nil, &config.Config{}) + res, err := fetcher.FetchQuota(context.Background(), &Account{ + ID: 80, + Platform: PlatformAntigravity, + Type: AccountTypeOAuth, + Credentials: map[string]any{ + "access_token": "token", + "project_id": "project", + "plan_type": tt.planType, + }, + }, "") + require.NoError(t, err) + require.NotNil(t, res) + require.NotNil(t, res.UsageInfo) + require.Equal(t, tt.wantUtilization, res.UsageInfo.AntigravityQuota["gemini-3-flash"].Utilization) + require.Len(t, res.UsageInfo.AntigravityQuotaGroups, 1) + require.InDelta(t, tt.wantGroupUtil, res.UsageInfo.AntigravityQuotaGroups[0].Windows[0].Utilization, 0.001) + + if tt.wantDaily { + require.Contains(t, dailyHits, "/v1internal:fetchAvailableModels") + require.Contains(t, dailyHits, "/v1internal:retrieveUserQuotaSummary") + require.NotContains(t, prodHits, "/v1internal:fetchAvailableModels") + require.NotContains(t, prodHits, "/v1internal:retrieveUserQuotaSummary") + } else { + require.Contains(t, prodHits, "/v1internal:fetchAvailableModels") + require.Contains(t, prodHits, "/v1internal:retrieveUserQuotaSummary") + require.NotContains(t, dailyHits, "/v1internal:fetchAvailableModels") + require.NotContains(t, dailyHits, "/v1internal:retrieveUserQuotaSummary") + } + }) + } +} + +func TestFetchQuota_PaidAccountDoesNotFallbackToProdQuotaOnDailyFailure(t *testing.T) { + t.Setenv(antigravityForwardBaseURLEnv, "") + + var prodQuotaHits int + prodServer := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if r.URL.Path == "/v1internal:fetchAvailableModels" || r.URL.Path == "/v1internal:retrieveUserQuotaSummary" { + prodQuotaHits++ + } + w.Header().Set("Content-Type", "application/json") + _, _ = w.Write([]byte(`{"models":{"gemini-3-flash":{"quotaInfo":{"remainingFraction":1}}}}`)) + })) + defer prodServer.Close() + + dailyServer := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { + http.Error(w, "upstream failure", http.StatusInternalServerError) + })) + defer dailyServer.Close() + + oldBaseURLs := append([]string(nil), antigravity.BaseURLs...) + oldAvailability := antigravity.DefaultURLAvailability + t.Cleanup(func() { + antigravity.BaseURLs = oldBaseURLs + antigravity.DefaultURLAvailability = oldAvailability + }) + antigravity.BaseURLs = []string{prodServer.URL, dailyServer.URL} + antigravity.DefaultURLAvailability = antigravity.NewURLAvailability(time.Minute) + + fetcher := NewAntigravityQuotaFetcher(nil, &config.Config{}) + _, err := fetcher.FetchQuota(context.Background(), &Account{ + ID: 77, + Platform: PlatformAntigravity, + Type: AccountTypeOAuth, + Credentials: map[string]any{ + "access_token": "token", + "project_id": "project", + "plan_type": "Ultra", + }, + }, "") + require.Error(t, err) + require.Zero(t, prodQuotaHits, "paid account quota query must not silently fall back to prod") +} diff --git a/backend/internal/service/antigravity_tool_result_images_test.go b/backend/internal/service/antigravity_tool_result_images_test.go index f555e0d0db11..9459ef22397f 100644 --- a/backend/internal/service/antigravity_tool_result_images_test.go +++ b/backend/internal/service/antigravity_tool_result_images_test.go @@ -3,6 +3,7 @@ package service import ( "context" "encoding/json" + "strings" "testing" "github.com/Wei-Shaw/sub2api/internal/pkg/antigravity" @@ -75,6 +76,23 @@ func TestAntigravityResponsesParallelToolResultImagesKeepFunctionResponsesContig {"type":"function_call_output","call_id":"call_cmd_3","output":"done"} ]}`) wire := toolImageCompatWire(t, raw, model) + if strings.HasPrefix(model, "gemini-") { + // Gemini rejects a turn whose parts continue past the last + // functionResponse ("Requests ending with a model turn are not + // supported."), so tool-result images move to the following user + // turn and each turn keeps its functionResponses contiguous. + frParts := gjson.GetBytes(wire, "request.contents.1.parts").Array() + require.Len(t, frParts, 3) + require.Equal(t, "view_image", frParts[0].Get("functionResponse.name").String()) + require.Equal(t, "view_image", frParts[1].Get("functionResponse.name").String()) + require.Equal(t, "exec_command", frParts[2].Get("functionResponse.name").String()) + imageParts := gjson.GetBytes(wire, "request.contents.2.parts").Array() + require.Len(t, imageParts, 2) + require.Equal(t, "user", gjson.GetBytes(wire, "request.contents.2.role").String()) + require.Equal(t, "AQID", imageParts[0].Get("inlineData.data").String()) + require.Equal(t, "BAUG", imageParts[1].Get("inlineData.data").String()) + return + } 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()) diff --git a/backend/internal/service/api_key_ws_policy_test.go b/backend/internal/service/api_key_ws_policy_test.go index 7bee1b6e0177..428d38e8e9a6 100644 --- a/backend/internal/service/api_key_ws_policy_test.go +++ b/backend/internal/service/api_key_ws_policy_test.go @@ -38,7 +38,7 @@ func TestAPIKeyWSPolicyAppliesToFirstAndSubsequentFrames(t *testing.T) { require.NoError(t, err) writeCtx, cancelWrite := context.WithTimeout(ctx, 3*time.Second) - err = client.Write(writeCtx, coderws.MessageText, []byte(`{"type":"response.create","model":"gpt-6.1-sol","Model":"gpt-6.1-sol","reasoning":{"effort":"ultra"}}`)) + err = client.Write(writeCtx, coderws.MessageText, []byte(`{"type":"response.create","model":"gpt-6.1-sol","reasoning":{"effort":"ultra"}}`)) cancelWrite() require.NoError(t, err) second := requirePassthroughUpstreamWrite(t, upstream, 3*time.Second) diff --git a/backend/internal/service/auth_service.go b/backend/internal/service/auth_service.go index b33cb486a108..cedccf5fd79f 100644 --- a/backend/internal/service/auth_service.go +++ b/backend/internal/service/auth_service.go @@ -1980,35 +1980,11 @@ func resolvedTokenVersion(user *User) int64 { // snapshotPlatformQuotaDefaults 把 plan.PlatformQuotas 中至少配置了一档限额的平台以 // BulkInsertInitial 形式写入 user_platform_quotas 表。失败 fail-open(仅 warn log)。 func (s *AuthService) snapshotPlatformQuotaDefaults(ctx context.Context, userID int64, plan *signupGrantPlan) error { - if s.userPlatformQuotaRepo == nil || plan == nil || len(plan.PlatformQuotas) == 0 { + if plan == nil { return nil } - // 平台配额快照是 best-effort(fail-open):必须脱离调用方事务执行。 - // 否则写入时的任何数据库错误(历史上是新平台尚未加入 user_platform_quotas 的 - // CHECK 约束)都会让整个调用方事务被 Postgres 标记 aborted,把"无关紧要的默认 - // 配额快照"放大成"整笔注册失败"(OAuth pending 路径曾因此 500 → 清 cookie → 404)。 - ctx = dbent.WithoutTx(ctx) - // 仅为至少配置了一档限额的平台建行:user_platform_quotas 中不存在的行等价于不限额, - // 三档全空的记录不携带任何可执行的限额。 - records := make([]UserPlatformQuotaRecord, 0, len(plan.PlatformQuotas)) - for platform, q := range plan.PlatformQuotas { - if !q.HasAnyLimit() { - continue - } - records = append(records, UserPlatformQuotaRecord{ - UserID: userID, - Platform: platform, - DailyLimitUSD: q.DailyLimitUSD, - WeeklyLimitUSD: q.WeeklyLimitUSD, - MonthlyLimitUSD: q.MonthlyLimitUSD, - }) - } - if len(records) == 0 { - return nil - } - if err := s.userPlatformQuotaRepo.BulkInsertInitial(ctx, records); err != nil { + if err := snapshotUserPlatformQuotaDefaults(ctx, s.userPlatformQuotaRepo, userID, plan.PlatformQuotas); err != nil { logger.LegacyPrintf("service.auth", "[Auth] Warning: snapshot platform quota failed user=%d: %v (fail-open)", userID, err) - return nil // fail-open:返回 nil,让调用方继续 } return nil } diff --git a/backend/internal/service/bedrock_request.go b/backend/internal/service/bedrock_request.go index 74df923e6323..0c103f8f58e4 100644 --- a/backend/internal/service/bedrock_request.go +++ b/backend/internal/service/bedrock_request.go @@ -765,14 +765,7 @@ func sanitizeBedrockThinking(body []byte, modelID string) []byte { } if claude.IsSonnet55(modelID) { - switch thinkingType { - case "enabled": - body, _ = sjson.SetBytes(body, "thinking.type", "adaptive") - body, _ = sjson.DeleteBytes(body, "thinking.budget_tokens") - case "disabled": - body, _ = sjson.SetBytes(body, "thinking.type", "between_tools") - } - return body + return adaptThinkingToClaude55(body, modelID) } if isBedrockOpus47OrNewer(modelID) { diff --git a/backend/internal/service/claude55_thinking.go b/backend/internal/service/claude55_thinking.go new file mode 100644 index 000000000000..b74a05420e57 --- /dev/null +++ b/backend/internal/service/claude55_thinking.go @@ -0,0 +1,27 @@ +package service + +import ( + "github.com/Wei-Shaw/sub2api/internal/pkg/claude" + "github.com/tidwall/gjson" + "github.com/tidwall/sjson" +) + +// adaptThinkingToClaude55 replaces a thinking mode that a Claude 5.5 model +// rejects with the nearest mode it accepts: enabled becomes adaptive without +// budget_tokens, and on Sonnet 5.5 disabled becomes between_tools. Other modes +// are left for validateClaude55Request to judge. +func adaptThinkingToClaude55(body []byte, model string) []byte { + if !isClaude55SignedThinkingModel(model) { + return body + } + switch gjson.GetBytes(body, "thinking.type").String() { + case "enabled": + body, _ = sjson.SetBytes(body, "thinking.type", "adaptive") + body, _ = sjson.DeleteBytes(body, "thinking.budget_tokens") + case "disabled": + if claude.IsSonnet55(model) { + body, _ = sjson.SetBytes(body, "thinking.type", "between_tools") + } + } + return body +} diff --git a/backend/internal/service/composite_platform.go b/backend/internal/service/composite_platform.go index ee5b1a713a1d..d9e5537ec011 100644 --- a/backend/internal/service/composite_platform.go +++ b/backend/internal/service/composite_platform.go @@ -53,6 +53,18 @@ func WithCompositeRouteDecision(ctx context.Context, decision CompositeRouteDeci return ctx } +// RewriteCompositeRequestModel puts a composite route's upstream model into the +// request body at modelPath. The client chose its thinking mode for the model +// it asked for, so a mode the upstream model rejects becomes the nearest mode +// it accepts. The body is returned unchanged when it cannot be rewritten. +func RewriteCompositeRequestModel(body []byte, modelPath, upstreamModel string) []byte { + rewritten, err := sjson.SetBytes(body, modelPath, upstreamModel) + if err != nil { + return body + } + return adaptThinkingToClaude55(rewritten, upstreamModel) +} + func ResolvedUpstreamModelFromContext(ctx context.Context) (string, bool) { if ctx == nil { return "", false diff --git a/backend/internal/service/composite_platform_thinking_test.go b/backend/internal/service/composite_platform_thinking_test.go new file mode 100644 index 000000000000..b7c2f315e744 --- /dev/null +++ b/backend/internal/service/composite_platform_thinking_test.go @@ -0,0 +1,82 @@ +//go:build unit + +package service + +import ( + "context" + "io" + "net/http" + "net/http/httptest" + "strings" + "testing" + + "github.com/gin-gonic/gin" + "github.com/stretchr/testify/require" + "github.com/tidwall/gjson" +) + +func forwardCompositeThinkingRequest(t *testing.T, publicModel, upstreamModel, clientBody string) (*httptest.ResponseRecorder, *anthropicHTTPUpstreamRecorder, error) { + t.Helper() + gin.SetMode(gin.TestMode) + rec := httptest.NewRecorder() + c, _ := gin.CreateTestContext(rec) + c.Request = httptest.NewRequest(http.MethodPost, "/v1/messages", nil) + + body := []byte(clientBody) + ctx := context.Background() + if upstreamModel != publicModel { + body = RewriteCompositeRequestModel(body, "model", upstreamModel) + ctx = WithCompositeRouteDecision(ctx, CompositeRouteDecision{ + Matched: true, Source: CompositeRouteSourceExplicit, + PublicModel: publicModel, TargetPlatform: PlatformAnthropic, UpstreamModel: upstreamModel, + }) + } + c.Request = c.Request.WithContext(ctx) + parsed, err := ParseGatewayRequest(NewRequestBodyRef(body), PlatformAnthropic) + require.NoError(t, err) + + upstream := &anthropicHTTPUpstreamRecorder{resp: &http.Response{ + StatusCode: http.StatusOK, + Header: http.Header{"Content-Type": []string{"application/json"}}, + Body: io.NopCloser(strings.NewReader(`{"id":"msg_1","type":"message","role":"assistant","model":"` + upstreamModel + `","content":[{"type":"text","text":"ok"}],"usage":{"input_tokens":1,"output_tokens":1}}`)), + }} + svc := newForwardPartialUsageServiceForTest(upstream) + _, err = svc.Forward(ctx, c, newAnthropicOAuthAccountForPartialUsageTest(), parsed) + return rec, upstream, err +} + +// A composite route that rewrites claude-sonnet-5 to claude-opus-5-5 sends the +// client's budget thinking upstream as adaptive thinking instead of failing +// Opus 5.5 validation. +func TestCompositeRewriteToOpus55SendsEnabledThinkingAsAdaptive(t *testing.T) { + rec, upstream, err := forwardCompositeThinkingRequest(t, "claude-sonnet-5", "claude-opus-5-5", + `{"model":"claude-sonnet-5","max_tokens":64,"stream":false,"thinking":{"type":"enabled","budget_tokens":4096},"messages":[{"role":"user","content":"hi"}]}`) + + require.NoError(t, err) + require.NotEqual(t, http.StatusBadRequest, rec.Code) + require.NotNil(t, upstream.lastReq, "request must reach the upstream") + require.Equal(t, "claude-opus-5-5", gjson.GetBytes(upstream.lastBody, "model").String()) + require.Equal(t, "adaptive", gjson.GetBytes(upstream.lastBody, "thinking.type").String()) + require.False(t, gjson.GetBytes(upstream.lastBody, "thinking.budget_tokens").Exists()) +} + +func TestCompositeRewriteToSonnet55SendsDisabledThinkingAsBetweenTools(t *testing.T) { + rec, upstream, err := forwardCompositeThinkingRequest(t, "claude-sonnet-5", "claude-sonnet-5-5", + `{"model":"claude-sonnet-5","max_tokens":64,"stream":false,"thinking":{"type":"disabled"},"messages":[{"role":"user","content":"hi"}]}`) + + require.NoError(t, err) + require.NotEqual(t, http.StatusBadRequest, rec.Code) + require.NotNil(t, upstream.lastReq, "request must reach the upstream") + require.Equal(t, "between_tools", gjson.GetBytes(upstream.lastBody, "thinking.type").String()) +} + +// Without a model rewrite the client's own invalid thinking mode is still +// rejected. +func TestDirectOpus55RequestWithEnabledThinkingIsStillRejected(t *testing.T) { + rec, upstream, err := forwardCompositeThinkingRequest(t, "claude-opus-5-5", "claude-opus-5-5", + `{"model":"claude-opus-5-5","max_tokens":64,"stream":false,"thinking":{"type":"enabled","budget_tokens":4096},"messages":[{"role":"user","content":"hi"}]}`) + + require.ErrorContains(t, err, "claude-opus-5-5 requires adaptive thinking") + require.Equal(t, http.StatusBadRequest, rec.Code) + require.Nil(t, upstream.lastReq) +} diff --git a/backend/internal/service/gateway_claude_oauth_body.go b/backend/internal/service/gateway_claude_oauth_body.go index 62eb2fdb2bac..4f08d5c6b3b8 100644 --- a/backend/internal/service/gateway_claude_oauth_body.go +++ b/backend/internal/service/gateway_claude_oauth_body.go @@ -1088,7 +1088,15 @@ func enforceCacheControlLimit(body []byte) []byte { } return normalizeCacheControlTTLOrder(body) } - return normalizeCacheControlTTLOrder(enforceCacheControlBlockLimit(body)) + out := enforceCacheControlBlockLimit(body) + // Escaped bodies returned earlier, so a missing "1h" literal here is exact: + // the TTL walk would find no 1h breakpoint and rewrite nothing, yet it still + // costs a full collectCacheControlPaths pass over the body. Deletions above + // only remove cache_control keys, so they cannot introduce a 1h breakpoint. + if !bytes.Contains(body, cacheTTL1hJSONBytes) { + return out + } + return normalizeCacheControlTTLOrder(out) } // enforceCacheControlBlockLimit 强制执行 cache_control 块数量限制(最多 4 个) @@ -1218,10 +1226,57 @@ func normalizeCacheControlTTLOrder(body []byte) []byte { // injectAnthropicCacheControlTTL1h 将已有 ephemeral cache_control 块的 ttl 强制写为 1h。 // 仅修改已经存在的 cache_control,不新增缓存断点。 +// +// Claude Code compaction requests are written at 5m instead: the conversation is +// replaced by the summary afterwards, so nothing reads the extra tokens again, +// and a 5m breakpoint still reads the prefix the main thread wrote at 1h. func injectAnthropicCacheControlTTL1h(body []byte) []byte { + if isClaudeCodeCompactionRequest(body) { + return forceEphemeralCacheControlTTL(body, cacheTTLTarget5m) + } return forceEphemeralCacheControlTTL(body, cacheTTLTarget1h) } +// claudeCodeCompactPreamble opens the compact prompt of Claude Code 2.1.282 in +// its full, partial-from and partial-up-to variants, and no other prompt it sends. +const claudeCodeCompactPreamble = "CRITICAL: Respond with TEXT ONLY. Do NOT call any tools.\n\n" + +// isClaudeCodeCompactionRequest reports whether the last user message is a compact +// prompt. When auto-compaction fires during a tool loop the prompt arrives as a text +// block merged into the user message that carries the tool_result. +func isClaudeCodeCompactionRequest(body []byte) bool { + return claudeLastUserTextHasPrefix(body, claudeCodeCompactPreamble) +} + +// claudeLastUserTextHasPrefix reports whether a text block (or the string content) of +// the last user message starts with any of prefixes. +func claudeLastUserTextHasPrefix(body []byte, prefixes ...string) bool { + hasPrefix := func(s string) bool { + for _, p := range prefixes { + if strings.HasPrefix(s, p) { + return true + } + } + return false + } + var last gjson.Result + gjson.GetBytes(body, "messages").ForEach(func(_, msg gjson.Result) bool { + if msg.Get("role").String() == "user" { + last = msg.Get("content") + } + return true + }) + if last.Type == gjson.String { + return hasPrefix(last.Str) + } + found := false + last.ForEach(func(_, block gjson.Result) bool { + found = block.Get("type").String() == "text" && hasPrefix(block.Get("text").String()) + return !found + }) + return found +} + func forceEphemeralCacheControlTTL(body []byte, ttl string) []byte { if len(body) == 0 || ttl == "" { return body diff --git a/backend/internal/service/gateway_compaction_cache_ttl_test.go b/backend/internal/service/gateway_compaction_cache_ttl_test.go new file mode 100644 index 000000000000..5dfb1a39c71c --- /dev/null +++ b/backend/internal/service/gateway_compaction_cache_ttl_test.go @@ -0,0 +1,87 @@ +package service + +import ( + "encoding/json" + "fmt" + "testing" + + "github.com/stretchr/testify/require" + "github.com/tidwall/gjson" +) + +// Only the preamble is the real marker; the rest of the prompt is placeholder text. +const testCompactPrompt = claudeCodeCompactPreamble + "placeholder compact instructions" + +// compactionTestBody builds a request with three breakpoints (two system blocks and +// the assistant message before the last user message) and a trailing role:system +// message. lastUser is the JSON content of the last user message; a non-empty +// cacheTTL is written into every breakpoint. +func compactionTestBody(t *testing.T, lastUser string, cacheTTL string) []byte { + t.Helper() + cc := `{"type":"ephemeral"}` + if cacheTTL != "" { + cc = fmt.Sprintf(`{"type":"ephemeral","ttl":%q}`, cacheTTL) + } + body := fmt.Sprintf(`{"model":"claude-test","messages":[`+ + `{"role":"user","content":[{"type":"text","text":"first question"}]},`+ + `{"role":"assistant","content":[{"type":"tool_use","id":"toolu_1","name":"Bash","input":{"command":"ls"},"cache_control":%[1]s}]},`+ + `{"role":"user","content":%[2]s},`+ + `{"role":"system","content":"placeholder trailing system message"}],`+ + `"system":[{"type":"text","text":"billing block"},`+ + `{"type":"text","text":"system block one","cache_control":%[1]s},`+ + `{"type":"text","text":"system block two","cache_control":%[1]s}],`+ + `"tools":[{"name":"Bash","input_schema":{}}],"max_tokens":1024,"stream":true}`, cc, lastUser) + require.True(t, json.Valid([]byte(body))) + return []byte(body) +} + +func compactionTestJSONString(t *testing.T, s string) string { + t.Helper() + b, err := json.Marshal(s) + require.NoError(t, err) + return string(b) +} + +func requireCompactionTestTTLs(t *testing.T, body []byte, want string) { + t.Helper() + for _, path := range []string{"system.1.cache_control", "system.2.cache_control", "messages.1.content.0.cache_control"} { + require.Equal(t, want, gjson.GetBytes(body, path+".ttl").String(), path) + } +} + +func TestInjectAnthropicCacheControlTTL1h_CompactionUses5m(t *testing.T) { + prompt := compactionTestJSONString(t, testCompactPrompt) + cases := map[string]string{ + "merged_with_tool_result": `[{"type":"tool_result","tool_use_id":"toolu_1","content":"ok"},{"type":"text","text":` + prompt + `}]`, + "own_message": prompt, + } + for name, lastUser := range cases { + for _, clientTTL := range []string{"", "1h"} { + t.Run(name+"/client_ttl="+clientTTL, func(t *testing.T) { + out := injectAnthropicCacheControlTTL1h(compactionTestBody(t, lastUser, clientTTL)) + require.NotContains(t, string(out), `"1h"`) + requireCompactionTestTTLs(t, out, "5m") + }) + } + } +} + +func TestInjectAnthropicCacheControlTTL1h_NonCompactionStill1h(t *testing.T) { + cases := map[string]string{ + "tool_result_and_reminder": `[{"type":"tool_result","tool_use_id":"toolu_1","content":"ok"},{"type":"text","text":"keep going"}]`, + "preamble_not_at_start": compactionTestJSONString(t, "note: "+testCompactPrompt), + } + for name, lastUser := range cases { + t.Run(name, func(t *testing.T) { + out := injectAnthropicCacheControlTTL1h(compactionTestBody(t, lastUser, "")) + requireCompactionTestTTLs(t, out, "1h") + }) + } +} + +func TestIsClaudeCodeCompactionRequest_OnlyLastUserMessageCounts(t *testing.T) { + earlier := `{"messages":[{"role":"user","content":` + compactionTestJSONString(t, testCompactPrompt) + `},{"role":"assistant","content":"summary"},{"role":"user","content":"next question"}]}` + require.False(t, isClaudeCodeCompactionRequest([]byte(earlier))) + require.False(t, isClaudeCodeCompactionRequest([]byte(`{"messages":[]}`))) + require.False(t, isClaudeCodeCompactionRequest([]byte(`{}`))) +} diff --git a/backend/internal/service/gateway_request.go b/backend/internal/service/gateway_request.go index c0d1abea6403..85d9930fc4b0 100644 --- a/backend/internal/service/gateway_request.go +++ b/backend/internal/service/gateway_request.go @@ -135,29 +135,115 @@ func clearGatewayRequestRanges(parsed *ParsedRequest) { parsed.inputRange = missingJSONRange() } -func setGatewayRequestRanges(parsed *ParsedRequest, protocol string, jsonStr string) { +// gatewayRequestRootFields 保存一次根对象遍历取到的原始值视图。全部零拷贝, +// 只在本次解析内使用,body 被改写后必须重新扫描。 +// +// 嵌套字段按 gjson.Get 的语义取值:路径的每一段都取「第一个能解析出子键的同名键」, +// 而不是简单取第一个同名键。例如 {"metadata":"x","metadata":{"user_id":"u"}} 在 +// gjson.Get("metadata.user_id") 下取到 "u",这里以 Exists() 作为「还没取到」的判据 +// 复现该重试行为。 +type gatewayRequestRootFields struct { + model gjson.Result + stream gjson.Result + maxTokens gjson.Result + metadataUID gjson.Result + thinkingType gjson.Result + outputEffort gjson.Result + speed gjson.Result + system gjson.Result + messages gjson.Result + input gjson.Result + contents gjson.Result + geminiSysParts gjson.Result +} + +// scanGatewayRequestRoot 用一次根对象遍历取出解析需要的全部字段。 +// +// 逐字段 gjson.Get 的问题在于「键不存在」也要把整份 body 扫一遍才能返回不存在: +// 1 MiB body 上每个缺失键约 142µs,而一次完整遍历约 220µs——解析一次要做 7 次查找, +// 其中 6 个键(metadata.user_id / thinking.type / output_config.effort / max_tokens / +// system / messages)在典型 Responses 请求里都不存在。 +func scanGatewayRequestRoot(body []byte) gatewayRequestRootFields { + var f gatewayRequestRootFields + parseRawJSONView(body).ForEach(func(key, value gjson.Result) bool { + switch key.Str { + case "model": + if !f.model.Exists() { + f.model = value + } + case "stream": + if !f.stream.Exists() { + f.stream = value + } + case "max_tokens": + if !f.maxTokens.Exists() { + f.maxTokens = value + } + case "metadata": + if !f.metadataUID.Exists() { + f.metadataUID = value.Get("user_id") + } + case "thinking": + if !f.thinkingType.Exists() { + f.thinkingType = value.Get("type") + } + case "output_config": + if !f.outputEffort.Exists() { + f.outputEffort = value.Get("effort") + } + case "speed": + if !f.speed.Exists() { + f.speed = value + } + case "system": + if !f.system.Exists() { + f.system = value + } + case "messages": + if !f.messages.Exists() { + f.messages = value + } + case "input": + if !f.input.Exists() { + f.input = value + } + case "contents": + if !f.contents.Exists() { + f.contents = value + } + case "systemInstruction": + if !f.geminiSysParts.Exists() { + f.geminiSysParts = value.Get("parts") + } + } + return true + }) + return f +} + +func setGatewayRequestRangesFromFields(parsed *ParsedRequest, protocol string, fields gatewayRequestRootFields) { if parsed == nil { return } switch protocol { case domain.PlatformGemini: - if sysParts := gjson.Get(jsonStr, "systemInstruction.parts"); sysParts.Exists() && sysParts.IsArray() { - parsed.systemRange = rangeFromResult(sysParts) + if fields.geminiSysParts.Exists() && fields.geminiSysParts.IsArray() { + parsed.systemRange = rangeFromResult(fields.geminiSysParts) } - if contents := gjson.Get(jsonStr, "contents"); contents.Exists() && contents.IsArray() { - parsed.messagesRange = rangeFromResult(contents) + if fields.contents.Exists() && fields.contents.IsArray() { + parsed.messagesRange = rangeFromResult(fields.contents) } default: - if sys := gjson.Get(jsonStr, "system"); sys.Exists() { + if fields.system.Exists() { parsed.HasSystem = true - parsed.systemRange = rangeFromResult(sys) + parsed.systemRange = rangeFromResult(fields.system) } - if msgs := gjson.Get(jsonStr, "messages"); msgs.Exists() && msgs.IsArray() { - parsed.messagesRange = rangeFromResult(msgs) + if fields.messages.Exists() && fields.messages.IsArray() { + parsed.messagesRange = rangeFromResult(fields.messages) } if protocol == "responses" { - if input := gjson.Get(jsonStr, "input"); input.Exists() { - parsed.inputRange = rangeFromResult(input) + if fields.input.Exists() { + parsed.inputRange = rangeFromResult(fields.input) } } } @@ -175,28 +261,31 @@ func normalizeClaudeCodeLongContextModel(model string) string { return model } -// parseGatewayRequestCurrentBody 只做标量和 raw range 轻量解析,不恢复 system/messages 对象图。 -func parseGatewayRequestCurrentBody(parsed *ParsedRequest, protocol string) error { +// parseGatewayRequestBody 只做标量和 raw range 轻量解析,不恢复 system/messages 对象图。 +// validate 为 false 时要求调用方已经确认 body 是合法 JSON(见 ParseGatewayRequestValidated)。 +func parseGatewayRequestBody(parsed *ParsedRequest, protocol string, validate bool) error { if parsed == nil || parsed.Body == nil { return fmt.Errorf("empty request body") } bodyBytes := parsed.Body.Bytes() - if !gjson.ValidBytes(bodyBytes) { + if validate && !gjson.ValidBytes(bodyBytes) { return DescribeInvalidJSON(bodyBytes) } - // 只在当前函数内零拷贝读取 JSON 字段;ReplaceBody 后必须重新进入本函数刷新派生状态。 - jsonStr := *(*string)(unsafe.Pointer(&bodyBytes)) + // Zero-copy JSON reads stay local to parsing. Persisted scalar strings must + // own their storage: an unescaped gjson string otherwise retains the complete + // request buffer when copied into queued billing work. Raw ranges stay zero-copy. clearGatewayRequestDerivedState(parsed) parsed.protocol = protocol - modelResult := gjson.Get(jsonStr, "model") - if modelResult.Exists() { - if modelResult.Type != gjson.String { + fields := scanGatewayRequestRoot(bodyBytes) + + if fields.model.Exists() { + if fields.model.Type != gjson.String { return fmt.Errorf("invalid model field type") } - parsed.Model = modelResult.String() + parsed.Model = strings.Clone(fields.model.String()) if protocol == domain.PlatformAnthropic { normalizedModel := normalizeClaudeCodeLongContextModel(parsed.Model) if normalizedModel != parsed.Model { @@ -206,46 +295,45 @@ func parseGatewayRequestCurrentBody(parsed *ParsedRequest, protocol string) erro } parsed.Body.Replace(normalizedBody) bodyBytes = normalizedBody - jsonStr = *(*string)(unsafe.Pointer(&bodyBytes)) + // 改写后旧的值视图指向已失效的字节,重新遍历一次(仅 [1m] 规范化这条罕见路径)。 + fields = scanGatewayRequestRoot(bodyBytes) parsed.Model = normalizedModel } } } - streamResult := gjson.Get(jsonStr, "stream") - if streamResult.Exists() { - if streamResult.Type != gjson.True && streamResult.Type != gjson.False { + if fields.stream.Exists() { + if fields.stream.Type != gjson.True && fields.stream.Type != gjson.False { return fmt.Errorf("invalid stream field type") } - parsed.Stream = streamResult.Bool() + parsed.Stream = fields.stream.Bool() } - parsed.MetadataUserID = gjson.Get(jsonStr, "metadata.user_id").String() + parsed.MetadataUserID = strings.Clone(fields.metadataUID.String()) - thinkingType := gjson.Get(jsonStr, "thinking.type").String() + thinkingType := fields.thinkingType.String() parsed.ThinkingEnabled = thinkingType == "enabled" || thinkingType == "adaptive" || thinkingType == "between_tools" || (protocol == domain.PlatformAnthropic && isClaude55SignedThinkingModel(parsed.Model)) - parsed.OutputEffort = strings.TrimSpace(gjson.Get(jsonStr, "output_config.effort").String()) + parsed.OutputEffort = strings.Clone(strings.TrimSpace(fields.outputEffort.String())) if protocol == domain.PlatformAnthropic { - parsed.Speed = strings.ToLower(strings.TrimSpace(gjson.Get(jsonStr, "speed").String())) + parsed.Speed = strings.Clone(strings.ToLower(strings.TrimSpace(fields.speed.String()))) } - maxTokensResult := gjson.Get(jsonStr, "max_tokens") - if maxTokensResult.Exists() && maxTokensResult.Type == gjson.Number { - f := maxTokensResult.Float() + if fields.maxTokens.Exists() && fields.maxTokens.Type == gjson.Number { + f := fields.maxTokens.Float() if !math.IsNaN(f) && !math.IsInf(f, 0) && f == math.Trunc(f) && f <= float64(math.MaxInt) && f >= float64(math.MinInt) { parsed.MaxTokens = int(f) } } - setGatewayRequestRanges(parsed, protocol, jsonStr) + setGatewayRequestRangesFromFields(parsed, protocol, fields) return nil } func refreshGatewayRequestRanges(parsed *ParsedRequest, protocol string) error { - return parseGatewayRequestCurrentBody(parsed, protocol) + return parseGatewayRequestBody(parsed, protocol, true) } // DescribeInvalidJSON returns a diagnostic error for a request body that @@ -352,8 +440,20 @@ func normalizeSessionUserAgentFallback(raw string) string { // protocol 指定请求协议格式(domain.PlatformAnthropic / domain.PlatformGemini), // 不同协议使用不同的 system/messages 字段名。 func ParseGatewayRequest(body *RequestBodyRef, protocol string) (*ParsedRequest, error) { + return parseGatewayRequest(body, protocol, true) +} + +// ParseGatewayRequestValidated 与 ParseGatewayRequest 结果相同,但要求调用方已经确认 +// body 是合法 JSON(例如 handler 已对同一份字节做过 gjson.ValidBytes,且此后的改写只 +// 经过 sjson)。它跳过这次全量校验——1 MiB body 上约 510µs,占解析耗时的七成。 +// 非法 JSON 的语义与未校验版本不同,只允许在校验过同一份字节的调用点使用。 +func ParseGatewayRequestValidated(body *RequestBodyRef, protocol string) (*ParsedRequest, error) { + return parseGatewayRequest(body, protocol, false) +} + +func parseGatewayRequest(body *RequestBodyRef, protocol string, validate bool) (*ParsedRequest, error) { parsed := &ParsedRequest{Body: body} - if err := parseGatewayRequestCurrentBody(parsed, protocol); err != nil { + if err := parseGatewayRequestBody(parsed, protocol, validate); err != nil { return nil, err } return parsed, nil diff --git a/backend/internal/service/gateway_request_json_bench_test.go b/backend/internal/service/gateway_request_json_bench_test.go index d56064a09cd3..2eca1091a765 100644 --- a/backend/internal/service/gateway_request_json_bench_test.go +++ b/backend/internal/service/gateway_request_json_bench_test.go @@ -10,8 +10,32 @@ import ( // claudeCodeLikeBody builds a ~32KB request shaped like a Claude Code turn: // 20 tools, a system prompt, and 40 messages with 4 content blocks each. func claudeCodeLikeBody(cacheControls int, with1h bool) []byte { + return claudeCodeLikeBodyWith(claudeCodeLikeBodyOptions{cacheControls: cacheControls, with1h: with1h}) +} + +// claudeCodeLikeBodyWithThinking builds the same shape with extended thinking +// enabled: the top-level thinking config plus a thinking block in the last +// assistant turn. Either occurrence makes the byte-level precheck in +// enforceCacheControlLimit inapplicable, so this is the shape that decides +// whether the cache_control walks can be skipped for real Claude Code traffic. +func claudeCodeLikeBodyWithThinking(with1h bool) []byte { + return claudeCodeLikeBodyWith(claudeCodeLikeBodyOptions{cacheControls: 4, with1h: with1h, thinking: true}) +} + +type claudeCodeLikeBodyOptions struct { + cacheControls int + with1h bool + thinking bool +} + +func claudeCodeLikeBodyWith(opts claudeCodeLikeBodyOptions) []byte { + cacheControls := opts.cacheControls var b strings.Builder - _, _ = b.WriteString(`{"model":"claude-sonnet-5-5","max_tokens":32000,"stream":true,"tools":[`) + _, _ = b.WriteString(`{"model":"claude-sonnet-5-5","max_tokens":32000,"stream":true`) + if opts.thinking { + _, _ = b.WriteString(`,"thinking":{"type":"enabled","budget_tokens":31999}`) + } + _, _ = b.WriteString(`,"tools":[`) for i := 0; i < 20; i++ { if i > 0 { _ = b.WriteByte(',') @@ -42,10 +66,14 @@ func claudeCodeLikeBody(cacheControls int, with1h bool) []byte { if c > 0 { _ = b.WriteByte(',') } + if opts.thinking && m == 39 && c == 0 { + _, _ = b.WriteString(`{"type":"thinking","thinking":"` + strings.Repeat("t", 80) + `","signature":"` + strings.Repeat("s", 64) + `"}`) + continue + } fmt.Fprintf(&b, `{"type":"text","text":"%s"`, strings.Repeat("x", 120)) if m >= 38 && c == 3 && cacheControls > 0 { ttl := "" - if with1h && m == 39 { + if opts.with1h && m == 39 { ttl = `,"ttl":"1h"` } fmt.Fprintf(&b, `,"cache_control":{"type":"ephemeral"%s}`, ttl) @@ -66,6 +94,8 @@ func BenchmarkEnforceCacheControlLimit(b *testing.B) { }{ {"common_4cc_no1h", claudeCodeLikeBody(4, false)}, {"with_1h", claudeCodeLikeBody(4, true)}, + {"thinking_4cc_no1h", claudeCodeLikeBodyWithThinking(false)}, + {"thinking_4cc_1h", claudeCodeLikeBodyWithThinking(true)}, } for _, tc := range cases { b.Run(tc.name+"/legacy", func(b *testing.B) { diff --git a/backend/internal/service/gateway_request_scan_benchmark_test.go b/backend/internal/service/gateway_request_scan_benchmark_test.go new file mode 100644 index 000000000000..f74bf099370d --- /dev/null +++ b/backend/internal/service/gateway_request_scan_benchmark_test.go @@ -0,0 +1,94 @@ +package service + +import ( + "strings" + "testing" + + "github.com/Wei-Shaw/sub2api/internal/domain" +) + +// buildGatewayRequestBenchmarkBody 生成 Codex / Claude Code 两种形态的大请求体。 +func buildGatewayRequestBenchmarkBody(targetBytes int, anthropic bool) []byte { + var sb strings.Builder + sb.Grow(targetBytes + 1024) + // strings.Builder.WriteString 的 error 恒为 nil,errcheck 不接受裸忽略,收口在这里。 + write := func(s string) { _, _ = sb.WriteString(s) } + item := `{"type":"message","role":"user","content":[{"type":"input_text","text":"` + strings.Repeat("x", 4000) + `"}]}` + if anthropic { + write(`{"model":"claude-sonnet-5-5","stream":true,"system":[{"type":"text","text":"`) + write(strings.Repeat("z", targetBytes/8)) + write(`"}],"tools":[{"name":"shell","description":"`) + write(strings.Repeat("y", targetBytes/16)) + write(`"}],"messages":[`) + msg := `{"role":"user","content":[{"type":"text","text":"` + strings.Repeat("x", 4000) + `"}]}` + for i := 0; sb.Len() < targetBytes; i++ { + if i > 0 { + write(`,`) + } + write(msg) + } + write(`]}`) + return []byte(sb.String()) + } + write(`{"model":"gpt-5.5","stream":true,"instructions":"`) + write(strings.Repeat("z", targetBytes/8)) + write(`","tools":[{"type":"function","name":"shell","description":"`) + write(strings.Repeat("y", targetBytes/16)) + write(`"}],"input":[`) + for i := 0; sb.Len() < targetBytes; i++ { + if i > 0 { + write(`,`) + } + write(item) + } + write(`]}`) + return []byte(sb.String()) +} + +func BenchmarkParseGatewayRequestScan(b *testing.B) { + cases := []struct { + name string + size int + protocol string + anthropic bool + }{ + {"responses_128KiB", 128 << 10, "responses", false}, + {"responses_1MiB", 1 << 20, "responses", false}, + {"anthropic_1MiB", 1 << 20, domain.PlatformAnthropic, true}, + } + + for _, tc := range cases { + body := buildGatewayRequestBenchmarkBody(tc.size, tc.anthropic) + b.Run(tc.name+"/legacy", func(b *testing.B) { + b.SetBytes(int64(len(body))) + b.ReportAllocs() + for range b.N { + parsed := &ParsedRequest{Body: NewRequestBodyRef(body)} + if err := legacyParseGatewayRequestCurrentBody(parsed, tc.protocol); err != nil { + b.Fatal(err) + } + } + }) + b.Run(tc.name+"/scan", func(b *testing.B) { + b.SetBytes(int64(len(body))) + b.ReportAllocs() + for range b.N { + parsed := &ParsedRequest{Body: NewRequestBodyRef(body)} + if err := parseGatewayRequestBody(parsed, tc.protocol, true); err != nil { + b.Fatal(err) + } + } + }) + // 调用方已经校验过同一份字节时(handler 已做 gjson.ValidBytes,且之后只经 sjson 改写)。 + b.Run(tc.name+"/scan_validated", func(b *testing.B) { + b.SetBytes(int64(len(body))) + b.ReportAllocs() + for range b.N { + parsed := &ParsedRequest{Body: NewRequestBodyRef(body)} + if err := parseGatewayRequestBody(parsed, tc.protocol, false); err != nil { + b.Fatal(err) + } + } + }) + } +} diff --git a/backend/internal/service/gateway_request_scan_equivalence_test.go b/backend/internal/service/gateway_request_scan_equivalence_test.go new file mode 100644 index 000000000000..b0d6e9ec2b3f --- /dev/null +++ b/backend/internal/service/gateway_request_scan_equivalence_test.go @@ -0,0 +1,324 @@ +package service + +import ( + "fmt" + "math" + "strings" + "testing" + "unsafe" + + "github.com/Wei-Shaw/sub2api/internal/domain" + "github.com/stretchr/testify/require" + "github.com/tidwall/gjson" + "github.com/tidwall/sjson" +) + +// 下面两个函数是重构前的 parseGatewayRequestCurrentBody / setGatewayRequestRanges +// 的逐字副本,作为差分测试的基准。任何一处语义变化都会在下面的对比里暴露。 +func legacyParseGatewayRequestCurrentBody(parsed *ParsedRequest, protocol string) error { + if parsed == nil || parsed.Body == nil { + return fmt.Errorf("empty request body") + } + + bodyBytes := parsed.Body.Bytes() + if !gjson.ValidBytes(bodyBytes) { + return DescribeInvalidJSON(bodyBytes) + } + + jsonStr := *(*string)(unsafe.Pointer(&bodyBytes)) + clearGatewayRequestDerivedState(parsed) + parsed.protocol = protocol + + modelResult := gjson.Get(jsonStr, "model") + if modelResult.Exists() { + if modelResult.Type != gjson.String { + return fmt.Errorf("invalid model field type") + } + parsed.Model = strings.Clone(modelResult.String()) + if protocol == domain.PlatformAnthropic { + normalizedModel := normalizeClaudeCodeLongContextModel(parsed.Model) + if normalizedModel != parsed.Model { + normalizedBody, err := sjson.SetBytes(bodyBytes, "model", normalizedModel) + if err != nil { + return fmt.Errorf("normalize model field: %w", err) + } + parsed.Body.Replace(normalizedBody) + bodyBytes = normalizedBody + jsonStr = *(*string)(unsafe.Pointer(&bodyBytes)) + parsed.Model = normalizedModel + } + } + } + + streamResult := gjson.Get(jsonStr, "stream") + if streamResult.Exists() { + if streamResult.Type != gjson.True && streamResult.Type != gjson.False { + return fmt.Errorf("invalid stream field type") + } + parsed.Stream = streamResult.Bool() + } + + parsed.MetadataUserID = strings.Clone(gjson.Get(jsonStr, "metadata.user_id").String()) + + thinkingType := gjson.Get(jsonStr, "thinking.type").String() + parsed.ThinkingEnabled = thinkingType == "enabled" || thinkingType == "adaptive" || thinkingType == "between_tools" || + (protocol == domain.PlatformAnthropic && isClaude55SignedThinkingModel(parsed.Model)) + + parsed.OutputEffort = strings.Clone(strings.TrimSpace(gjson.Get(jsonStr, "output_config.effort").String())) + if protocol == domain.PlatformAnthropic { + parsed.Speed = strings.Clone(strings.ToLower(strings.TrimSpace(gjson.Get(jsonStr, "speed").String()))) + } + + maxTokensResult := gjson.Get(jsonStr, "max_tokens") + if maxTokensResult.Exists() && maxTokensResult.Type == gjson.Number { + f := maxTokensResult.Float() + if !math.IsNaN(f) && !math.IsInf(f, 0) && f == math.Trunc(f) && + f <= float64(math.MaxInt) && f >= float64(math.MinInt) { + parsed.MaxTokens = int(f) + } + } + + legacySetGatewayRequestRanges(parsed, protocol, jsonStr) + return nil +} + +func legacySetGatewayRequestRanges(parsed *ParsedRequest, protocol string, jsonStr string) { + if parsed == nil { + return + } + switch protocol { + case domain.PlatformGemini: + if sysParts := gjson.Get(jsonStr, "systemInstruction.parts"); sysParts.Exists() && sysParts.IsArray() { + parsed.systemRange = rangeFromResult(sysParts) + } + if contents := gjson.Get(jsonStr, "contents"); contents.Exists() && contents.IsArray() { + parsed.messagesRange = rangeFromResult(contents) + } + default: + if sys := gjson.Get(jsonStr, "system"); sys.Exists() { + parsed.HasSystem = true + parsed.systemRange = rangeFromResult(sys) + } + if msgs := gjson.Get(jsonStr, "messages"); msgs.Exists() && msgs.IsArray() { + parsed.messagesRange = rangeFromResult(msgs) + } + if protocol == "responses" { + if input := gjson.Get(jsonStr, "input"); input.Exists() { + parsed.inputRange = rangeFromResult(input) + } + } + } +} + +// parsedSnapshot 只记录解析产出的可观测结果,避免比较实现内部的缓存指针。 +type parsedSnapshot struct { + err string + model string + stream bool + metadataUserID string + thinkingOn bool + outputEffort string + speed string + maxTokens int + hasSystem bool + systemRange jsonRange + messagesRange jsonRange + inputRange jsonRange + protocol string + bodyAfter string +} + +func snapshotOf(parsed *ParsedRequest, err error) parsedSnapshot { + snap := parsedSnapshot{} + if err != nil { + snap.err = err.Error() + } + if parsed == nil { + return snap + } + snap.model = parsed.Model + snap.stream = parsed.Stream + snap.metadataUserID = parsed.MetadataUserID + snap.thinkingOn = parsed.ThinkingEnabled + snap.outputEffort = parsed.OutputEffort + snap.speed = parsed.Speed + snap.maxTokens = parsed.MaxTokens + snap.hasSystem = parsed.HasSystem + snap.systemRange = parsed.systemRange + snap.messagesRange = parsed.messagesRange + snap.inputRange = parsed.inputRange + snap.protocol = parsed.protocol + if parsed.Body != nil { + snap.bodyAfter = string(parsed.Body.Bytes()) + } + return snap +} + +func parseBoth(t *testing.T, protocol string, body []byte) (parsedSnapshot, parsedSnapshot) { + t.Helper() + legacyBody := NewRequestBodyRef(append([]byte(nil), body...)) + legacyParsed := &ParsedRequest{Body: legacyBody} + legacyErr := legacyParseGatewayRequestCurrentBody(legacyParsed, protocol) + + // 直接调被重构的这一步:ParseGatewayRequest 在失败时返回 nil,无法比较错误路径上的中间状态。 + newBody := NewRequestBodyRef(append([]byte(nil), body...)) + newParsed := &ParsedRequest{Body: newBody} + newErr := parseGatewayRequestBody(newParsed, protocol, true) + + return snapshotOf(legacyParsed, legacyErr), snapshotOf(newParsed, newErr) +} + +func TestParseGatewayRequestMatchesLegacy(t *testing.T) { + escape := string(rune(92)) + cases := []struct { + name string + body string + }{ + {"typical responses", `{"model":"gpt-5.5","stream":true,"input":[{"type":"message"}]}`}, + {"typical anthropic", `{"model":"claude-sonnet-5-5","stream":true,"system":"s","messages":[{"role":"user","content":"hi"}],"max_tokens":1024,"thinking":{"type":"enabled"},"output_config":{"effort":" high "},"speed":"Fast"}`}, + {"typical gemini", `{"contents":[{"parts":[{"text":"hi"}]}],"systemInstruction":{"parts":[{"text":"sys"}]},"generationConfig":{"maxOutputTokens":32}}`}, + {"empty object", `{}`}, + {"empty string", ``}, + {"invalid json", `{"model":`}, + {"invalid json with image tool", `{"tools":[{"type":"image_generation"}]`}, + {"model wrong type", `{"model":123}`}, + {"model null", `{"model":null}`}, + {"stream wrong type", `{"model":"m","stream":"yes"}`}, + {"stream null", `{"model":"m","stream":null}`}, + {"stream false", `{"model":"m","stream":false}`}, + {"max_tokens float", `{"model":"m","max_tokens":1024.5}`}, + {"max_tokens negative", `{"model":"m","max_tokens":-8}`}, + {"max_tokens huge", `{"model":"m","max_tokens":1e30}`}, + {"max_tokens string", `{"model":"m","max_tokens":"1024"}`}, + {"metadata nested", `{"metadata":{"user_id":"u1"}}`}, + {"metadata string first", `{"metadata":"x","metadata":{"user_id":"u2"}}`}, + {"metadata null child", `{"metadata":{"user_id":null},"metadata":{"user_id":"u3"}}`}, + {"metadata wrong shape", `{"metadata":[],"metadata":{"user_id":"u4"}}`}, + {"thinking string first", `{"thinking":"x","thinking":{"type":"enabled"}}`}, + {"thinking adaptive", `{"thinking":{"type":"adaptive"}}`}, + {"thinking between tools", `{"thinking":{"type":"between_tools"}}`}, + {"effort with spaces", `{"output_config":{"effort":" medium "}}`}, + {"effort first empty", `{"output_config":{"effort":""},"output_config":{"effort":"high"}}`}, + {"speed uppercase", `{"speed":" FAST "}`}, + {"system string", `{"system":"sys","messages":[{"role":"user"}]}`}, + {"system object", `{"system":{"type":"text"},"messages":[]}`}, + {"system wrong shape", `{"system":123}`}, + {"messages not array", `{"messages":"x"}`}, + {"input present", `{"input":[{"a":1}]}`}, + {"contents not array", `{"contents":"x"}`}, + {"gemini parts not array", `{"systemInstruction":{"parts":"x"}}`}, + {"gemini parts retry", `{"systemInstruction":{"parts":"x"},"systemInstruction":{"parts":[{"a":1}]}}`}, + {"duplicate model", `{"model":"m1","model":"m2"}`}, + {"duplicate stream", `{"stream":true,"stream":false}`}, + {"long context suffix", `{"model":"claude-sonnet-5-5[1m]","messages":[]}`}, + {"long context suffix duplicated", `{"model":"claude-sonnet-5-5[1m][1m]","messages":[]}`}, + {"escaped system key", `{"` + escape + `u0073ystem":"s","messages":[]}`}, + {"escaped model key", `{"` + escape + `u006dodel":"m"}`}, + {"root array", `[1,2,3]`}, + {"root scalar", `"just a string"`}, + {"nested nulls", `{"model":"m","system":null,"messages":[{"a":1}],"input":null}`}, + {"unicode content", `{"model":"m","messages":[{"content":"中文 😀"}]}`}, + } + + protocols := []string{"responses", "chat_completions", domain.PlatformAnthropic, domain.PlatformGemini} + + for _, tc := range cases { + for _, protocol := range protocols { + t.Run(tc.name+"/"+protocol, func(t *testing.T) { + want, got := parseBoth(t, protocol, []byte(tc.body)) + require.Equal(t, want, got, "body=%s", tc.body) + }) + } + } +} + +// deterministic 随机组合,覆盖键顺序、重复键、类型混杂的组合空间。 +func TestParseGatewayRequestMatchesLegacyRandomized(t *testing.T) { + pieces := []string{ + `"model":"m"`, `"model":"claude-x[1m]"`, `"model":null`, `"model":1`, + `"stream":true`, `"stream":"x"`, `"stream":null`, + `"max_tokens":16`, `"max_tokens":16.5`, `"max_tokens":"16"`, + `"metadata":{"user_id":"u"}`, `"metadata":"s"`, `"metadata":null`, + `"thinking":{"type":"enabled"}`, `"thinking":{"type":"adaptive"}`, `"thinking":"x"`, + `"output_config":{"effort":" low "}`, `"output_config":null`, + `"speed":" FAST "`, `"speed":null`, + `"system":"sys"`, `"system":[{"type":"text"}]`, `"system":null`, + `"messages":[]`, `"messages":[{"role":"user"}]`, `"messages":"x"`, + `"input":[]`, `"input":[{"a":1}]`, `"input":null`, + `"contents":[]`, `"contents":"x"`, + `"systemInstruction":{"parts":[]}`, `"systemInstruction":{"parts":"x"}`, + `"unknown":1`, `"unknown":{"nested":true}`, + } + protocols := []string{"responses", "chat_completions", domain.PlatformAnthropic, domain.PlatformGemini} + + seed := uint64(0x9e3779b97f4a7c15) + next := func() uint64 { + seed ^= seed << 13 + seed ^= seed >> 7 + seed ^= seed << 17 + return seed + } + + for i := 0; i < 3000; i++ { + n := int(next()%6) + 1 + parts := make([]string, 0, n) + for j := 0; j < n; j++ { + parts = append(parts, pieces[int(next()%uint64(len(pieces)))]) + } + body := []byte("{" + strings.Join(parts, ",") + "}") + protocol := protocols[int(next()%uint64(len(protocols)))] + + want, got := parseBoth(t, protocol, body) + require.Equal(t, want, got, "iteration=%d protocol=%s body=%s", i, protocol, body) + } +} + +// 已校验变体只允许在「body 合法」的前提下使用;合法 JSON 上两者必须产出完全相同的结果。 +func TestParseGatewayRequestValidatedMatchesValidatingPath(t *testing.T) { + bodies := []string{ + `{"model":"gpt-5.5","stream":true,"input":[{"type":"message"}]}`, + `{"model":"claude-x[1m]","messages":[],"system":"s","max_tokens":8}`, + `{"metadata":{"user_id":"u"},"thinking":{"type":"enabled"},"output_config":{"effort":" high "}}`, + `{"contents":[],"systemInstruction":{"parts":[]}}`, + `{}`, + } + protocols := []string{"responses", "chat_completions", domain.PlatformAnthropic, domain.PlatformGemini} + for _, body := range bodies { + for _, protocol := range protocols { + validating := &ParsedRequest{Body: NewRequestBodyRef([]byte(body))} + validatingErr := parseGatewayRequestBody(validating, protocol, true) + + trusted := &ParsedRequest{Body: NewRequestBodyRef([]byte(body))} + trustedErr := parseGatewayRequestBody(trusted, protocol, false) + + require.Equal(t, snapshotOf(validating, validatingErr), snapshotOf(trusted, trustedErr), + "body=%s protocol=%s", body, protocol) + } + } +} + +func FuzzParseGatewayRequestMatchesLegacy(f *testing.F) { + f.Add([]byte(`{"model":"m","stream":true,"input":[]}`), "responses") + f.Add([]byte(`{"model":"claude-x[1m]","messages":[],"system":"s"}`), domain.PlatformAnthropic) + f.Add([]byte(`{"metadata":{"user_id":"u"},"thinking":{"type":"enabled"}}`), "chat_completions") + f.Add([]byte(`{"contents":[],"systemInstruction":{"parts":[]}}`), domain.PlatformGemini) + f.Fuzz(func(t *testing.T, body []byte, protocol string) { + switch protocol { + case "responses", "chat_completions", domain.PlatformAnthropic, domain.PlatformGemini: + default: + return + } + want, got := parseBoth(t, protocol, body) + require.Equal(t, want, got, "body=%q protocol=%s", body, protocol) + + // 合法 JSON 上,跳过校验不得改变结果。 + if gjson.ValidBytes(body) { + validating := &ParsedRequest{Body: NewRequestBodyRef(append([]byte(nil), body...))} + validatingErr := parseGatewayRequestBody(validating, protocol, true) + trusted := &ParsedRequest{Body: NewRequestBodyRef(append([]byte(nil), body...))} + trustedErr := parseGatewayRequestBody(trusted, protocol, false) + require.Equal(t, snapshotOf(validating, validatingErr), snapshotOf(trusted, trustedErr), + "validated path diverged: body=%q protocol=%s", body, protocol) + } + }) +} diff --git a/backend/internal/service/gateway_systemone.go b/backend/internal/service/gateway_systemone.go index b50a45c80b49..b2a23c635b28 100644 --- a/backend/internal/service/gateway_systemone.go +++ b/backend/internal/service/gateway_systemone.go @@ -11,6 +11,7 @@ import ( "github.com/Wei-Shaw/sub2api/internal/pkg/typesafe" "github.com/gin-gonic/gin" + "github.com/tidwall/sjson" ) type SystemOneForwardResult struct { @@ -47,6 +48,15 @@ func (s *GatewayService) ForwardSystemOne(ctx context.Context, c *gin.Context, a if err != nil { return nil, err } + mappedModel := firstNonEmpty(account.GetMappedModel(typesafe.JevLatestModel), typesafe.JevLatestModel) + var upstreamModel string + if mappedModel != typesafe.JevLatestModel { + body, err = sjson.SetBytes(body, "model", mappedModel) + if err != nil { + return nil, fmt.Errorf("apply TypeSafe account model mapping: %w", err) + } + upstreamModel = mappedModel + } req, err := typesafe.NewSystemOneRequest(ctx, baseURL, key, body) if err != nil { return nil, err @@ -59,6 +69,7 @@ func (s *GatewayService) ForwardSystemOne(ctx context.Context, c *gin.Context, a if err := checkAPIKeyLongContextBeforeForward(ctx, c, s.billingService, body); err != nil { return nil, err } + SetOpsUpstreamModel(c, upstreamModel) resp, err := s.httpUpstream.Do(req, proxyURL, account.ID, account.Concurrency) if err != nil { return nil, s.handleUpstreamTransportError(ctx, c, account, err, OpsUpstreamErrorEvent{ @@ -98,6 +109,7 @@ func (s *GatewayService) ForwardSystemOne(ctx context.Context, c *gin.Context, a UpstreamHeaders: resp.Header.Clone(), Usage: ClaudeUsage{InputTokens: decoded.Usage.InputTokens, OutputTokens: decoded.Usage.OutputTokens}, Model: typesafe.JevLatestModel, + UpstreamModel: upstreamModel, UpstreamResponseModel: decoded.Model, Duration: time.Since(started), }, diff --git a/backend/internal/service/gateway_systemone_test.go b/backend/internal/service/gateway_systemone_test.go index 657b9347ae50..fc68e1449b46 100644 --- a/backend/internal/service/gateway_systemone_test.go +++ b/backend/internal/service/gateway_systemone_test.go @@ -101,6 +101,40 @@ func TestForwardSystemOneForwardsNativeProtocolAndUsage(t *testing.T) { require.Equal(t, 7, result.Usage.OutputTokens) } +func TestForwardSystemOneAppliesAccountModelMapping(t *testing.T) { + const requestBody = `{"model":"jev-latest","state":{"model":"sample"},"questions":{"q":{"type":"noul","instructions":"Evaluate the sample"}},"stream":false}` + const mappedBody = `{"model":"decision-model-preview","state":{"model":"sample"},"questions":{"q":{"type":"noul","instructions":"Evaluate the sample"}},"stream":false}` + const responseBody = `{"model":"decision-model-2026-10","answers":{"q":{"type":"noul"}},"usage":{"input_tokens":12,"output_tokens":2}}` + var sentBody []byte + upstream := &systemOneHTTPUpstream{do: func(req *http.Request) (*http.Response, error) { + var err error + sentBody, err = io.ReadAll(req.Body) + require.NoError(t, err) + return &http.Response{StatusCode: http.StatusOK, Header: make(http.Header), Body: io.NopCloser(strings.NewReader(responseBody))}, nil + }} + svc := newSystemOneTestService(upstream) + svc.billingService = NewBillingService(&config.Config{}, nil) + account := &Account{ID: 7, Platform: PlatformTypeSafe, Type: AccountTypeAPIKey, Credentials: map[string]any{ + "base_url": "http://typesafe.test", + "api_key": "ts-fixture", + "model_mapping": map[string]any{"jev-latest": "decision-model-preview"}, + }} + c := newSystemOneTestContext() + body := []byte(requestBody) + result, err := svc.ForwardSystemOne(context.Background(), c, account, body) + require.NoError(t, err) + require.JSONEq(t, mappedBody, string(sentBody)) + require.Equal(t, requestBody, string(body)) + require.Equal(t, typesafe.JevLatestModel, result.Model) + require.Equal(t, "decision-model-preview", result.UpstreamModel) + require.Equal(t, "decision-model-preview", c.GetString(OpsUpstreamModelKey)) + require.Equal(t, "decision-model-2026-10", result.UpstreamResponseModel) + require.Equal(t, []byte(responseBody), result.Body) + apiKey := &APIKey{Group: &Group{Platform: PlatformTypeSafe}} + usageFields := ChannelUsageFields{OriginalModel: result.Model, BillingModelSource: BillingModelSourceUpstream} + require.Equal(t, typesafe.JevLatestModel, svc.recordUsageBillingModel(context.Background(), apiKey, &result.ForwardResult, usageFields)) +} + func TestForwardSystemOneAllowsSuccessfulResponseWithoutModel(t *testing.T) { responseBody := []byte(`{"answers":{"q":{"type":"noul","answer":"ok"}},"usage":{"input_tokens":12}}`) upstream := &systemOneHTTPUpstream{do: func(*http.Request) (*http.Response, error) { diff --git a/backend/internal/service/gemini_messages_compat_service.go b/backend/internal/service/gemini_messages_compat_service.go index ad5cffdcf401..1135b6e8c113 100644 --- a/backend/internal/service/gemini_messages_compat_service.go +++ b/backend/internal/service/gemini_messages_compat_service.go @@ -3706,6 +3706,34 @@ func convertClaudeMessagesToGeminiContents(messages any, toolUseIDToName map[str "parts": parts, }) } + // Gemini/Vertex 拒收「以 functionResponse 开头、后面还跟着其它 part」的最后一个 turn, + // 报错文案是误导性的 "Requests ending with a model turn are not supported."。 + // 客户端在工具结果后紧跟一条 user 文本时(例如 ACP nudge),CC→Claude 的 + // mergeConsecutiveMessages 会把它并进同一个 user 消息,这里再把尾部的非 + // functionResponse part 拆成独立的一轮 user,语义顺序不变。 + if n := len(out); n > 0 { + if last, ok := out[n-1].(map[string]any); ok { + if parts, ok := last["parts"].([]any); ok { + lastFR := -1 + for i, p := range parts { + pm, ok := p.(map[string]any) + if !ok { + continue + } + if _, isFR := pm["functionResponse"]; isFR { + lastFR = i + } + } + if lastFR >= 0 && lastFR < len(parts)-1 { + last["parts"] = parts[:lastFR+1] + out = append(out, map[string]any{ + "role": "user", + "parts": parts[lastFR+1:], + }) + } + } + } + } return out, nil } diff --git a/backend/internal/service/gemini_messages_compat_service_test.go b/backend/internal/service/gemini_messages_compat_service_test.go index a207153b7a5c..8380ea7608c3 100644 --- a/backend/internal/service/gemini_messages_compat_service_test.go +++ b/backend/internal/service/gemini_messages_compat_service_test.go @@ -990,7 +990,10 @@ func TestConvertClaudeMessagesToGeminiGenerateContent_ExtractsToolResultImages(t require.True(t, ok) parts, ok := content["parts"].([]any) require.True(t, ok) - require.Len(t, parts, 4) + // Gemini 拒绝 functionResponse 之后仍带其它 part 的轮次 + //("Requests ending with a model turn are not supported."), + // 工具结果图片因此被拆到紧随其后的独立 user 轮。 + require.Len(t, parts, 2) firstPart, ok := parts[0].(map[string]any) require.True(t, ok) @@ -1009,13 +1012,20 @@ func TestConvertClaudeMessagesToGeminiGenerateContent_ExtractsToolResultImages(t require.True(t, ok) require.Equal(t, "[image attached below]", secondResponseBody["content"]) - firstImagePart, ok := parts[2].(map[string]any) + imageContent, ok := contents[2].(map[string]any) + require.True(t, ok) + require.Equal(t, "user", imageContent["role"]) + imageParts, ok := imageContent["parts"].([]any) + require.True(t, ok) + require.Len(t, imageParts, 2) + + firstImagePart, ok := imageParts[0].(map[string]any) require.True(t, ok) firstImage, ok := firstImagePart["inlineData"].(map[string]any) require.True(t, ok) require.Equal(t, "image/png", firstImage["mimeType"]) require.Equal(t, "aGVsbG8=", firstImage["data"]) - secondImagePart, ok := parts[3].(map[string]any) + secondImagePart, ok := imageParts[1].(map[string]any) require.True(t, ok) secondImage, ok := secondImagePart["inlineData"].(map[string]any) require.True(t, ok) diff --git a/backend/internal/service/grok_media.go b/backend/internal/service/grok_media.go index 8f7254acbfe0..e5aaeef4c583 100644 --- a/backend/internal/service/grok_media.go +++ b/backend/internal/service/grok_media.go @@ -33,9 +33,17 @@ const ( GrokMediaEndpointVideoContent GrokMediaEndpoint = "video_content" // Official xAI Imagine image-edit limit. - grokMediaMaxEditSourceImages = 3 + grokMediaMaxEditSourceImages = 5 ) +type GrokMediaInputValidationError struct { + Reason string +} + +func (e *GrokMediaInputValidationError) Error() string { + return e.Reason +} + func (e GrokMediaEndpoint) RequiresRequestBody() bool { return !e.IsVideoLookupRequest() } @@ -1076,7 +1084,7 @@ func prepareGrokMediaForwardBody(endpoint GrokMediaEndpoint, body []byte, conten images = append(images, grokMediaImageObject(dataURL)) } if len(images) > grokMediaMaxEditSourceImages { - return nil, "", fmt.Errorf("a maximum of %d source images is supported for image edits", grokMediaMaxEditSourceImages) + return nil, "", &GrokMediaInputValidationError{Reason: fmt.Sprintf("a maximum of %d source images is supported for image edits", grokMediaMaxEditSourceImages)} } if len(images) > 0 { payload["image"] = images[0] @@ -1107,7 +1115,7 @@ func prepareGrokMediaForwardBody(endpoint GrokMediaEndpoint, body []byte, conten func normalizeGrokMediaJSONImageRefs(body []byte) ([]byte, error) { info := ParseGrokMediaRequest("application/json", body) if len(info.InputImageURLs) > grokMediaMaxEditSourceImages { - return nil, fmt.Errorf("a maximum of %d source images is supported for image edits", grokMediaMaxEditSourceImages) + return nil, &GrokMediaInputValidationError{Reason: fmt.Sprintf("a maximum of %d source images is supported for image edits", grokMediaMaxEditSourceImages)} } out := body var err error diff --git a/backend/internal/service/grok_media_input_validation_test.go b/backend/internal/service/grok_media_input_validation_test.go new file mode 100644 index 000000000000..8e10d6c471a9 --- /dev/null +++ b/backend/internal/service/grok_media_input_validation_test.go @@ -0,0 +1,99 @@ +//go:build unit + +package service + +import ( + "bytes" + "context" + "encoding/json" + "fmt" + "mime/multipart" + "testing" + + "github.com/stretchr/testify/require" + "github.com/tidwall/gjson" +) + +func TestPrepareGrokImageEditSourceLimit(t *testing.T) { + for _, format := range []string{"json", "multipart URLs", "multipart uploads", "multipart mixed"} { + for _, count := range []int{3, 4, 5, 6} { + t.Run(fmt.Sprintf("%s/%d", format, count), func(t *testing.T) { + var body []byte + contentType := "application/json" + if format == "json" { + images := make([]string, count-1) + for index := range images { + images[index] = fmt.Sprintf("https://example.test/%d.png", index+1) + } + var err error + body, err = json.Marshal(map[string]any{ + "image": "https://example.test/0.png", "images": images, + "mask": "https://example.test/mask.png", + }) + require.NoError(t, err) + } else { + var buffer bytes.Buffer + writer := multipart.NewWriter(&buffer) + for index := 0; index < count; index++ { + if format == "multipart URLs" || (format == "multipart mixed" && index%2 == 0) { + require.NoError(t, writer.WriteField("image", fmt.Sprintf("https://example.test/%d.png", index))) + } else { + part, err := writer.CreateFormFile("image[]", fmt.Sprintf("%d.png", index)) + require.NoError(t, err) + _, err = part.Write([]byte("\x89PNG\r\n\x1a\nsynthetic")) + require.NoError(t, err) + } + } + if format == "multipart URLs" { + require.NoError(t, writer.WriteField("mask", "https://example.test/mask.png")) + } else { + part, err := writer.CreateFormFile("mask", "mask.png") + require.NoError(t, err) + _, err = part.Write([]byte("\x89PNG\r\n\x1a\nmask")) + require.NoError(t, err) + } + require.NoError(t, writer.Close()) + body, contentType = buffer.Bytes(), writer.FormDataContentType() + } + out, outputType, err := prepareGrokMediaForwardBody(GrokMediaEndpointImagesEdits, body, contentType) + if count > 5 { + var validationErr *GrokMediaInputValidationError + require.ErrorAs(t, err, &validationErr) + require.Equal(t, "a maximum of 5 source images is supported for image edits", validationErr.Error()) + require.Nil(t, out) + return + } + require.NoError(t, err) + require.Equal(t, "application/json", outputType) + if format == "json" { + require.Len(t, gjson.GetBytes(out, "images").Array(), count-1) + } else { + require.Len(t, gjson.GetBytes(out, "images").Array(), count) + } + require.NotEmpty(t, gjson.GetBytes(out, "image.url").String()) + require.NotEmpty(t, gjson.GetBytes(out, "mask.url").String()) + }) + } + } +} + +func TestGrokMediaInternalErrorsAreNotInputValidation(t *testing.T) { + for _, test := range []struct { + name string + account *Account + }{ + {"missing account", nil}, + {"wrong platform", &Account{Platform: PlatformOpenAI}}, + {"missing credential", &Account{Platform: PlatformGrok, Type: AccountTypeAPIKey}}, + {"invalid base URL", &Account{Platform: PlatformGrok, Type: AccountTypeAPIKey, Credentials: map[string]any{"api_key": "test", "base_url": "://invalid"}}}, + {"missing OAuth provider", &Account{Platform: PlatformGrok, Type: AccountTypeOAuth}}, + } { + t.Run(test.name, func(t *testing.T) { + svc := &OpenAIGatewayService{} + _, err := svc.ForwardGrokMedia(context.Background(), nil, test.account, GrokMediaEndpointImagesEdits, "", []byte(`{"images":[]}`), "application/json") + require.Error(t, err) + var validationErr *GrokMediaInputValidationError + require.NotErrorAs(t, err, &validationErr) + }) + } +} diff --git a/backend/internal/service/grok_search_count.go b/backend/internal/service/grok_search_count.go index 2b8136b62f8d..e641072d2d72 100644 --- a/backend/internal/service/grok_search_count.go +++ b/backend/internal/service/grok_search_count.go @@ -13,10 +13,18 @@ import ( // Counts: web_search_call, x_search_call, tool_search_call, and function_call // named tool_search / web_search / x_search, and custom_tool_call items the xAI // server runs itself (apicompat.IsServerSideSearchCall: call_id xs_ / as_). +// +// When usage.server_side_tool_usage_details is present, xAI's reported success +// counts replace the item count (see grokSearchCountFromUsage). func countGrokNativeSearchCallsFromJSONBytes(body []byte) int { if len(body) == 0 || !gjson.ValidBytes(body) { return 0 } + for _, path := range []string{"response.usage", "usage"} { + if n, ok := grokSearchCountFromUsage(gjson.GetBytes(body, path)); ok { + return n + } + } // Responses envelopes normally expose either top-level output (JSON mode) // or response.output (terminal SSE payload). Compatibility layers can retain // both copies; counting both would bill the same search twice. Prefer the @@ -35,10 +43,47 @@ func countGrokNativeSearchCallsFromSSEBody(body string) int { total := 0 forEachOpenAISSEDataPayload(body, func(data []byte) { total += countGrokNativeSearchCallsInSSEDataDedup(data, seen) + total = grokSearchCountWithTerminalUsage(total, data) }) return total } +// grokSearchCountFromUsage reads xAI's per-class success counts from a usage +// object. xAI documents these counts as what determines billing for per-call +// tools (https://docs.x.ai/developers/tools/tool-usage-details#server-side-tool-calls-vs-tool-usage). +// Only the classes the item counter also counts are read: web_search_calls +// (web_search_call items), x_search_calls (xs_ custom_tool_call items) and +// document_search_calls (as_ custom_tool_call items). Other classes and the +// X Search item counts (x_posts_fetched, x_users_fetched) are not read. ok is +// false when server_side_tool_usage_details is absent, so callers keep the +// item count. +func grokSearchCountFromUsage(usage gjson.Result) (int, bool) { + details := usage.Get("server_side_tool_usage_details") + if !details.IsObject() { + return 0, false + } + total := details.Get("web_search_calls").Int() + + details.Get("x_search_calls").Int() + + details.Get("document_search_calls").Int() + if total < 0 { + total = 0 + } + return int(total), true +} + +// grokSearchCountWithTerminalUsage returns xAI's usage-reported count when data +// is a terminal stream event carrying server_side_tool_usage_details (the +// request total per the xAI X Search docs), else keeps the running total. +func grokSearchCountWithTerminalUsage(total int, data []byte) int { + switch strings.TrimSpace(gjson.GetBytes(data, "type").String()) { + case "response.completed", "response.incomplete", "response.done": + if n, ok := grokSearchCountFromUsage(gjson.GetBytes(data, "response.usage")); ok { + return n + } + } + return total +} + // countGrokNativeSearchCallsInSSEData counts search tool calls in one SSE // payload without cross-event dedup. Prefer countGrokNativeSearchCallsInSSEDataDedup // for live streams so item.done + response.completed do not double-bill. diff --git a/backend/internal/service/grok_search_usage_billing_test.go b/backend/internal/service/grok_search_usage_billing_test.go new file mode 100644 index 000000000000..6b41aa8587a6 --- /dev/null +++ b/backend/internal/service/grok_search_usage_billing_test.go @@ -0,0 +1,147 @@ +//go:build unit + +package service + +import ( + "bytes" + "context" + "fmt" + "io" + "net/http" + "net/http/httptest" + "strings" + "testing" + "time" + + "github.com/gin-gonic/gin" + "github.com/stretchr/testify/require" +) + +// Usage fixtures follow the public xAI Responses captures: x_search_calls and the +// x_posts_fetched / x_users_fetched item counts as in big-AGI grok-4.3_x-search, and the +// web_search_calls + x_search_calls + code_interpreter_calls mix as in grok-4.3_web+x-search+code. +// document_search_calls is listed in the xAI ModelOutput schema (server_side_tool_usage_details). +const ( + grokUsageXSearchDetails = `{"x_search_calls":3,"x_posts_fetched":13,"x_users_fetched":3}` + grokUsageWebXCodeDetails = `{"web_search_calls":2,"x_search_calls":1,"code_interpreter_calls":1,"x_posts_fetched":6}` + grokUsageDocumentDetails = `{"document_search_calls":5}` + grokUsageUnrelatedDetails = `{"code_interpreter_calls":1,"file_search_calls":1,"mcp_calls":1,"x_posts_fetched":7,"x_users_fetched":2}` + grokFailedXSearchItemJSON = `{"type":"custom_tool_call","id":"ctc_4","call_id":"xs_999","name":"x_thread_fetch","input":"{}","status":"failed"}` +) + +func grokUsageJSON(details string) string { + usage := `{"input_tokens":5,"output_tokens":2,"total_tokens":7` + if details != "" { + usage += `,"server_side_tool_usage_details":` + details + } + return usage + "}" +} + +type grokUsageCase struct { + name string + items []string + details string + want int +} + +func grokUsageCases() []grokUsageCase { + return []grokUsageCase{ + {"x_search_calls only, posts and users fetched not read", []string{grokXSearchItemJSON}, grokUsageXSearchDetails, 3}, + {"web_search_calls, x_search_calls summed, code_interpreter_calls not read", []string{grokXSearchItemJSON}, grokUsageWebXCodeDetails, 3}, + {"document_search_calls", []string{grokXSearchItemJSON}, grokUsageDocumentDetails, 5}, + {"all three fields", []string{grokXSearchItemJSON}, `{"web_search_calls":1,"x_search_calls":2,"document_search_calls":3}`, 6}, + {"only unrelated classes: usage wins with zero", []string{grokXSearchItemJSON, grokASearchItemJSON}, grokUsageUnrelatedDetails, 0}, + {"usage absent: items counted", []string{grokXSearchItemJSON, grokASearchItemJSON, grokClientToolJSON}, "", 2}, + {"usage lower than items: failed call not billed", []string{grokXSearchItemJSON, grokFailedXSearchItemJSON}, `{"x_search_calls":1}`, 1}, + {"usage zero, items present", []string{grokXSearchItemJSON}, `{"x_search_calls":0}`, 0}, + } +} + +func TestGrokSearchCountFromUsageJSON(t *testing.T) { + for _, tc := range grokUsageCases() { + t.Run(tc.name, func(t *testing.T) { + output := "[" + strings.Join(tc.items, ",") + "]" + top := `{"output":` + output + `,"usage":` + grokUsageJSON(tc.details) + "}" + nested := `{"response":{"output":` + output + `,"usage":` + grokUsageJSON(tc.details) + "}}" + require.Equal(t, tc.want, countGrokNativeSearchCallsFromJSONBytes([]byte(top))) + require.Equal(t, tc.want, countGrokNativeSearchCallsFromJSONBytes([]byte(nested))) + }) + } +} + +func TestGrokSearchCountFromUsageSSEBody(t *testing.T) { + for _, tc := range grokUsageCases() { + t.Run(tc.name, func(t *testing.T) { + sse := withGrokUsage(grokCustomToolCallStream(tc.items, "[]"), tc.details) + require.Equal(t, tc.want, countGrokNativeSearchCallsFromSSEBody(sse)) + }) + } +} + +func TestGrokSearchCountWithTerminalUsage(t *testing.T) { + usage := `"usage":` + grokUsageJSON(`{"x_search_calls":4}`) + for _, eventType := range []string{"response.completed", "response.incomplete", "response.done"} { + data := []byte(fmt.Sprintf(`{"type":%q,"response":{"output":[],%s}}`, eventType, usage)) + require.Equal(t, 4, grokSearchCountWithTerminalUsage(1, data), eventType) + } + for _, eventType := range []string{"response.created", "response.in_progress", "response.output_item.done"} { + data := []byte(fmt.Sprintf(`{"type":%q,"response":{%s}}`, eventType, usage)) + require.Equal(t, 1, grokSearchCountWithTerminalUsage(1, data), eventType) + } + require.Equal(t, 1, grokSearchCountWithTerminalUsage(1, []byte(`{"type":"response.completed","response":{"usage":{"input_tokens":1}}}`))) +} + +func withGrokUsage(sse, details string) string { + return strings.Replace(sse, `"usage":{"input_tokens":5,"output_tokens":2,"total_tokens":7}`, `"usage":`+grokUsageJSON(details), 1) +} + +func TestGrokSearchCountFromUsageAcrossEndpoints(t *testing.T) { + account := healthyGrokOAuthGatewayTestAccount(4243, "access-token") + for _, tc := range grokUsageCases() { + sse := withGrokUsage(grokCustomToolCallStream(tc.items, "[]"), tc.details) + for _, path := range []string{"/v1/messages", "/v1/chat/completions"} { + for _, streaming := range []bool{false, true} { + t.Run(fmt.Sprintf("%s %s stream=%v", tc.name, path, streaming), func(t *testing.T) { + got := forwardGrokCustomToolCallStream(t, path, streaming, account, sse) + require.Equal(t, tc.want, got.searchCount) + }) + } + } + t.Run(fmt.Sprintf("%s /v1/responses stream", tc.name), func(t *testing.T) { + require.Equal(t, tc.want, forwardGrokResponsesSearchCount(t, true, sse)) + }) + t.Run(fmt.Sprintf("%s /v1/responses json", tc.name), func(t *testing.T) { + body := `{"id":"resp_1","object":"response","model":"grok-4.7","status":"completed","output":[` + + strings.Join(tc.items, ",") + `],"usage":` + grokUsageJSON(tc.details) + "}" + require.Equal(t, tc.want, forwardGrokResponsesSearchCount(t, false, body)) + }) + } +} + +func forwardGrokResponsesSearchCount(t *testing.T, streaming bool, upstreamBody string) int { + t.Helper() + gin.SetMode(gin.TestMode) + body := []byte(fmt.Sprintf(`{"model":"grok","input":"search","stream":%t}`, streaming)) + c, _ := gin.CreateTestContext(httptest.NewRecorder()) + c.Request = httptest.NewRequest(http.MethodPost, "/v1/responses", bytes.NewReader(body)) + account := healthyGrokOAuthGatewayTestAccount(9903, "access-token") + repo := &mockAccountRepoForPlatform{accountsByID: map[int64]*Account{account.ID: account}} + contentType := "application/json" + if streaming { + contentType = "text/event-stream" + } + upstream := &httpUpstreamRecorder{resp: &http.Response{ + StatusCode: http.StatusOK, + Header: http.Header{"Content-Type": []string{contentType}}, + Body: io.NopCloser(strings.NewReader(upstreamBody)), + }} + svc := &OpenAIGatewayService{ + httpUpstream: upstream, + grokTokenProvider: NewGrokTokenProvider(repo, nil), + accountRepo: repo, + } + result, err := svc.forwardGrokResponses(context.Background(), c, account, body, "grok", streaming, time.Now()) + require.NoError(t, err) + require.NotNil(t, result) + return result.SearchCount +} diff --git a/backend/internal/service/image_generation_intent.go b/backend/internal/service/image_generation_intent.go index 76e6f6f325a1..17f3eeeb3b7b 100644 --- a/backend/internal/service/image_generation_intent.go +++ b/backend/internal/service/image_generation_intent.go @@ -37,21 +37,105 @@ func GroupAllowsImageGeneration(group *Group) bool { return group == nil || group.AllowImageGeneration } +var ( + // imageGenLiteralBytes 覆盖扫描侧的全部非模型分支:tool type image_generation + // 自带该前缀,namespace / tool_choice / 函数引用的名字都是 image_gen。 + imageGenLiteralBytes = []byte("image_gen") + // imageModelFoldBytes 覆盖 model 分支:gpt-image-* 与 grok-imagine* 都含 imag, + // 模型名按 ToLower 比较,这里做 ASCII 折叠匹配。 + imageModelFoldBytes = []byte("imag") +) + +// openAIBodyMayDeclareImageGeneration 是生图意图扫描的字节级必要条件。 +// +// 扫描侧每个能让意图成立的取值都要求 body 里出现 image_gen 字面量,或 model 值本身 +// 是图片模型;因此不满足本判定的 body 一定不会命中扫描,可以整段跳过 +// gjson.ValidBytes 全量校验与根对象遍历(大 body 上这两步各占数百微秒)。 +// 只做字节级预检查,宁多算不漏判:含 \u 转义时交给完整扫描兜底,因为 JSON 字符串 +// 允许把 image_gen 的任意字节写成 unicode 转义。 +// +// 唯一的理论缺口:模型名比较走 strings.ToLower(Unicode 简易映射),把非 ASCII +// 字母折叠成 ASCII 的拼写(如 İ→i)不在字节折叠覆盖内;这类拼写不是真实模型 id, +// 且以 \u 形式出现时仍由上面的转义兜底放行。 +func openAIBodyMayDeclareImageGeneration(body []byte) bool { + if len(body) == 0 { + return false + } + if bytes.Contains(body, imageGenLiteralBytes) { + return true + } + if containsASCIIFold(body, imageModelFoldBytes) { + return true + } + return bytes.Contains(body, jsonUnicodeEscapeBytes) +} + // IsImageGenerationIntent classifies requests that can produce generated images. func IsImageGenerationIntent(endpoint string, requestedModel string, body []byte) bool { - if IsImageGenerationEndpoint(endpoint) { - return true + return openAIImageGenerationIntent(endpoint, requestedModel, body, false, true) +} + +// IsExplicitImageGenerationIntent 仅检测原生 image_generation 工具、图片模型和显式 tool_choice, +// 不检测被动的 image_gen namespace 声明。用于 capability 路由决策——被动 namespace 不应 +// 强制要求原生 Responses 能力,否则 Chat Completions-only 账号会被误过滤(#4476)。 +func IsExplicitImageGenerationIntent(endpoint string, requestedModel string, body []byte) bool { + return openAIImageGenerationIntent(endpoint, requestedModel, body, true, true) +} + +// IsImageGenerationIntentForPlatform applies platform-specific intent rules. +// +// Codex advertises the image_gen namespace on ordinary Responses requests so +// that it is available if the model needs it. Grok strips namespace and +// Responses Lite additional_tools declarations before forwarding, so those +// declarations alone must not turn every Codex request into an image request. +// Native image_generation tools, explicit image selection and image models +// remain image intent. Other platforms retain the original declaration rule. +func IsImageGenerationIntentForPlatform(endpoint string, requestedModel string, body []byte, platform string) bool { + return openAIImageGenerationIntentForPlatform(endpoint, requestedModel, body, platform, true) +} + +// IsImageGenerationIntentForPlatformValidated 与 IsImageGenerationIntentForPlatform 判定相同, +// 但要求调用方已经确认 body 是合法 JSON(例如 handler 已对同一份字节做过 gjson.ValidBytes)。 +// 它跳过这次全量校验——大 body 上这一项占判定耗时的六成以上。非法 JSON 的语义与未校验 +// 版本不同,只允许在校验过同一份字节、且后续改写只经由 sjson / json.Marshal 的调用点使用。 +func IsImageGenerationIntentForPlatformValidated(endpoint string, requestedModel string, body []byte, platform string) bool { + return openAIImageGenerationIntentForPlatform(endpoint, requestedModel, body, platform, false) +} + +func openAIImageGenerationIntentForPlatform(endpoint string, requestedModel string, body []byte, platform string, validate bool) bool { + if !strings.EqualFold(strings.TrimSpace(platform), PlatformGrok) { + return openAIImageGenerationIntent(endpoint, requestedModel, body, false, validate) } - if isOpenAIImageGenerationModel(requestedModel) { + // Grok removes namespace catalogs before forwarding. Native image_generation + // remains an explicit capability request. + return openAIImageGenerationIntent(endpoint, requestedModel, body, true, validate) +} + +// openAIImageGenerationIntent 统一入口:先做 O(1) 端点/模型判断,再用字节级预检查 +// 挡住不可能命中扫描的 body,最后才按需校验并遍历根对象。 +func openAIImageGenerationIntent(endpoint string, requestedModel string, body []byte, explicit bool, validate bool) bool { + if IsImageGenerationEndpoint(endpoint) || isOpenAIImageGenerationModel(requestedModel) { return true } - if len(body) == 0 || !gjson.ValidBytes(body) { + if (explicit && !mayContainExplicitImageGenerationIntent(body)) || (!explicit && !openAIBodyMayDeclareImageGeneration(body)) { + return false + } + if validate && !gjson.ValidBytes(body) { return false } + root := parseRawJSONView(body) + if explicit { + return explicitImageGenerationDeclarationsFromRoot(root) + } + return imageGenerationDeclarationsFromRoot(root) +} +// imageGenerationDeclarationsFromRoot 走一遍根对象,保留「重复键取第一个」语义, +// 覆盖 model、tools、input.additional_tools 与 tool_choice。调用方负责 JSON 合法性。 +func imageGenerationDeclarationsFromRoot(root gjson.Result) bool { var modelSeen, toolsSeen, inputSeen, toolChoiceSeen bool imageIntent := false - parseRawJSONView(body).ForEach(func(key, value gjson.Result) bool { + root.ForEach(func(key, value gjson.Result) bool { // GetBytes returns the first duplicate key; retain that behavior while walking the root once. switch key.Str { case "model": @@ -80,85 +164,12 @@ func IsImageGenerationIntent(endpoint string, requestedModel string, body []byte return imageIntent } -// IsExplicitImageGenerationIntent 仅检测原生 image_generation 工具、图片模型和显式 tool_choice, -// 不检测被动的 image_gen namespace 声明。用于 capability 路由决策——被动 namespace 不应 -// 强制要求原生 Responses 能力,否则 Chat Completions-only 账号会被误过滤(#4476)。 -func IsExplicitImageGenerationIntent(endpoint string, requestedModel string, body []byte) bool { - if IsImageGenerationEndpoint(endpoint) || isOpenAIImageGenerationModel(requestedModel) { - return true - } - if len(body) == 0 || !mayContainExplicitImageGenerationIntent(body) || !gjson.ValidBytes(body) { - return false - } - var modelSeen, toolsSeen, toolChoiceSeen bool - imageIntent := false - parseRawJSONView(body).ForEach(func(key, value gjson.Result) bool { - switch key.Str { - case "model": - if !modelSeen { - modelSeen = true - imageIntent = isOpenAIImageGenerationModel(strings.TrimSpace(value.String())) - } - case "tools": - if !toolsSeen { - toolsSeen = true - imageIntent = openAIJSONToolsContainNativeImageGeneration(value) - } - case "tool_choice": - if !toolChoiceSeen { - toolChoiceSeen = true - imageIntent = openAIJSONToolChoiceSelectsExplicitImageGeneration(value) - } - } - return !imageIntent && (!modelSeen || !toolsSeen || !toolChoiceSeen) - }) - return imageIntent -} - -// A false result rules out the markers used by the explicit intent checks. -// Escaped Unicode and native tool declarations use the full validator and -// parser, as do model or tool-choice candidates. -// Keep this filter aligned with the recognized tool types and tool choices -// whenever those rules gain new forms. -func mayContainExplicitImageGenerationIntent(body []byte) bool { - if bytes.Contains(body, []byte("_generation")) || bytes.Contains(body, []byte(`\u`)) { - return true - } - if isOpenAIImageGenerationModel(gjson.GetBytes(body, "model").String()) { - return true - } - if !bytes.Contains(body, []byte("_gen")) || !bytes.Contains(body, []byte("_choice")) { - return false - } - return strings.Contains(gjson.GetBytes(body, "tool_choice").Raw, "image_gen") -} - -// IsImageGenerationIntentForPlatform applies platform-specific intent rules. -// -// Codex advertises the image_gen namespace on ordinary Responses requests so -// that it is available if the model needs it. Grok strips namespace and -// Responses Lite additional_tools declarations before forwarding, so those -// declarations alone must not turn every Codex request into an image request. -// Native image_generation tools, explicit image selection and image models -// remain image intent. Other platforms retain the original declaration rule. -func IsImageGenerationIntentForPlatform(endpoint string, requestedModel string, body []byte, platform string) bool { - if !strings.EqualFold(strings.TrimSpace(platform), PlatformGrok) { - return IsImageGenerationIntent(endpoint, requestedModel, body) - } - return isExplicitGrokImageGenerationIntent(endpoint, requestedModel, body) -} - -func isExplicitGrokImageGenerationIntent(endpoint string, requestedModel string, body []byte) bool { - if IsImageGenerationEndpoint(endpoint) || isOpenAIImageGenerationModel(requestedModel) { - return true - } - if len(body) == 0 || !gjson.ValidBytes(body) { - return false - } - +// explicitImageGenerationDeclarationsFromRoot 只认原生 image_generation 工具、图片模型 +// 与显式 tool_choice,不认被动的 image_gen namespace 声明。 +func explicitImageGenerationDeclarationsFromRoot(root gjson.Result) bool { var modelSeen, toolsSeen, toolChoiceSeen bool imageIntent := false - parseRawJSONView(body).ForEach(func(key, value gjson.Result) bool { + root.ForEach(func(key, value gjson.Result) bool { switch key.Str { case "model": if !modelSeen { @@ -168,8 +179,6 @@ func isExplicitGrokImageGenerationIntent(endpoint string, requestedModel string, case "tools": if !toolsSeen { toolsSeen = true - // Grok removes namespace catalogs before forwarding. Native - // image_generation remains an explicit capability request. imageIntent = openAIJSONToolsContainNativeImageGeneration(value) } case "tool_choice": @@ -292,7 +301,7 @@ func openAIJSONInputContainsImageGenTool(input gjson.Result) bool { } func openAIRequestBodyHasImageGenerationDeclaration(body []byte) bool { - if len(body) == 0 || !gjson.ValidBytes(body) { + if len(body) == 0 || !openAIBodyMayDeclareImageGeneration(body) || !gjson.ValidBytes(body) { return false } return openAIJSONToolsContainImageGeneration(gjson.GetBytes(body, "tools")) || @@ -301,7 +310,7 @@ func openAIRequestBodyHasImageGenerationDeclaration(body []byte) bool { } func openAIRequestBodyImageGenerationToolNeedsNormalization(body []byte) bool { - if len(body) == 0 || !gjson.ValidBytes(body) { + if len(body) == 0 || !openAIBodyMayDeclareImageGeneration(body) || !gjson.ValidBytes(body) { return false } tools := gjson.GetBytes(body, "tools") @@ -547,3 +556,21 @@ func openAIJSONString(value gjson.Result) string { } return strings.TrimSpace(value.String()) } + +// A false result rules out the markers used by the explicit intent checks. +// Escaped Unicode and native tool declarations use the full validator and +// parser, as do model or tool-choice candidates. +// Keep this filter aligned with the recognized tool types and tool choices +// whenever those rules gain new forms. +func mayContainExplicitImageGenerationIntent(body []byte) bool { + if bytes.Contains(body, []byte("_generation")) || bytes.Contains(body, []byte(`\u`)) { + return true + } + if isOpenAIImageGenerationModel(gjson.GetBytes(body, "model").String()) { + return true + } + if !bytes.Contains(body, []byte("_gen")) || !bytes.Contains(body, []byte("_choice")) { + return false + } + return strings.Contains(gjson.GetBytes(body, "tool_choice").Raw, "image_gen") +} diff --git a/backend/internal/service/image_generation_intent_prefilter_benchmark_test.go b/backend/internal/service/image_generation_intent_prefilter_benchmark_test.go new file mode 100644 index 000000000000..3136faab9701 --- /dev/null +++ b/backend/internal/service/image_generation_intent_prefilter_benchmark_test.go @@ -0,0 +1,102 @@ +package service + +import ( + "strings" + "testing" +) + +// buildImageIntentPrefilterBenchmarkBody 生成形状接近 Codex 客户端的大请求体: +// tools 在 input 之前、input 内含大量 items;withImageGen 控制是否带上 Codex +// 默认注入的 image_gen namespace 声明。 +func buildImageIntentPrefilterBenchmarkBody(targetBytes int, withImageGen bool) []byte { + var builder strings.Builder + builder.Grow(targetBytes + 512) + _, _ = builder.WriteString(`{"model":"gpt-5.5","instructions":"`) + _, _ = builder.WriteString(strings.Repeat("z", targetBytes/8)) + _, _ = builder.WriteString(`","tools":[{"type":"function","name":"shell","description":"`) + _, _ = builder.WriteString(strings.Repeat("y", targetBytes/16)) + _, _ = builder.WriteString(`"}`) + if withImageGen { + _, _ = builder.WriteString(`,{"type":"namespace","name":"image_gen"}`) + } + _, _ = builder.WriteString(`],"input":[`) + item := `{"type":"message","role":"user","content":[{"type":"input_text","text":"` + strings.Repeat("x", 4000) + `"}]}` + for i := 0; builder.Len() < targetBytes; i++ { + if i > 0 { + _, _ = builder.WriteString(`,`) + } + _, _ = builder.WriteString(item) + } + _, _ = builder.WriteString(`]}`) + return []byte(builder.String()) +} + +// 字节级预检查把「没有生图声明」的请求整段跳过校验与根对象遍历; +// scan_without_prefilter 是修复前的等价路径,两者同一次运行即可对比。 +func BenchmarkImageGenerationIntentPrefilter(b *testing.B) { + const targetBytes = 1 << 20 + plain := buildImageIntentPrefilterBenchmarkBody(targetBytes, false) + codex := buildImageIntentPrefilterBenchmarkBody(targetBytes, true) + + b.Run("prefilter_only/plain", func(b *testing.B) { + b.SetBytes(int64(len(plain))) + b.ReportAllocs() + for range b.N { + if openAIBodyMayDeclareImageGeneration(plain) { + b.Fatal("plain body must not declare image generation") + } + } + }) + + b.Run("scan_without_prefilter/plain", func(b *testing.B) { + b.SetBytes(int64(len(plain))) + b.ReportAllocs() + for range b.N { + if referenceImageGenerationIntent(plain) { + b.Fatal("plain body must not have image intent") + } + } + }) + + b.Run("intent/plain", func(b *testing.B) { + b.SetBytes(int64(len(plain))) + b.ReportAllocs() + for range b.N { + if IsImageGenerationIntent(openAIResponsesEndpoint, "gpt-5.5", plain) { + b.Fatal("plain body must not have image intent") + } + } + }) + + b.Run("scan_without_prefilter/codex", func(b *testing.B) { + b.SetBytes(int64(len(codex))) + b.ReportAllocs() + for range b.N { + if !referenceImageGenerationIntent(codex) { + b.Fatal("codex namespace body must have image intent") + } + } + }) + + // Codex 在普通请求里就带 image_gen namespace,预检查必然放行, + // 这类流量只能靠「已校验」变体省掉重复的全量校验。 + b.Run("intent/codex_namespace", func(b *testing.B) { + b.SetBytes(int64(len(codex))) + b.ReportAllocs() + for range b.N { + if !IsImageGenerationIntent(openAIResponsesEndpoint, "gpt-5.5", codex) { + b.Fatal("codex namespace body must have image intent") + } + } + }) + + b.Run("validated_intent/codex_namespace", func(b *testing.B) { + b.SetBytes(int64(len(codex))) + b.ReportAllocs() + for range b.N { + if !IsImageGenerationIntentForPlatformValidated(openAIResponsesEndpoint, "gpt-5.5", codex, PlatformOpenAI) { + b.Fatal("codex namespace body must have image intent") + } + } + }) +} diff --git a/backend/internal/service/image_generation_intent_prefilter_test.go b/backend/internal/service/image_generation_intent_prefilter_test.go new file mode 100644 index 000000000000..0b9b8413c089 --- /dev/null +++ b/backend/internal/service/image_generation_intent_prefilter_test.go @@ -0,0 +1,147 @@ +package service + +import ( + "strings" + "testing" + + "github.com/stretchr/testify/require" + "github.com/tidwall/gjson" +) + +// 生图意图的字节级预检查只能少算、不能漏判:任何能让扫描成立的 body, +// openAIBodyMayDeclareImageGeneration 都必须放行。下面用扫描函数本身作为基准, +// 逐个语料核对「带预检查」与「不带预检查」的结果完全一致。 +func TestImageGenerationIntentPrefilterPreservesScanOutcomes(t *testing.T) { + escape := string(rune(92)) + "u005f" // _ + bodies := map[string]string{ + "no image declarations": `{"model":"gpt-5.5","input":"hello"}`, + "empty body": ``, + "invalid json": `{"tools":[{"type":"image_generation"}]`, + "native tool": `{"model":"gpt-5.5","tools":[{"type":"image_generation"}]}`, + "namespace tool": `{"model":"gpt-5.5","tools":[{"type":"namespace","name":"image_gen"}]}`, + "tool choice string": `{"model":"gpt-5.5","tool_choice":"image_generation"}`, + "tool choice namespace": `{"model":"gpt-5.5","tool_choice":{"type":"namespace","name":"image_gen"}}`, + "tool choice function": `{"model":"gpt-5.5","tool_choice":{"type":"function","function":{"name":"image_gen.imagegen"}}}`, + "input additional": `{"input":[{"type":"additional_tools","tools":[{"type":"image_generation"}]}]}`, + "escaped key": `{"tool_` + string(rune(92)) + `u0063hoice":{"type":"image_generation"}}`, + "escaped tool type": `{"tools":[{"type":"image` + escape + `generation"}]}`, + "escaped namespace": `{"tools":[{"type":"namespace","name":"image` + escape + `gen"}]}`, + "uppercase model": `{"model":"GPT-Image-2"}`, + "grok model": `{"model":"grok-imagine"}`, + "uppercase grok model": `{"model":"Grok-Imagine"}`, + "duplicate model": `{"model":"gpt-5.5","model":"gpt-image-2"}`, + "model only": `{"model":"gpt-image-2"}`, + "prose mentions image": `{"model":"gpt-5.5","input":"please imagine a cat"}`, + "namespace value": `{"tools":[{"type":"namespace","name":"image_gen","tools":[]}]}`, + } + for name, raw := range bodies { + body := []byte(raw) + t.Run(name, func(t *testing.T) { + // endpoint 与 requestedModel 都取非图片值,预检查才会真正生效。 + require.Equal(t, + referenceImageGenerationIntent(body), + IsImageGenerationIntent("/v1/responses", "gpt-5.5", body), + "declaration rule must not change with the prefilter") + require.Equal(t, + referenceExplicitImageGenerationIntent(body), + IsExplicitImageGenerationIntent("/v1/responses", "gpt-5.5", body), + "explicit rule must not change with the prefilter") + require.Equal(t, + referenceExplicitImageGenerationIntent(body), + IsImageGenerationIntentForPlatform("/v1/responses", "gpt-5.5", body, PlatformGrok), + "grok rule must not change with the prefilter") + require.Equal(t, + referenceImageGenerationIntent(body), + IsImageGenerationIntentForPlatform("/v1/responses", "gpt-5.5", body, PlatformOpenAI), + "platform rule must not change with the prefilter") + }) + } +} + +// 下面两个参考实现就是修复前的完整扫描:校验 + 根对象遍历,不带字节级预检查。 +func referenceImageGenerationIntent(body []byte) bool { + if len(body) == 0 || !gjson.ValidBytes(body) { + return false + } + return imageGenerationDeclarationsFromRoot(parseRawJSONView(body)) +} + +func referenceExplicitImageGenerationIntent(body []byte) bool { + if len(body) == 0 || !gjson.ValidBytes(body) { + return false + } + return explicitImageGenerationDeclarationsFromRoot(parseRawJSONView(body)) +} + +// 预检查的健全性:扫描能成立的 body 一定被放行。语料之外由 fuzz 继续探索。 +func TestImageGenerationIntentPrefilterIsNecessary(t *testing.T) { + seeds := []string{ + `{"model":"gpt-image-2"}`, + `{"tools":[{"type":"image_generation"}]}`, + `{"tools":[{"type":"namespace","name":"image_gen"}]}`, + `{"tool_choice":{"type":"namespace","name":"image_gen"}}`, + `{"input":[{"type":"additional_tools","tools":[{"type":"image_generation"}]}]}`, + `{"model":"grok-imagine"}`, + `{"model":"gpt-5.5","input":"nothing here"}`, + } + for _, seed := range seeds { + body := []byte(seed) + if referenceImageGenerationIntent(body) { + require.True(t, openAIBodyMayDeclareImageGeneration(body), "prefilter must not hide a detected body: %s", seed) + } + } +} + +func FuzzImageGenerationIntentPrefilter(f *testing.F) { + f.Add([]byte(`{"model":"gpt-image-2"}`)) + f.Add([]byte(`{"tools":[{"type":"namespace","name":"image_gen"}]}`)) + f.Add([]byte(`{"model":"gpt-5.5"}`)) + f.Add([]byte(`{"tools":[{"type":"image` + string(rune(92)) + `u005fgeneration"}]}`)) + f.Fuzz(func(t *testing.T, body []byte) { + if referenceImageGenerationIntent(body) && !openAIBodyMayDeclareImageGeneration(body) { + t.Fatalf("prefilter hid a detected body: %q", body) + } + if referenceExplicitImageGenerationIntent(body) && !openAIBodyMayDeclareImageGeneration(body) { + t.Fatalf("prefilter hid a detected body: %q", body) + } + // 已校验分支不得与校验分支结论不同:同一份合法 JSON 上两者必须一致。 + if gjson.ValidBytes(body) { + require.Equal(t, + referenceImageGenerationIntent(body), + IsImageGenerationIntentForPlatformValidated(openAIResponsesEndpoint, "gpt-5.5", body, PlatformOpenAI), + "validated variant must agree with the reference scan: %q", body) + } + }) +} + +func TestContainsASCIIFold(t *testing.T) { + cases := []struct { + name string + haystack string + needle string + want bool + }{ + {"exact", "gpt-image-2", "imag", true}, + {"upper", "GPT-IMAGE-2", "imag", true}, + {"mixed", "Gpt-ImAgE-2", "imag", true}, + {"grok", "grok-imagine", "imag", true}, + {"absent", "gpt-5.5", "imag", false}, + {"needle longer", "img", "imag", false}, + {"empty haystack", "", "imag", false}, + {"partial at end", "xxIma", "imag", false}, + {"second candidate matches", "iaaiimag", "imag", true}, + } + for _, tt := range cases { + t.Run(tt.name, func(t *testing.T) { + require.Equal(t, tt.want, containsASCIIFold([]byte(tt.haystack), []byte(tt.needle))) + }) + } + require.False(t, containsASCIIFold(nil, []byte("imag"))) + + // 与 strings.Contains(strings.ToLower(...)) 对拍一段混合大小写文本。 + haystack := []byte(`{"model":"Gpt-Image-2","input":"IMAGINE this, Image and IMAGE"}`) + require.True(t, containsASCIIFold(haystack, []byte("imag"))) + require.Equal(t, + strings.Contains(strings.ToLower(string(haystack)), "imag"), + containsASCIIFold(haystack, []byte("imag"))) +} diff --git a/backend/internal/service/lottery_integration_test.go b/backend/internal/service/lottery_integration_test.go index fbd845a216b9..be3acc9f11c4 100644 --- a/backend/internal/service/lottery_integration_test.go +++ b/backend/internal/service/lottery_integration_test.go @@ -490,7 +490,8 @@ func TestLotteryPostgres(t *testing.T) { require.NoError(t, codes.Create(ctx, code)) _, e := redeem.Redeem(ctx, f.uid, code.Code) require.NoError(t, e) - admin := service.ProvideAdminService(nil, f.users, nil, nil, nil, nil, codes, nil, nil, nil, nil, nil, nil, c, nil, f.subs, repository.NewUserSubscriptionRepository(c), nil, nil, nil, nil, nil, nil, f.s) + quotaRepo := repository.NewUserPlatformQuotaServiceAdapter(repository.NewUserPlatformQuotaRepository(c)) + admin := service.ProvideAdminService(nil, f.users, nil, nil, nil, nil, codes, nil, nil, nil, nil, nil, nil, c, nil, f.subs, repository.NewUserSubscriptionRepository(c), nil, nil, nil, nil, nil, nil, f.s, quotaRepo) opctx := service.WithAdminBalanceOperation(ctx, "admin:test", fmt.Sprint(f.uid)) _, e = admin.UpdateUserBalance(opctx, f.uid, 100, "set", "") require.NoError(t, e) diff --git a/backend/internal/service/lottery_wire.go b/backend/internal/service/lottery_wire.go index f046a940f12f..597c67fb0b0b 100644 --- a/backend/internal/service/lottery_wire.go +++ b/backend/internal/service/lottery_wire.go @@ -17,9 +17,9 @@ func ProvideAdminService( rpm UserRPMCache, billing *BillingCacheService, prober ProxyExitInfoProber, latency ProxyLatencyCache, auth APIKeyAuthCacheInvalidator, client *dbent.Client, settings *SettingService, assigner DefaultSubscriptionAssigner, subs UserSubscriptionRepository, privacy PrivacyClientFactory, blocker AccountRuntimeBlocker, affiliate *AffiliateService, - routes CompositeModelRouteRepository, resolver *CompositeRouteResolver, channels ChannelCacheInvalidator, lottery *LotteryService, + routes CompositeModelRouteRepository, resolver *CompositeRouteResolver, channels ChannelCacheInvalidator, lottery *LotteryService, quotas UserPlatformQuotaRepository, ) AdminService { - s := NewAdminService(cfg, users, groups, accounts, proxies, keys, codes, rates, rpm, billing, prober, latency, auth, client, settings, assigner, subs, privacy, blocker, affiliate, routes, resolver, channels) + s := NewAdminService(cfg, users, groups, accounts, proxies, keys, codes, rates, rpm, billing, prober, latency, auth, client, settings, assigner, subs, privacy, blocker, affiliate, routes, resolver, channels, quotas) impl, ok := s.(*adminServiceImpl) if !ok { panic("unexpected AdminService implementation") diff --git a/backend/internal/service/oauth_refresh_api.go b/backend/internal/service/oauth_refresh_api.go index 9dade7235db8..f709bfb5f687 100644 --- a/backend/internal/service/oauth_refresh_api.go +++ b/backend/internal/service/oauth_refresh_api.go @@ -5,6 +5,7 @@ import ( "errors" "fmt" "log/slog" + "reflect" "strconv" "strings" "sync" @@ -46,10 +47,17 @@ type GrokOAuthRefreshSuccessRepository interface { ) (bool, error) } +type OpenAIOAuthRefreshSuccessRepository interface { + UpdateOpenAIOAuthCredentialsIfUnchanged(ctx context.Context, id int64, expectedCredentials map[string]any, expectedProxyID *int64, credentials map[string]any) (bool, error) +} + const ( defaultRefreshLockTTL = 60 * time.Second defaultRefreshLockReleaseTimeout = 2 * time.Second defaultRefreshPostPersistCleanupTimeout = 2 * time.Second + defaultOpenAIRefreshPersistTimeout = 10 * time.Second + // Repository snapshot propagation uses its own detached timeout after CAS. + defaultRefreshRepositorySyncTimeout = 2 * time.Second ) var ( @@ -217,6 +225,17 @@ func (api *OAuthRefreshAPI) RefreshIfNeeded( return &OAuthRefreshResult{LockHeld: true}, nil } else { defer api.releaseRefreshLock(ctx, cacheKey) + if account.Platform == PlatformOpenAI && account.Type == AccountTypeOAuth { + // Reserve lease time for the irreversible rotation's detached save, + // cache invalidation and lock release, including request-path calls. + budget := api.lockTTL - defaultOpenAIRefreshPersistTimeout - defaultRefreshRepositorySyncTimeout - defaultRefreshPostPersistCleanupTimeout - defaultRefreshLockReleaseTimeout - maxTokenRefreshLockSafetyMargin + if budget <= 0 { + return nil, &providerConfigurationRefreshError{err: errors.New("OpenAI OAuth refresh lock lease is too short for credential persistence")} + } + var cancel context.CancelFunc + ctx, cancel = context.WithTimeout(ctx, budget) + defer cancel() + } } } @@ -268,6 +287,26 @@ func (api *OAuthRefreshAPI) RefreshIfNeeded( // 4. 执行平台特定刷新逻辑 attemptedAccount := snapshotOAuthRefreshAccount(freshAccount) newCredentials, refreshErr := executor.Refresh(ctx, freshAccount) + if refreshErr == nil && hasOpenAIRefreshCredentials(attemptedAccount, newCredentials) { + // The upstream rotation is irreversible. Cancellation of optional + // enrichment must not discard its result or cause an old-token retry. + durableAccount, applied, persistErr := persistOpenAIRefreshCredentials(ctx, api.accountRepo, attemptedAccount, newCredentials) + if applied && api.tokenCache != nil { + cleanupCtx, cancel := context.WithTimeout(context.WithoutCancel(ctx), defaultRefreshPostPersistCleanupTimeout) + defer cancel() + if err := api.tokenCache.DeleteAccessToken(cleanupCtx, cacheKey); err != nil { + slog.Warn("oauth_refresh_post_persist_cache_delete_failed", "account_id", account.ID, "error", err) + } + } + if persistErr != nil { + return nil, persistErr + } + result := &OAuthRefreshResult{Refreshed: applied, Account: durableAccount} + if applied { + result.NewCredentials = shallowCopyMap(durableAccount.Credentials) + } + return result, nil + } if ctxErr := refreshContextErr(ctx); ctxErr != nil { // A provider implementation may ignore cancellation and return late // credentials. Never persist them after the attempt/cycle boundary. @@ -392,6 +431,66 @@ func (api *OAuthRefreshAPI) RefreshIfNeeded( }, nil } +func hasOpenAIRefreshCredentials(account *Account, credentials map[string]any) bool { + if account == nil || account.Platform != PlatformOpenAI || account.Type != AccountTypeOAuth || + account.IsCredentialShadow() || account.IsOpenAIPersonalAccessToken() { + return false + } + accessToken, _ := credentials["access_token"].(string) + refreshToken, _ := credentials["refresh_token"].(string) + return strings.TrimSpace(accessToken) != "" && strings.TrimSpace(refreshToken) != "" +} + +func persistOpenAIRefreshCredentials(parent context.Context, repo AccountRepository, attempted *Account, credentials map[string]any) (*Account, bool, error) { + conditionalRepo, ok := repo.(OpenAIOAuthRefreshSuccessRepository) + if !ok { + return nil, false, &providerConfigurationRefreshError{err: errors.New("OpenAI OAuth refresh success CAS repository is not configured")} + } + ctx, cancel := context.WithTimeout(context.WithoutCancel(parent), defaultOpenAIRefreshPersistTimeout) + defer cancel() + credentials["_token_version"] = time.Now().UnixMilli() + expected := attempted + replacement := credentials + for saveAttempt := 0; saveAttempt < 3; saveAttempt++ { + applied, err := conditionalRepo.UpdateOpenAIOAuthCredentialsIfUnchanged(ctx, attempted.ID, expected.Credentials, expected.ProxyID, replacement) + if err != nil { + return nil, false, &providerCycleContainmentRefreshError{err: fmt.Errorf("%w: %v", errOAuthRefreshCredentialPersist, err)} + } + // Read the durable row rather than publishing the pre-refresh scheduling + // snapshot; an administrator may have changed the account while we waited. + current, err := repo.GetByID(ctx, attempted.ID) + if err != nil || current == nil || current.ID != attempted.ID { + return nil, applied, &providerCycleContainmentRefreshError{err: fmt.Errorf("%w: durable account unavailable after OpenAI refresh", errOAuthRefreshCredentialPersist)} + } + if applied { + return current, true, nil + } + if current.Platform != PlatformOpenAI || current.Type != AccountTypeOAuth || + current.IsCredentialShadow() || current.IsOpenAIPersonalAccessToken() || + current.GetCredential("refresh_token") != attempted.GetCredential("refresh_token") || + current.GetCredential("access_token") != attempted.GetCredential("access_token") || + current.GetCredentialAsInt64("_token_version") != attempted.GetCredentialAsInt64("_token_version") { + return current, false, nil + } + // A proxy or non-token setting edit must not discard a completed rotation. + // Reapply only this refresh's credential changes to the newest snapshot. + expected = snapshotOAuthRefreshAccount(current) + replacement = shallowCopyMap(current.Credentials) + for key, value := range credentials { + previous, exists := attempted.Credentials[key] + if !exists || !reflect.DeepEqual(previous, value) { + replacement[key] = value + } + } + for key := range attempted.Credentials { + if _, exists := credentials[key]; !exists { + delete(replacement, key) + } + } + } + return nil, false, &providerCycleContainmentRefreshError{err: fmt.Errorf("%w: OpenAI credentials changed repeatedly during persistence", errOAuthRefreshCredentialPersist)} +} + func (api *OAuthRefreshAPI) releaseRefreshLock(parent context.Context, cacheKey string) { cleanupParent := context.Background() if parent != nil { diff --git a/backend/internal/service/oauth_refresh_api_test.go b/backend/internal/service/oauth_refresh_api_test.go index e92bd99f02ea..9319ed6b8f0d 100644 --- a/backend/internal/service/oauth_refresh_api_test.go +++ b/backend/internal/service/oauth_refresh_api_test.go @@ -5,11 +5,14 @@ package service import ( "context" "errors" + "fmt" "reflect" "sync" "testing" "time" + "github.com/Wei-Shaw/sub2api/internal/pkg/openai" + "github.com/imroc/req/v3" "github.com/stretchr/testify/require" ) @@ -30,9 +33,16 @@ type refreshAPIAccountRepo struct { beforeSuccessCAS func(*refreshAPIAccountRepo) lastExpectedCredentials map[string]any lastExpectedProxyID *int64 + openAISuccessCASCalls int + openAIPersistCtxErr error + openAIPersistDeadline time.Time + respectReadContext bool } -func (r *refreshAPIAccountRepo) GetByID(_ context.Context, _ int64) (*Account, error) { +func (r *refreshAPIAccountRepo) GetByID(ctx context.Context, _ int64) (*Account, error) { + if r.respectReadContext && ctx.Err() != nil { + return nil, ctx.Err() + } r.getByIDCalls++ if r.getByIDErrAfterCall > 0 && r.getByIDCalls >= r.getByIDErrAfterCall { return nil, r.getByIDErrAfterCallErr @@ -103,16 +113,50 @@ func (r *refreshAPIAccountRepo) UpdateGrokOAuthCredentialsIfUnchanged( return true, nil } +func (r *refreshAPIAccountRepo) UpdateOpenAIOAuthCredentialsIfUnchanged( + ctx context.Context, + id int64, + expectedCredentials map[string]any, + expectedProxyID *int64, + credentials map[string]any, +) (bool, error) { + r.openAISuccessCASCalls++ + r.openAIPersistCtxErr = ctx.Err() + r.openAIPersistDeadline, _ = ctx.Deadline() + if err := ctx.Err(); err != nil { + return false, err + } + r.lastExpectedCredentials = shallowCopyMap(expectedCredentials) + r.lastExpectedProxyID = expectedProxyID + if r.beforeSuccessCAS != nil { + r.beforeSuccessCAS(r) + } + if r.updateErr != nil { + return false, r.updateErr + } + if r.account == nil || r.account.ID != id || r.account.Platform != PlatformOpenAI || + r.account.Type != AccountTypeOAuth || r.account.IsCredentialShadow() || + !reflect.DeepEqual(r.account.Credentials, expectedCredentials) || + !reflect.DeepEqual(r.account.ProxyID, expectedProxyID) { + return false, nil + } + r.updateCalls++ + r.updateCredentialsCalls++ + r.account.Credentials = shallowCopyMap(credentials) + return true, nil +} + // refreshAPIExecutorStub implements OAuthRefreshExecutor for tests. type refreshAPIExecutorStub struct { - needsRefresh bool - cannotRefresh bool - credentials map[string]any - err error - refreshCalls int - canRefresh func(*Account) bool - onRefresh func() - delay time.Duration + needsRefresh bool + cannotRefresh bool + credentials map[string]any + err error + refreshCalls int + canRefresh func(*Account) bool + onRefresh func() + onRefreshContext func(context.Context) + delay time.Duration } func (e *refreshAPIExecutorStub) CanRefresh(account *Account) bool { @@ -129,7 +173,7 @@ func (e *refreshAPIExecutorStub) NeedsRefresh(_ *Account, _ time.Duration) bool return e.needsRefresh } -func (e *refreshAPIExecutorStub) Refresh(_ context.Context, _ *Account) (map[string]any, error) { +func (e *refreshAPIExecutorStub) Refresh(ctx context.Context, _ *Account) (map[string]any, error) { e.refreshCalls++ if e.delay > 0 { time.Sleep(e.delay) @@ -137,6 +181,9 @@ func (e *refreshAPIExecutorStub) Refresh(_ context.Context, _ *Account) (map[str if e.onRefresh != nil { e.onRefresh() } + if e.onRefreshContext != nil { + e.onRefreshContext(ctx) + } if e.err != nil { return nil, e.err } @@ -652,6 +699,220 @@ func TestRefreshIfNeeded_LateSuccessAfterDeadlineDoesNotPersist(t *testing.T) { require.Zero(t, repo.updateCredentialsCalls, "late credentials must not cross the unified API persistence boundary") } +type openAIRotationClientStub struct { + openaiOAuthClientRefreshStub + rotationCalls int +} + +func (c *openAIRotationClientStub) RefreshTokenWithClientID(context.Context, string, string, string) (*openai.TokenResponse, error) { + c.rotationCalls++ + return &openai.TokenResponse{ + AccessToken: "rotated-access", RefreshToken: "rotated-refresh", ExpiresIn: 3600, + }, nil +} + +func TestRefreshIfNeeded_OpenAIEnrichmentTimeoutKeepsRotatedCredentials(t *testing.T) { + account := openAIRefreshTestAccount() + account.Credentials["expires_at"] = time.Now().Add(-time.Minute).UTC().Format(time.RFC3339) + repo := &refreshAPIAccountRepo{account: account, respectReadContext: true} + client := &openAIRotationClientStub{} + oauthService := NewOpenAIOAuthService(nil, client) + defer oauthService.Stop() + privacyCalls := 0 + oauthService.SetPrivacyClientFactory(func(string) (*req.Client, error) { + return req.C().WrapRoundTripFunc(func(req.RoundTripper) req.RoundTripFunc { + return func(request *req.Request) (*req.Response, error) { + privacyCalls++ + <-request.Context().Done() + return nil, request.Context().Err() + } + }), nil + }) + ctx, cancel := context.WithTimeout(context.Background(), 20*time.Millisecond) + defer cancel() + executor := NewOpenAITokenRefresher(oauthService, repo) + + result, err := NewOAuthRefreshAPI(repo, nil).RefreshIfNeeded(ctx, account, executor, time.Hour) + + require.NoError(t, err) + require.ErrorIs(t, ctx.Err(), context.DeadlineExceeded) + require.Positive(t, privacyCalls, "optional enrichment must be the operation that exhausts the context") + require.Equal(t, 1, client.rotationCalls) + require.True(t, result.Refreshed) + require.Equal(t, "rotated-refresh", result.Account.GetOpenAIRefreshToken()) + require.Equal(t, "rotated-refresh", repo.account.GetOpenAIRefreshToken()) + require.Equal(t, 1, repo.openAISuccessCASCalls) + require.NoError(t, repo.openAIPersistCtxErr) +} + +func TestRefreshIfNeeded_OpenAILockLeaseReservesPersistenceBudget(t *testing.T) { + account := openAIRefreshTestAccount() + repo := &refreshAPIAccountRepo{account: account} + cache := &refreshAPICacheStub{lockResult: true} + var executorBudget time.Duration + executor := &refreshAPIExecutorStub{ + needsRefresh: true, + credentials: map[string]any{"access_token": "rotated-access", "refresh_token": "rotated-refresh"}, + onRefreshContext: func(ctx context.Context) { + deadline, ok := ctx.Deadline() + require.True(t, ok) + executorBudget = time.Until(deadline) + }, + } + + _, err := NewOAuthRefreshAPI(repo, cache).RefreshIfNeeded(context.Background(), account, executor, time.Hour) + + require.NoError(t, err) + require.Positive(t, executorBudget) + require.LessOrEqual(t, executorBudget, 41*time.Second, "60-second lease must reserve 19 seconds for persistence and cleanup") + require.Equal(t, 1, executor.refreshCalls) + require.Equal(t, 1, cache.releaseCalls) +} + +func TestRefreshIfNeeded_OpenAIShortLockLeaseDoesNotConsumeRefreshToken(t *testing.T) { + for _, lease := range []time.Duration{time.Second, 19 * time.Second} { + t.Run(lease.String(), func(t *testing.T) { + account := openAIRefreshTestAccount() + repo := &refreshAPIAccountRepo{account: account} + cache := &refreshAPICacheStub{lockResult: true} + executor := &refreshAPIExecutorStub{ + needsRefresh: true, + credentials: map[string]any{"access_token": "rotated-access", "refresh_token": "rotated-refresh"}, + } + + _, err := NewOAuthRefreshAPI(repo, cache, lease).RefreshIfNeeded(context.Background(), account, executor, time.Hour) + + var configuration *providerConfigurationRefreshError + require.ErrorAs(t, err, &configuration) + require.Zero(t, executor.refreshCalls) + require.Zero(t, repo.openAISuccessCASCalls) + require.Equal(t, "old-refresh", repo.account.GetOpenAIRefreshToken()) + require.Equal(t, 1, cache.releaseCalls) + }) + } +} + +func TestRefreshIfNeeded_OpenAILateSuccessPersistsWithBoundedContext(t *testing.T) { + for _, cancellation := range []string{"deadline", "parent cancellation"} { + t.Run(cancellation, func(t *testing.T) { + account := openAIRefreshTestAccount() + expected := shallowCopyMap(account.Credentials) + repo := &refreshAPIAccountRepo{account: account, respectReadContext: true} + cache := &refreshAPICacheStub{lockResult: true} + ctx, cancel := context.WithCancel(context.Background()) + if cancellation == "deadline" { + cancel() + ctx, cancel = context.WithTimeout(context.Background(), 10*time.Millisecond) + } + defer cancel() + executor := &refreshAPIExecutorStub{ + needsRefresh: true, + credentials: map[string]any{"access_token": "rotated-access", "refresh_token": "rotated-refresh"}, + onRefresh: func() { + if cancellation == "parent cancellation" { + cancel() + } + <-ctx.Done() + }, + } + + result, err := NewOAuthRefreshAPI(repo, cache).RefreshIfNeeded(ctx, account, executor, time.Hour) + + require.NoError(t, err) + require.True(t, result.Refreshed) + require.Equal(t, "rotated-refresh", result.Account.GetOpenAIRefreshToken()) + require.Equal(t, "rotated-refresh", repo.account.GetOpenAIRefreshToken()) + require.Equal(t, expected, repo.lastExpectedCredentials) + require.Equal(t, 1, executor.refreshCalls) + require.Equal(t, 1, repo.openAISuccessCASCalls) + require.NoError(t, repo.openAIPersistCtxErr) + require.False(t, repo.openAIPersistDeadline.IsZero(), "detached persistence must remain bounded") + require.LessOrEqual(t, time.Until(repo.openAIPersistDeadline), 10*time.Second) + require.Equal(t, 1, cache.releaseCalls) + require.NoError(t, cache.releaseCtxErr) + }) + } +} + +func openAIRefreshTestAccount() *Account { + return &Account{ + ID: 154, Platform: PlatformOpenAI, Type: AccountTypeOAuth, Status: StatusActive, + Credentials: map[string]any{ + "access_token": "old-access", "refresh_token": "old-refresh", "_token_version": int64(1), + }, + } +} + +func TestRefreshIfNeeded_OpenAICASKeepsConcurrentReauthorization(t *testing.T) { + account := openAIRefreshTestAccount() + expected := shallowCopyMap(account.Credentials) + repo := &refreshAPIAccountRepo{account: account} + repo.beforeSuccessCAS = func(repo *refreshAPIAccountRepo) { + repo.account.Credentials = map[string]any{ + "access_token": "reauthorized-access", "refresh_token": "reauthorized-refresh", "_token_version": int64(2), + } + } + executor := &refreshAPIExecutorStub{ + needsRefresh: true, + credentials: map[string]any{"access_token": "rotated-access", "refresh_token": "rotated-refresh"}, + } + + result, err := NewOAuthRefreshAPI(repo, nil).RefreshIfNeeded(context.Background(), account, executor, time.Hour) + + require.NoError(t, err) + require.False(t, result.Refreshed) + require.Equal(t, "reauthorized-refresh", result.Account.GetOpenAIRefreshToken()) + require.Equal(t, expected, repo.lastExpectedCredentials) + require.Zero(t, repo.updateCalls) +} + +func TestRefreshIfNeeded_OpenAIPersistenceFailureContainsProvider(t *testing.T) { + for _, failure := range []string{"CAS write", "durable reread"} { + t.Run(failure, func(t *testing.T) { + account := openAIRefreshTestAccount() + repo := &refreshAPIAccountRepo{account: account} + if failure == "CAS write" { + repo.updateErr = errors.New("database unavailable") + } else { + repo.getByIDErrAfterCall = 2 + repo.getByIDErrAfterCallErr = errors.New("database reread unavailable") + } + executor := &refreshAPIExecutorStub{ + needsRefresh: true, + credentials: map[string]any{"access_token": "rotated-access", "refresh_token": "rotated-refresh"}, + } + + _, err := NewOAuthRefreshAPI(repo, nil).RefreshIfNeeded(context.Background(), account, executor, time.Hour) + + var containment *providerCycleContainmentRefreshError + require.ErrorAs(t, err, &containment) + require.Equal(t, 1, executor.refreshCalls) + require.Equal(t, 1, repo.openAISuccessCASCalls) + if failure == "CAS write" { + require.Equal(t, "old-refresh", account.GetOpenAIRefreshToken(), "failed persistence must not publish in-memory credentials") + } + }) + } +} + +func TestRefreshIfNeeded_OpenAICanceledWithoutSuccessfulCredentialsDoesNotPersist(t *testing.T) { + for _, refreshErr := range []error{nil, errors.New("token endpoint failed")} { + t.Run(fmt.Sprint(refreshErr), func(t *testing.T) { + account := openAIRefreshTestAccount() + repo := &refreshAPIAccountRepo{account: account} + ctx, cancel := context.WithCancel(context.Background()) + defer cancel() + executor := &refreshAPIExecutorStub{needsRefresh: true, err: refreshErr, onRefresh: cancel} + + _, err := NewOAuthRefreshAPI(repo, nil).RefreshIfNeeded(ctx, account, executor, time.Hour) + + require.Error(t, err) + require.Zero(t, repo.openAISuccessCASCalls) + require.Zero(t, repo.updateCalls) + }) + } +} + func TestRefreshIfNeeded_NilCredentials(t *testing.T) { account := &Account{ID: 9, Platform: PlatformGemini, Type: AccountTypeOAuth, Status: StatusActive} repo := &refreshAPIAccountRepo{account: account} diff --git a/backend/internal/service/openai_alpha_search.go b/backend/internal/service/openai_alpha_search.go index a820d56503bf..0f814ed0f5ee 100644 --- a/backend/internal/service/openai_alpha_search.go +++ b/backend/internal/service/openai_alpha_search.go @@ -104,7 +104,7 @@ func (s *OpenAIGatewayService) ForwardAlphaSearch(ctx context.Context, c *gin.Co // 漏过 PAT 类型判断。这里仍允许本次请求换号,但不修改任何账号状态; // 真正的凭据失效由普通 Responses 请求或 whoami 校验判定。 shouldDisable := false - if shouldApplyOpenAIAlphaSearchAccountErrorSideEffects(resp.StatusCode) { + if shouldApplyOpenAIAlphaSearchAccountErrorSideEffects(resp.StatusCode, upstreamMessage, respBody) { shouldDisable = s.handleFailoverSideEffects(ctx, resp, account, respBody, openAIAlphaSearchSchedulingModel(account, requestedModel)) } retryableOnSameAccount := !shouldDisable && account.IsPoolMode() && account.IsPoolModeRetryableStatus(resp.StatusCode) @@ -183,7 +183,7 @@ func (s *OpenAIGatewayService) forwardAlphaSearchViaResponsesWebSearch( resp.Body = io.NopCloser(bytes.NewReader(respBody)) // 仍按 alpha/search 工具请求处理:PAT 的工具链路失败不能直接永久置错。 shouldDisable := false - if shouldApplyOpenAIAlphaSearchAccountErrorSideEffects(resp.StatusCode) { + if shouldApplyOpenAIAlphaSearchAccountErrorSideEffects(resp.StatusCode, upstreamMessage, respBody) { shouldDisable = s.handleFailoverSideEffects(ctx, resp, account, respBody, openAIAlphaSearchSchedulingModel(account, requestedModel)) } retryableOnSameAccount := !shouldDisable && account.IsPoolMode() && account.IsPoolModeRetryableStatus(resp.StatusCode) @@ -546,13 +546,20 @@ func isOpenAIAlphaSearchEndpointUnsupported(account *Account, statusCode int) bo return statusCode == http.StatusNotFound || statusCode == http.StatusMethodNotAllowed } -func shouldApplyOpenAIAlphaSearchAccountErrorSideEffects(statusCode int) bool { +func shouldApplyOpenAIAlphaSearchAccountErrorSideEffects(statusCode int, upstreamMessage string, responseBody []byte) bool { switch statusCode { case http.StatusUnauthorized, http.StatusNotFound, http.StatusMethodNotAllowed: // 401:工具端点的 access enforcement 不代表凭据全局失效; // 404/405:端点不存在只说明该上游不支持独立搜索,账号本身健康。 // 两类都只换号,不写账号错误状态。 return false + case http.StatusForbidden: + // 403 只有在明确是账号/工作区访问状态错误(停用、禁用等)时才是账号级 + // 证据。其余 403 是搜索工具本身的拒绝,例如套餐不含文献检索时的 + // {"detail":"Literature search is unavailable."}:同一请求会在 failover + // 中逐号重放,若按通用 403 处理(首次冷却 10 分钟、3 次永久置错), + // 一条请求就能停掉整个号池。这类 403 只换号,不写账号状态。 + return isOpenAIHTTPUpstreamAccessStateError(statusCode, upstreamMessage, responseBody) default: return true } diff --git a/backend/internal/service/openai_alpha_search_test.go b/backend/internal/service/openai_alpha_search_test.go index 378378b2fca0..0de2fe3394d2 100644 --- a/backend/internal/service/openai_alpha_search_test.go +++ b/backend/internal/service/openai_alpha_search_test.go @@ -621,11 +621,106 @@ func TestForwardAlphaSearchOAuthNotFoundPassesThrough(t *testing.T) { } func TestShouldApplyOpenAIAlphaSearchAccountErrorSideEffects(t *testing.T) { - require.False(t, shouldApplyOpenAIAlphaSearchAccountErrorSideEffects(http.StatusUnauthorized)) - require.False(t, shouldApplyOpenAIAlphaSearchAccountErrorSideEffects(http.StatusNotFound)) - require.False(t, shouldApplyOpenAIAlphaSearchAccountErrorSideEffects(http.StatusMethodNotAllowed)) - require.True(t, shouldApplyOpenAIAlphaSearchAccountErrorSideEffects(http.StatusForbidden)) - require.True(t, shouldApplyOpenAIAlphaSearchAccountErrorSideEffects(http.StatusTooManyRequests)) + require.False(t, shouldApplyOpenAIAlphaSearchAccountErrorSideEffects(http.StatusUnauthorized, "", nil)) + require.False(t, shouldApplyOpenAIAlphaSearchAccountErrorSideEffects(http.StatusNotFound, "", nil)) + require.False(t, shouldApplyOpenAIAlphaSearchAccountErrorSideEffects(http.StatusMethodNotAllowed, "", nil)) + require.True(t, shouldApplyOpenAIAlphaSearchAccountErrorSideEffects(http.StatusTooManyRequests, "", nil)) + + // 403:只有账号/工作区访问状态错误才写账号状态;搜索工具自身的拒绝只换号。 + literature := []byte(`{"detail":"Literature search is unavailable."}`) + require.False(t, shouldApplyOpenAIAlphaSearchAccountErrorSideEffects(http.StatusForbidden, "Literature search is unavailable.", literature)) + require.False(t, shouldApplyOpenAIAlphaSearchAccountErrorSideEffects(http.StatusForbidden, "", nil)) + deactivated := []byte(`{"error":{"code":"deactivated_workspace","message":"Workspace is deactivated"}}`) + require.True(t, shouldApplyOpenAIAlphaSearchAccountErrorSideEffects(http.StatusForbidden, "Workspace is deactivated", deactivated)) +} + +// 回归:上游对文献检索返回 403 {"detail":"Literature search is unavailable."} +// (套餐不含该能力)时,只换号,不能写账号错误状态。此前按通用 OpenAI 403 +// 处理:首次冷却 10 分钟、3 小时内 3 次永久置错,同一请求逐号重放,4 秒内 +// 停掉整个 OAuth 号池。 +func TestForwardAlphaSearchLiteratureSearchForbiddenDoesNotPenalizeAccount(t *testing.T) { + cases := []struct { + name string + credentials map[string]any + wantURL string + }{ + { + name: "oauth", + credentials: map[string]any{"access_token": "oauth-token", "chatgpt_account_id": "chatgpt-account"}, + wantURL: chatgptCodexAlphaSearchURL, + }, + { + name: "pat responses fallback", + credentials: map[string]any{"access_token": "at-test-token", "auth_mode": OpenAIAuthModePersonalAccessToken, "chatgpt_account_id": "chatgpt-account"}, + wantURL: chatgptCodexURL, + }, + } + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + gin.SetMode(gin.TestMode) + body := []byte(`{"id":"search-session","model":"gpt-6.2-astra","commands":{"literature_search_query":[{"q":"protein folding"}]}}`) + recorder := httptest.NewRecorder() + c, _ := gin.CreateTestContext(recorder) + c.Request = httptest.NewRequest(http.MethodPost, "/alpha/search", bytes.NewReader(body)) + + upstream := &httpUpstreamRecorder{resp: &http.Response{ + StatusCode: http.StatusForbidden, + Header: http.Header{"Content-Type": []string{"application/json"}}, + Body: io.NopCloser(strings.NewReader(`{"detail":"Literature search is unavailable."}`)), + }} + repo := &alphaSearchAccountStateRepo{} + cfg := &config.Config{} + service := &OpenAIGatewayService{ + cfg: cfg, + httpUpstream: upstream, + accountRepo: repo, + rateLimitService: NewRateLimitService(repo, nil, cfg, nil, nil), + } + account := &Account{ID: 45, Platform: PlatformOpenAI, Type: AccountTypeOAuth, Concurrency: 1, Credentials: tc.credentials} + + result, err := service.ForwardAlphaSearch(context.Background(), c, account, body) + + require.Nil(t, result) + var failoverErr *UpstreamFailoverError + require.ErrorAs(t, err, &failoverErr, "the request may still succeed on another account") + require.Equal(t, http.StatusForbidden, failoverErr.StatusCode) + require.Zero(t, repo.setErrorCalls, "a tool-level 403 must not mark the account as errored") + require.Empty(t, repo.lastError) + require.Equal(t, tc.wantURL, upstream.lastReq.URL.String()) + require.False(t, c.Writer.Written()) + }) + } +} + +// 账号/工作区访问状态 403 仍是账号级证据,必须继续写账号状态。 +func TestForwardAlphaSearchAccessStateForbiddenStillMarksAccount(t *testing.T) { + gin.SetMode(gin.TestMode) + body := []byte(`{"id":"search-session","model":"gpt-5.6-sol","commands":{}}`) + recorder := httptest.NewRecorder() + c, _ := gin.CreateTestContext(recorder) + c.Request = httptest.NewRequest(http.MethodPost, "/v1/alpha/search", bytes.NewReader(body)) + + upstream := &httpUpstreamRecorder{resp: &http.Response{ + StatusCode: http.StatusForbidden, + Header: http.Header{"Content-Type": []string{"application/json"}}, + Body: io.NopCloser(strings.NewReader(`{"error":{"code":"deactivated_workspace","message":"Workspace is deactivated"}}`)), + }} + repo := &alphaSearchAccountStateRepo{} + cfg := &config.Config{} + service := &OpenAIGatewayService{ + cfg: cfg, + httpUpstream: upstream, + accountRepo: repo, + rateLimitService: NewRateLimitService(repo, nil, cfg, nil, nil), + } + account := &Account{ID: 46, Platform: PlatformOpenAI, Type: AccountTypeOAuth, Concurrency: 1, Credentials: map[string]any{"access_token": "oauth-token", "chatgpt_account_id": "chatgpt-account"}} + + _, err := service.ForwardAlphaSearch(context.Background(), c, account, body) + + var failoverErr *UpstreamFailoverError + require.ErrorAs(t, err, &failoverErr) + require.Equal(t, 1, repo.setErrorCalls, "a deactivated workspace is account-level evidence") + require.Contains(t, repo.lastError, "Workspace is deactivated") } func TestOpenAIAlphaSearchSchedulingModelUsesCanonicalAccountMapping(t *testing.T) { diff --git a/backend/internal/service/openai_codex_model_metadata.go b/backend/internal/service/openai_codex_model_metadata.go index a597c712a796..66695c1c9aff 100644 --- a/backend/internal/service/openai_codex_model_metadata.go +++ b/backend/internal/service/openai_codex_model_metadata.go @@ -220,6 +220,7 @@ func groupCodexModelMetadata( publicAlias := upstreamModel != modelID candidates := make([]UpstreamModelMetadata, 0) missingMetadata := false + audioInput := true for i := range accounts { account := &accounts[i] if !codexAccountServesPlatformModel(account, platform, modelID) { @@ -244,6 +245,7 @@ func groupCodexModelMetadata( publicAlias = true } metadata, ok := account.GetUpstreamModelMetadata(lookupModel) + audioInput = audioInput && accountCodexModelSupportsAudioInput(account, lookupModel, metadata.InputModalities) if !ok { if explicitTargetsConflict { return codexModelMetadataOverride{ @@ -269,9 +271,25 @@ func groupCodexModelMetadata( metadata.DisplayName = modelID metadata.Description = configuredCodexCustomDescription } + metadata.audioInput = audioInput return metadata, true } +func accountCodexModelSupportsAudioInput(account *Account, modelID string, modalities []string) bool { + if account == nil || !account.IsOpenAI() { + return false + } + if resolveUpstreamProtocol(account, APIProtocolResponses, modelID, nil) != APIProtocolResponses { + return false + } + if len(modalities) > 0 { + return stringSliceContains(modalities, "audio") + } + // The bundled Codex subscription manifest declares audio for Sol. The + // public API model with the same slug has different input capabilities. + return account.IsOpenAIOAuthLike() && openai.GPT62ModelID(modelID) == "gpt-6.2-sol" +} + func codexExplicitModelTargetsConflict(accounts []Account, modelID string) bool { targets := make(map[string]struct{}) for i := range accounts { diff --git a/backend/internal/service/openai_codex_model_metadata_test.go b/backend/internal/service/openai_codex_model_metadata_test.go index f990f25bb40a..d8ef23e25f95 100644 --- a/backend/internal/service/openai_codex_model_metadata_test.go +++ b/backend/internal/service/openai_codex_model_metadata_test.go @@ -6,9 +6,102 @@ import ( "errors" "testing" + "github.com/Wei-Shaw/sub2api/internal/pkg/openai" "github.com/stretchr/testify/require" ) +func TestCodexCatalogAudioInput(t *testing.T) { + const sol = "gpt-6.2-sol" + const astra = "gpt-6.2-astra" + manifest, err := json.Marshal(map[string][]json.RawMessage{"models": {openai.CodexGPT62SolMetadata, openai.CodexGPT62AstraMetadata}}) + require.NoError(t, err) + _, metadata, err := extractUpstreamModelCatalog(manifest, false) + require.NoError(t, err) + t.Run("sync keeps the declared input modalities", func(t *testing.T) { + require.Equal(t, []string{"text", "image", "audio"}, metadata[sol].InputModalities) + require.Equal(t, []string{"text", "image"}, metadata[astra].InputModalities) + }) + subscription := Account{ID: 1, Platform: PlatformOpenAI, Type: AccountTypeOAuth} + synced := Account{ID: 2, Platform: PlatformOpenAI, Type: AccountTypeOAuth} + synced.SetUpstreamModelMetadataSnapshot(UpstreamModelMetadataSnapshot{Models: metadata}) + key := Account{ID: 3, Platform: PlatformOpenAI, Type: AccountTypeAPIKey} + native := Account{ID: 4, Platform: PlatformOpenAI, Type: AccountTypeAPIKey, + Credentials: map[string]any{"base_url": "https://native.example/v1"}} + native.SetUpstreamModelMetadataSnapshot(UpstreamModelMetadataSnapshot{Models: metadata}) + bridged := Account{ID: 5, Platform: PlatformOpenAI, Type: AccountTypeAPIKey, + Credentials: native.Credentials, Extra: map[string]any{"openai_responses_mode": "force_chat_completions"}} + bridged.SetUpstreamModelMetadataSnapshot(UpstreamModelMetadataSnapshot{Models: metadata}) + for _, tc := range []struct { + name string + model string + accounts []Account + want []any + }{ + {"Codex subscription", sol, []Account{subscription}, []any{"text", "image", "audio"}}, + {"synced Codex subscription", sol, []Account{synced}, []any{"text", "image", "audio"}}, + {"Astra excludes audio", astra, []Account{synced}, []any{"text", "image"}}, + {"public API key excludes subscription-only audio", sol, []Account{key}, []any{"text", "image"}}, + {"mixed subscription and API key", sol, []Account{synced, key}, []any{"text", "image"}}, + {"native compatible route declares audio", sol, []Account{native}, []any{"text", "image", "audio"}}, + {"mixed native and chat bridge", sol, []Account{native, bridged}, []any{"text", "image"}}, + {"empty group has no audio route", sol, nil, []any{"text", "image"}}, + } { + t.Run(tc.name, func(t *testing.T) { + svc := &GatewayService{accountRepo: codexModelsVisibilityAccountRepo{byGroup: map[int64][]Account{1: tc.accounts}}} + body, err := svc.BuildCodexModelsManifestForGroup(context.Background(), &Group{ID: 1, Platform: PlatformOpenAI}, "", []string{tc.model}) + require.NoError(t, err) + require.Equal(t, tc.want, decodeCodexManifestModels(t, body)[0]["input_modalities"]) + }) + } + for _, tc := range []struct { + account *Account + want []any + }{ + {&native, []any{"text", "image", "audio"}}, + {&bridged, []any{"text", "image"}}, + } { + response := &OpenAIModelsResponse{Body: []byte(`{"models":[{"slug":"gpt-6.2-sol"}]}`)} + require.NoError(t, (&OpenAIGatewayService{}).CompleteAPIKeyCodexModelsManifestForClient(response, tc.account)) + require.Equal(t, tc.want, decodeCodexManifestModels(t, response.Body)[0]["input_modalities"]) + } +} + +func TestCodexCatalogAudioFromLiveAPIKeyManifest(t *testing.T) { + native := Account{Platform: PlatformOpenAI, Type: AccountTypeAPIKey, + Credentials: map[string]any{"base_url": "https://native.example/v1"}} + for _, fixture := range []struct { + name, body string + converted bool + }{ + {"Codex manifest", `{"models":[{"slug":"gpt-6.2-sol","input_modalities":["text","image","audio"]}]}`, false}, + {"OpenAI list", `{"data":[{"id":"gpt-6.2-sol","input_modalities":["text","image","audio"]}]}`, true}, + {"nested modalities", `{"data":[{"id":"gpt-6.2-sol","modalities":{"input":["text","image","audio"]}}]}`, true}, + } { + for _, tc := range []struct { + name string + extra map[string]any + want []any + }{ + {"native Responses", nil, []any{"text", "image", "audio"}}, + {"forced Chat bridge", map[string]any{"openai_responses_mode": "force_chat_completions"}, []any{"text", "image"}}, + {"probed Chat fallback", map[string]any{"openai_responses_supported": false}, []any{"text", "image"}}, + } { + t.Run(fixture.name+"/"+tc.name, func(t *testing.T) { + account := native + account.Extra = tc.extra + body := convertOpenAIModelListToCodexManifestForAccount([]byte(fixture.body), &account) + response := &OpenAIModelsResponse{ + Body: body, + upstreamSourceBody: []byte(fixture.body), + convertedFromOpenAIModelList: fixture.converted, + } + require.NoError(t, (&OpenAIGatewayService{}).CompleteAPIKeyCodexModelsManifestForClient(response, &account)) + require.Equal(t, tc.want, decodeCodexManifestModels(t, response.Body)[0]["input_modalities"]) + }) + } + } +} + func TestCodexCatalogUsesAntigravityCapabilitiesInGeminiMixedGroup(t *testing.T) { const groupID int64 = 93 account := Account{ diff --git a/backend/internal/service/openai_codex_models_service.go b/backend/internal/service/openai_codex_models_service.go index db92fd12a08f..6a4d47b6027a 100644 --- a/backend/internal/service/openai_codex_models_service.go +++ b/backend/internal/service/openai_codex_models_service.go @@ -12,6 +12,7 @@ import ( "net/http" "net/url" "regexp" + "slices" "sort" "strings" "sync" @@ -443,6 +444,7 @@ type configuredCodexModelDescriptor struct { type codexModelMetadataOverride struct { UpstreamModelMetadata + audioInput bool reasoningConflict bool inputModalitiesConflict bool } @@ -1075,6 +1077,7 @@ func buildCodexModelsManifest( // a stale official Astra snapshot cannot downgrade the catalog. descriptor.InputModalities = []string{"text", "image"} } + descriptor.InputModalities = codexAudioInputModalities(descriptor.InputModalities, modelMetadata[modelID].audioInput) if metadataModelID != modelID { descriptor.DisplayName = modelID descriptor.Description = configuredCodexCustomDescription @@ -1101,6 +1104,16 @@ func buildCodexModelsManifest( }{Models: models}) } +func codexAudioInputModalities(modalities []string, supported bool) []string { + if !supported { + return slices.DeleteFunc(modalities, func(modality string) bool { return modality == "audio" }) + } + if !slices.Contains(modalities, "audio") { + return append(modalities, "audio") + } + return modalities +} + func resolveCodexCatalogMetadataModel( platform string, modelID string, @@ -2349,9 +2362,21 @@ func convertOpenAIModelListToCodexManifestForAccount(body []byte, account *Accou capabilities["multi_agent_version"] = json.RawMessage("null") capabilities["multi_agent_reasoning_effort"] = json.RawMessage("null") } - modelMetadata[id] = codexModelMetadataOverride{UpstreamModelMetadata: UpstreamModelMetadata{ - CodexToolCapabilities: capabilities, - }} + var modalities []string + _ = json.Unmarshal(entry["input_modalities"], &modalities) + if len(modalities) == 0 { + var declared modelsDevModalities + _ = json.Unmarshal(entry["modalities"], &declared) + modalities = declared.Input + } + if len(modalities) == 0 && account != nil { + synced, _ := account.GetUpstreamModelMetadata(capabilityModel) + modalities = synced.InputModalities + } + modelMetadata[id] = codexModelMetadataOverride{ + UpstreamModelMetadata: UpstreamModelMetadata{CodexToolCapabilities: capabilities}, + audioInput: accountCodexModelSupportsAudioInput(account, capabilityModel, normalizeCodexInputModalities(modalities)), + } } if len(modelIDs) == 0 { return body @@ -2576,6 +2601,8 @@ func completeAPIKeyCodexModelsManifestMetadata(body []byte, completeAll bool, ac } descriptor := newConfiguredCodexModelDescriptor(slug) + // A subscription descriptor alone cannot establish audio support for an API key. + descriptor.InputModalities = codexAudioInputModalities(descriptor.InputModalities, false) descriptor.SupportsSearchTool = shouldForwardOpenAIResponsesViaRawChatCompletions(account) if accountCodexModelSupportsImageInput(account, slug) { descriptor.InputModalities = []string{"text", "image"} @@ -2625,6 +2652,15 @@ func completeAPIKeyCodexModelsManifestMetadata(body []byte, completeAll bool, ac model["supports_image_detail_original"] = imageDetailOriginal modelChanged = true } + } else if account != nil && resolveUpstreamProtocol(account, APIProtocolResponses, capabilityModel, nil) != APIProtocolResponses { + var modalities []string + if json.Unmarshal(model["input_modalities"], &modalities) == nil && slices.Contains(modalities, "audio") { + model["input_modalities"], err = json.Marshal(codexAudioInputModalities(modalities, false)) + if err != nil { + return nil, fmt.Errorf("encode input modalities for model %q: %w", slug, err) + } + modelChanged = true + } } if !modelChanged { continue diff --git a/backend/internal/service/openai_codex_tool_names.go b/backend/internal/service/openai_codex_tool_names.go index 849a45e417ab..94b7d8d39b8d 100644 --- a/backend/internal/service/openai_codex_tool_names.go +++ b/backend/internal/service/openai_codex_tool_names.go @@ -1,6 +1,7 @@ package service import ( + "bytes" "encoding/json" "fmt" "strings" @@ -132,7 +133,7 @@ func collectOpenAIResponsesToolNameFields(reqBody map[string]any) []codexToolNam continue } typ := strings.ToLower(strings.TrimSpace(firstNonEmptyString(item["type"]))) - if typ == "additional_tools" { + if typ == "additional_tools" || typ == "tool_search_output" { collectTools(item["tools"]) } if typ == "function_call" { @@ -165,28 +166,52 @@ func aliasOpenAIOAuthReservedToolNamesBody(body []byte) ([]byte, map[string]stri return normalized, reverse, true, nil } +// containsASCIIFold reports whether haystack contains needle under ASCII case +// folding. +// +// 逐字节比较在 1MiB 级请求体上等于整段扫描;只按首字节 memchr 又会为每个候选 +// 重新探测「大小写两种首字节」各自的整段尾部,候选一多就退化成平方级。这里给 +// 大小写两条候选游标,每条只在自身未消费的区间上前进,整体保持线性, +// 结果与逐字节折叠比较完全一致。 func containsASCIIFold(haystack, needle []byte) bool { if len(needle) == 0 || len(haystack) < len(needle) { return false } - for i := 0; i <= len(haystack)-len(needle); i++ { - matched := true - for j := range needle { - a, b := haystack[i+j], needle[j] - if a >= 'A' && a <= 'Z' { - a += 'a' - 'A' - } - if b >= 'A' && b <= 'Z' { - b += 'a' - 'A' - } - if a != b { - matched = false - break - } + first := needle[0] + upper := first + if 'a' <= first && first <= 'z' { + upper = first - ('a' - 'A') + } + last := len(haystack) - len(needle) + + lowerPos := bytes.IndexByte(haystack, first) + upperPos := -1 + if upper != first { + upperPos = bytes.IndexByte(haystack, upper) + } + for lowerPos >= 0 || upperPos >= 0 { + pos := lowerPos + if pos < 0 || (upperPos >= 0 && upperPos < pos) { + pos = upperPos } - if matched { + if pos > last { + return false + } + if bytes.EqualFold(haystack[pos:pos+len(needle)], needle) { return true } + // 只推进刚刚消费掉的那条游标。 + if pos == lowerPos { + lowerPos = -1 + if next := bytes.IndexByte(haystack[pos+1:], first); next >= 0 { + lowerPos = pos + 1 + next + } + continue + } + upperPos = -1 + if next := bytes.IndexByte(haystack[pos+1:], upper); next >= 0 { + upperPos = pos + 1 + next + } } return false } diff --git a/backend/internal/service/openai_cursor_warmup_pipeline_test.go b/backend/internal/service/openai_cursor_warmup_pipeline_test.go index 19bb13d607ae..efa704052510 100644 --- a/backend/internal/service/openai_cursor_warmup_pipeline_test.go +++ b/backend/internal/service/openai_cursor_warmup_pipeline_test.go @@ -168,6 +168,7 @@ func TestCursorMixedShape_StripsUnsupportedFields(t *testing.T) { "safety_identifier": "cursor-user-xyz", "metadata": {"trace_id":"abc","caller":"cursor"}, "stream_options": {"include_usage": true}, + "stop": ["STOP_HERE"], "input": [{"role":"user","content":"hi"}] }`) diff --git a/backend/internal/service/openai_gateway_buffered_hosted_items.go b/backend/internal/service/openai_gateway_buffered_hosted_items.go new file mode 100644 index 000000000000..69ac8f6205da --- /dev/null +++ b/backend/internal/service/openai_gateway_buffered_hosted_items.go @@ -0,0 +1,474 @@ +package service + +import ( + "encoding/json" + "math" + "sort" + "strings" + + "github.com/Wei-Shaw/sub2api/internal/pkg/apicompat" + "github.com/tidwall/gjson" +) + +// openAICompatPartText keeps the delta text of one kind per part index, the +// content_index or summary_index of its events, so that a part of an item is +// completed with the text of that part only. +type openAICompatPartText struct { + parts map[int64]*strings.Builder +} + +func (p *openAICompatPartText) write(index int64, delta string) { + if p.parts == nil { + p.parts = map[int64]*strings.Builder{} + } + if p.parts[index] == nil { + p.parts[index] = &strings.Builder{} + } + _, _ = p.parts[index].WriteString(delta) +} + +func (p *openAICompatPartText) any() bool { + return len(p.parts) > 0 +} + +func (p *openAICompatPartText) at(index int64) string { + if builder := p.parts[index]; builder != nil { + return builder.String() + } + return "" +} + +// unclaimed joins, in part order, the text of the parts from index from on that +// are not in claimed. +func (p *openAICompatPartText) unclaimed(claimed map[int64]bool, from int64) string { + indexes := make([]int64, 0, len(p.parts)) + for index := range p.parts { + if index >= from && !claimed[index] { + indexes = append(indexes, index) + } + } + sort.Slice(indexes, func(i, j int) bool { return indexes[i] < indexes[j] }) + var text strings.Builder + for _, index := range indexes { + _, _ = text.WriteString(p.parts[index].String()) + } + return text.String() +} + +// openAICompatOutputSlot is everything the upstream stream said about one output +// item: the item of its output_item.added and output_item.done events and the +// text, refusal and argument deltas that arrived for it. Text, refusal and the +// two kinds of reasoning text are kept per part, and the reasoning text also in +// arrival order across its kinds. +type openAICompatOutputSlot struct { + index int64 + indexed bool + itemType string + id string + added *apicompat.ResponsesOutput + done *apicompat.ResponsesOutput + reasoning strings.Builder + summaryText openAICompatPartText + reasoningText openAICompatPartText + text openAICompatPartText + refusal openAICompatPartText + args strings.Builder + argsDone string +} + +// openAICompatOutputSlots records the output items of a buffered upstream stream +// so that an empty terminal output can be rebuilt from them. +type openAICompatOutputSlots struct { + slots []*openAICompatOutputSlot + // xaiServerSideSearch is set when the upstream is xAI, so that the rebuilt + // output keeps a server-side search call out of the client tool calls. + xaiServerSideSearch bool +} + +func openAICompatIsToolCallType(itemType string) bool { + return itemType == "function_call" || itemType == "custom_tool_call" +} + +func (o *openAICompatOutputSlots) Observe(payload []byte) { + if o == nil { + return + } + switch strings.TrimSpace(gjson.GetBytes(payload, "type").String()) { + case "response.output_item.added": + if item, ok := openAICompatEventItem(payload); ok { + slot := o.slot(payload, item.Type, item.ID, item.CallID, false, true) + slot.added = &item + } + case "response.output_item.done": + if item, ok := openAICompatEventItem(payload); ok { + slot := o.slot(payload, item.Type, item.ID, item.CallID, true, true) + slot.done = &item + } + case "response.output_text.delta": + if delta := gjson.GetBytes(payload, "delta").String(); delta != "" { + o.slot(payload, "message", gjson.GetBytes(payload, "item_id").String(), "", false, true).text.write(gjson.GetBytes(payload, "content_index").Int(), delta) + } + case "response.refusal.delta": + if delta := gjson.GetBytes(payload, "delta").String(); delta != "" { + o.slot(payload, "message", gjson.GetBytes(payload, "item_id").String(), "", false, true).refusal.write(gjson.GetBytes(payload, "content_index").Int(), delta) + } + case "response.reasoning_summary_text.delta": + if delta := gjson.GetBytes(payload, "delta").String(); delta != "" { + slot := o.slot(payload, "reasoning", gjson.GetBytes(payload, "item_id").String(), "", false, true) + _, _ = slot.reasoning.WriteString(delta) + slot.summaryText.write(gjson.GetBytes(payload, "summary_index").Int(), delta) + } + case "response.reasoning_text.delta": + if delta := gjson.GetBytes(payload, "delta").String(); delta != "" { + slot := o.slot(payload, "reasoning", gjson.GetBytes(payload, "item_id").String(), "", false, true) + _, _ = slot.reasoning.WriteString(delta) + slot.reasoningText.write(gjson.GetBytes(payload, "content_index").Int(), delta) + } + case "response.function_call_arguments.delta", "response.custom_tool_call_input.delta": + if delta := gjson.GetBytes(payload, "delta").String(); delta != "" { + if slot := o.slot(payload, "function_call", gjson.GetBytes(payload, "item_id").String(), "", false, false); slot != nil { + _, _ = slot.args.WriteString(delta) + } + } + case "response.function_call_arguments.done": + if slot := o.slot(payload, "function_call", gjson.GetBytes(payload, "item_id").String(), "", false, false); slot != nil { + if completed := gjson.GetBytes(payload, "arguments").String(); completed != "" { + slot.argsDone = completed + } + } + case "response.custom_tool_call_input.done": + if slot := o.slot(payload, "function_call", gjson.GetBytes(payload, "item_id").String(), "", false, false); slot != nil { + if completed := gjson.GetBytes(payload, "input").String(); completed != "" { + slot.argsDone = completed + } + } + } +} + +func openAICompatEventItem(payload []byte) (apicompat.ResponsesOutput, bool) { + var item apicompat.ResponsesOutput + raw := gjson.GetBytes(payload, "item") + if !raw.IsObject() || !gjson.ValidBytes(payload) || json.Unmarshal([]byte(raw.Raw), &item) != nil { + return item, false + } + item.Type = strings.TrimSpace(item.Type) + return item, item.Type != "" +} + +// slot finds the slot an event belongs to. id is the id of the item the event +// is about (the item of an added or done event, the item_id of a delta) and +// callID the call_id of a tool call item. A done event whose item has an id +// belongs to the slot that already holds a done item with that id, so a repeated +// item replaces its earlier copy. Otherwise an event whose id a slot already +// has, because the deltas or the added event of that item opened it, belongs to +// that slot, also when the event has no output_index. Otherwise an event with an +// output_index belongs to the newest slot of that index that can hold its kind +// of item and has no other id (an added event: the newest one without an added or +// done item; a done event with an id: the newest one without a done item; a done +// event without an id replaces the done item of that slot), so items that merely +// share an output_index stay apart. An event without an output_index belongs to +// the newest slot of its kind that is not done, else to the newest unindexed +// one; a done event with a call_id belongs to the slot of that call, else to the +// oldest unindexed slot of its kind without a done item, and an added event +// always starts a new slot, so unindexed items keep arrival order. With create +// unset, a missing slot returns nil. +func (o *openAICompatOutputSlots) slot(payload []byte, kind, id, callID string, done, create bool) *openAICompatOutputSlot { + index := gjson.GetBytes(payload, "output_index") + added := strings.TrimSpace(gjson.GetBytes(payload, "type").String()) == "response.output_item.added" + matches := func(slot *openAICompatOutputSlot) bool { + if slot.itemType == "" || slot.itemType == kind { + return true + } + return openAICompatIsToolCallType(kind) && openAICompatIsToolCallType(slot.itemType) + } + fits := func(slot *openAICompatOutputSlot) bool { + return matches(slot) && (slot.id == "" || id == "" || slot.id == id) + } + newest := func(accept func(*openAICompatOutputSlot) bool) *openAICompatOutputSlot { + for i := len(o.slots) - 1; i >= 0; i-- { + if accept(o.slots[i]) { + return o.slots[i] + } + } + return nil + } + var found *openAICompatOutputSlot + if done && id != "" { + found = newest(func(slot *openAICompatOutputSlot) bool { return slot.done != nil && slot.done.ID == id }) + } + if found == nil && id != "" && (done || added || !index.Exists()) { + found = newest(func(slot *openAICompatOutputSlot) bool { + return slot.id == id && matches(slot) && slot.done == nil && (!added || slot.added == nil) + }) + } + if found == nil { + switch { + case index.Exists(): + atIndex := func(slot *openAICompatOutputSlot) bool { + return slot.indexed && slot.index == index.Int() && matches(slot) + } + switch { + case done && id != "": + found = newest(func(slot *openAICompatOutputSlot) bool { return atIndex(slot) && slot.done == nil }) + case added: + found = newest(func(slot *openAICompatOutputSlot) bool { return atIndex(slot) && slot.added == nil && slot.done == nil }) + default: + found = newest(atIndex) + } + case added: + case done: + if callID != "" { + found = newest(func(slot *openAICompatOutputSlot) bool { + return slot.done == nil && slot.added != nil && slot.added.CallID == callID && matches(slot) + }) + } + for _, slot := range o.slots { + if found == nil && !slot.indexed && slot.done == nil && slot.itemType == kind { + found = slot + } + } + default: + found = newest(func(slot *openAICompatOutputSlot) bool { return slot.done == nil && fits(slot) }) + if found == nil { + found = newest(func(slot *openAICompatOutputSlot) bool { return !slot.indexed && fits(slot) }) + } + } + } + if found == nil && index.Exists() && (added || done) { + // Deltas that came with no output_index and before their item was announced + // belong to the newest such item of this kind. + found = newest(func(slot *openAICompatOutputSlot) bool { + return !slot.indexed && slot.added == nil && slot.done == nil && fits(slot) + }) + } + if found == nil { + if !create { + return nil + } + found = &openAICompatOutputSlot{} + o.slots = append(o.slots, found) + } + if index.Exists() && !found.indexed { + found.index, found.indexed = index.Int(), true + } + if found.id == "" { + found.id = id + } + if found.itemType == "" || done || added { + found.itemType = kind + } + return found +} + +// fillTerminalOutput rebuilds an empty terminal output from the stream's output +// items, in output_index order, items without an output_index after the indexed +// ones in arrival order. Items with the same output_index keep arrival order. +// An item that received output_item.done is taken from that event, completed with the deltas where the event left a text, refusal or +// the arguments empty, a part with the deltas of its own content_index or +// summary_index; an item that never received it is rebuilt from its deltas. Only terminals that carry a result are filled; the output of +// response.failed and error terminals never reaches the client and is left as +// the upstream sent it. +func (o *openAICompatOutputSlots) fillTerminalOutput(eventType string, response *apicompat.ResponsesResponse) { + switch strings.TrimSpace(eventType) { + case "response.completed", "response.done", "response.incomplete", "response.cancelled", "response.canceled": + default: + return + } + if o == nil || response == nil || len(response.Output) > 0 { + return + } + slots := append([]*openAICompatOutputSlot(nil), o.slots...) + sort.SliceStable(slots, func(i, j int) bool { + a, b := slots[i], slots[j] + if a.indexed != b.indexed { + return a.indexed + } + return a.indexed && a.index < b.index + }) + for _, slot := range slots { + if item, ok := slot.build(); ok { + // The streaming converters render a web search only once it is completed. + if item.Type == "web_search_call" && item.Status != "completed" { + continue + } + response.Output = append(response.Output, item) + if item.Type == "custom_tool_call" { + response.RenderCustomToolCalls = true + response.XAIServerSideSearch = o.xaiServerSideSearch + } + } + } +} + +func (s *openAICompatOutputSlot) build() (apicompat.ResponsesOutput, bool) { + switch s.itemType { + case "reasoning": + return s.buildReasoning() + case "message": + return s.buildMessage() + case "function_call", "custom_tool_call": + return s.buildToolCall() + } + if s.done == nil { + return apicompat.ResponsesOutput{}, false + } + return *s.done, true +} + +func (s *openAICompatOutputSlot) buildReasoning() (apicompat.ResponsesOutput, bool) { + item := apicompat.ResponsesOutput{Type: "reasoning"} + if s.done != nil { + item = *s.done + } + // The signature may be on the added event only. + if s.added != nil && strings.TrimSpace(item.EncryptedContent) == "" { + item.EncryptedContent = s.added.EncryptedContent + } + // The converters render the summary text and fall back to the reasoning_text + // content only when the summary has none, so an item carrying both would lose + // one. The deltas carried every text the client is shown, so they stand in + // for a text field that is empty or that would be dropped. + if s.reasoning.Len() > 0 { + var summary, content bool + for _, part := range item.Summary { + summary = summary || (part.Type == "summary_text" && part.Text != "") + } + for _, part := range item.Content { + content = content || (part.Type == "reasoning_text" && part.Text != "") + } + switch { + case summary == content: + item.Summary = []apicompat.ResponsesSummary{{Type: "summary_text", Text: s.reasoning.String()}} + item.Content = nil + case summary: + // The item keeps its text; a summary part it left empty takes the + // deltas of its own summary_index. + item.Summary = append([]apicompat.ResponsesSummary(nil), item.Summary...) + claimed := map[int64]bool{} + for i := range item.Summary { + if part := &item.Summary[i]; part.Type == "summary_text" { + claimed[int64(i)] = true + if part.Text == "" { + part.Text = s.summaryText.at(int64(i)) + } + } + } + if rest := s.summaryText.unclaimed(claimed, int64(len(item.Summary))); rest != "" { + item.Summary = append(item.Summary, apicompat.ResponsesSummary{Type: "summary_text", Text: rest}) + } + default: + item.Content = append([]apicompat.ResponsesContentPart(nil), item.Content...) + claimed := map[int64]bool{} + for i := range item.Content { + if part := &item.Content[i]; part.Type == "reasoning_text" { + claimed[int64(i)] = true + if part.Text == "" { + part.Text = s.reasoningText.at(int64(i)) + } + } + } + if rest := s.reasoningText.unclaimed(claimed, int64(len(item.Content))); rest != "" { + item.Content = append(item.Content, apicompat.ResponsesContentPart{Type: "reasoning_text", Text: rest}) + } + } + } + return item, s.done != nil || s.reasoning.Len() > 0 || strings.TrimSpace(item.EncryptedContent) != "" +} + +func (s *openAICompatOutputSlot) buildMessage() (apicompat.ResponsesOutput, bool) { + item := apicompat.ResponsesOutput{Type: "message", Role: "assistant"} + if s.done != nil { + item = *s.done + item.Content = append([]apicompat.ResponsesContentPart(nil), item.Content...) + } + declared := int64(len(item.Content)) + if s.text.any() { + blank := func(text string) bool { return strings.TrimSpace(text) == "" } + if rest := completeContentParts(item.Content, &s.text, "output_text", declared, blank); rest != "" { + item.Content = append(item.Content, apicompat.ResponsesContentPart{Type: "output_text", Text: rest}) + } + } + if s.refusal.any() { + blank := func(text string) bool { return text == "" } + if rest := completeContentParts(item.Content, &s.refusal, "refusal", declared, blank); rest != "" { + item.Content = append(item.Content, apicompat.ResponsesContentPart{Type: "refusal", Refusal: rest}) + } + } + return item, s.done != nil || s.text.any() || s.refusal.any() +} + +// completeContentParts gives each blank part of partType the deltas of its own +// content_index, the position of the part in the content, and leaves the parts +// that have text as they are. It returns the deltas of the indexes that have no +// part of that type: all of them when no part has text, else those beyond the +// last of the declared parts of the done item. +func completeContentParts(content []apicompat.ResponsesContentPart, deltas *openAICompatPartText, partType string, declared int64, blank func(string) bool) string { + claimed := map[int64]bool{} + present := false + for i := range content { + part := &content[i] + if part.Type != partType { + continue + } + field := &part.Text + if partType == "refusal" { + field = &part.Refusal + } + claimed[int64(i)] = true + if blank(*field) { + if delta := deltas.at(int64(i)); delta != "" { + *field = delta + } + } + present = present || !blank(*field) + } + from := declared + if !present { + from = math.MinInt64 + } + return deltas.unclaimed(claimed, from) +} + +// buildToolCall returns the function_call or custom_tool_call item of the slot, +// with the arguments or input a done item left empty taken from the deltas. +func (s *openAICompatOutputSlot) buildToolCall() (apicompat.ResponsesOutput, bool) { + if s.done == nil && s.added == nil { + return apicompat.ResponsesOutput{}, false + } + var item apicompat.ResponsesOutput + if s.done != nil { + item = *s.done + } else { + item = *s.added + } + if s.added != nil { + if item.CallID == "" { + item.CallID = s.added.CallID + } + if item.Name == "" { + item.Name = s.added.Name + } + if item.Namespace == "" { + item.Namespace = s.added.Namespace + } + if item.EncryptedFunctionArgs == nil { + item.EncryptedFunctionArgs = s.added.EncryptedFunctionArgs + } + } + arguments := item.Arguments + if item.Type == "custom_tool_call" { + arguments = item.Input + } + if arguments == "" { + arguments = s.argsDone + } + if arguments == "" { + arguments = s.args.String() + } + if item.Type == "custom_tool_call" { + item.Input = arguments + } else { + item.Arguments = arguments + } + return item, true +} diff --git a/backend/internal/service/openai_gateway_buffered_hosted_items_test.go b/backend/internal/service/openai_gateway_buffered_hosted_items_test.go new file mode 100644 index 000000000000..acdae921804f --- /dev/null +++ b/backend/internal/service/openai_gateway_buffered_hosted_items_test.go @@ -0,0 +1,777 @@ +//go:build unit + +package service + +import ( + "bytes" + "context" + "io" + "net/http" + "net/http/httptest" + "strconv" + "strings" + "testing" + + "github.com/gin-gonic/gin" + "github.com/stretchr/testify/require" + "github.com/tidwall/gjson" +) + +const bufferedHostedItemsMessagesBody = `{"model":"gpt-5.5","max_tokens":64,"stream":false,"messages":[{"role":"user","content":"search the web"}]}` + +const bufferedHostedItemsThinkingBody = `{"model":"gpt-5.5","max_tokens":4096,"stream":false,"thinking":{"type":"enabled","budget_tokens":2048},"messages":[{"role":"user","content":"search the web"}]}` + +const bufferedHostedItemsChatBody = `{"model":"gpt-5.5","stream":false,"messages":[{"role":"user","content":"search the web"}]}` + +const bufferedHostedItemsCreated = `{"type":"response.created","response":{"id":"resp_1","model":"gpt-5.5"}}` + +const bufferedHostedItemsCompleted = `{"type":"response.completed","response":{"id":"resp_1","status":"completed","output":[],"usage":{"input_tokens":5,"output_tokens":2,"total_tokens":7}}}` + +const ( + bufferedHostedItemsWebSearchDone = `{"type":"response.output_item.done","output_index":0,"item":{"type":"web_search_call","id":"ws_1","status":"completed","action":{"type":"search","query":"q","sources":[{"type":"url","url":"https://a.example/1"}]}}}` + bufferedHostedItemsImageDone = `{"type":"response.output_item.done","output_index":1,"item":{"type":"image_generation_call","id":"ig_1","status":"completed","result":"aGVsbG8="}}` + bufferedHostedItemsTextDelta = `{"type":"response.output_text.delta","output_index":2,"delta":"found it"}` + bufferedHostedItemsMessageDone = `{"type":"response.output_item.done","output_index":2,"item":{"type":"message","id":"msg_1","role":"assistant","status":"completed","content":[{"type":"output_text","text":"found it"}]}}` +) + +// bufferedItemsSSE joins JSON events into an SSE body. +func bufferedItemsSSE(events ...string) string { + var b strings.Builder + for _, event := range events { + b.WriteString("data: " + event + "\n\n") + } + return b.String() +} + +// The upstream reports every output item on output_item.done but ends with an +// empty terminal output. +var bufferedHostedItemsSSE = bufferedItemsSSE( + bufferedHostedItemsCreated, + `{"type":"response.output_item.added","output_index":0,"item":{"type":"web_search_call","id":"ws_1","status":"in_progress"}}`, + bufferedHostedItemsWebSearchDone, + bufferedHostedItemsImageDone, + bufferedHostedItemsTextDelta, + bufferedHostedItemsMessageDone, + bufferedHostedItemsCompleted, +) + +func bufferedHostedItemsOAuthAccount() *Account { + return &Account{ + ID: 1, Name: "openai-oauth", Platform: PlatformOpenAI, Type: AccountTypeOAuth, Concurrency: 1, + Credentials: map[string]any{"access_token": "oauth-token", "chatgpt_account_id": "chatgpt-acc"}, + } +} + +func bufferedHostedItemsSSEResponse(sse string) *http.Response { + return &http.Response{ + StatusCode: http.StatusOK, + Header: http.Header{"Content-Type": []string{"text/event-stream"}}, + Body: io.NopCloser(strings.NewReader(sse)), + } +} + +func forwardBufferedHostedItems(t *testing.T, path, requestBody, upstreamSSE string) string { + t.Helper() + gin.SetMode(gin.TestMode) + rec := httptest.NewRecorder() + c, _ := gin.CreateTestContext(rec) + body := []byte(requestBody) + c.Request = httptest.NewRequest(http.MethodPost, path, bytes.NewReader(body)) + c.Request.Header.Set("Content-Type", "application/json") + svc := &OpenAIGatewayService{ + httpUpstream: &httpUpstreamRecorder{resp: bufferedHostedItemsSSEResponse(upstreamSSE)}, + cfg: rawChatCompletionsTestConfig(), + } + account := bufferedHostedItemsOAuthAccount() + var err error + if path == "/v1/chat/completions" { + _, err = svc.ForwardAsChatCompletions(context.Background(), c, account, body, "", "") + } else { + _, err = svc.ForwardAsAnthropic(context.Background(), c, account, body, "", "") + } + require.NoError(t, err) + require.Equal(t, http.StatusOK, rec.Code, rec.Body.String()) + return rec.Body.String() +} + +func TestForwardAsAnthropic_CodexOAuthNonStreamingKeepsHostedOutputItems(t *testing.T) { + out := forwardBufferedHostedItems(t, "/v1/messages", bufferedHostedItemsMessagesBody, bufferedHostedItemsSSE) + + content := gjson.Get(out, "content").Array() + require.Len(t, content, 3, out) + require.Equal(t, "server_tool_use", content[0].Get("type").String()) + require.Equal(t, "web_search", content[0].Get("name").String()) + require.Equal(t, "q", content[0].Get("input.query").String()) + require.Equal(t, "web_search_tool_result", content[1].Get("type").String()) + require.Equal(t, content[0].Get("id").String(), content[1].Get("tool_use_id").String()) + require.Equal(t, "text", content[2].Get("type").String()) + require.Equal(t, "found it", content[2].Get("text").String()) +} + +func TestForwardAsAnthropic_BufferedHostedItemsFollowReasoning(t *testing.T) { + sse := bufferedItemsSSE( + bufferedHostedItemsCreated, + `{"type":"response.reasoning_summary_text.delta","output_index":0,"summary_index":0,"delta":"plan"}`, + `{"type":"response.output_item.done","output_index":0,"item":{"type":"reasoning","id":"rs_1","summary":[]}}`, + `{"type":"response.output_item.done","output_index":1,"item":{"type":"web_search_call","id":"ws_1","status":"completed","action":{"type":"search","query":"q"}}}`, + `{"type":"response.output_text.delta","output_index":2,"delta":"found it"}`, + bufferedHostedItemsCompleted, + ) + out := forwardBufferedHostedItems(t, "/v1/messages", bufferedHostedItemsThinkingBody, sse) + + var types []string + for _, block := range gjson.Get(out, "content").Array() { + types = append(types, block.Get("type").String()) + } + require.Equal(t, []string{"thinking", "server_tool_use", "web_search_tool_result", "text"}, types, out) +} + +func TestReadOpenAICompatBufferedTerminal_EmptyTerminalOutputGainsHostedItems(t *testing.T) { + gin.SetMode(gin.TestMode) + c, _ := gin.CreateTestContext(httptest.NewRecorder()) + c.Request = httptest.NewRequest(http.MethodPost, "/v1/chat/completions", nil) + account := &Account{ID: 1, Platform: PlatformOpenAI, Type: AccountTypeOAuth, Concurrency: 1} + + response, _, acc, _, err := (&OpenAIGatewayService{}).readOpenAICompatBufferedTerminal( + bufferedHostedItemsSSEResponse(bufferedHostedItemsSSE), c, account, "openai chat buffered", "req-1") + require.NoError(t, err) + require.NotNil(t, response) + + var types []string + for _, item := range response.Output { + types = append(types, item.Type) + } + require.Equal(t, []string{"web_search_call", "image_generation_call", "message"}, types) + + // The handler supplements the output afterwards; the text must not be added twice. + acc.SupplementResponseOutput(response) + require.Len(t, response.Output, 3) +} + +func TestReadOpenAICompatBufferedTerminal_HostedItemsWithoutOutputIndexKeepArrivalOrder(t *testing.T) { + gin.SetMode(gin.TestMode) + c, _ := gin.CreateTestContext(httptest.NewRecorder()) + c.Request = httptest.NewRequest(http.MethodPost, "/v1/chat/completions", nil) + account := &Account{ID: 1, Platform: PlatformOpenAI, Type: AccountTypeOAuth, Concurrency: 1} + sse := bufferedItemsSSE( + bufferedHostedItemsCreated, + `{"type":"response.output_item.done","item":{"type":"web_search_call","id":"ws_1","status":"completed"}}`, + `{"type":"response.output_item.done","item":{"type":"image_generation_call","id":"ig_1","status":"completed"}}`, + bufferedHostedItemsCompleted, + ) + + response, _, _, _, err := (&OpenAIGatewayService{}).readOpenAICompatBufferedTerminal( + bufferedHostedItemsSSEResponse(sse), c, account, "openai chat buffered", "req-1") + require.NoError(t, err) + + var ids []string + for _, item := range response.Output { + ids = append(ids, item.ID) + } + require.Equal(t, []string{"ws_1", "ig_1"}, ids) +} + +// With an empty terminal output the accumulator keeps building reasoning, text +// and function calls from deltas. Only the types it does not know are added. +func TestBufferedCompat_EmptyTerminalOutputKeepsAccumulatedItems(t *testing.T) { + fnTool := `"tools":[{"type":"function","function":{"name":"get","parameters":{"type":"object"}}}]` + customTool := `"tools":[{"type":"custom","custom":{"name":"exec","description":"run"}}]` + chatBody := func(extra string) string { + return `{"model":"gpt-5.5","stream":false,` + extra + `,"messages":[{"role":"user","content":"hi"}]}` + } + toolMessagesBody := `{"model":"gpt-5.5","max_tokens":64,"stream":false,"tools":[{"name":"get","input_schema":{"type":"object"}}],"messages":[{"role":"user","content":"hi"}]}` + + // The reasoning done item has an empty summary; its text only streamed as deltas. + reasoningSSE := bufferedItemsSSE( + bufferedHostedItemsCreated, + `{"type":"response.output_item.added","output_index":0,"item":{"type":"reasoning","id":"rs_1","summary":[]}}`, + `{"type":"response.reasoning_summary_text.delta","output_index":0,"summary_index":0,"delta":"thinking hard"}`, + `{"type":"response.output_item.done","output_index":0,"item":{"type":"reasoning","id":"rs_1","summary":[]}}`, + `{"type":"response.output_text.delta","output_index":1,"delta":"answer"}`, + `{"type":"response.output_item.done","output_index":1,"item":{"type":"message","id":"msg_1","role":"assistant","status":"completed","content":[{"type":"output_text","text":"answer"}]}}`, + bufferedHostedItemsCompleted, + ) + // Item events without output_index, two calls. + noIndexSSE := bufferedItemsSSE( + bufferedHostedItemsCreated, + `{"type":"response.output_item.added","item":{"type":"function_call","id":"fc_1","call_id":"call_1","name":"get","arguments":""}}`, + `{"type":"response.function_call_arguments.delta","item_id":"fc_1","delta":"{\"a\":1}"}`, + `{"type":"response.output_item.done","item":{"type":"function_call","id":"fc_1","call_id":"call_1","name":"get","arguments":"{\"a\":1}","status":"completed"}}`, + `{"type":"response.output_item.added","item":{"type":"function_call","id":"fc_2","call_id":"call_2","name":"get","arguments":""}}`, + `{"type":"response.function_call_arguments.delta","item_id":"fc_2","delta":"{\"b\":2}"}`, + `{"type":"response.output_item.done","item":{"type":"function_call","id":"fc_2","call_id":"call_2","name":"get","arguments":"{\"b\":2}","status":"completed"}}`, + bufferedHostedItemsCompleted, + ) + customSSE := bufferedItemsSSE( + bufferedHostedItemsCreated, + `{"type":"response.output_item.added","output_index":0,"item":{"type":"custom_tool_call","id":"ctc_1","call_id":"call_1","name":"exec","input":""}}`, + `{"type":"response.custom_tool_call_input.delta","output_index":0,"item_id":"ctc_1","delta":"dir"}`, + `{"type":"response.custom_tool_call_input.done","output_index":0,"item_id":"ctc_1","input":"dir"}`, + `{"type":"response.output_item.done","output_index":0,"item":{"type":"custom_tool_call","id":"ctc_1","call_id":"call_1","name":"exec","input":"dir","status":"completed"}}`, + bufferedHostedItemsCompleted, + ) + + t.Run("reasoning text from deltas, chat", func(t *testing.T) { + out := forwardBufferedHostedItems(t, "/v1/chat/completions", chatBody(`"reasoning_effort":"high"`), reasoningSSE) + require.Equal(t, "thinking hard", gjson.Get(out, "choices.0.message.reasoning_content").String(), out) + require.Equal(t, "answer", gjson.Get(out, "choices.0.message.content").String(), out) + }) + t.Run("reasoning text from deltas, messages", func(t *testing.T) { + out := forwardBufferedHostedItems(t, "/v1/messages", bufferedHostedItemsThinkingBody, reasoningSSE) + require.Equal(t, "thinking", gjson.Get(out, "content.0.type").String(), out) + require.Equal(t, "thinking hard", gjson.Get(out, "content.0.thinking").String(), out) + require.Equal(t, "answer", gjson.Get(out, "content.1.text").String(), out) + }) + t.Run("two function calls without output_index, chat", func(t *testing.T) { + out := forwardBufferedHostedItems(t, "/v1/chat/completions", chatBody(fnTool), noIndexSSE) + calls := gjson.Get(out, "choices.0.message.tool_calls").Array() + require.Len(t, calls, 2, out) + require.Equal(t, "call_1", calls[0].Get("id").String()) + require.Equal(t, "call_2", calls[1].Get("id").String()) + }) + t.Run("two function calls without output_index, messages", func(t *testing.T) { + out := forwardBufferedHostedItems(t, "/v1/messages", toolMessagesBody, noIndexSSE) + content := gjson.Get(out, "content").Array() + require.Len(t, content, 2, out) + require.Equal(t, "call_1", content[0].Get("id").String()) + require.Equal(t, "call_2", content[1].Get("id").String()) + }) + t.Run("custom tool call, chat", func(t *testing.T) { + out := forwardBufferedHostedItems(t, "/v1/chat/completions", chatBody(customTool), customSSE) + calls := gjson.Get(out, "choices.0.message.tool_calls").Array() + require.Len(t, calls, 1, out) + require.Equal(t, "exec", calls[0].Get("function.name").String()) + require.Equal(t, "dir", calls[0].Get("function.arguments").String()) + }) +} + +// Native search calls are billed from the terminal Responses body, so an empty +// terminal output that is rebuilt with hosted items must count them, and a +// terminal output that already has items must keep the count it reports. +func TestBufferedCompat_GrokSearchCountFromRebuiltHostedItems(t *testing.T) { + const searchDone = `{"type":"response.output_item.done","output_index":0,"item":{"type":"web_search_call","id":"ws_1","status":"completed","action":{"type":"search","query":"q"}}}` + const xSearchDone = `{"type":"response.output_item.done","output_index":1,"item":{"type":"x_search_call","id":"xs_1","status":"completed"}}` + const messageDone = `{"type":"response.output_item.done","output_index":2,"item":{"type":"message","id":"msg_1","role":"assistant","status":"completed","content":[{"type":"output_text","text":"found it"}]}}` + const usage = `"usage":{"input_tokens":5,"output_tokens":2,"total_tokens":7}` + completed := func(output string) string { + return `{"type":"response.completed","response":{"id":"resp_1","status":"completed","output":` + output + `,` + usage + `}}` + } + stream := func(terminalOutput string) string { + return bufferedItemsSSE(bufferedHostedItemsCreated, searchDone, xSearchDone, bufferedHostedItemsTextDelta, messageDone, completed(terminalOutput)) + } + + cases := []struct { + name string + terminalOutput string + wantSearches int + }{ + {"empty terminal output", `[]`, 2}, + {"terminal output with the search items", `[{"type":"web_search_call","id":"ws_1","status":"completed"},{"type":"x_search_call","id":"xs_1","status":"completed"},{"type":"message","id":"msg_1","role":"assistant","status":"completed","content":[{"type":"output_text","text":"found it"}]}]`, 2}, + {"terminal output without search items", `[{"type":"message","id":"msg_1","role":"assistant","status":"completed","content":[{"type":"output_text","text":"found it"}]}]`, 0}, + } + for _, tc := range cases { + for _, path := range []string{"/v1/messages", "/v1/chat/completions"} { + t.Run(tc.name+" "+path, func(t *testing.T) { + gin.SetMode(gin.TestMode) + rec := httptest.NewRecorder() + c, _ := gin.CreateTestContext(rec) + body := []byte(`{"model":"grok-4.7","stream":false,"messages":[{"role":"user","content":"hi"}]}`) + c.Request = httptest.NewRequest(http.MethodPost, path, bytes.NewReader(body)) + c.Request.Header.Set("Content-Type", "application/json") + c.Set("api_key", &APIKey{ID: 88000, AllowLongContext: true}) + account := healthyGrokOAuthGatewayTestAccount(4242, "access-token") + svc := grokAuditOAuthService(&httpUpstreamRecorder{resp: bufferedHostedItemsSSEResponse(stream(tc.terminalOutput))}, account) + + var result *OpenAIForwardResult + var err error + if path == "/v1/chat/completions" { + result, err = svc.ForwardAsChatCompletions(context.Background(), c, account, body, "", "") + } else { + result, err = svc.ForwardAsAnthropic(context.Background(), c, account, body, "", "") + } + require.NoError(t, err) + require.Equal(t, http.StatusOK, rec.Code, rec.Body.String()) + require.NotNil(t, result) + require.Equal(t, tc.wantSearches, result.SearchCount) + }) + } + } +} + +// The output of a failed terminal only feeds the error payload, so hosted items +// reported before the failure must not change the payload recorded for ops. +func TestBufferedCompat_FailedTerminalKeepsErrorPayload(t *testing.T) { + const failed = `{"type":"response.failed","response":{"id":"resp_err","object":"response","status":"failed","error":{"type":"rate_limit_error","message":"Rate limit reached"},"output":[],"usage":{"input_tokens":10,"output_tokens":0,"total_tokens":10}}}` + plain := bufferedItemsSSE(bufferedHostedItemsCreated, failed) + withHosted := bufferedItemsSSE(bufferedHostedItemsCreated, bufferedHostedItemsWebSearchDone, bufferedHostedItemsImageDone, failed) + + recordedPayload := func(t *testing.T, path, requestBody, sse string) string { + t.Helper() + gin.SetMode(gin.TestMode) + c, _ := gin.CreateTestContext(httptest.NewRecorder()) + body := []byte(requestBody) + c.Request = httptest.NewRequest(http.MethodPost, path, bytes.NewReader(body)) + c.Request.Header.Set("Content-Type", "application/json") + cfg := rawChatCompletionsTestConfig() + cfg.Gateway.LogUpstreamErrorBody = true + cfg.Gateway.LogUpstreamErrorBodyMaxBytes = 4096 + svc := &OpenAIGatewayService{ + httpUpstream: &httpUpstreamRecorder{resp: bufferedHostedItemsSSEResponse(sse)}, + cfg: cfg, + } + account := bufferedHostedItemsOAuthAccount() + var err error + if path == "/v1/chat/completions" { + _, err = svc.ForwardAsChatCompletions(context.Background(), c, account, body, "", "") + } else { + _, err = svc.ForwardAsAnthropic(context.Background(), c, account, body, "", "") + } + var failoverErr *UpstreamFailoverError + require.ErrorAs(t, err, &failoverErr) + events, _ := c.Get(OpsUpstreamErrorsKey) + recorded, _ := events.([]*OpsUpstreamErrorEvent) + require.NotEmpty(t, recorded) + return recorded[0].Detail + } + + for path, requestBody := range map[string]string{ + "/v1/messages": bufferedHostedItemsMessagesBody, + "/v1/chat/completions": bufferedHostedItemsChatBody, + } { + t.Run(path, func(t *testing.T) { + want := recordedPayload(t, path, requestBody, plain) + require.Contains(t, want, `"output":[]`) + require.Equal(t, want, recordedPayload(t, path, requestBody, withHosted)) + }) + } +} + +func readBufferedOutputItems(t *testing.T, sse string) []string { + t.Helper() + gin.SetMode(gin.TestMode) + c, _ := gin.CreateTestContext(httptest.NewRecorder()) + c.Request = httptest.NewRequest(http.MethodPost, "/v1/chat/completions", nil) + account := &Account{ID: 1, Platform: PlatformOpenAI, Type: AccountTypeOAuth, Concurrency: 1} + response, _, _, _, err := (&OpenAIGatewayService{}).readOpenAICompatBufferedTerminal( + bufferedHostedItemsSSEResponse(sse), c, account, "openai chat buffered", "req-1") + require.NoError(t, err) + require.NotNil(t, response) + var items []string + for _, item := range response.Output { + items = append(items, item.Type+":"+item.ID+":"+item.Arguments+":"+item.Input) + } + return items +} + +// Items that share an output_index stay apart; the same item reported again +// replaces its earlier copy; equal indexes keep arrival order. +func TestReadOpenAICompatBufferedTerminal_DoneItemsMergeByItemID(t *testing.T) { + done := func(index int, id string) string { + return `{"type":"response.output_item.done","output_index":` + strconv.Itoa(index) + `,"item":{"type":"web_search_call","id":"` + id + `","status":"completed"}}` + } + items := readBufferedOutputItems(t, bufferedItemsSSE( + bufferedHostedItemsCreated, + done(0, "ws_a"), done(0, "ws_b"), done(1, "ws_c"), done(0, "ws_a"), + bufferedHostedItemsCompleted, + )) + require.Equal(t, []string{"web_search_call:ws_a::", "web_search_call:ws_b::", "web_search_call:ws_c::"}, items) +} + +// The done item is the upstream's final form of an item; deltas only complete a +// text, refusal or arguments field that the done item left empty, and rebuild an +// item that never got a done event. +func TestReadOpenAICompatBufferedTerminal_DoneItemsWinOverDeltas(t *testing.T) { + items := readBufferedOutputItems(t, bufferedItemsSSE( + bufferedHostedItemsCreated, + `{"type":"response.output_item.added","output_index":0,"item":{"type":"function_call","id":"fc_1","call_id":"call_1","name":"get","arguments":""}}`, + `{"type":"response.function_call_arguments.delta","output_index":0,"delta":"{\"stale\":1}"}`, + `{"type":"response.function_call_arguments.done","output_index":0,"arguments":"{\"a\":1}"}`, + `{"type":"response.output_item.done","output_index":0,"item":{"type":"function_call","id":"fc_1","call_id":"call_1","name":"get","arguments":""}}`, + `{"type":"response.output_item.added","output_index":1,"item":{"type":"function_call","id":"fc_2","call_id":"call_2","name":"get","arguments":""}}`, + `{"type":"response.function_call_arguments.delta","output_index":1,"delta":"{\"b\":2}"}`, + `{"type":"response.output_item.done","output_index":2,"item":{"type":"function_call","id":"fc_3","call_id":"call_3","name":"get","arguments":"{\"c\":3}"}}`, + bufferedHostedItemsCompleted, + )) + require.Equal(t, []string{ + `function_call:fc_1:{"a":1}:`, + `function_call:fc_2:{"b":2}:`, + `function_call:fc_3:{"c":3}:`, + }, items) +} + +func TestForwardAsAnthropic_CancelledTerminalKeepsHostedOutputItems(t *testing.T) { + cancelled := `{"type":"response.cancelled","response":{"id":"resp_1","status":"cancelled","output":[],"usage":{"input_tokens":5,"output_tokens":2,"total_tokens":7}}}` + out := forwardBufferedHostedItems(t, "/v1/messages", bufferedHostedItemsMessagesBody, + bufferedItemsSSE(bufferedHostedItemsCreated, bufferedHostedItemsWebSearchDone, cancelled)) + require.Equal(t, "server_tool_use", gjson.Get(out, "content.0.type").String(), out) +} + +// A tool call whose arguments are not a JSON object must not empty the response: +// a truncated function call gets {}, a custom tool call its input wrapped. +func TestForwardAsAnthropic_BufferedNonObjectToolInput(t *testing.T) { + toolBody := `{"model":"gpt-5.5","max_tokens":64,"stream":false,"tools":[{"name":"get","input_schema":{"type":"object"}}],"messages":[{"role":"user","content":"hi"}]}` + truncated := bufferedItemsSSE( + bufferedHostedItemsCreated, + `{"type":"response.output_item.done","output_index":0,"item":{"type":"reasoning","id":"rs_1","summary":[{"type":"summary_text","text":"plan"}]}}`, + `{"type":"response.output_item.added","output_index":1,"item":{"type":"function_call","id":"fc_1","call_id":"call_1","name":"get","arguments":""}}`, + `{"type":"response.function_call_arguments.delta","output_index":1,"delta":"{\"a\":1"}`, + `{"type":"response.incomplete","response":{"id":"resp_1","status":"incomplete","incomplete_details":{"reason":"max_output_tokens"},"output":[]}}`, + ) + out := forwardBufferedHostedItems(t, "/v1/messages", toolBody, truncated) + require.Equal(t, "thinking", gjson.Get(out, "content.0.type").String(), out) + require.Equal(t, "plan", gjson.Get(out, "content.0.thinking").String(), out) + require.Equal(t, "tool_use", gjson.Get(out, "content.1.type").String(), out) + require.Equal(t, "{}", gjson.Get(out, "content.1.input").Raw, out) + require.Equal(t, "max_tokens", gjson.Get(out, "stop_reason").String(), out) + + custom := bufferedItemsSSE( + bufferedHostedItemsCreated, + `{"type":"response.output_item.added","output_index":0,"item":{"type":"custom_tool_call","id":"ctc_1","call_id":"call_1","name":"get","input":""}}`, + `{"type":"response.custom_tool_call_input.delta","output_index":0,"delta":"dir"}`, + `{"type":"response.output_item.done","output_index":0,"item":{"type":"custom_tool_call","id":"ctc_1","call_id":"call_1","name":"get","input":"dir"}}`, + bufferedHostedItemsCompleted, + ) + out = forwardBufferedHostedItems(t, "/v1/messages", toolBody, custom) + require.Equal(t, "tool_use", gjson.Get(out, "content.0.type").String(), out) + require.Equal(t, `{"input":"dir"}`, gjson.Get(out, "content.0.input").Raw, out) + require.Equal(t, "tool_use", gjson.Get(out, "stop_reason").String(), out) +} + +// A reasoning item with a summary and raw reasoning_text content: the converters render one of the two, +// so the deltas that carried both supply the text, as the streaming path shows it. +func TestForwardAsAnthropic_BufferedReasoningSummaryAndContentKeepBoth(t *testing.T) { + sse := bufferedItemsSSE( + bufferedHostedItemsCreated, + `{"type":"response.reasoning_text.delta","output_index":0,"content_index":0,"delta":"raw thoughts"}`, + `{"type":"response.reasoning_summary_text.delta","output_index":0,"summary_index":0,"delta":"summary"}`, + `{"type":"response.output_item.done","output_index":0,"item":{"type":"reasoning","id":"rs_1","summary":[{"type":"summary_text","text":"summary"}],"content":[{"type":"reasoning_text","text":"raw thoughts"}]}}`, + bufferedHostedItemsCompleted, + ) + out := forwardBufferedHostedItems(t, "/v1/messages", bufferedHostedItemsThinkingBody, sse) + require.Equal(t, "raw thoughtssummary", gjson.Get(out, "content.0.thinking").String(), out) +} + +// bufferedPartsEntries are the two buffered entries, each with the request that +// makes it show the field under test. +var bufferedPartsEntries = []struct{ name, path, body string }{ + {"messages", "/v1/messages", bufferedHostedItemsThinkingBody}, + {"chat", "/v1/chat/completions", `{"model":"gpt-5.5","stream":false,"reasoning_effort":"high","messages":[{"role":"user","content":"search the web"}]}`}, +} + +// bufferedPartsVisible is the text of one kind ("text", "thinking" or "refusal") +// the client is shown: the text or thinking blocks joined for /v1/messages, the +// content, reasoning_content or refusal of the message for /v1/chat/completions. +func bufferedPartsVisible(out, path, kind string) string { + if path == "/v1/chat/completions" { + return gjson.Get(out, "choices.0.message."+map[string]string{"text": "content", "thinking": "reasoning_content", "refusal": "refusal"}[kind]).String() + } + var text strings.Builder + for _, block := range gjson.Get(out, "content").Array() { + if block.Get("type").String() == kind { + text.WriteString(block.Get(kind).String()) + } + } + return text.String() +} + +// One item with several parts whose done item leaves only some of them empty, and +// an empty terminal output: a part is completed with the deltas of its own part +// index, a part that has text and the order of the parts stay as the done item +// has them. +func TestBufferedCompat_PartialTextParts(t *testing.T) { + text := func(s string) string { return `{"type":"output_text","text":"` + s + `"}` } + cases := []struct { + name, parts, want string + deltas []string + }{ + {"first empty", "[" + text("") + "," + text("second") + "]", "first second", []string{"first ", "second"}}, + {"second empty", "[" + text("first ") + "," + text("") + "]", "first second", []string{"first ", "second"}}, + {"both empty", "[" + text("") + "," + text("") + "]", "first second", []string{"first ", "second"}}, + {"both with text, the done item wins", "[" + text("one ") + "," + text("two") + "]", "one two", []string{"first ", "second"}}, + {"middle with text of three", "[" + text("") + "," + text("b ") + "," + text("") + "]", "a b c", []string{"a ", "b ", "c"}}, + } + for _, entry := range bufferedPartsEntries { + for _, tc := range cases { + t.Run(entry.name+" "+tc.name, func(t *testing.T) { + events := []string{ + bufferedHostedItemsCreated, + `{"type":"response.output_item.added","output_index":0,"item":{"type":"message","id":"msg_1","role":"assistant","content":[]}}`, + } + for index, delta := range tc.deltas { + events = append(events, `{"type":"response.output_text.delta","output_index":0,"content_index":`+strconv.Itoa(index)+`,"delta":"`+delta+`"}`) + } + events = append(events, + `{"type":"response.output_item.done","output_index":0,"item":{"type":"message","id":"msg_1","role":"assistant","content":`+tc.parts+`}}`, + bufferedHostedItemsCompleted) + sse := bufferedItemsSSE(events...) + out := forwardBufferedHostedItems(t, entry.path, entry.body, sse) + require.Equal(t, tc.want, bufferedPartsVisible(out, entry.path, "text"), out) + }) + } + } +} + +// The same for the refusal parts of a message, which only /v1/chat/completions renders. +func TestBufferedCompat_PartialRefusalParts(t *testing.T) { + refusal := func(s string) string { return `{"type":"refusal","refusal":"` + s + `"}` } + cases := []struct{ name, parts, want string }{ + {"first empty", "[" + refusal("") + "," + refusal("second") + "]", "first second"}, + {"second empty", "[" + refusal("first ") + "," + refusal("") + "]", "first second"}, + {"both empty", "[" + refusal("") + "," + refusal("") + "]", "first second"}, + {"both with text, the done item wins", "[" + refusal("one ") + "," + refusal("two") + "]", "one two"}, + } + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + sse := bufferedItemsSSE( + bufferedHostedItemsCreated, + `{"type":"response.refusal.delta","output_index":0,"content_index":0,"delta":"first "}`, + `{"type":"response.refusal.delta","output_index":0,"content_index":1,"delta":"second"}`, + `{"type":"response.output_item.done","output_index":0,"item":{"type":"message","id":"msg_1","role":"assistant","content":`+tc.parts+`}}`, + bufferedHostedItemsCompleted, + ) + out := forwardBufferedHostedItems(t, "/v1/chat/completions", bufferedHostedItemsChatBody, sse) + require.Equal(t, tc.want, bufferedPartsVisible(out, "/v1/chat/completions", "refusal"), out) + }) + } +} + +// A refusal part and a text part of one message keep their own deltas. +func TestBufferedCompat_RefusalAndTextPartsKeepTheirOwnDeltas(t *testing.T) { + sse := bufferedItemsSSE( + bufferedHostedItemsCreated, + `{"type":"response.output_text.delta","output_index":0,"content_index":0,"delta":"answer"}`, + `{"type":"response.refusal.delta","output_index":0,"content_index":1,"delta":"no"}`, + `{"type":"response.output_item.done","output_index":0,"item":{"type":"message","id":"msg_1","role":"assistant","content":[{"type":"output_text","text":""},{"type":"refusal","refusal":""}]}}`, + bufferedHostedItemsCompleted, + ) + out := forwardBufferedHostedItems(t, "/v1/chat/completions", bufferedHostedItemsChatBody, sse) + require.Equal(t, "answer", bufferedPartsVisible(out, "/v1/chat/completions", "text"), out) + require.Equal(t, "no", bufferedPartsVisible(out, "/v1/chat/completions", "refusal"), out) +} + +// Reasoning with several summary parts, or several reasoning_text parts, whose +// done item leaves only some of them empty. +func TestBufferedCompat_PartialReasoningParts(t *testing.T) { + summary := func(s string) string { return `{"type":"summary_text","text":"` + s + `"}` } + raw := func(s string) string { return `{"type":"reasoning_text","text":"` + s + `"}` } + summaryDeltas := []string{ + `{"type":"response.reasoning_summary_text.delta","output_index":0,"summary_index":0,"delta":"first "}`, + `{"type":"response.reasoning_summary_text.delta","output_index":0,"summary_index":1,"delta":"second"}`, + } + rawDeltas := []string{ + `{"type":"response.reasoning_text.delta","output_index":0,"content_index":0,"delta":"first "}`, + `{"type":"response.reasoning_text.delta","output_index":0,"content_index":1,"delta":"second"}`, + } + cases := []struct { + name string + deltas []string + summary, content string + want string + }{ + {"summary, first empty", summaryDeltas, "[" + summary("") + "," + summary("second") + "]", "[]", "first second"}, + {"summary, second empty", summaryDeltas, "[" + summary("first ") + "," + summary("") + "]", "[]", "first second"}, + {"summary, both empty", summaryDeltas, "[" + summary("") + "," + summary("") + "]", "[]", "first second"}, + {"summary, both with text, the done item wins", summaryDeltas, "[" + summary("one ") + "," + summary("two") + "]", "[]", "one two"}, + {"reasoning_text, first empty", rawDeltas, "[]", "[" + raw("") + "," + raw("second") + "]", "first second"}, + {"reasoning_text, second empty", rawDeltas, "[]", "[" + raw("first ") + "," + raw("") + "]", "first second"}, + {"reasoning_text, both empty", rawDeltas, "[]", "[" + raw("") + "," + raw("") + "]", "first second"}, + {"reasoning_text, both with text, the done item wins", rawDeltas, "[]", "[" + raw("one ") + "," + raw("two") + "]", "one two"}, + } + for _, entry := range bufferedPartsEntries { + for _, tc := range cases { + t.Run(entry.name+" "+tc.name, func(t *testing.T) { + events := append([]string{bufferedHostedItemsCreated}, tc.deltas...) + events = append(events, + `{"type":"response.output_item.done","output_index":0,"item":{"type":"reasoning","id":"rs_1","summary":`+tc.summary+`,"content":`+tc.content+`}}`, + bufferedHostedItemsCompleted) + out := forwardBufferedHostedItems(t, entry.path, entry.body, bufferedItemsSSE(events...)) + require.Equal(t, tc.want, bufferedPartsVisible(out, entry.path, "thinking"), out) + }) + } + } +} + +// The streaming converters render a web search once it is completed, so a +// rebuilt output does the same. +func TestBufferedCompat_WebSearchNotCompletedIsNotRebuilt(t *testing.T) { + for _, tc := range []struct { + status string + want []string + }{ + {"completed", []string{"server_tool_use", "web_search_tool_result"}}, + {"in_progress", []string{"text"}}, + } { + t.Run(tc.status, func(t *testing.T) { + sse := bufferedItemsSSE( + bufferedHostedItemsCreated, + `{"type":"response.output_item.done","output_index":0,"item":{"type":"web_search_call","id":"ws_1","status":"`+tc.status+`","action":{"type":"search","query":"q"}}}`, + bufferedHostedItemsCompleted, + ) + out := forwardBufferedHostedItems(t, "/v1/messages", bufferedHostedItemsMessagesBody, sse) + var types []string + for _, block := range gjson.Get(out, "content").Array() { + types = append(types, block.Get("type").String()) + } + require.Equal(t, tc.want, types, out) + }) + } +} + +// A custom tool call without input is {} as in the streamed tool_use. +func TestBufferedCompat_EmptyCustomToolInputIsAnEmptyObject(t *testing.T) { + sse := bufferedItemsSSE( + bufferedHostedItemsCreated, + `{"type":"response.output_item.added","output_index":0,"item":{"type":"custom_tool_call","id":"ctc_1","call_id":"call_1","name":"exec","input":""}}`, + `{"type":"response.output_item.done","output_index":0,"item":{"type":"custom_tool_call","id":"ctc_1","call_id":"call_1","name":"exec","input":""}}`, + bufferedHostedItemsCompleted, + ) + toolBody := `{"model":"gpt-5.5","max_tokens":64,"stream":false,"tools":[{"name":"exec","input_schema":{"type":"object"}}],"messages":[{"role":"user","content":"hi"}]}` + out := forwardBufferedHostedItems(t, "/v1/messages", toolBody, sse) + require.Equal(t, "tool_use", gjson.Get(out, "content.0.type").String(), out) + require.Equal(t, "{}", gjson.Get(out, "content.0.input").Raw, out) +} + +// Deltas without an output_index belong to their item, found by item_id or as the +// newest open item of their kind, not to a second copy of it. +func TestBufferedCompat_DeltasWithoutOutputIndexJoinTheirItem(t *testing.T) { + customBody := `{"model":"gpt-5.5","stream":false,"tools":[{"type":"custom","custom":{"name":"exec","description":"run"}}],"messages":[{"role":"user","content":"hi"}]}` + cases := []struct { + name, shown string + sse string + }{ + {"item_id, no added event", "text", bufferedItemsSSE(bufferedHostedItemsCreated, + `{"type":"response.output_text.delta","item_id":"msg_1","content_index":0,"delta":"hello"}`, + `{"type":"response.output_item.done","output_index":0,"item":{"type":"message","id":"msg_1","role":"assistant","content":[{"type":"output_text","text":"hello"}]}}`, + bufferedHostedItemsCompleted)}, + {"item_id, after added", "thinking", bufferedItemsSSE(bufferedHostedItemsCreated, + `{"type":"response.output_item.added","output_index":0,"item":{"type":"reasoning","id":"rs_1","summary":[]}}`, + `{"type":"response.reasoning_text.delta","item_id":"rs_1","content_index":0,"delta":"hello"}`, + `{"type":"response.output_item.done","output_index":0,"item":{"type":"reasoning","id":"rs_1","summary":[],"content":[{"type":"reasoning_text","text":"hello"}]}}`, + bufferedHostedItemsCompleted)}, + {"no item_id, after added", "text", bufferedItemsSSE(bufferedHostedItemsCreated, + `{"type":"response.output_item.added","output_index":1,"item":{"type":"message","role":"assistant","content":[]}}`, + `{"type":"response.output_text.delta","content_index":0,"delta":"hello"}`, + `{"type":"response.output_item.done","output_index":1,"item":{"type":"message","role":"assistant","content":[{"type":"output_text","text":"hello"}]}}`, + bufferedHostedItemsCompleted)}, + } + for _, entry := range bufferedPartsEntries { + for _, tc := range cases { + t.Run(entry.name+" "+tc.name, func(t *testing.T) { + out := forwardBufferedHostedItems(t, entry.path, entry.body, tc.sse) + require.Equal(t, "hello", bufferedPartsVisible(out, entry.path, tc.shown), out) + }) + } + } + t.Run("custom tool call input", func(t *testing.T) { + sse := bufferedItemsSSE(bufferedHostedItemsCreated, + `{"type":"response.output_item.added","output_index":1,"item":{"type":"reasoning","summary":[]}}`, + `{"type":"response.reasoning_summary_text.delta","summary_index":0,"delta":"plan"}`, + `{"type":"response.output_item.added","output_index":0,"item":{"type":"custom_tool_call","call_id":"call_1","name":"exec","input":""}}`, + `{"type":"response.custom_tool_call_input.delta","delta":"dir"}`, + `{"type":"response.custom_tool_call_input.done"}`, + `{"type":"response.output_item.done","output_index":0,"item":{"type":"custom_tool_call","call_id":"call_1","name":"exec","input":""}}`, + bufferedHostedItemsCompleted) + out := forwardBufferedHostedItems(t, "/v1/chat/completions", customBody, sse) + require.Equal(t, "dir", gjson.Get(out, "choices.0.message.tool_calls.0.function.arguments").String(), out) + require.Equal(t, "plan", gjson.Get(out, "choices.0.message.reasoning_content").String(), out) + }) +} + +// Items that share an output_index, or have none, and lack an added or a done +// event keep their own deltas. +func TestBufferedCompat_ItemsOfOneOutputIndexKeepTheirOwnEvents(t *testing.T) { + fnBody := `{"model":"gpt-5.5","stream":false,"tools":[{"type":"function","function":{"name":"get","parameters":{"type":"object"}}}],"messages":[{"role":"user","content":"hi"}]}` + t.Run("reasoning deltas, then a message added at the same index", func(t *testing.T) { + sse := bufferedItemsSSE(bufferedHostedItemsCreated, + `{"type":"response.reasoning_summary_text.delta","output_index":0,"summary_index":0,"delta":"plan"}`, + `{"type":"response.output_item.added","output_index":0,"item":{"type":"message","id":"msg_1","role":"assistant","content":[]}}`, + `{"type":"response.output_text.delta","output_index":0,"content_index":0,"item_id":"msg_1","delta":"answer"}`, + `{"type":"response.output_item.done","output_index":0,"item":{"type":"message","id":"msg_1","role":"assistant","content":[{"type":"output_text","text":"answer"}]}}`, + bufferedHostedItemsCompleted) + for _, entry := range bufferedPartsEntries { + out := forwardBufferedHostedItems(t, entry.path, entry.body, sse) + require.Equal(t, "plan", bufferedPartsVisible(out, entry.path, "thinking"), out) + require.Equal(t, "answer", bufferedPartsVisible(out, entry.path, "text"), out) + } + }) + t.Run("a message done, then another message added at the same index", func(t *testing.T) { + sse := bufferedItemsSSE(bufferedHostedItemsCreated, + `{"type":"response.output_text.delta","output_index":0,"content_index":0,"delta":"first "}`, + `{"type":"response.output_item.done","output_index":0,"item":{"type":"message","role":"assistant","content":[{"type":"output_text","text":""}]}}`, + `{"type":"response.output_item.added","output_index":0,"item":{"type":"message","role":"assistant","content":[]}}`, + `{"type":"response.output_text.delta","output_index":0,"content_index":0,"delta":"second"}`, + `{"type":"response.output_item.done","output_index":0,"item":{"type":"message","role":"assistant","content":[{"type":"output_text","text":"second"}]}}`, + bufferedHostedItemsCompleted) + for _, entry := range bufferedPartsEntries { + out := forwardBufferedHostedItems(t, entry.path, entry.body, sse) + require.Equal(t, "first second", bufferedPartsVisible(out, entry.path, "text"), out) + } + }) + t.Run("a hosted call added at the index of delta-only text", func(t *testing.T) { + sse := bufferedItemsSSE(bufferedHostedItemsCreated, + `{"type":"response.refusal.delta","output_index":0,"content_index":0,"delta":"no"}`, + `{"type":"response.output_item.added","output_index":0,"item":{"type":"web_search_call","status":"in_progress"}}`, + `{"type":"response.output_item.done","output_index":0,"item":{"type":"web_search_call","status":"completed"}}`, + bufferedHostedItemsCompleted) + out := forwardBufferedHostedItems(t, "/v1/chat/completions", bufferedHostedItemsChatBody, sse) + require.Equal(t, "no", bufferedPartsVisible(out, "/v1/chat/completions", "refusal"), out) + }) + t.Run("two function calls without index and id", func(t *testing.T) { + sse := bufferedItemsSSE(bufferedHostedItemsCreated, + `{"type":"response.output_item.added","item":{"type":"function_call","call_id":"call_a","name":"get","arguments":""}}`, + `{"type":"response.function_call_arguments.delta","delta":"{\"a\":1}"}`, + `{"type":"response.output_item.added","item":{"type":"function_call","call_id":"call_b","name":"get","arguments":""}}`, + `{"type":"response.function_call_arguments.delta","delta":"{\"b\":2}"}`, + `{"type":"response.output_item.done","item":{"type":"function_call","call_id":"call_b","name":"get","arguments":""}}`, + bufferedHostedItemsCompleted) + out := forwardBufferedHostedItems(t, "/v1/chat/completions", fnBody, sse) + calls := gjson.Get(out, "choices.0.message.tool_calls").Array() + require.Len(t, calls, 2, out) + require.Equal(t, "call_a", calls[0].Get("id").String()) + require.Equal(t, `{"a":1}`, calls[0].Get("function.arguments").String()) + require.Equal(t, "call_b", calls[1].Get("id").String()) + require.Equal(t, `{"b":2}`, calls[1].Get("function.arguments").String()) + }) +} + +// The signature of a reasoning item may be on its added event only; the item is +// kept for it even without text, as the streaming path keeps it. +func TestBufferedCompat_ReasoningSignatureOnAddedEventIsKept(t *testing.T) { + cases := []struct { + name, sse string + want []string + }{ + {"with text deltas and a done item without it", bufferedItemsSSE(bufferedHostedItemsCreated, + `{"type":"response.output_item.added","output_index":0,"item":{"type":"reasoning","id":"rs_1","summary":[],"encrypted_content":"ENC"}}`, + `{"type":"response.reasoning_summary_text.delta","output_index":0,"summary_index":0,"delta":"plan"}`, + `{"type":"response.output_item.done","output_index":0,"item":{"type":"reasoning","id":"rs_1","summary":[{"type":"summary_text","text":"plan"}]}}`, + bufferedHostedItemsCompleted), []string{`thinking "plan" ENC`}}, + {"added event only", bufferedItemsSSE(bufferedHostedItemsCreated, + `{"type":"response.output_item.added","output_index":0,"item":{"type":"reasoning","id":"rs_1","summary":[],"encrypted_content":"ENC"}}`, + bufferedHostedItemsCompleted), []string{`thinking "" ENC`}}, + } + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + out := forwardBufferedHostedItems(t, "/v1/messages", bufferedHostedItemsThinkingBody, tc.sse) + var got []string + for _, block := range gjson.Get(out, "content").Array() { + got = append(got, block.Get("type").String()+" "+strconv.Quote(block.Get("thinking").String())+" "+block.Get("signature").String()) + } + require.Equal(t, tc.want, got, out) + }) + } +} + +// Reasoning deltas that came with no output_index before the item was added belong +// to that item, so the text keeps its arrival order. +func TestBufferedCompat_UnindexedReasoningDeltasJoinTheItemAddedLater(t *testing.T) { + sse := bufferedItemsSSE(bufferedHostedItemsCreated, + `{"type":"response.reasoning_text.delta","content_index":0,"delta":"first "}`, + `{"type":"response.output_item.added","output_index":1,"item":{"type":"reasoning","summary":[]}}`, + `{"type":"response.reasoning_summary_text.delta","summary_index":0,"delta":"second"}`, + bufferedHostedItemsCompleted) + for _, entry := range bufferedPartsEntries { + out := forwardBufferedHostedItems(t, entry.path, entry.body, sse) + require.Equal(t, "first second", bufferedPartsVisible(out, entry.path, "thinking"), out) + } +} diff --git a/backend/internal/service/openai_gateway_buffered_server_side_search_test.go b/backend/internal/service/openai_gateway_buffered_server_side_search_test.go new file mode 100644 index 000000000000..99be34e3491d --- /dev/null +++ b/backend/internal/service/openai_gateway_buffered_server_side_search_test.go @@ -0,0 +1,65 @@ +//go:build unit + +package service + +import ( + "testing" + + "github.com/stretchr/testify/require" +) + +// A nonstreaming request rebuilds an empty terminal output from the output_item.done items and +// renders its custom_tool_call items as tool calls. On xAI an xs_ / as_ item is a search the +// server ran, so it is not a tool call but still counts as a Grok search. +func TestGrokBufferedRebuiltOutputKeepsServerSideSearchOutOfToolCalls(t *testing.T) { + account := healthyGrokOAuthGatewayTestAccount(4242, "access-token") + for _, path := range []string{"/v1/messages", "/v1/chat/completions"} { + t.Run(path+" search only", func(t *testing.T) { + sse := grokCustomToolCallStream([]string{grokXSearchItemJSON}, `[]`) + got := forwardGrokCustomToolCallStream(t, path, false, account, sse) + + require.Equal(t, 1, got.searchCount) + require.NotContains(t, got.body, "tool_use", got.body) + require.NotContains(t, got.body, "tool_calls", got.body) + require.NotContains(t, got.body, "x_keyword_search", got.body) + require.Contains(t, got.body, "found it", got.body) + if path == "/v1/messages" { + require.Contains(t, got.body, `"stop_reason":"end_turn"`, got.body) + } else { + require.Contains(t, got.body, `"finish_reason":"stop"`, got.body) + } + }) + t.Run(path+" search next to a client tool", func(t *testing.T) { + sse := grokCustomToolCallStream([]string{grokXSearchItemJSON, grokClientToolJSON}, `[]`) + got := forwardGrokCustomToolCallStream(t, path, false, account, sse) + + require.Equal(t, 1, got.searchCount) + require.NotContains(t, got.body, "x_keyword_search", got.body) + require.Contains(t, got.body, "exec", got.body) + if path == "/v1/messages" { + require.Contains(t, got.body, `"stop_reason":"tool_use"`, got.body) + } else { + require.Contains(t, got.body, `"finish_reason":"tool_calls"`, got.body) + } + }) + } +} + +// Off xAI the same call_id is an ordinary custom tool call and stays one. +func TestOpenAIBufferedRebuiltOutputKeepsXSCallIDAsToolCall(t *testing.T) { + account := rawChatCompletionsTestAccount() + for _, path := range []string{"/v1/messages", "/v1/chat/completions"} { + t.Run(path, func(t *testing.T) { + sse := grokCustomToolCallStream([]string{grokXSearchItemJSON}, `[]`) + got := forwardGrokCustomToolCallStream(t, path, false, account, sse) + + require.Equal(t, 0, got.searchCount) + require.Contains(t, got.body, "x_keyword_search", got.body) + if path == "/v1/messages" { + require.Contains(t, got.body, "tool_use", got.body) + } else { + require.Contains(t, got.body, "tool_calls", got.body) + } + }) + } +} diff --git a/backend/internal/service/openai_gateway_buffered_stream_parity_test.go b/backend/internal/service/openai_gateway_buffered_stream_parity_test.go new file mode 100644 index 000000000000..322798f09cad --- /dev/null +++ b/backend/internal/service/openai_gateway_buffered_stream_parity_test.go @@ -0,0 +1,437 @@ +//go:build unit + +package service + +import ( + "bytes" + "context" + "fmt" + "net/http" + "net/http/httptest" + "sort" + "strings" + "testing" + + "github.com/gin-gonic/gin" + "github.com/stretchr/testify/require" + "github.com/tidwall/gjson" +) + +const bufferedParityMessagesBody = `{"model":"gpt-5.5","max_tokens":4096,"stream":%t,"thinking":{"type":"enabled","budget_tokens":2048},"tools":[{"name":"record_version","input_schema":{"type":"object"}}],"messages":[{"role":"user","content":"USER_PROMPT_PLACEHOLDER"}]}` + +const bufferedParityChatBody = `{"model":"gpt-5.5","stream":%t,"reasoning_effort":"medium","tools":[{"type":"function","function":{"name":"record_version","parameters":{"type":"object"}}}],"messages":[{"role":"user","content":"USER_PROMPT_PLACEHOLDER"}]}` + +func bufferedParityReasoning(index int, id, text, encrypted string) []string { + summary := `[]` + if text != "" { + summary = fmt.Sprintf(`[{"type":"summary_text","text":%q}]`, text) + } + events := []string{ + fmt.Sprintf(`{"type":"response.output_item.added","output_index":%d,"item":{"type":"reasoning","id":%q,"summary":[]}}`, index, id), + } + if text != "" { + events = append(events, + fmt.Sprintf(`{"type":"response.reasoning_summary_part.added","output_index":%d,"summary_index":0,"part":{"type":"summary_text","text":""}}`, index), + fmt.Sprintf(`{"type":"response.reasoning_summary_text.delta","output_index":%d,"summary_index":0,"delta":%q}`, index, text), + fmt.Sprintf(`{"type":"response.reasoning_summary_text.done","output_index":%d,"summary_index":0,"text":%q}`, index, text), + ) + } + return append(events, fmt.Sprintf(`{"type":"response.output_item.done","output_index":%d,"item":{"type":"reasoning","id":%q,"summary":%s,"encrypted_content":%q}}`, index, id, summary, encrypted)) +} + +func bufferedParityWebSearch(index int, id, query string) []string { + return []string{ + fmt.Sprintf(`{"type":"response.output_item.added","output_index":%d,"item":{"type":"web_search_call","id":%q,"status":"in_progress"}}`, index, id), + fmt.Sprintf(`{"type":"response.web_search_call.in_progress","output_index":%d,"item_id":%q}`, index, id), + fmt.Sprintf(`{"type":"response.web_search_call.searching","output_index":%d,"item_id":%q}`, index, id), + fmt.Sprintf(`{"type":"response.web_search_call.completed","output_index":%d,"item_id":%q}`, index, id), + fmt.Sprintf(`{"type":"response.output_item.done","output_index":%d,"item":{"type":"web_search_call","id":%q,"status":"completed","action":{"type":"search","query":%q}}}`, index, id, query), + } +} + +func bufferedParityFunctionCall(index int) []string { + return []string{ + fmt.Sprintf(`{"type":"response.output_item.added","output_index":%d,"item":{"type":"function_call","id":"fc_1","call_id":"call_c","name":"record_version","arguments":""}}`, index), + fmt.Sprintf(`{"type":"response.function_call_arguments.delta","output_index":%d,"item_id":"fc_1","delta":"{\"version\""}`, index), + fmt.Sprintf(`{"type":"response.function_call_arguments.delta","output_index":%d,"item_id":"fc_1","delta":":\"1.25\"}"}`, index), + fmt.Sprintf(`{"type":"response.function_call_arguments.done","output_index":%d,"item_id":"fc_1","arguments":"{\"version\":\"1.25\"}"}`, index), + fmt.Sprintf(`{"type":"response.output_item.done","output_index":%d,"item":{"type":"function_call","id":"fc_1","call_id":"call_c","name":"record_version","arguments":"{\"version\":\"1.25\"}","status":"completed"}}`, index), + } +} + +func bufferedParityMessage(index int, text string) []string { + content := `[{"type":"output_text","text":""}]` + events := []string{ + fmt.Sprintf(`{"type":"response.output_item.added","output_index":%d,"item":{"type":"message","id":"msg_1","role":"assistant","status":"in_progress","phase":"final_answer","content":[]}}`, index), + fmt.Sprintf(`{"type":"response.content_part.added","output_index":%d,"content_index":0,"part":{"type":"output_text","text":""}}`, index), + } + if text != "" { + content = fmt.Sprintf(`[{"type":"output_text","text":%q}]`, text) + events = append(events, + fmt.Sprintf(`{"type":"response.output_text.delta","output_index":%d,"content_index":0,"delta":%q}`, index, text), + fmt.Sprintf(`{"type":"response.output_text.done","output_index":%d,"content_index":0,"text":%q}`, index, text), + ) + } + return append(events, + fmt.Sprintf(`{"type":"response.content_part.done","output_index":%d,"content_index":0,"part":{"type":"output_text","text":%q}}`, index, text), + fmt.Sprintf(`{"type":"response.output_item.done","output_index":%d,"item":{"type":"message","id":"msg_1","role":"assistant","status":"completed","phase":"final_answer","content":%s}}`, index, content), + ) +} + +func bufferedParityStream(terminalOutput string, groups ...[]string) string { + events := []string{bufferedHostedItemsCreated} + for _, group := range groups { + events = append(events, group...) + } + events = append(events, fmt.Sprintf(`{"type":"response.completed","response":{"id":"resp_1","status":"completed","output":%s,"usage":{"input_tokens":5,"output_tokens":2,"total_tokens":7}}}`, terminalOutput)) + return bufferedItemsSSE(events...) +} + +// bufferedParityBlocks reduces an Anthropic content array to one line per block. +func bufferedParityBlocks(blocks []gjson.Result) []string { + var lines []string + for _, block := range blocks { + switch block.Get("type").String() { + case "thinking": + lines = append(lines, fmt.Sprintf("thinking %q signature=%q", block.Get("thinking").String(), block.Get("signature").String())) + case "text": + lines = append(lines, fmt.Sprintf("text %q", block.Get("text").String())) + case "tool_use": + lines = append(lines, fmt.Sprintf("tool_use %s %s %s", block.Get("id").String(), block.Get("name").String(), block.Get("input").Raw)) + case "server_tool_use": + lines = append(lines, fmt.Sprintf("server_tool_use %s %s", block.Get("id").String(), block.Get("input").Raw)) + case "web_search_tool_result": + lines = append(lines, fmt.Sprintf("web_search_tool_result %s", block.Get("tool_use_id").String())) + default: + lines = append(lines, "other "+block.Get("type").String()) + } + } + return lines +} + +// bufferedParityStreamBlocks folds an Anthropic SSE body back into content blocks. +func bufferedParityStreamBlocks(t *testing.T, sse string) []string { + t.Helper() + type streamed struct { + kind, id, name, toolUseID, thinking, text, signature, input string + } + byIndex := map[int64]*streamed{} + for _, line := range strings.Split(sse, "\n") { + data, ok := strings.CutPrefix(line, "data: ") + if !ok || !gjson.Valid(data) { + continue + } + index := gjson.Get(data, "index").Int() + switch gjson.Get(data, "type").String() { + case "content_block_start": + block := gjson.Get(data, "content_block") + byIndex[index] = &streamed{ + kind: block.Get("type").String(), id: block.Get("id").String(), name: block.Get("name").String(), + toolUseID: block.Get("tool_use_id").String(), input: block.Get("input").Raw, + } + case "content_block_delta": + block := byIndex[index] + require.NotNil(t, block, data) + delta := gjson.Get(data, "delta") + switch delta.Get("type").String() { + case "thinking_delta": + block.thinking += delta.Get("thinking").String() + case "text_delta": + block.text += delta.Get("text").String() + case "signature_delta": + block.signature = delta.Get("signature").String() + case "input_json_delta": + if block.input == "{}" { + block.input = "" + } + block.input += delta.Get("partial_json").String() + } + } + } + indexes := make([]int64, 0, len(byIndex)) + for index := range byIndex { + indexes = append(indexes, index) + } + sort.Slice(indexes, func(i, j int) bool { return indexes[i] < indexes[j] }) + var lines []string + for _, index := range indexes { + block := byIndex[index] + switch block.kind { + case "thinking": + lines = append(lines, fmt.Sprintf("thinking %q signature=%q", block.thinking, block.signature)) + case "text": + lines = append(lines, fmt.Sprintf("text %q", block.text)) + case "tool_use": + lines = append(lines, fmt.Sprintf("tool_use %s %s %s", block.id, block.name, block.input)) + case "server_tool_use": + lines = append(lines, fmt.Sprintf("server_tool_use %s %s", block.id, block.input)) + case "web_search_tool_result": + lines = append(lines, fmt.Sprintf("web_search_tool_result %s", block.toolUseID)) + default: + lines = append(lines, "other "+block.kind) + } + } + return lines +} + +// bufferedParityChat reduces a Chat Completions answer to the fields a client reads. +func bufferedParityChatSummary(reasoning, content string, calls []string, finish string) string { + return fmt.Sprintf("reasoning=%q content=%q tool_calls=%v finish_reason=%s", reasoning, content, calls, finish) +} + +func bufferedParityChatNonStream(body string) string { + message := gjson.Get(body, "choices.0.message") + var calls []string + for _, call := range message.Get("tool_calls").Array() { + calls = append(calls, fmt.Sprintf("%s %s %s", call.Get("id").String(), call.Get("function.name").String(), call.Get("function.arguments").String())) + } + return bufferedParityChatSummary(message.Get("reasoning_content").String(), message.Get("content").String(), calls, gjson.Get(body, "choices.0.finish_reason").String()) +} + +func bufferedParityChatStream(sse string) string { + var reasoning, content, finish string + type call struct{ id, name, args string } + calls := map[int64]*call{} + for _, line := range strings.Split(sse, "\n") { + data, ok := strings.CutPrefix(line, "data: ") + if !ok || !gjson.Valid(data) { + continue + } + choice := gjson.Get(data, "choices.0") + reasoning += choice.Get("delta.reasoning_content").String() + content += choice.Get("delta.content").String() + if reason := choice.Get("finish_reason"); reason.Exists() && reason.Type != gjson.Null { + finish = reason.String() + } + for _, tc := range choice.Get("delta.tool_calls").Array() { + index := tc.Get("index").Int() + if calls[index] == nil { + calls[index] = &call{} + } + if id := tc.Get("id").String(); id != "" { + calls[index].id = id + } + if name := tc.Get("function.name").String(); name != "" { + calls[index].name = name + } + calls[index].args += tc.Get("function.arguments").String() + } + } + indexes := make([]int64, 0, len(calls)) + for index := range calls { + indexes = append(indexes, index) + } + sort.Slice(indexes, func(i, j int) bool { return indexes[i] < indexes[j] }) + var lines []string + for _, index := range indexes { + lines = append(lines, fmt.Sprintf("%s %s %s", calls[index].id, calls[index].name, calls[index].args)) + } + return bufferedParityChatSummary(reasoning, content, lines, finish) +} + +func forwardBufferedParity(t *testing.T, path, requestBody, upstreamSSE string) string { + t.Helper() + gin.SetMode(gin.TestMode) + rec := httptest.NewRecorder() + c, _ := gin.CreateTestContext(rec) + body := []byte(requestBody) + c.Request = httptest.NewRequest(http.MethodPost, path, bytes.NewReader(body)) + c.Request.Header.Set("Content-Type", "application/json") + svc := &OpenAIGatewayService{ + httpUpstream: &httpUpstreamRecorder{resp: bufferedHostedItemsSSEResponse(upstreamSSE)}, + cfg: rawChatCompletionsTestConfig(), + } + account := bufferedHostedItemsOAuthAccount() + var err error + if path == "/v1/chat/completions" { + _, err = svc.ForwardAsChatCompletions(context.Background(), c, account, body, "", "") + } else { + _, err = svc.ForwardAsAnthropic(context.Background(), c, account, body, "", "") + } + require.NoError(t, err) + require.Equal(t, http.StatusOK, rec.Code, rec.Body.String()) + return rec.Body.String() +} + +// A buffered /v1/messages or /v1/chat/completions answer must carry what the +// streaming path delivers for the same upstream event stream. The shapes are the +// ones real Codex streams produced; texts are placeholders. +func TestBufferedCompat_MatchesStreamingPathOnRealStreamShapes(t *testing.T) { + reasoningThenMessage := func(terminal string) string { + return bufferedParityStream(terminal, + bufferedParityReasoning(0, "rs_1", "REASON_TEXT_PLACEHOLDER", "ENC_PLACEHOLDER_1"), + bufferedParityMessage(1, "ANSWER_PLACEHOLDER")) + } + signatureOnlyThenEmptyMessage := func(terminal string) string { + return bufferedParityStream(terminal, + bufferedParityReasoning(0, "rs_1", "", "ENC_PLACEHOLDER_1"), + bufferedParityMessage(1, "")) + } + const filledTerminal = `[{"type":"reasoning","id":"rs_1","summary":[{"type":"summary_text","text":"REASON_TEXT_PLACEHOLDER"}],"encrypted_content":"ENC_PLACEHOLDER_1"},{"type":"message","id":"msg_1","role":"assistant","status":"completed","content":[{"type":"output_text","text":"ANSWER_PLACEHOLDER"}]}]` + const signatureOnlyTerminal = `[{"type":"reasoning","id":"rs_1","summary":[],"encrypted_content":"ENC_PLACEHOLDER_1"},{"type":"message","id":"msg_1","role":"assistant","status":"completed","content":[{"type":"output_text","text":""}]}]` + webSearchTurn := bufferedParityStream(`[]`, + bufferedParityReasoning(0, "rs_1", "REASON_ONE_PLACEHOLDER", "ENC_PLACEHOLDER_1"), + bufferedParityWebSearch(1, "ws_1", "QUERY_ONE_PLACEHOLDER"), + bufferedParityReasoning(2, "rs_2", "REASON_TWO_PLACEHOLDER", "ENC_PLACEHOLDER_2"), + bufferedParityWebSearch(3, "ws_2", "QUERY_TWO_PLACEHOLDER"), + bufferedParityReasoning(4, "rs_3", "REASON_THREE_PLACEHOLDER", "ENC_PLACEHOLDER_3"), + bufferedParityFunctionCall(5)) + + cases := []struct { + name string + sse string + wantMessages []string + wantChat string + }{ + { + name: "reasoning and message, filled terminal", + sse: reasoningThenMessage(filledTerminal), + wantMessages: []string{ + `thinking "REASON_TEXT_PLACEHOLDER" signature="ENC_PLACEHOLDER_1"`, + `text "ANSWER_PLACEHOLDER"`, + }, + wantChat: bufferedParityChatSummary("REASON_TEXT_PLACEHOLDER", "ANSWER_PLACEHOLDER", nil, "stop"), + }, + { + name: "reasoning and message, empty terminal", + sse: reasoningThenMessage(`[]`), + wantMessages: []string{ + `thinking "REASON_TEXT_PLACEHOLDER" signature="ENC_PLACEHOLDER_1"`, + `text "ANSWER_PLACEHOLDER"`, + }, + wantChat: bufferedParityChatSummary("REASON_TEXT_PLACEHOLDER", "ANSWER_PLACEHOLDER", nil, "stop"), + }, + { + name: "signature only reasoning and empty message, filled terminal", + sse: signatureOnlyThenEmptyMessage(signatureOnlyTerminal), + wantMessages: []string{`thinking "" signature="ENC_PLACEHOLDER_1"`}, + wantChat: bufferedParityChatSummary("", "", nil, "stop"), + }, + { + name: "signature only reasoning and empty message, empty terminal", + sse: signatureOnlyThenEmptyMessage(`[]`), + wantMessages: []string{`thinking "" signature="ENC_PLACEHOLDER_1"`}, + wantChat: bufferedParityChatSummary("", "", nil, "stop"), + }, + { + name: "web search turn with a client tool, empty terminal", + sse: webSearchTurn, + wantMessages: []string{ + `thinking "REASON_ONE_PLACEHOLDER" signature="ENC_PLACEHOLDER_1"`, + `server_tool_use srvtoolu_ws_1 {"query":"QUERY_ONE_PLACEHOLDER"}`, + `web_search_tool_result srvtoolu_ws_1`, + `thinking "REASON_TWO_PLACEHOLDER" signature="ENC_PLACEHOLDER_2"`, + `server_tool_use srvtoolu_ws_2 {"query":"QUERY_TWO_PLACEHOLDER"}`, + `web_search_tool_result srvtoolu_ws_2`, + `thinking "REASON_THREE_PLACEHOLDER" signature="ENC_PLACEHOLDER_3"`, + `tool_use call_c record_version {"version":"1.25"}`, + }, + wantChat: bufferedParityChatSummary("REASON_ONE_PLACEHOLDERREASON_TWO_PLACEHOLDERREASON_THREE_PLACEHOLDER", "", []string{`call_c record_version {"version":"1.25"}`}, "tool_calls"), + }, + } + for _, tc := range cases { + t.Run(tc.name+" messages", func(t *testing.T) { + buffered := forwardBufferedParity(t, "/v1/messages", fmt.Sprintf(bufferedParityMessagesBody, false), tc.sse) + streamed := forwardBufferedParity(t, "/v1/messages", fmt.Sprintf(bufferedParityMessagesBody, true), tc.sse) + require.Equal(t, tc.wantMessages, bufferedParityBlocks(gjson.Get(buffered, "content").Array()), buffered) + streamedBlocks := bufferedParityStreamBlocks(t, streamed) + require.Equal(t, tc.wantMessages, streamedBlocks, streamed) + }) + t.Run(tc.name+" chat", func(t *testing.T) { + buffered := forwardBufferedParity(t, "/v1/chat/completions", fmt.Sprintf(bufferedParityChatBody, false), tc.sse) + streamed := forwardBufferedParity(t, "/v1/chat/completions", fmt.Sprintf(bufferedParityChatBody, true), tc.sse) + require.Equal(t, tc.wantChat, bufferedParityChatNonStream(buffered), buffered) + require.Equal(t, tc.wantChat, bufferedParityChatStream(streamed), streamed) + }) + } +} + +// bufferedParityStreamedText folds the text of one kind ("text", "thinking" or +// "refusal") out of a streamed answer of the entry at path. +func bufferedParityStreamedText(sse, path, kind string) string { + var text strings.Builder + for _, line := range strings.Split(sse, "\n") { + data, ok := strings.CutPrefix(line, "data: ") + if !ok || !gjson.Valid(data) { + continue + } + if path == "/v1/chat/completions" { + text.WriteString(gjson.Get(data, "choices.0.delta."+map[string]string{"text": "content", "thinking": "reasoning_content", "refusal": "refusal"}[kind]).String()) + continue + } + if delta := gjson.Get(data, "delta"); delta.Get("type").String() == kind+"_delta" { + text.WriteString(delta.Get(kind).String()) + } + } + return text.String() +} + +// bufferedParityPartItem is a streamed item of several parts: every part gets its +// own part.added, delta and done events, with its own content_index or +// summary_index, and the item.done event carries the part texts of done. +func bufferedParityPartItem(kind string, deltas, done []string) []string { + var events []string + itemType, doneKey, deltaType, indexKey, partType, partKey := "message", "content", "response.output_text.delta", "content_index", "output_text", "text" + switch kind { + case "refusal": + deltaType, partType, partKey = "response.refusal.delta", "refusal", "refusal" + case "summary": + itemType, doneKey, deltaType, indexKey, partType = "reasoning", "summary", "response.reasoning_summary_text.delta", "summary_index", "summary_text" + case "reasoning_text": + itemType, deltaType, partType = "reasoning", "response.reasoning_text.delta", "reasoning_text" + } + events = append(events, fmt.Sprintf(`{"type":"response.output_item.added","output_index":0,"item":{"type":%q,"id":"item_1","role":"assistant","summary":[],"content":[]}}`, itemType)) + for i, delta := range deltas { + events = append(events, fmt.Sprintf(`{"type":%q,"output_index":0,%q:%d,"delta":%q}`, deltaType, indexKey, i, delta)) + } + parts := make([]string, len(done)) + for i, text := range done { + parts[i] = fmt.Sprintf(`{"type":%q,%q:%q}`, partType, partKey, text) + } + item := fmt.Sprintf(`{"type":%q,"id":"item_1","role":"assistant","status":"completed",%q:[%s]`, itemType, doneKey, strings.Join(parts, ",")) + if itemType == "reasoning" && doneKey == "content" { + item += `,"summary":[]` + } + return append(events, `{"type":"response.output_item.done","output_index":0,"item":`+item+`}}`) +} + +// An item with several parts, of which the done item leaves some empty, and an +// empty terminal output: the buffered answer carries the text the streaming path +// delivers, for every kind of part that has a part index. +func TestBufferedCompat_MatchesStreamingPathOnMultiPartItems(t *testing.T) { + deltas := []string{"first ", "second"} + variants := []struct { + name string + done []string + }{ + {"first part empty", []string{"", "second"}}, + {"second part empty", []string{"first ", ""}}, + {"both parts empty", []string{"", ""}}, + {"both parts with text", []string{"first ", "second"}}, + } + kinds := []struct{ kind, shown string }{ + {"text", "text"}, + {"summary", "thinking"}, + {"reasoning_text", "thinking"}, + {"refusal", "refusal"}, + } + for _, k := range kinds { + for _, v := range variants { + sse := bufferedParityStream(`[]`, bufferedParityPartItem(k.kind, deltas, v.done)) + for _, entry := range []struct{ name, path, body string }{ + {"messages", "/v1/messages", bufferedParityMessagesBody}, + {"chat", "/v1/chat/completions", bufferedParityChatBody}, + } { + if k.shown == "refusal" && entry.path == "/v1/messages" { + continue // an Anthropic message has no refusal block + } + t.Run(k.kind+" "+v.name+" "+entry.name, func(t *testing.T) { + buffered := forwardBufferedParity(t, entry.path, fmt.Sprintf(entry.body, false), sse) + streamed := forwardBufferedParity(t, entry.path, fmt.Sprintf(entry.body, true), sse) + require.Equal(t, "first second", bufferedParityStreamedText(streamed, entry.path, k.shown), streamed) + require.Equal(t, "first second", bufferedPartsVisible(buffered, entry.path, k.shown), buffered) + }) + } + } + } +} diff --git a/backend/internal/service/openai_gateway_chat_completions.go b/backend/internal/service/openai_gateway_chat_completions.go index 78a384c6e034..a1c2eb8af092 100644 --- a/backend/internal/service/openai_gateway_chat_completions.go +++ b/backend/internal/service/openai_gateway_chat_completions.go @@ -25,20 +25,55 @@ import ( "go.uber.org/zap" ) -// cursorResponsesUnsupportedFields are top-level Responses API parameters that -// Codex upstreams reject with "Unsupported parameter: ...". They must be -// stripped when forwarding a raw client body through the Responses-shape -// short-circuit in ForwardAsChatCompletions (see isResponsesShape branch). -// The normal Chat Completions → Responses conversion path is unaffected -// because ChatCompletionsRequest has no fields for these parameters — unknown -// fields are dropped naturally by json.Unmarshal. Kept semantically in sync -// with the list in openai_gateway_service.go:2034 used by the /v1/responses -// passthrough path. +// The Responses-shaped shortcut forwards a raw body. Strip fields that the +// typed Chat Completions → Responses conversion omits for this upstream. var cursorResponsesUnsupportedFields = []string{ "prompt_cache_retention", "safety_identifier", "metadata", "stream_options", + "stop", +} + +// Kimi Chat can append function declarations to the conversation in system +// messages. Responses and Anthropic use a request-level tool list for the +// current generation. Native Chat forwarding keeps the declarations in place. +func parseChatRequestForBridge(body []byte, platform string, req *apicompat.ChatCompletionsRequest) error { + if platform != PlatformKimi { + return json.Unmarshal(body, req) + } + var wire struct { + *apicompat.ChatCompletionsRequest + Messages []struct { + apicompat.ChatMessage + Tools json.RawMessage `json:"tools"` + } `json:"messages"` + } + wire.ChatCompletionsRequest = req + if err := json.Unmarshal(body, &wire); err != nil { + return err + } + req.Messages = make([]apicompat.ChatMessage, 0, len(wire.Messages)) + for i, msg := range wire.Messages { + if msg.Role != "system" || msg.Tools == nil { + req.Messages = append(req.Messages, msg.ChatMessage) + continue + } + if msg.Content != nil { + return fmt.Errorf("messages[%d]: Kimi system tools cannot be used with content", i) + } + var tools []apicompat.ChatTool + if err := json.Unmarshal(msg.Tools, &tools); err != nil { + return fmt.Errorf("messages[%d].tools: %w", i, err) + } + for j, tool := range tools { + if tool.Type != "function" || tool.Function == nil || strings.TrimSpace(tool.Function.Name) == "" { + return fmt.Errorf("messages[%d].tools[%d]: expected a named function", i, j) + } + } + req.Tools = append(req.Tools, tools...) + } + return nil } // ForwardAsChatCompletions accepts a Chat Completions request body, converts it @@ -206,7 +241,10 @@ func (s *OpenAIGatewayService) forwardAsChatCompletions( // 1. Parse Chat Completions request var chatReq apicompat.ChatCompletionsRequest - if err := json.Unmarshal(body, &chatReq); err != nil { + if err := parseChatRequestForBridge(body, account.Platform, &chatReq); err != nil { + if account.Platform == PlatformKimi { + writeChatCompletionsError(c, http.StatusBadRequest, "invalid_request_error", err.Error()) + } return nil, fmt.Errorf("parse chat completions request: %w", err) } originalModel := chatReq.Model @@ -292,6 +330,9 @@ func (s *OpenAIGatewayService) forwardAsChatCompletions( if err != nil { return nil, fmt.Errorf("marshal responses request: %w", err) } + // responsesReq lives until billing after the stream; only its scalar + // fields are read from here on, so drop the body-sized input. + responsesReq.Input = nil } logFields := []zap.Field{ @@ -999,6 +1040,7 @@ func (s *OpenAIGatewayService) handleChatStreamingResponse( payload = string(restoreCodexToolNamesFromContext(c, []byte(payload))) if countSearch { searchCount += countGrokNativeSearchCallsInSSEDataDedup([]byte(payload), streamSearchSeen) + searchCount = grokSearchCountWithTerminalUsage(searchCount, []byte(payload)) } var event apicompat.ResponsesStreamEvent diff --git a/backend/internal/service/openai_gateway_chat_completions_anthropic_native.go b/backend/internal/service/openai_gateway_chat_completions_anthropic_native.go index 3d3f39793f19..e284960db8e0 100644 --- a/backend/internal/service/openai_gateway_chat_completions_anthropic_native.go +++ b/backend/internal/service/openai_gateway_chat_completions_anthropic_native.go @@ -46,7 +46,7 @@ func (s *OpenAIGatewayService) forwardChatCompletionsViaNativeAnthropic( // 1. Parse Chat Completions request var ccReq apicompat.ChatCompletionsRequest - if err := json.Unmarshal(body, &ccReq); err != nil { + if err := parseChatRequestForBridge(body, account.Platform, &ccReq); err != nil { writeChatCompletionsError(c, http.StatusBadRequest, "invalid_request_error", "Failed to parse request body") return nil, fmt.Errorf("parse chat completions request: %w", err) } diff --git a/backend/internal/service/openai_gateway_deepseek_anthropic_thinking.go b/backend/internal/service/openai_gateway_deepseek_anthropic_thinking.go new file mode 100644 index 000000000000..055a40ebf6c6 --- /dev/null +++ b/backend/internal/service/openai_gateway_deepseek_anthropic_thinking.go @@ -0,0 +1,110 @@ +package service + +// DeepSeek 官方 Anthropic 原生端点(/v1/messages)的 thinking 历史补位。 +// +// DeepSeek 在 thinking 模式下要求工具续接请求把 assistant 历史里的 thinking +// 块完整回传;缺失时上游会按 tool-call ID 尝试自动恢复,恢复失败返回 400 +// "The content[].thinking in the thinking mode must be passed back to the API"。 +// 会话历史中由其他后端(如 Ollama 中转)生成的 tool_use 轮没有 thinking 块, +// 被 file-owner 固定到 DeepSeek 官方账号后就会触发该 400。 +// +// Chat Completions 链已有同构先例 ensureDeepSeekChatReasoningPlaceholders +// (见 openai_gateway_responses_chat_fallback.go),这里为 Anthropic 原生直通链 +// 做对应补位。 + +import ( + "strconv" + "strings" + + "github.com/tidwall/gjson" + "github.com/tidwall/sjson" +) + +// deepSeekAnthropicThinkingPlaceholderBlock 是插到 assistant 历史 content 首位的 +// thinking 占位块。thinking 填单个空格而非空串:DeepSeek 可能把空串按缺失处理 +// (同 Chat 链 ensureDeepSeekChatReasoningPlaceholders 的结论:DeepSeek 拒绝 +// 空串,非空即可通过,LiteLLM 同样注入单个空格)。signature 可以省略: +// DeepSeek 官方文档说明 input 侧的 signature 不做校验。 +const deepSeekAnthropicThinkingPlaceholderBlock = `{"type":"thinking","thinking":" "}` + +// anthropicBodyThinkingEnabled 报告 Anthropic Messages 请求体是否处于 thinking +// 模式。thinking.type 为 enabled/adaptive 视为启用、disabled 视为关闭;没有 +// type 时看 output_config.effort,none 关闭、其余(含缺失)视为启用——DeepSeek +// 对 deepseek-flash 默认启用 thinking。 +func anthropicBodyThinkingEnabled(body []byte) bool { + switch strings.ToLower(strings.TrimSpace(gjson.GetBytes(body, "thinking.type").String())) { + case "enabled", "adaptive": + return true + case "disabled": + return false + } + effort := strings.TrimSpace(gjson.GetBytes(body, "output_config.effort").String()) + return !strings.EqualFold(effort, "none") +} + +// ensureDeepSeekAnthropicThinkingBlocks 给带 tool_use 但缺 thinking 的 assistant +// 历史消息补单个空格占位的 thinking 块(DeepSeek 可能把空串按缺失处理),插在 +// content 数组最前面。已有 thinking / redacted_thinking 的消息、只有文本的消息 +// 都不改写。 +// +// 用 gjson 定位、sjson.SetRawBytes 只重写 messages..content,保留请求体其余 +// 字节。非法 JSON、messages 非数组、content 非数组(如字符串)时原样返回; +// 合法 JSON 但无需改动时返回同一份 body。 +func ensureDeepSeekAnthropicThinkingBlocks(body []byte) []byte { + if !gjson.ValidBytes(body) { + return body + } + messages := gjson.GetBytes(body, "messages") + if !messages.IsArray() { + return body + } + updated := body + changed := false + for i, msg := range messages.Array() { + if strings.TrimSpace(msg.Get("role").String()) != "assistant" { + continue + } + content := msg.Get("content") + if !content.IsArray() { + continue + } + hasToolUse := false + hasThinking := false + for _, block := range content.Array() { + switch block.Get("type").String() { + case "tool_use": + hasToolUse = true + case "thinking", "redacted_thinking": + hasThinking = true + } + } + if !hasToolUse || hasThinking { + continue + } + raw := content.Raw + if len(raw) < 2 || raw[0] != '[' { + continue + } + prefixed := "[" + deepSeekAnthropicThinkingPlaceholderBlock + "," + raw[1:] + next, err := sjson.SetRawBytes(updated, "messages."+strconv.Itoa(i)+".content", []byte(prefixed)) + if err != nil { + return body + } + updated = next + changed = true + } + if !changed { + return body + } + return updated +} + +// shouldRepairDeepSeekAnthropicThinking 报告该请求是否需要做 DeepSeek Anthropic +// thinking 补位:仅 DeepSeek 官方上游账号且请求启用 +// thinking 时生效,其他上游保持字节不变。 +func shouldRepairDeepSeekAnthropicThinking(account *Account, body []byte) bool { + if account == nil { + return false + } + return isDeepSeekAPIHost(account.GetAnthropicProtocolBaseURL()) && anthropicBodyThinkingEnabled(body) +} diff --git a/backend/internal/service/openai_gateway_deepseek_anthropic_thinking_test.go b/backend/internal/service/openai_gateway_deepseek_anthropic_thinking_test.go new file mode 100644 index 000000000000..00000c867443 --- /dev/null +++ b/backend/internal/service/openai_gateway_deepseek_anthropic_thinking_test.go @@ -0,0 +1,207 @@ +package service + +import ( + "encoding/json" + "testing" + + "github.com/stretchr/testify/require" + "github.com/tidwall/gjson" +) + +// deepSeekAnthropicOfficialAccount 构造 DeepSeek 官方 Anthropic 原生端点账号。 +func deepSeekAnthropicOfficialAccount() *Account { + return &Account{ + ID: 88, + Name: "deepseek-anthropic-official", + Platform: PlatformDeepseek, + Type: AccountTypeAPIKey, + Credentials: map[string]any{ + "api_key": "sk-test", + "base_url": DefaultDeepseekBaseURL, + "api_protocol": APIProtocolAnthropic, + }, + } +} + +// ollamaCloudAnthropicAccount 构造 base_url 指向 ollama.com 的非 DeepSeek 账号。 +func ollamaCloudAnthropicAccount() *Account { + return &Account{ + ID: 89, + Name: "ollama-cloud", + Platform: PlatformAnthropic, + Type: AccountTypeAPIKey, + Credentials: map[string]any{ + "api_key": "ollama-key", + "base_url": "https://ollama.com/v1", + }, + } +} + +func TestEnsureDeepSeekAnthropicThinkingBlocks(t *testing.T) { + tests := []struct { + name string + body string + wantChanged bool + check func(t *testing.T, got []byte) + }{ + { + name: "assistant_tool_use_without_thinking_gets_placeholder_block_first", + body: `{"model":"deepseek-flash","thinking":{"type":"enabled"},"messages":[` + + `{"role":"user","content":"hi"},` + + `{"role":"assistant","content":[{"type":"tool_use","id":"call_1","name":"exec","input":{}}]},` + + `{"role":"user","content":[{"type":"tool_result","tool_use_id":"call_1","content":"ok"}]}]}`, + wantChanged: true, + check: func(t *testing.T, got []byte) { + t.Helper() + require.True(t, json.Valid(got)) + require.Equal(t, "thinking", gjson.GetBytes(got, "messages.1.content.0.type").String()) + require.Equal(t, " ", gjson.GetBytes(got, "messages.1.content.0.thinking").String()) + require.False(t, gjson.GetBytes(got, "messages.1.content.0.signature").Exists()) + require.Equal(t, "tool_use", gjson.GetBytes(got, "messages.1.content.1.type").String()) + require.Equal(t, "call_1", gjson.GetBytes(got, "messages.1.content.1.id").String()) + require.Equal(t, "user", gjson.GetBytes(got, "messages.0.role").String()) + require.Equal(t, 3, len(gjson.GetBytes(got, "messages").Array())) + }, + }, + { + name: "assistant_with_thinking_and_tool_use_unchanged", + body: `{"model":"deepseek-flash","thinking":{"type":"enabled"},"messages":[` + + `{"role":"assistant","content":[{"type":"thinking","thinking":"real","signature":"sig"},` + + `{"type":"tool_use","id":"call_1","name":"exec","input":{}}]}]}`, + wantChanged: false, + check: func(t *testing.T, got []byte) { + t.Helper() + require.Equal(t, 2, len(gjson.GetBytes(got, "messages.0.content").Array())) + require.Equal(t, "real", gjson.GetBytes(got, "messages.0.content.0.thinking").String()) + }, + }, + { + name: "assistant_text_only_unchanged", + body: `{"model":"deepseek-flash","thinking":{"type":"enabled"},"messages":[` + + `{"role":"assistant","content":[{"type":"text","text":"done"}]}]}`, + wantChanged: false, + }, + { + name: "only_message_missing_thinking_is_modified", + body: `{"model":"deepseek-flash","thinking":{"type":"enabled"},"messages":[` + + `{"role":"assistant","content":[{"type":"text","text":"first"}]},` + + `{"role":"assistant","content":[{"type":"tool_use","id":"call_2","name":"exec","input":{}}]},` + + `{"role":"assistant","content":[{"type":"thinking","thinking":"kept"},{"type":"tool_use","id":"call_3","name":"exec","input":{}}]}]}`, + wantChanged: true, + check: func(t *testing.T, got []byte) { + t.Helper() + require.True(t, json.Valid(got)) + require.Equal(t, "text", gjson.GetBytes(got, "messages.0.content.0.type").String()) + require.Equal(t, "thinking", gjson.GetBytes(got, "messages.1.content.0.type").String()) + require.Equal(t, "tool_use", gjson.GetBytes(got, "messages.1.content.1.type").String()) + require.Equal(t, "kept", gjson.GetBytes(got, "messages.2.content.0.thinking").String()) + require.Equal(t, 2, len(gjson.GetBytes(got, "messages.2.content").Array())) + }, + }, + { + name: "content_string_unchanged", + body: `{"model":"deepseek-flash","thinking":{"type":"enabled"},"messages":[` + + `{"role":"assistant","content":"plain text"}]}`, + wantChanged: false, + }, + { + name: "messages_not_array_unchanged", + body: `{"model":"deepseek-flash","messages":{"role":"assistant","content":[{"type":"tool_use"}]}}`, + wantChanged: false, + }, + { + name: "invalid_json_unchanged", + body: `{"messages":[{"role":"assistant","content":[`, + wantChanged: false, + }, + { + name: "empty_body_unchanged", + body: ``, + wantChanged: false, + }, + { + name: "empty_messages_unchanged", + body: `{"model":"deepseek-flash","messages":[]}`, + wantChanged: false, + }, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + body := []byte(tt.body) + got := ensureDeepSeekAnthropicThinkingBlocks(body) + require.Equal(t, tt.wantChanged, string(got) != tt.body) + if !tt.wantChanged { + require.Equal(t, tt.body, string(got), "无需改动时必须原样返回") + if len(body) > 0 { + require.True(t, &body[0] == &got[0], "无需改动时必须返回同一份 body") + } + } + if tt.check != nil { + tt.check(t, got) + } + }) + } +} + +func TestAnthropicBodyThinkingEnabled(t *testing.T) { + tests := []struct { + name string + body string + want bool + }{ + {name: "enabled", body: `{"thinking":{"type":"enabled"}}`, want: true}, + {name: "adaptive", body: `{"thinking":{"type":"adaptive"}}`, want: true}, + {name: "no_thinking_field", body: `{"model":"deepseek-flash"}`, want: true}, + {name: "effort_none_disables", body: `{"output_config":{"effort":"none"}}`, want: false}, + {name: "effort_high_enables", body: `{"output_config":{"effort":"high"}}`, want: true}, + {name: "disabled", body: `{"thinking":{"type":"disabled"}}`, want: false}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + require.Equal(t, tt.want, anthropicBodyThinkingEnabled([]byte(tt.body))) + }) + } +} + +func TestShouldRepairDeepSeekAnthropicThinking(t *testing.T) { + thinkingBody := []byte(`{"model":"deepseek-flash","thinking":{"type":"enabled"},"messages":[{"role":"assistant","content":[{"type":"tool_use","id":"call_1","name":"exec","input":{}}]}]}`) + disabledBody := []byte(`{"model":"deepseek-flash","thinking":{"type":"disabled"},"messages":[{"role":"assistant","content":[{"type":"tool_use","id":"call_1","name":"exec","input":{}}]}]}`) + + tests := []struct { + name string + account *Account + body []byte + want bool + }{ + { + name: "deepseek_official_thinking_enabled", + account: deepSeekAnthropicOfficialAccount(), + body: thinkingBody, + want: true, + }, + { + name: "deepseek_official_thinking_disabled", + account: deepSeekAnthropicOfficialAccount(), + body: disabledBody, + want: false, + }, + { + name: "non_deepseek_upstream", + account: ollamaCloudAnthropicAccount(), + body: thinkingBody, + want: false, + }, + { + name: "nil_account", + account: nil, + body: thinkingBody, + want: false, + }, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + require.Equal(t, tt.want, shouldRepairDeepSeekAnthropicThinking(tt.account, tt.body)) + }) + } +} diff --git a/backend/internal/service/openai_gateway_grok_405_test.go b/backend/internal/service/openai_gateway_grok_405_test.go index 10ed8a599e71..bc17dd520ed9 100644 --- a/backend/internal/service/openai_gateway_grok_405_test.go +++ b/backend/internal/service/openai_gateway_grok_405_test.go @@ -17,12 +17,12 @@ func TestShouldFailoverUpstreamError_405IsFailoverEligible(t *testing.T) { func TestShouldFailoverUpstreamError_ExistingCodesStillWork(t *testing.T) { svc := &OpenAIGatewayService{} - failoverCodes := []int{401, 402, 403, 405, 429, 529, 500, 502, 503, 504} + failoverCodes := []int{401, 402, 403, 405, http.StatusRequestTimeout, 429, 529, 500, 502, 503, 504} for _, code := range failoverCodes { assert.True(t, svc.shouldFailoverUpstreamError(code), "status %d should trigger failover", code) } - nonFailoverCodes := []int{200, 201, 400, 404, 408, 422} + nonFailoverCodes := []int{200, 201, 400, 404, 422} for _, code := range nonFailoverCodes { assert.False(t, svc.shouldFailoverUpstreamError(code), "status %d should NOT trigger failover", code) } diff --git a/backend/internal/service/openai_gateway_grok_test.go b/backend/internal/service/openai_gateway_grok_test.go index 76ea0ab30b2b..a80aaa37d701 100644 --- a/backend/internal/service/openai_gateway_grok_test.go +++ b/backend/internal/service/openai_gateway_grok_test.go @@ -1158,13 +1158,15 @@ func TestPrepareGrokImageEditNormalizesOfficialImageObjects(t *testing.T) { } } -func TestPrepareGrokImageEditRejectsMoreThanThreeSources(t *testing.T) { - body := []byte(`{"images":["https://example.com/1.png","https://example.com/2.png","https://example.com/3.png","https://example.com/4.png"]}`) +func TestPrepareGrokImageEditRejectsMoreThanFiveSources(t *testing.T) { + body := []byte(`{"images":["https://example.com/1.png","https://example.com/2.png","https://example.com/3.png","https://example.com/4.png","https://example.com/5.png","https://example.com/6.png"]}`) out, _, err := prepareGrokMediaForwardBody(GrokMediaEndpointImagesEdits, body, "application/json") require.Error(t, err) require.Nil(t, out) - require.Contains(t, err.Error(), "maximum of 3 source images") + var validationErr *GrokMediaInputValidationError + require.ErrorAs(t, err, &validationErr) + require.Contains(t, err.Error(), "maximum of 5 source images") } func TestNormalizeGrokMediaModelForEndpoint(t *testing.T) { diff --git a/backend/internal/service/openai_gateway_kimi_dynamic_tools_test.go b/backend/internal/service/openai_gateway_kimi_dynamic_tools_test.go new file mode 100644 index 000000000000..3f97e561be25 --- /dev/null +++ b/backend/internal/service/openai_gateway_kimi_dynamic_tools_test.go @@ -0,0 +1,55 @@ +//go:build unit + +package service + +import ( + "context" + "errors" + "testing" + + "github.com/gin-gonic/gin" + "github.com/stretchr/testify/require" + "github.com/tidwall/gjson" +) + +func TestKimiChatDynamicToolsAcrossProtocols(t *testing.T) { + gin.SetMode(gin.TestMode) + body := []byte(`{ + "model":"kimi-k3.1-pro", + "tools":[{"type":"function","function":{"name":"Lookup","parameters":{"type":"object"}}}], + "tool_choice":"required", + "messages":[ + {"role":"system","content":"Answer briefly."}, + {"role":"user","content":"Calculate 23 * 47.","tools":[{"type":"function","function":{"name":"IgnoreMe"}}]}, + {"role":"system","tools":[{"type":"function","function":{"name":"Calculator","parameters":{"type":"object","properties":{"expr":{"type":"string"}},"required":["expr"]}}}]} + ] + }`) + for _, protocol := range []string{APIProtocolChatCompletions, APIProtocolResponses, APIProtocolAnthropic} { + t.Run(protocol, func(t *testing.T) { + upstream := &httpUpstreamRecorder{err: errors.New("stop after capture")} + svc := &OpenAIGatewayService{cfg: rawChatCompletionsTestConfig(), httpUpstream: upstream} + account := adaptiveProtocolTestAccount(PlatformKimi, map[string]any{protocol: "http://kimi.example"}) + account.Credentials["api_protocol"] = protocol + c := adaptiveProtocolTestContext("/v1/chat/completions", body) + _, err := svc.ForwardAsChatCompletions(context.Background(), c, account, body, "", "") + require.Error(t, err) + require.NotNil(t, upstream.lastReq) + out := gjson.ParseBytes(upstream.lastBody) + schema := gjson.GetBytes(body, "messages.2.tools.0.function.parameters").Raw + switch protocol { + case APIProtocolChatCompletions: + require.JSONEq(t, string(body), string(upstream.lastBody)) + case APIProtocolResponses: + require.JSONEq(t, `["Lookup","Calculator"]`, out.Get("tools.#.name").Raw) + require.JSONEq(t, schema, out.Get("tools.1.parameters").Raw) + require.Equal(t, "required", out.Get("tool_choice").String()) + require.Len(t, out.Get("input").Array(), 2) + case APIProtocolAnthropic: + require.JSONEq(t, `["Lookup","Calculator"]`, out.Get("tools.#.name").Raw) + require.JSONEq(t, schema, out.Get("tools.1.input_schema").Raw) + require.Equal(t, "any", out.Get("tool_choice.type").String()) + require.Equal(t, "Answer briefly.", out.Get("system").String()) + } + }) + } +} diff --git a/backend/internal/service/openai_gateway_messages.go b/backend/internal/service/openai_gateway_messages.go index dc069c6238a5..8e78ef95a8fe 100644 --- a/backend/internal/service/openai_gateway_messages.go +++ b/backend/internal/service/openai_gateway_messages.go @@ -215,6 +215,16 @@ func (s *OpenAIGatewayService) forwardAsAnthropic( responsesReq.ServiceTier = "priority" } + // 3c. ChatGPT/Codex accounts whose model supports tool_search get Claude + // Code's ToolSearch as the native protocol, keeping deferred tools out of + // the top-level tools. + if account.UsesOpenAICodexProtocol() && account.Platform != PlatformGrok && + string(accountCodexToolCapabilities(account, upstreamModel)["supports_search_tool"]) == "true" { + if err := apicompat.ApplyNativeToolSearch(&anthropicReq, responsesReq); err != nil { + return nil, fmt.Errorf("apply native tool_search: %w", err) + } + } + responsesReq.Model = upstreamModel if responsesReq.Reasoning != nil { responsesReq.Reasoning.Effort = openAICompatAnthropicReasoningEffort(&anthropicReq, upstreamModel, responsesReq.Reasoning.Effort) @@ -257,12 +267,18 @@ func (s *OpenAIGatewayService) forwardAsAnthropic( logFields = append(logFields, zap.Bool("compat_turn_state_attached", true)) } logger.L().Debug("openai messages: model mapping applied", logFields...) + if account.Platform == PlatformOpenAI { + apicompat.IncludeWebSearchSources(responsesReq) + } // 4. Marshal Responses request body, then apply the ChatGPT/Codex transform. responsesBody, err := json.Marshal(responsesReq) if err != nil { return nil, fmt.Errorf("marshal responses request: %w", err) } + // responsesReq lives until billing after the stream; only its scalar + // fields are read from here on, so drop the body-sized input. + responsesReq.Input = nil if account.UsesOpenAICodexProtocol() && account.Platform != PlatformGrok { var reqBody map[string]any @@ -894,6 +910,7 @@ func (s *OpenAIGatewayService) readOpenAICompatBufferedTerminal( ) (*apicompat.ResponsesResponse, OpenAIUsage, *apicompat.BufferedResponseAccumulator, openAICompatPriorModelAudit, error) { acc := apicompat.NewBufferedResponseAccumulator() acc.XAIServerSideSearch = account != nil && account.IsGrok() + outputSlots := &openAICompatOutputSlots{xaiServerSideSearch: acc.XAIServerSideSearch} var usage OpenAIUsage if resp == nil || resp.Body == nil { return nil, usage, acc, openAICompatPriorModelAudit{}, errors.New("upstream response body is nil") @@ -974,6 +991,7 @@ func (s *OpenAIGatewayService) readOpenAICompatBufferedTerminal( if frame, ok := parser.Finish(); ok { payload := openAICompatPayloadWithEventType(frame.Data, frame.EventType) payload = string(restoreCodexToolNamesFromContext(c, []byte(payload))) + outputSlots.Observe([]byte(payload)) var event apicompat.ResponsesStreamEvent if err := json.Unmarshal([]byte(payload), &event); err == nil { s.parseSSEUsageBytesWithType([]byte(payload), event.Type, &usage) @@ -989,6 +1007,7 @@ func (s *OpenAIGatewayService) readOpenAICompatBufferedTerminal( if response.Usage != nil { usage = copyOpenAIUsageFromResponsesUsage(response.Usage, usage) } + outputSlots.fillTerminalOutput(event.Type, response) return response, usage, acc, prior, nil } } @@ -1015,6 +1034,7 @@ func (s *OpenAIGatewayService) readOpenAICompatBufferedTerminal( } payload := openAICompatPayloadWithEventType(frame.Data, frame.EventType) payload = string(restoreCodexToolNamesFromContext(c, []byte(payload))) + outputSlots.Observe([]byte(payload)) var event apicompat.ResponsesStreamEvent if err := json.Unmarshal([]byte(payload), &event); err != nil { @@ -1039,6 +1059,7 @@ func (s *OpenAIGatewayService) readOpenAICompatBufferedTerminal( if response.Usage != nil { usage = copyOpenAIUsageFromResponsesUsage(response.Usage, usage) } + outputSlots.fillTerminalOutput(event.Type, response) return response, usage, acc, prior, nil } @@ -1168,6 +1189,7 @@ func (s *OpenAIGatewayService) handleAnthropicStreamingResponse( } if countSearch { searchCount += countGrokNativeSearchCallsInSSEDataDedup([]byte(payload), streamSearchSeen) + searchCount = grokSearchCountWithTerminalUsage(searchCount, []byte(payload)) } var event apicompat.ResponsesStreamEvent diff --git a/backend/internal/service/openai_gateway_messages_anthropic_native.go b/backend/internal/service/openai_gateway_messages_anthropic_native.go index cf498c3d5fad..8fdb69d50992 100644 --- a/backend/internal/service/openai_gateway_messages_anthropic_native.go +++ b/backend/internal/service/openai_gateway_messages_anthropic_native.go @@ -31,7 +31,8 @@ import ( // forwardAnthropicViaNativeAnthropicEndpoint 将 Anthropic Messages 请求零转换 // 直通到国产供应商的原生 Anthropic 端点。仅做模型名映射与少量 body 清洗 -// (空文本块 / web-search 历史块),协议本身不转换。 +// (空文本块 / web-search 历史块),协议本身不转换。对 DeepSeek 官方账号补齐 +// tool_use 历史的单个空格占位 thinking 块(thinking 模式下缺 thinking 会被上游 400)。 func (s *OpenAIGatewayService) forwardAnthropicViaNativeAnthropicEndpoint( ctx context.Context, c *gin.Context, @@ -77,6 +78,12 @@ func (s *OpenAIGatewayService) forwardAnthropicViaNativeAnthropicEndpoint( body = StripEmptyTextBlocks(body) body = FilterWebSearchHistoryBlocks(body, upstreamModel) + // thinking 模式下 DeepSeek 要求工具续接历史回传 thinking 块;缺失时上游 + // 自动恢复失败会返回 400。仅对 DeepSeek 官方账号、thinking 启用时生效。 + if shouldRepairDeepSeekAnthropicThinking(account, body) { + body = ensureDeepSeekAnthropicThinkingBlocks(body) + } + logger.LegacyPrintf("service.gateway", "[CN Anthropic 直通] account=%d(%s) platform=%s model=%s upstream=%s stream=%v", account.ID, account.Name, account.Platform, originalModel, upstreamModel, clientStream) diff --git a/backend/internal/service/openai_gateway_messages_tool_search_test.go b/backend/internal/service/openai_gateway_messages_tool_search_test.go new file mode 100644 index 000000000000..27c22fea453f --- /dev/null +++ b/backend/internal/service/openai_gateway_messages_tool_search_test.go @@ -0,0 +1,234 @@ +//go:build unit + +package service + +import ( + "bytes" + "context" + "io" + "net/http" + "net/http/httptest" + "strings" + "testing" + + "github.com/gin-gonic/gin" + "github.com/stretchr/testify/require" + "github.com/tidwall/gjson" +) + +const messagesToolSearchBody = `{"model":"gpt-6-astra","max_tokens":64,"stream":true, + "tools":[ + {"name":"Bash","description":"run","input_schema":{"type":"object","properties":{"command":{"type":"string"}}}}, + {"name":"ToolSearch","description":"search deferred tools","input_schema":{"type":"object","properties":{"query":{"type":"string"},"max_results":{"type":"number"}},"required":["query","max_results"]}}, + {"name":"WebFetch","description":"fetch a url","input_schema":{"type":"object","properties":{"url":{"type":"string"}}},"defer_loading":true}], + "messages":[ + {"role":"user","content":"fetch the page"}, + {"role":"assistant","content":[{"type":"tool_use","id":"toolu_search","name":"ToolSearch","input":{"query":"select:WebFetch","max_results":5}}]}, + {"role":"user","content":[{"type":"tool_result","tool_use_id":"toolu_search","content":[{"type":"tool_reference","tool_name":"WebFetch"}]}]}]}` + +func forwardMessagesToolSearch(t *testing.T, account *Account, requestBody, upstreamSSE, mappedModel string) (*httpUpstreamRecorder, *httptest.ResponseRecorder) { + t.Helper() + gin.SetMode(gin.TestMode) + rec := httptest.NewRecorder() + c, _ := gin.CreateTestContext(rec) + body := []byte(requestBody) + c.Request = httptest.NewRequest(http.MethodPost, "/v1/messages", bytes.NewReader(body)) + c.Request.Header.Set("Content-Type", "application/json") + upstream := &httpUpstreamRecorder{resp: &http.Response{ + StatusCode: http.StatusOK, + Header: http.Header{"Content-Type": []string{"text/event-stream"}}, + Body: io.NopCloser(strings.NewReader(upstreamSSE)), + }} + svc := &OpenAIGatewayService{ + httpUpstream: upstream, + cfg: rawChatCompletionsTestConfig(), + } + _, err := svc.ForwardAsAnthropic(context.Background(), c, account, body, "", mappedModel) + require.NoError(t, err) + return upstream, rec +} + +const toolSearchCallSSE = "data: {\"type\":\"response.created\",\"response\":{\"id\":\"resp_ts\",\"model\":\"gpt-6-astra\"}}\n\n" + + "data: {\"type\":\"response.output_item.done\",\"output_index\":0,\"item\":{\"type\":\"tool_search_call\",\"call_id\":\"call_search_2\",\"execution\":\"client\",\"status\":\"completed\",\"arguments\":{\"query\":\"notebook\",\"max_results\":5}}}\n\n" + + "data: {\"type\":\"response.completed\",\"response\":{\"id\":\"resp_ts\",\"status\":\"completed\",\"output\":[],\"usage\":{\"input_tokens\":5,\"output_tokens\":2,\"total_tokens\":7}}}\n\n" + +func TestForwardAsAnthropic_CodexOAuthUsesNativeToolSearch(t *testing.T) { + account := &Account{ + ID: 1, Name: "openai-oauth", Platform: PlatformOpenAI, Type: AccountTypeOAuth, Concurrency: 1, + Credentials: map[string]any{"access_token": "oauth-token", "chatgpt_account_id": "chatgpt-acc"}, + } + upstream, rec := forwardMessagesToolSearch(t, account, messagesToolSearchBody, toolSearchCallSSE, "gpt-6-astra") + + tools := gjson.GetBytes(upstream.lastBody, "tools").Array() + require.Len(t, tools, 2, "deferred WebFetch stays out of the top-level tools") + require.Equal(t, "Bash", tools[0].Get("name").String()) + require.Equal(t, "tool_search", tools[1].Get("type").String()) + require.Equal(t, "client", tools[1].Get("execution").String()) + + var types []string + for _, item := range gjson.GetBytes(upstream.lastBody, "input").Array() { + types = append(types, item.Get("type").String()) + } + require.Contains(t, types, "tool_search_call") + require.Contains(t, types, "tool_search_output") + require.NotContains(t, types, "function_call") + + out := rec.Body.String() + require.Contains(t, out, `"name":"ToolSearch"`) + require.Contains(t, out, `"id":"call_search_2"`) + require.Contains(t, out, `"stop_reason":"tool_use"`) +} + +func TestForwardAsAnthropic_NonCodexAccountKeepsFunctionToolSearch(t *testing.T) { + completed := "data: {\"type\":\"response.completed\",\"response\":{\"id\":\"resp_fn\",\"status\":\"completed\",\"output\":[],\"usage\":{\"input_tokens\":5,\"output_tokens\":2,\"total_tokens\":7}}}\n\n" + upstream, _ := forwardMessagesToolSearch(t, rawChatCompletionsTestAccount(), messagesToolSearchBody, completed, "gpt-6-astra") + + var names []string + for _, tool := range gjson.GetBytes(upstream.lastBody, "tools").Array() { + require.Equal(t, "function", tool.Get("type").String()) + names = append(names, tool.Get("name").String()) + } + require.Equal(t, []string{"Bash", "ToolSearch", "WebFetch"}, names) + require.NotContains(t, string(upstream.lastBody), "tool_search_call") +} + +// A Codex OAuth model without supports_search_tool keeps ToolSearch and the +// deferred tools as plain function tools. +func TestForwardAsAnthropic_CodexOAuthModelWithoutSearchSupportKeepsFunctionToolSearch(t *testing.T) { + account := &Account{ + ID: 1, Name: "openai-oauth", Platform: PlatformOpenAI, Type: AccountTypeOAuth, Concurrency: 1, + Credentials: map[string]any{"access_token": "oauth-token", "chatgpt_account_id": "chatgpt-acc"}, + } + completed := "data: {\"type\":\"response.completed\",\"response\":{\"id\":\"resp_fn\",\"status\":\"completed\",\"output\":[],\"usage\":{\"input_tokens\":5,\"output_tokens\":2,\"total_tokens\":7}}}\n\n" + body := strings.Replace(messagesToolSearchBody, `"model":"gpt-6-astra"`, `"model":"gpt-5.5"`, 1) + upstream, _ := forwardMessagesToolSearch(t, account, body, completed, "gpt-5.5") + + var names []string + for _, tool := range gjson.GetBytes(upstream.lastBody, "tools").Array() { + require.Equal(t, "function", tool.Get("type").String()) + names = append(names, tool.Get("name").String()) + } + require.Equal(t, []string{"Bash", "ToolSearch", "WebFetch"}, names) + require.NotContains(t, string(upstream.lastBody), "tool_search_call") +} + +func codexOAuthToolSearchAccount() *Account { + return &Account{ + ID: 1, Name: "openai-oauth", Platform: PlatformOpenAI, Type: AccountTypeOAuth, Concurrency: 1, + Credentials: map[string]any{"access_token": "oauth-token", "chatgpt_account_id": "chatgpt-acc"}, + } +} + +const toolSearchNoopSSE = "data: {\"type\":\"response.completed\",\"response\":{\"id\":\"resp_noop\",\"status\":\"completed\",\"output\":[],\"usage\":{\"input_tokens\":5,\"output_tokens\":2,\"total_tokens\":7}}}\n\n" + +// A revealed tool is declared in tool_search_output and replayed as a +// function_call; both must carry the same upstream name. +func TestForwardAsAnthropic_CodexOAuthRevealedToolNameMatchesReplay(t *testing.T) { + for _, tc := range []struct{ name, want string }{ + {"python", "python__sub2api"}, + {"Python", "python__sub2api"}, + {"Echo", "Echo"}, + } { + t.Run(tc.name, func(t *testing.T) { + body := strings.ReplaceAll(messagesToolSearchBody, "WebFetch", tc.name) + body = strings.TrimSuffix(body, "]}") + `, + {"role":"assistant","content":[{"type":"tool_use","id":"toolu_call","name":"` + tc.name + `","input":{"url":"https://example.com"}}]}, + {"role":"user","content":[{"type":"tool_result","tool_use_id":"toolu_call","content":"ok"}]}]}` + upstream, _ := forwardMessagesToolSearch(t, codexOAuthToolSearchAccount(), body, toolSearchNoopSSE, "gpt-6-astra") + + var declared, replayed []string + for _, item := range gjson.GetBytes(upstream.lastBody, "input").Array() { + switch item.Get("type").String() { + case "tool_search_output": + for _, tool := range item.Get("tools").Array() { + declared = append(declared, tool.Get("name").String()) + } + case "function_call": + replayed = append(replayed, item.Get("name").String()) + } + } + require.Equal(t, []string{tc.want}, declared) + require.Equal(t, []string{tc.want}, replayed) + }) + } +} + +// Selections that name a top-level function or carry no name are forwarded +// as the bridge produced them. +func TestForwardAsAnthropic_CodexOAuthToolChoiceControls(t *testing.T) { + for choice, want := range map[string]string{ + `{"type":"tool","name":"Bash"}`: `{"type":"function","name":"Bash"}`, + `{"type":"auto"}`: `"auto"`, + `{"type":"any"}`: `"required"`, + } { + t.Run(choice, func(t *testing.T) { + body := strings.Replace(messagesToolSearchBody, `"stream":true,`, `"stream":true,"tool_choice":`+choice+`,`, 1) + upstream, _ := forwardMessagesToolSearch(t, codexOAuthToolSearchAccount(), body, toolSearchNoopSSE, "gpt-6-astra") + require.JSONEq(t, want, gjson.GetBytes(upstream.lastBody, "tool_choice").Raw) + }) + } +} + +func TestForwardAsAnthropic_CodexOAuthForcedHiddenToolKeepsFunctionTools(t *testing.T) { + for _, name := range []string{"ToolSearch", "WebFetch"} { + t.Run(name, func(t *testing.T) { + body := strings.Replace(messagesToolSearchBody, `"stream":true,`, `"stream":true,"tool_choice":{"type":"tool","name":"`+name+`"},`, 1) + upstream, _ := forwardMessagesToolSearch(t, codexOAuthToolSearchAccount(), body, toolSearchNoopSSE, "gpt-6-astra") + + var names []string + for _, tool := range gjson.GetBytes(upstream.lastBody, "tools").Array() { + require.Equal(t, "function", tool.Get("type").String()) + names = append(names, tool.Get("name").String()) + } + require.Equal(t, []string{"Bash", "ToolSearch", "WebFetch"}, names) + require.JSONEq(t, `{"type":"function","name":"`+name+`"}`, gjson.GetBytes(upstream.lastBody, "tool_choice").Raw) + require.NotContains(t, string(upstream.lastBody), "tool_search_call") + require.NotContains(t, string(upstream.lastBody), "tool_search_output") + }) + } +} + +// Claude Code also sends stream:false turns; their upstream stream can end +// with an empty terminal output, rebuilt from the buffered output items. +func TestForwardAsAnthropic_CodexOAuthNonStreamingRestoresToolSearchCall(t *testing.T) { + account := &Account{ + ID: 1, Name: "openai-oauth", Platform: PlatformOpenAI, Type: AccountTypeOAuth, Concurrency: 1, + Credentials: map[string]any{"access_token": "oauth-token", "chatgpt_account_id": "chatgpt-acc"}, + } + body := strings.Replace(messagesToolSearchBody, `"stream":true`, `"stream":false`, 1) + _, rec := forwardMessagesToolSearch(t, account, body, toolSearchCallSSE, "gpt-6-astra") + + out := rec.Body.String() + require.Contains(t, out, `"name":"ToolSearch"`) + require.Contains(t, out, `"id":"call_search_2"`) + require.Contains(t, out, `"stop_reason":"tool_use"`) + require.Equal(t, "notebook", gjson.Get(out, "content.0.input.query").String()) +} + +// Grok OAuth accounts also speak the Codex protocol, but xAI has no native +// tool_search: ToolSearch and deferred tools stay function tools there. +func TestForwardAsAnthropic_GrokOAuthKeepsFunctionToolSearch(t *testing.T) { + gin.SetMode(gin.TestMode) + c, _ := gin.CreateTestContext(httptest.NewRecorder()) + body := []byte(messagesToolSearchBody) + c.Request = httptest.NewRequest(http.MethodPost, "/v1/messages", bytes.NewReader(body)) + account := healthyGrokOAuthGatewayTestAccount(71, "access-token") + repo := &grokQuotaAccountRepo{mockAccountRepoForPlatform: &mockAccountRepoForPlatform{accountsByID: map[int64]*Account{71: account}}} + upstream := &httpUpstreamRecorder{resp: grokMessagesSSECompletedResponse("resp_grok_ts", 0)} + svc := &OpenAIGatewayService{httpUpstream: upstream, grokTokenProvider: NewGrokTokenProvider(repo, nil), accountRepo: repo} + + _, err := svc.ForwardAsAnthropic(context.Background(), c, account, body, "", "") + require.NoError(t, err) + + var functions []string + for _, tool := range gjson.GetBytes(upstream.lastBody, "tools").Array() { + require.NotEqual(t, "tool_search", tool.Get("type").String()) + if tool.Get("type").String() == "function" { + functions = append(functions, tool.Get("name").String()) + } + } + require.Contains(t, functions, "ToolSearch") + require.Contains(t, functions, "WebFetch") + require.NotContains(t, string(upstream.lastBody), "tool_search_call") + require.NotContains(t, string(upstream.lastBody), "tool_search_output") +} diff --git a/backend/internal/service/openai_gateway_messages_web_search_sources_test.go b/backend/internal/service/openai_gateway_messages_web_search_sources_test.go new file mode 100644 index 000000000000..9c859cc3b081 --- /dev/null +++ b/backend/internal/service/openai_gateway_messages_web_search_sources_test.go @@ -0,0 +1,123 @@ +//go:build unit + +package service + +import ( + "bytes" + "context" + "io" + "net/http" + "net/http/httptest" + "strings" + "testing" + + "github.com/gin-gonic/gin" + "github.com/stretchr/testify/require" + "github.com/tidwall/gjson" +) + +const messagesWebSearchBody = `{"model":"gpt-5.5","max_tokens":64,"stream":true, + "tools":[{"type":"web_search_20250305","name":"web_search"}], + "messages":[{"role":"user","content":"search the web"}]}` + +const messagesWithoutWebSearchBody = `{"model":"gpt-5.5","max_tokens":64,"stream":true, + "messages":[{"role":"user","content":"hello"}]}` + +const webSearchCompletedSSE = "data: {\"type\":\"response.completed\",\"response\":{\"id\":\"resp_ws\",\"status\":\"completed\",\"output\":[],\"usage\":{\"input_tokens\":5,\"output_tokens\":2,\"total_tokens\":7}}}\n\n" + +func codexOAuthWebSearchTestAccount() *Account { + return &Account{ + ID: 1, Name: "openai-oauth", Platform: PlatformOpenAI, Type: AccountTypeOAuth, Concurrency: 1, + Credentials: map[string]any{"access_token": "oauth-token", "chatgpt_account_id": "chatgpt-acc"}, + } +} + +func upstreamInclude(body []byte) []string { + var include []string + for _, v := range gjson.GetBytes(body, "include").Array() { + include = append(include, v.String()) + } + return include +} + +func forwardMessagesWebSearch(t *testing.T, account *Account, requestBody, upstreamSSE string) (*httpUpstreamRecorder, *httptest.ResponseRecorder) { + t.Helper() + gin.SetMode(gin.TestMode) + rec := httptest.NewRecorder() + c, _ := gin.CreateTestContext(rec) + body := []byte(requestBody) + c.Request = httptest.NewRequest(http.MethodPost, "/v1/messages", bytes.NewReader(body)) + c.Request.Header.Set("Content-Type", "application/json") + upstream := &httpUpstreamRecorder{resp: &http.Response{ + StatusCode: http.StatusOK, + Header: http.Header{"Content-Type": []string{"text/event-stream"}}, + Body: io.NopCloser(strings.NewReader(upstreamSSE)), + }} + svc := &OpenAIGatewayService{ + httpUpstream: upstream, + cfg: rawChatCompletionsTestConfig(), + } + _, err := svc.ForwardAsAnthropic(context.Background(), c, account, body, "", "gpt-5.5") + require.NoError(t, err) + return upstream, rec +} + +func forwardGrokMessages(t *testing.T, requestBody string) *httpUpstreamRecorder { + t.Helper() + gin.SetMode(gin.TestMode) + c, _ := gin.CreateTestContext(httptest.NewRecorder()) + body := []byte(requestBody) + c.Request = httptest.NewRequest(http.MethodPost, "/v1/messages", bytes.NewReader(body)) + account := healthyGrokOAuthGatewayTestAccount(71, "access-token") + repo := &grokQuotaAccountRepo{mockAccountRepoForPlatform: &mockAccountRepoForPlatform{accountsByID: map[int64]*Account{71: account}}} + upstream := &httpUpstreamRecorder{resp: grokMessagesSSECompletedResponse("resp_grok_ws", 0)} + svc := &OpenAIGatewayService{httpUpstream: upstream, grokTokenProvider: NewGrokTokenProvider(repo, nil), accountRepo: repo} + + _, err := svc.ForwardAsAnthropic(context.Background(), c, account, body, "", "") + require.NoError(t, err) + return upstream +} + +func TestForwardAsAnthropic_WebSearchRequestsSources(t *testing.T) { + for name, account := range map[string]*Account{ + "openai apikey": rawChatCompletionsTestAccount(), + "codex oauth": codexOAuthWebSearchTestAccount(), + } { + t.Run(name, func(t *testing.T) { + upstream, _ := forwardMessagesWebSearch(t, account, messagesWebSearchBody, webSearchCompletedSSE) + require.Equal(t, []string{"reasoning.encrypted_content", "web_search_call.action.sources"}, upstreamInclude(upstream.lastBody)) + }) + } +} + +func TestForwardAsAnthropic_WebSearchSourcesNotRequestedWithoutTool(t *testing.T) { + for name, account := range map[string]*Account{ + "openai apikey": rawChatCompletionsTestAccount(), + "codex oauth": codexOAuthWebSearchTestAccount(), + } { + t.Run(name, func(t *testing.T) { + upstream, _ := forwardMessagesWebSearch(t, account, messagesWithoutWebSearchBody, webSearchCompletedSSE) + require.NotContains(t, upstreamInclude(upstream.lastBody), "web_search_call.action.sources") + }) + } + t.Run("grok with web_search tool", func(t *testing.T) { + upstream := forwardGrokMessages(t, messagesWebSearchBody) + require.NotEmpty(t, gjson.GetBytes(upstream.lastBody, "tools").Array(), "the web_search tool reaches xAI") + require.NotContains(t, upstreamInclude(upstream.lastBody), "web_search_call.action.sources") + }) +} + +// A source entry of an unexpected shape must not cost the terminal event that +// carries it: that would turn a finished answer into a missing-terminal error. +func TestWebSearchMalformedSourcesKeepTerminalEvent(t *testing.T) { + sse := "data: {\"type\":\"response.created\",\"response\":{\"id\":\"resp_ws\",\"model\":\"gpt-5.5\"}}\n\n" + + "data: {\"type\":\"response.output_text.delta\",\"output_index\":0,\"content_index\":0,\"delta\":\"found it\"}\n\n" + + "data: {\"type\":\"response.completed\",\"response\":{\"id\":\"resp_ws\",\"status\":\"completed\",\"output\":[" + + "{\"type\":\"message\",\"id\":\"msg_1\",\"role\":\"assistant\",\"status\":\"completed\",\"content\":[{\"type\":\"output_text\",\"text\":\"found it\"}]}," + + "{\"type\":\"web_search_call\",\"id\":\"ws_1\",\"status\":\"completed\",\"action\":{\"type\":\"search\",\"query\":\"q\",\"sources\":[\"https://a\"]}}]," + + "\"usage\":{\"input_tokens\":5,\"output_tokens\":2,\"total_tokens\":7}}}\n\n" + _, rec := forwardMessagesWebSearch(t, rawChatCompletionsTestAccount(), messagesWebSearchBody, sse) + + out := strings.TrimSpace(rec.Body.String()) + require.True(t, strings.HasSuffix(out, `{"type":"message_stop"}`), "body: %s", out) +} diff --git a/backend/internal/service/openai_gateway_request_body.go b/backend/internal/service/openai_gateway_request_body.go index e5f6bace497e..0e3454935946 100644 --- a/backend/internal/service/openai_gateway_request_body.go +++ b/backend/internal/service/openai_gateway_request_body.go @@ -1145,12 +1145,17 @@ func newOpenAIRequestView(body []byte) openAIRequestView { view := openAIRequestView{body: body} var seen uint8 - // parseRawJSONView reads body without copying; view keeps body alive for extracted strings. + // parseRawJSONView reads body without copying, so extracted strings alias the + // body. They flow into usage logs and async tasks that outlive the request, so + // clone them; otherwise a multi-MB body stays alive after its budget is freed. + field := func(value gjson.Result) string { + return strings.Clone(strings.TrimSpace(value.String())) + } parseRawJSONView(body).ForEach(func(key, value gjson.Result) bool { switch key.Str { case "model": if seen&modelField == 0 { - view.Model = strings.TrimSpace(value.String()) + view.Model = field(value) seen |= modelField } case "stream": @@ -1160,22 +1165,22 @@ func newOpenAIRequestView(body []byte) openAIRequestView { } case "prompt_cache_key": if seen&promptCacheKeyField == 0 { - view.PromptCacheKey = strings.TrimSpace(value.String()) + view.PromptCacheKey = field(value) seen |= promptCacheKeyField } case "previous_response_id": if seen&previousResponseIDField == 0 { - view.PreviousResponseID = strings.TrimSpace(value.String()) + view.PreviousResponseID = field(value) seen |= previousResponseIDField } case "service_tier": if seen&serviceTierField == 0 { - view.ServiceTier = strings.TrimSpace(value.String()) + view.ServiceTier = field(value) seen |= serviceTierField } case "reasoning": if seen&reasoningField == 0 { - view.ReasoningEffort = strings.TrimSpace(value.Get("effort").String()) + view.ReasoningEffort = field(value.Get("effort")) seen |= reasoningField } } @@ -1831,7 +1836,34 @@ func extractOpenAIReasoningEffortFromBody(body []byte, modelCandidates ...string return &value } +const responsesConfigurationUpdate = "configuration_update" + +// Responses clients can keep the top-level effort fixed for prompt caching. +// Each input update takes effect from its position until another sets effort. +func latestResponsesInputEffort(body []byte) string { + if !bytes.Contains(body, []byte(responsesConfigurationUpdate)) && !JSONMayEscapePlainASCII(body) { + return "" + } + input := parseRawJSONView(body).Get("input") + if !input.IsArray() { + return "" + } + var latest string + input.ForEach(func(_, item gjson.Result) bool { + if item.Get("type").Str == responsesConfigurationUpdate { + if effort := strings.TrimSpace(item.Get("reasoning.effort").Str); effort != "" { + latest = effort + } + } + return true + }) + return latest +} + func explicitRequestedReasoningEffortFromBody(body []byte) string { + if latest := latestResponsesInputEffort(body); latest != "" { + return latest + } raw := strings.TrimSpace(gjson.GetBytes(body, "reasoning.effort").String()) if raw == "" { raw = strings.TrimSpace(gjson.GetBytes(body, "reasoning_effort").String()) @@ -1848,11 +1880,7 @@ func explicitRequestedReasoningEffortFromBody(body []byte) string { // later persist "xhigh". func CanonicalRequestedReasoningEffort(body []byte, modelCandidates ...string) *string { if raw := explicitRequestedReasoningEffortFromBody(body); raw != "" { - canonical := NormalizeMaxReasoningEffort(raw) - if canonical == "" { - return nil - } - return &canonical + return optionalTrimmedStringPtr(normalizeReasoningEffortMappingSource(raw)) } for _, model := range modelCandidates { if value := canonicalReasoningEffortFromModelSuffix(model); value != "" { @@ -2628,12 +2656,19 @@ func CanonicalRequestedReasoningEffortFromReqBody(reqBody map[string]any, modelC raw = strings.TrimSpace(effort) } } - if raw != "" { - canonical := NormalizeMaxReasoningEffort(raw) - if canonical == "" { - return nil + items, _ := reqBody["input"].([]any) + for i := len(items) - 1; i >= 0; i-- { + item, _ := items[i].(map[string]any) + if item["type"] == responsesConfigurationUpdate { + reasoning, _ := item["reasoning"].(map[string]any) + if effort, _ := reasoning["effort"].(string); strings.TrimSpace(effort) != "" { + raw = effort + break + } } - return &canonical + } + if raw != "" { + return optionalTrimmedStringPtr(normalizeReasoningEffortMappingSource(raw)) } return CanonicalRequestedReasoningEffort(nil, modelCandidates...) } diff --git a/backend/internal/service/openai_gateway_request_timeout_test.go b/backend/internal/service/openai_gateway_request_timeout_test.go new file mode 100644 index 000000000000..b0fb1dae144d --- /dev/null +++ b/backend/internal/service/openai_gateway_request_timeout_test.go @@ -0,0 +1,71 @@ +package service + +import ( + "context" + "io" + "net/http" + "net/http/httptest" + "strings" + "testing" + + "github.com/gin-gonic/gin" + "github.com/stretchr/testify/require" +) + +func TestShouldFailoverOpenAIUpstreamResponse_RequestTimeout(t *testing.T) { + svc := &OpenAIGatewayService{} + account := &Account{Platform: PlatformOpenAI, Type: AccountTypeAPIKey} + tests := []struct { + name string + status int + body string + want bool + }{ + {"adobe_upstream", http.StatusRequestTimeout, `{"error":{"code":"upstream_unavailable","message":"Upstream request failed","type":"adobe_upstream"}}`, true}, + {"model_overloaded", http.StatusRequestTimeout, `{"error":{"message":"Model is overloaded, please retry later","type":"rate_limit_error"}}`, true}, + {"adobe_throttled", http.StatusRequestTimeout, `{"error":{"message":"adobe throttled: status 429 retry-after=21.48s envoy=false {\"error_code\":\"rate_limited\",\"message\":\"Too many requests. Please try again later.\"}","type":"rate_limit_error"}}`, true}, + {"plain_timeout", http.StatusRequestTimeout, `Request Timeout`, true}, + {"bad_gateway", http.StatusBadGateway, `{"error":{"message":"Upstream service temporarily unavailable","type":"upstream_error"}}`, true}, + {"rate_limit", http.StatusTooManyRequests, `{"error":{"message":"rate limited","type":"rate_limit_error"}}`, true}, + {"method_not_allowed", http.StatusMethodNotAllowed, ``, true}, + {"bad_request", http.StatusBadRequest, `{"error":{"message":"Invalid image size","type":"invalid_request_error"}}`, false}, + {"not_found", http.StatusNotFound, `{"error":{"message":"Not found"}}`, false}, + {"unprocessable_entity", http.StatusUnprocessableEntity, `{"error":{"message":"Invalid request"}}`, false}, + {"cyber_policy", http.StatusRequestTimeout, `{"error":{"code":"cyber_policy","message":"blocked"}}`, false}, + {"context_length", http.StatusRequestTimeout, `{"error":{"code":"context_length_exceeded","message":"Maximum context length exceeded"}}`, false}, + {"context_window", http.StatusRequestTimeout, `{"error":{"message":"Input exceeds the context window"}}`, false}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + body := []byte(tt.body) + require.Equal(t, tt.want, svc.shouldFailoverOpenAIUpstreamResponse(account, tt.status, extractUpstreamErrorMessage(body), body)) + }) + } +} + +func TestOpenAIRequestTimeout_CustomErrorCodesStillTakePrecedence(t *testing.T) { + gin.SetMode(gin.TestMode) + rec := httptest.NewRecorder() + c, _ := gin.CreateTestContext(rec) + c.Request = httptest.NewRequest(http.MethodPost, "/v1/responses", nil) + account := &Account{ + Platform: PlatformOpenAI, + Type: AccountTypeAPIKey, + Credentials: map[string]any{ + "custom_error_codes_enabled": true, + "custom_error_codes": []any{float64(http.StatusTooManyRequests)}, + }, + } + resp := &http.Response{ + StatusCode: http.StatusRequestTimeout, + Header: http.Header{}, + Body: io.NopCloser(strings.NewReader(`{"error":{"message":"Upstream request failed","type":"adobe_upstream"}}`)), + } + result, err := (&OpenAIGatewayService{}).handleErrorResponse(context.Background(), resp, c, account, nil) + require.Nil(t, result) + require.ErrorContains(t, err, "not in custom error codes") + var failoverErr *UpstreamFailoverError + require.NotErrorAs(t, err, &failoverErr) + require.Equal(t, http.StatusInternalServerError, rec.Code) + require.True(t, c.Writer.Written()) +} diff --git a/backend/internal/service/openai_gateway_response_handling.go b/backend/internal/service/openai_gateway_response_handling.go index 059f3c80dd05..5aa1fb3b7dfc 100644 --- a/backend/internal/service/openai_gateway_response_handling.go +++ b/backend/internal/service/openai_gateway_response_handling.go @@ -804,6 +804,7 @@ func (s *OpenAIGatewayService) handleStreamingResponseWithReasoning(ctx context. } imageCounter.AddSSEData(dataBytes) searchCounter += countGrokNativeSearchCallsInSSEDataDedup(dataBytes, streamSearchSeen) + searchCounter = grokSearchCountWithTerminalUsage(searchCounter, dataBytes) // Correct Codex tool calls if needed (apply_patch -> edit, etc.) if correctedData, corrected := s.toolCorrector.CorrectToolCallsInSSEBytes(dataBytes); corrected { diff --git a/backend/internal/service/openai_gateway_service_hotpath_test.go b/backend/internal/service/openai_gateway_service_hotpath_test.go index 16f497600680..a330452b5e67 100644 --- a/backend/internal/service/openai_gateway_service_hotpath_test.go +++ b/backend/internal/service/openai_gateway_service_hotpath_test.go @@ -39,6 +39,21 @@ func TestOpenAIRequestView_ExtractsFieldsAfterLargeInput(t *testing.T) { require.Equal(t, "high", view.ReasoningEffort) } +func TestOpenAIRequestView_FieldsDoNotAliasBody(t *testing.T) { + body := []byte(`{"model":"gpt-5","prompt_cache_key":"session-1","previous_response_id":"resp-1","service_tier":"flex","reasoning":{"effort":"high"}}`) + + view := newOpenAIRequestView(body) + for i := range body { + body[i] = 'x' + } + + require.Equal(t, "gpt-5", view.Model) + require.Equal(t, "session-1", view.PromptCacheKey) + require.Equal(t, "resp-1", view.PreviousResponseID) + require.Equal(t, "flex", view.ServiceTier) + require.Equal(t, "high", view.ReasoningEffort) +} + func TestOpenAIRequestView_KeepsFirstDuplicateField(t *testing.T) { view := newOpenAIRequestView([]byte(`{"model":"gpt-5","model":"gpt-5.1","reasoning":{"effort":"low"},"reasoning":{"effort":"high"}}`)) diff --git a/backend/internal/service/openai_gateway_upstream_errors.go b/backend/internal/service/openai_gateway_upstream_errors.go index 024b851779e6..f55650515377 100644 --- a/backend/internal/service/openai_gateway_upstream_errors.go +++ b/backend/internal/service/openai_gateway_upstream_errors.go @@ -303,7 +303,7 @@ func isOpenAIContextWindowError(upstreamMsg string, upstreamBody []byte) bool { func (s *OpenAIGatewayService) shouldFailoverUpstreamError(statusCode int) bool { switch statusCode { - case 401, 402, 403, 405, 429, 529: + case 401, 402, 403, 405, http.StatusRequestTimeout, 429, 529: return true default: return statusCode >= 500 diff --git a/backend/internal/service/openai_gateway_usage.go b/backend/internal/service/openai_gateway_usage.go index 9c4bc74d0632..7233f4bfdca1 100644 --- a/backend/internal/service/openai_gateway_usage.go +++ b/backend/internal/service/openai_gateway_usage.go @@ -505,14 +505,13 @@ func (s *OpenAIGatewayService) RecordUsage(ctx context.Context, input *OpenAIRec billingMode := string(BillingModeToken) usageLog.BillingMode = &billingMode } - // 添加 UserAgent - if input.UserAgent != "" { - usageLog.UserAgent = &input.UserAgent + // 添加 UserAgent / IPAddress。取副本地址:指向 input 字段会让整个 input(含 Result + // 及其引用的请求体)随异步写入的 usageLog 一直存活。 + if userAgent := input.UserAgent; userAgent != "" { + usageLog.UserAgent = &userAgent } - - // 添加 IPAddress - if input.IPAddress != "" { - usageLog.IPAddress = &input.IPAddress + if ipAddress := input.IPAddress; ipAddress != "" { + usageLog.IPAddress = &ipAddress } // 添加 SessionID(客户端显式会话标识;缺失/无效时保持 nil) diff --git a/backend/internal/service/openai_images_direct_test.go b/backend/internal/service/openai_images_direct_test.go index e7156f738804..ac19b4cb1ec6 100644 --- a/backend/internal/service/openai_images_direct_test.go +++ b/backend/internal/service/openai_images_direct_test.go @@ -122,6 +122,30 @@ func TestCodexDirectImagesStreamRejectsPlainJSON(t *testing.T) { require.Nil(t, result) } +// The live endpoint pretty-prints its JSON; the usage copied into the +// completed event must not split the SSE data line. +func TestCodexDirectImagesStreamKeepsPrettyPrintedUsageOnOneLine(t *testing.T) { + body := []byte(`{"model":"gpt-image-2","prompt":"draw","stream":true}`) + c, rec := newOpenAIImagesTestContext(t, body) + const event = "image_generation.completed" + usage := []byte("{\n \"input_tokens\": 10,\n \"output_tokens\": 20\n}") + payload := buildOpenAIImagesStreamCompletedPayload(event, openAIResponsesImageResult{Result: "aGVsbG8="}, "b64_json", 1710000000, usage) + svc := &OpenAIGatewayService{} + require.NoError(t, svc.writeOpenAIImagesStreamEvent(c, rec, event, payload)) + + out := strings.TrimRight(rec.Body.String(), "\n") + var data string + for _, line := range strings.Split(out, "\n") { + require.True(t, line == "" || strings.HasPrefix(line, "event: ") || strings.HasPrefix(line, "data: "), "SSE line split mid-payload: %q", line) + if strings.HasPrefix(line, "data: ") { + data = strings.TrimPrefix(line, "data: ") + } + } + require.True(t, gjson.Valid(data), "data line is not complete JSON: %q", data) + require.Equal(t, "aGVsbG8=", gjson.Get(data, "b64_json").String()) + require.Equal(t, int64(20), gjson.Get(data, "usage.output_tokens").Int()) +} + func TestCodexDirectImagesMultipleOutputs(t *testing.T) { for _, stream := range []bool{false, true} { t.Run(fmt.Sprint(stream), func(t *testing.T) { diff --git a/backend/internal/service/openai_images_responses.go b/backend/internal/service/openai_images_responses.go index 93bdb4185f0a..b751df6d9c94 100644 --- a/backend/internal/service/openai_images_responses.go +++ b/backend/internal/service/openai_images_responses.go @@ -5,6 +5,7 @@ import ( "bytes" "context" "encoding/base64" + "encoding/json" "errors" "fmt" "io" @@ -301,6 +302,11 @@ func buildOpenAIImagesStreamCompletedPayload( payload, _ = sjson.SetBytes(payload, "model", img.Model) } if len(usageRaw) > 0 && gjson.ValidBytes(usageRaw) { + // Upstream JSON may be pretty-printed; a newline would split the SSE data line. + var compact bytes.Buffer + if json.Compact(&compact, usageRaw) == nil { + usageRaw = compact.Bytes() + } payload, _ = sjson.SetRawBytes(payload, "usage", usageRaw) } return payload diff --git a/backend/internal/service/openai_images_test.go b/backend/internal/service/openai_images_test.go index 3aff8711096c..4e48015a96fb 100644 --- a/backend/internal/service/openai_images_test.go +++ b/backend/internal/service/openai_images_test.go @@ -1463,6 +1463,49 @@ func TestOpenAIGatewayServiceForwardImages_APIKeyAccessStateUsesTypedFailover(t require.False(t, c.Writer.Written()) } +func TestOpenAIGatewayServiceForwardImages_APIKeyRequestTimeoutReturnsFailoverBeforeWrite(t *testing.T) { + gin.SetMode(gin.TestMode) + for _, upstreamBody := range []string{ + `{"error":{"code":"upstream_unavailable","message":"Upstream request failed","type":"adobe_upstream"}}`, + `{"error":{"message":"Model is overloaded, please retry later","type":"rate_limit_error"}}`, + `{"error":{"message":"adobe throttled: status 429 retry-after=21.48s envoy=false {\"error_code\":\"rate_limited\",\"message\":\"Too many requests. Please try again later.\"}","type":"rate_limit_error"}}`, + } { + t.Run(extractUpstreamErrorMessage([]byte(upstreamBody)), func(t *testing.T) { + body := []byte(`{"model":"gpt-image-1","prompt":"draw a cat"}`) + rec := httptest.NewRecorder() + c, _ := gin.CreateTestContext(rec) + c.Request = httptest.NewRequest(http.MethodPost, "/v1/images/generations", bytes.NewReader(body)) + c.Request.Header.Set("Content-Type", "application/json") + upstream := &httpUpstreamRecorder{resp: &http.Response{ + StatusCode: http.StatusRequestTimeout, + Header: http.Header{ + "Content-Type": {"application/json"}, + }, + Body: io.NopCloser(strings.NewReader(upstreamBody)), + }} + svc := &OpenAIGatewayService{cfg: &config.Config{}, httpUpstream: upstream} + parsed, err := svc.ParseOpenAIImagesRequest(c, body) + require.NoError(t, err) + account := &Account{ + ID: 51, Platform: PlatformOpenAI, Type: AccountTypeAPIKey, + Credentials: map[string]any{"api_key": "sk-test"}, + } + + result, err := svc.ForwardImages(context.Background(), c, account, body, parsed, "") + + require.Nil(t, result) + var failoverErr *UpstreamFailoverError + require.ErrorAs(t, err, &failoverErr) + require.Equal(t, http.StatusRequestTimeout, failoverErr.StatusCode) + require.Equal(t, upstreamBody, string(failoverErr.ResponseBody)) + require.False(t, failoverErr.RetryableOnSameAccount) + require.False(t, IsResponseCommitted(c)) + require.False(t, c.Writer.Written()) + require.Empty(t, rec.Body.String()) + }) + } +} + func TestOpenAIGatewayServiceForwardImages_APIKeyStreamJSONResponseBillsImage(t *testing.T) { gin.SetMode(gin.TestMode) body := []byte(`{"model":"gpt-image-2","prompt":"draw a cat","stream":true,"response_format":"b64_json"}`) diff --git a/backend/internal/service/openai_model_mapping.go b/backend/internal/service/openai_model_mapping.go index 7fd67468b14b..a590c76a8458 100644 --- a/backend/internal/service/openai_model_mapping.go +++ b/backend/internal/service/openai_model_mapping.go @@ -25,11 +25,12 @@ func resolveOpenAIForwardModel(account *Account, requestedModel, messagesDispatc // Codex 上游不可能服务这些模型:转发阶段 normalizeOpenAIModelForUpstream // 对未知模型原样透传,上游必然返回不可重试的 400。 // -// 采用保守黑名单而非 Codex 模型白名单:未知/自定义别名保持「允许」, -// 以兼容渠道级模型映射等「账号选定之后才改写模型名」的部署方式 -// (调度过滤看到的是改写前的原始模型名)。前缀分类的先例见 +// 采用保守黑名单而非 Codex 模型白名单:未知/自定义别名保持「允许」。 +// 渠道级模型映射不受影响:各 OpenAI 入口都按渠道映射后的模型名调度, +// 把 claude-* 等别名映射到 gpt-5.x 的渠道照常落到 OAuth 账号。前缀分类的先例见 // ResolveThinkingProtocol(thinking_protocol.go)。 var openAIOAuthForeignModelPrefixes = []string{ + "claude-", "deepseek-", "glm-", "kimi-", diff --git a/backend/internal/service/openai_oauth_model_support_test.go b/backend/internal/service/openai_oauth_model_support_test.go index 8ea10d1371c9..c641066ba4aa 100644 --- a/backend/internal/service/openai_oauth_model_support_test.go +++ b/backend/internal/service/openai_oauth_model_support_test.go @@ -27,12 +27,10 @@ func TestIsModelSupported_OpenAIOAuthEmptyMapping_ServableModels(t *testing.T) { "gpt-5.1-codex-mini", "gpt-5", "codex-mini-latest", - "gpt5.3codexspark", // 别名拼写 - "gpt-image-1", // 图像生成模型 - "claude-sonnet-4-6", // /v1/messages 调度默认映射兜底 - "claude-3-opus-20240229", - "gpt-4o", // 保守 fail-open:非黑名单模型保持允许 - "my-custom-alias", // 自定义别名可能由渠道级映射在转发前改写,保持允许 + "gpt5.3codexspark", // 别名拼写 + "gpt-image-1", // 图像生成模型 + "gpt-4o", // 保守 fail-open:非黑名单模型保持允许 + "my-custom-alias", // 自定义别名可能由渠道级映射在转发前改写,保持允许 } for _, model := range servable { require.True(t, account.IsModelSupported(model), "expected %q to be servable by empty-mapping OpenAI OAuth account", model) @@ -45,6 +43,9 @@ func TestIsModelSupported_OpenAIOAuthEmptyMapping_RejectsForeignModels(t *testin // Codex 上游必然以不可重试的 400 拒绝这些厂商家族;调度阶段就应跳过 // 该账号,让显式声明支持的 API Key 账号接手(#3662)。 foreign := []string{ + "claude-sonnet-4-6", // /v1/messages 的 opus/sonnet/haiku 在调度前已映射到 gpt-5.x + "claude-3-opus-20240229", + "claude-fable-5-1", "deepseek-v4", "deepseek-chat", "glm-4.7", @@ -80,11 +81,39 @@ func TestIsModelSupported_OpenAIOAuthExplicitMappingUnchanged(t *testing.T) { require.False(t, account.IsModelSupported("glm-4.7")) } -func TestIsModelSupported_OpenAIOAuthPassthroughAllowsAll(t *testing.T) { +func TestIsModelSupported_OpenAIOAuthPassthroughRejectsForeignModels(t *testing.T) { account := newOpenAIOAuthAccountForModelTest() account.Extra = map[string]any{"openai_passthrough": true} - // 透传模式仅替换认证,模型语义由上游决定,保持"允许所有"。 + // 透传仍放行 Codex 上游可能认识的任意名字,但 OAuth 透传的出口恒为 + // chatgpt.com/backend-api/codex,异族厂商模型在那里必然 400,调度阶段就应跳过。 + require.True(t, account.IsModelSupported("gpt-5.6-sol")) + require.True(t, account.IsModelSupported("my-custom-alias")) + require.False(t, account.IsModelSupported("claude-fable-5-1")) + require.False(t, account.IsModelSupported("claude-opus-5-5")) + require.False(t, account.IsModelSupported("deepseek-v4")) + + setupToken := &Account{ + ID: 5, + Platform: PlatformOpenAI, + Type: AccountTypeSetupToken, + Extra: map[string]any{"openai_passthrough": true}, + } + // Setup Token 与 OAuth 共用 Codex 出口。 + require.True(t, setupToken.IsModelSupported("gpt-5.6-sol")) + require.False(t, setupToken.IsModelSupported("claude-fable-5-1")) +} + +func TestIsModelSupported_OpenAIAPIKeyPassthroughAllowsForeignModels(t *testing.T) { + account := &Account{ + ID: 4, + Platform: PlatformOpenAI, + Type: AccountTypeAPIKey, + Extra: map[string]any{"openai_passthrough": true}, + } + + // API Key 透传的上游由 base_url 决定,可能正是服务 claude-*/deepseek-* 的中转站。 + require.True(t, account.IsModelSupported("claude-fable-5-1")) require.True(t, account.IsModelSupported("deepseek-v4")) } @@ -99,7 +128,7 @@ func TestIsModelSupported_OpenAIOAuthPassthroughIgnoresLeftoverMapping(t *testin } require.True(t, account.IsModelSupported("gpt-5.6-sol"), "透传应放行不在残留白名单中的新模型") - require.True(t, account.IsModelSupported("deepseek-v4"), "透传应放行任意模型") + require.True(t, account.IsModelSupported("my-custom-alias"), "透传应放行不在残留白名单中的自定义别名") } func TestIsModelSupported_OpenAIAPIKeyEmptyMappingAllowsAll(t *testing.T) { @@ -123,7 +152,8 @@ func TestIsModelSupported_NonOpenAIPlatformsUnchanged(t *testing.T) { func TestIsOpenAIOAuthServableModel(t *testing.T) { require.True(t, isOpenAIOAuthServableModel("gpt-5.4-high")) require.True(t, isOpenAIOAuthServableModel(" gpt-5.3-codex ")) - require.True(t, isOpenAIOAuthServableModel("claude-3-5-haiku-20241022")) + require.False(t, isOpenAIOAuthServableModel("claude-3-5-haiku-20241022")) + require.False(t, isOpenAIOAuthServableModel("provider/claude-fable-5-1")) require.True(t, isOpenAIOAuthServableModel("DeepThink-x")) // 非黑名单前缀,保持允许 require.False(t, isOpenAIOAuthServableModel("DeepSeek-V4")) // 大小写不敏感 require.False(t, isOpenAIOAuthServableModel("qwen3-235b-thinking")) diff --git a/backend/internal/service/openai_reasoning_effort_policy_test.go b/backend/internal/service/openai_reasoning_effort_policy_test.go index 6362fa22c67f..6bd10c2e4b42 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" + "encoding/json" "fmt" "testing" @@ -49,6 +50,36 @@ func TestCanonicalRequestedReasoningEffort(t *testing.T) { require.Nil(t, CanonicalRequestedReasoningEffort([]byte(`{"model":"gpt-5.4"}`), "gpt-5.4")) } +func TestCanonicalRequestedReasoningEffortFromConfigurationUpdates(t *testing.T) { + for _, tc := range []struct { + name, input, want string + }{ + {"current turn", `[{"role":"user","content":"hi"},{"type":"configuration_update","reasoning":{"effort":"high"}}]`, "high"}, + {"history and partial updates", `[{"type":"configuration_update","reasoning":{"effort":"high"}},{"type":"configuration_update","reasoning":{"effort":"MAX"}},{"type":"configuration_update","text":{"verbosity":"low"}},{"role":"user","content":"next"}]`, "max"}, + {"thinking off", `[{"type":"configuration_update","reasoning":{"effort":"none"}}]`, "none"}, + {"escaped type", `[{"type":"configuration\u005fupdate","reasoning":{"effort":"low"}}]`, "low"}, + {"no effort selected", `[{"type":"configuration_update","text":{"verbosity":"low"}}]`, "medium"}, + {"non-string effort", `[{"type":"configuration_update","reasoning":{"effort":123}}]`, "medium"}, + {"nested in message", `[{"role":"user","content":[{"type":"configuration_update","reasoning":{"effort":"low"}}]}]`, "medium"}, + {"non-array input", `{"item":{"type":"configuration_update","reasoning":{"effort":"low"}}}`, "medium"}, + {"unknown explicit effort", `[{"type":"configuration_update","reasoning":{"effort":"unknown"}}]`, ""}, + } { + t.Run(tc.name, func(t *testing.T) { + body := []byte(`{"model":"gpt-6.1-sol","reasoning":{"effort":"medium"},"input":` + tc.input + `}`) + var parsed map[string]any + require.NoError(t, json.Unmarshal(body, &parsed)) + for _, got := range []*string{CanonicalRequestedReasoningEffort(body), CanonicalRequestedReasoningEffortFromReqBody(parsed)} { + if tc.want == "" { + require.Nil(t, got) + } else { + require.NotNil(t, got) + require.Equal(t, tc.want, *got) + } + } + }) + } +} + func TestRequestedReasoningEffortContext(t *testing.T) { t.Parallel() diff --git a/backend/internal/service/openai_responses_namespace.go b/backend/internal/service/openai_responses_namespace.go index 3f56bdb8c2c1..3f73fa562cb3 100644 --- a/backend/internal/service/openai_responses_namespace.go +++ b/backend/internal/service/openai_responses_namespace.go @@ -14,6 +14,11 @@ import ( const openAIResponsesNamespaceNamesContextKey = "openai_responses_namespace_names" +// openAIResponsesNamespaceFieldBytes 是入口预检查用的字面量。带引号可避免匹配到 +// 正文里的普通单词;键写成 unicode 转义时无法字节匹配,那条路径不会进入清理逻辑, +// 与改动前一致。 +var openAIResponsesNamespaceFieldBytes = []byte(`"namespace"`) + // shouldFlattenOpenAIResponsesNamespaces 判定原生 Responses 转发前是否摊平 // Codex namespace 工具。 // @@ -120,6 +125,7 @@ func hasOpenAIResponsesNamespaceToolDeclaration(body []byte) bool { return found } + // 与 stripOpenAIResponsesInputNamespaces 同理:input 可能很大,用零拷贝视图取值。 root := parseRawJSONView(body) if hasNamespaceTool(root.Get("tools")) { return true @@ -171,7 +177,7 @@ func isOpenAIResponsesToolCallItemType(itemType string) bool { } func flattenOpenAIResponsesNamespaces(c *gin.Context, body []byte) ([]byte, error) { - if !bytes.Contains(body, []byte(`"namespace"`)) { + if !bytes.Contains(body, openAIResponsesNamespaceFieldBytes) { return body, nil } var requestBody map[string]any @@ -198,22 +204,28 @@ func flattenOpenAIResponsesNamespaces(c *gin.Context, body []byte) ([]byte, erro // untouched. Rebuilding the input array once keeps this linear for long // histories and avoids decoding JSON numbers through float64. // +// 读取走 parseRawJSONView(零拷贝 string 视图)而不是 gjson.GetBytes:后者会把 +// input 数组物化成一份拷贝,而这个函数在 Codex 流量上几乎每个请求都会进来 +// (tools 里就有 namespace 声明,入口预检查必然放行),未改动时那份拷贝纯属浪费。 +// // keepToolCallNamespaces 保留工具调用项(function_call / custom_tool_call 等)上的 // namespace,让 Codex 调用能按上游要求原样回传;判定见 // shouldKeepOpenAIResponsesToolCallNamespaces。 func stripOpenAIResponsesInputNamespaces(body []byte, keepToolCallNamespaces bool) ([]byte, error) { - if !bytes.Contains(body, []byte(`"namespace"`)) { + if !bytes.Contains(body, openAIResponsesNamespaceFieldBytes) { return body, nil } - // Zero-copy view: input.Raw aliases body and is only read below; the - // rebuilt array is written into a fresh buffer. input := parseRawJSONView(body).Get("input") if !input.IsArray() { return body, nil } + // inputStart/inputEnd 是 input 数组在 body 里的字节区间。 + inputStart := input.Index + inputEnd := inputStart + len(input.Raw) - var rebuilt bytes.Buffer - changed := false + // 输出缓冲只在首次真正改写时分配,容量按整个 body 预留,prefix + 改写后的数组 + + // suffix 一次写完,不再额外走一遍 sjson.SetRawBytes(那会再拷一份完整 body)。 + var out []byte // Offsets below are relative to input.Raw, not the full request body. copyFrom := 0 var stripErr error @@ -222,35 +234,30 @@ func stripOpenAIResponsesInputNamespaces(body []byte, keepToolCallNamespaces boo (keepToolCallNamespaces && isOpenAIResponsesToolCallItemType(item.Get("type").String())) { return true } - itemBody, err := sjson.DeleteBytes([]byte(item.Raw), "namespace") + itemBody, err := sjson.Delete(item.Raw, "namespace") if err != nil { stripErr = err return false } - if !changed { - // Allocate only on the first change; copy unchanged spans without - // traversing their items again or converting them to byte slices. - rebuilt.Grow(len(input.Raw)) - changed = true + if out == nil { + out = make([]byte, 0, len(body)) + out = append(out, body[:inputStart]...) } itemStart := item.Index - input.Index - _, _ = rebuilt.WriteString(input.Raw[copyFrom:itemStart]) - _, _ = rebuilt.Write(itemBody) + out = append(out, input.Raw[copyFrom:itemStart]...) + out = append(out, itemBody...) copyFrom = itemStart + len(item.Raw) return true }) if stripErr != nil { return body, fmt.Errorf("delete OpenAI input namespace: %w", stripErr) } - if !changed { + if out == nil { return body, nil } - _, _ = rebuilt.WriteString(input.Raw[copyFrom:]) - stripped, err := sjson.SetRawBytes(body, "input", rebuilt.Bytes()) - if err != nil { - return body, fmt.Errorf("replace OpenAI input after namespace deletion: %w", err) - } - return stripped, nil + out = append(out, input.Raw[copyFrom:]...) + out = append(out, body[inputEnd:]...) + return out, nil } func setOpenAIResponsesNamespaceNames(c *gin.Context, names map[string]apicompat.ResponsesNamespaceName) { diff --git a/backend/internal/service/openai_responses_namespace_benchmark_test.go b/backend/internal/service/openai_responses_namespace_benchmark_test.go index 9297354b0219..7cd84ff96602 100644 --- a/backend/internal/service/openai_responses_namespace_benchmark_test.go +++ b/backend/internal/service/openai_responses_namespace_benchmark_test.go @@ -10,7 +10,9 @@ import ( "github.com/tidwall/gjson" ) -func BenchmarkStripOpenAIResponsesInputNamespaces(b *testing.B) { +type stripFunc func(body []byte, keep bool) ([]byte, error) + +func benchmarkStripOpenAIResponsesInputNamespaces(b *testing.B, variant string, fn stripFunc) { for _, size := range []int{1 << 20, 8 << 20} { message := `{"type":"message","content":"` + strings.Repeat("x", size) + `"}` call := `{"type":"function_call","namespace":"files","name":"search"}` @@ -20,15 +22,16 @@ func BenchmarkStripOpenAIResponsesInputNamespaces(b *testing.B) { keep bool stripIndex int }{ + // tools 里带 namespace 声明、input 里没有:Codex 常态,入口预检查必然放行。 {"tools_only", message, false, -1}, {"nested_only", `{"content":{"namespace":"nested"}},` + message, false, -1}, {"keep_calls", call + "," + message, true, -1}, {"strip_first", call + "," + message, false, 0}, {"strip_last", message + "," + call, false, 1}, } { - b.Run(fmt.Sprintf("%s/%dMiB", tc.name, size>>20), func(b *testing.B) { + b.Run(fmt.Sprintf("%s/%s/%dMiB", variant, tc.name, size>>20), func(b *testing.B) { body := []byte(`{"tools":[{"type":"namespace","name":"files","tools":[]}],"input":[` + tc.input + `]}`) - out, err := stripOpenAIResponsesInputNamespaces(body, tc.keep) + out, err := fn(body, tc.keep) if err != nil { b.Fatal(err) } @@ -43,7 +46,7 @@ func BenchmarkStripOpenAIResponsesInputNamespaces(b *testing.B) { b.SetBytes(int64(len(body))) b.ResetTimer() for i := 0; i < b.N; i++ { - out, err = stripOpenAIResponsesInputNamespaces(body, tc.keep) + out, err = fn(body, tc.keep) if err != nil { b.Fatal(err) } @@ -53,3 +56,11 @@ func BenchmarkStripOpenAIResponsesInputNamespaces(b *testing.B) { } } } + +func BenchmarkStripOpenAIResponsesInputNamespaces(b *testing.B) { + benchmarkStripOpenAIResponsesInputNamespaces(b, "current", stripOpenAIResponsesInputNamespaces) +} + +func BenchmarkStripOpenAIResponsesInputNamespacesLegacy(b *testing.B) { + benchmarkStripOpenAIResponsesInputNamespaces(b, "legacy", legacyStripOpenAIResponsesInputNamespaces) +} diff --git a/backend/internal/service/openai_responses_namespace_equivalence_test.go b/backend/internal/service/openai_responses_namespace_equivalence_test.go new file mode 100644 index 000000000000..52f766d7dab3 --- /dev/null +++ b/backend/internal/service/openai_responses_namespace_equivalence_test.go @@ -0,0 +1,241 @@ +package service + +import ( + "bytes" + "fmt" + "strings" + "testing" + + "github.com/stretchr/testify/require" + "github.com/tidwall/gjson" + "github.com/tidwall/sjson" +) + +// legacyStripOpenAIResponsesInputNamespaces 是改动前的逐字副本,作为差分基准。 +func legacyStripOpenAIResponsesInputNamespaces(body []byte, keepToolCallNamespaces bool) ([]byte, error) { + if !bytes.Contains(body, []byte(`"namespace"`)) { + return body, nil + } + input := gjson.GetBytes(body, "input") + if !input.IsArray() { + return body, nil + } + + var rebuilt bytes.Buffer + changed := false + copyFrom := 0 + var stripErr error + input.ForEach(func(_, item gjson.Result) bool { + if !item.IsObject() || !item.Get("namespace").Exists() || + (keepToolCallNamespaces && isOpenAIResponsesToolCallItemType(item.Get("type").String())) { + return true + } + itemBody, err := sjson.DeleteBytes([]byte(item.Raw), "namespace") + if err != nil { + stripErr = err + return false + } + if !changed { + rebuilt.Grow(len(input.Raw)) + changed = true + } + itemStart := item.Index - input.Index + _, _ = rebuilt.WriteString(input.Raw[copyFrom:itemStart]) + _, _ = rebuilt.Write(itemBody) + copyFrom = itemStart + len(item.Raw) + return true + }) + if stripErr != nil { + return body, fmt.Errorf("delete OpenAI input namespace: %w", stripErr) + } + if !changed { + return body, nil + } + _, _ = rebuilt.WriteString(input.Raw[copyFrom:]) + stripped, err := sjson.SetRawBytes(body, "input", rebuilt.Bytes()) + if err != nil { + return body, fmt.Errorf("replace OpenAI input after namespace deletion: %w", err) + } + return stripped, nil +} + +type stripSnapshot struct { + err string + output string + unchanged bool // 是否原样返回了传入的 slice(两个实现都应如此) +} + +func stripSnapshotOf(out []byte, err error, body []byte) stripSnapshot { + snap := stripSnapshot{} + if err != nil { + snap.err = err.Error() + } + snap.output = string(out) + if len(out) == len(body) && len(body) > 0 && &out[0] == &body[0] { + snap.unchanged = true + } + if len(out) == 0 && len(body) == 0 { + snap.unchanged = true + } + return snap +} + +func stripBoth(t *testing.T, input string, keep bool) (stripSnapshot, stripSnapshot) { + t.Helper() + legacyBody := []byte(input) + legacyOut, legacyErr := legacyStripOpenAIResponsesInputNamespaces(legacyBody, keep) + + newBody := []byte(input) + newOut, newErr := stripOpenAIResponsesInputNamespaces(newBody, keep) + + return stripSnapshotOf(legacyOut, legacyErr, legacyBody), stripSnapshotOf(newOut, newErr, newBody) +} + +func TestStripOpenAIResponsesInputNamespacesMatchesLegacy(t *testing.T) { + escape := string(rune(92)) + cases := []string{ + ``, + `{}`, + `{"model":"gpt-5.5"}`, + // 无 namespace:入口预检查直接返回 + `{"input":[{"type":"message","content":"hi"}]}`, + // namespace 只在 tools 里(Codex 常态) + `{"tools":[{"type":"namespace","name":"image_gen"}],"input":[{"type":"message","content":"hi"}]}`, + // namespace 嵌套在 item 内容里,不是数组项的直接字段 + `{"input":[{"content":{"namespace":"nested"}}]}`, + `{"tools":[{"type":"namespace"}],"input":[{"content":{"namespace":"nested"}}]}`, + // 真正要改写 + `{"input":[{"type":"function_call","namespace":"files","name":"search"}]}`, + `{"input":[{"namespace":"files"},{"type":"message","content":"hi"}]}`, + `{"input":[{"type":"message","content":"hi"},{"namespace":"files"}]}`, + `{"input":[{"namespace":"a"},{"namespace":"b"},{"namespace":"c"}]}`, + `{"input":[{"namespace":null}]}`, + `{"input":[{"namespace":["x"]}]}`, + `{"input":[{"namespace":"files","namespace":"dup"}]}`, + // 工具调用项在 keep 模式下的区分 + `{"input":[{"type":"function_call","namespace":"files"}]}`, + `{"input":[{"type":"custom_tool_call","namespace":"files"}]}`, + `{"input":[{"type":"mcp_tool_call","namespace":"files"}]}`, + `{"input":[{"type":"tool_call","namespace":"files"}]}`, + `{"input":[{"type":"message","namespace":"files"}]}`, + `{"input":[{"type":"FUNCTION_CALL","namespace":"files"}]}`, + // 非对象 item + `{"input":["x",null,{"namespace":"files"},42]}`, + // input 不是数组 / 缺失 + `{"input":{"namespace":"x"}}`, + `{"input":"namespace"}`, + `{"input":null}`, + `{"namespace":"top"}`, + // 重复 input 键:两边都取第一个 + `{"input":[{"namespace":"first"}],"input":[{"namespace":"second"}]}`, + `{"input":[],"input":[{"namespace":"second"}]}`, + // 转义的键与值 + `{"` + escape + `u0069nput":[{"namespace":"files"}]}`, + `{"input":[{"namespace":"fi` + escape + `u006ces"}]}`, + // 大内容与 unicode + `{"input":[{"namespace":"files","content":"` + strings.Repeat("x", 4096) + `"},{"type":"message","content":"中文 😀"}]}`, + // item 内部同时有直接 namespace 与嵌套 namespace + `{"input":[{"namespace":"files","content":{"namespace":"nested"}}]}`, + // 非法 JSON + `{"input":[{"namespace":"files"}]`, + `{"input":[{"namespace":"files"},`, + // 根不是对象 + `[{"namespace":"files"}]`, + `"namespace"`, + } + + for _, tc := range cases { + for _, keep := range []bool{false, true} { + t.Run(fmt.Sprintf("%s/keep=%v", truncateForName(tc), keep), func(t *testing.T) { + want, got := stripBoth(t, tc, keep) + if !gjson.ValidBytes([]byte(tc)) { + // 畸形输入上 gjson.GetBytes 与 gjson.Parse 返回的区间不同: + // 前者会一路扫到结尾,后者遇到非法结构就停。本实现走后者,因此在 + // 无法解析的片段上不改写(更保守),只比较错误。 + require.Equal(t, want.err, got.err, "input=%q keep=%v", tc, keep) + return + } + require.Equal(t, want, got, "input=%q keep=%v", tc, keep) + }) + } + } +} + +func truncateForName(s string) string { + if len(s) > 40 { + return s[:40] + "..." + } + if s == "" { + return "empty" + } + return s +} + +// 组合随机:多个 item、namespace 位置随机、keep 随机。 +func TestStripOpenAIResponsesInputNamespacesMatchesLegacyRandomized(t *testing.T) { + items := []string{ + `{"type":"message","content":"hi"}`, + `{"namespace":"files"}`, + `{"type":"function_call","namespace":"files","name":"search"}`, + `{"type":"custom_tool_call","namespace":"files"}`, + `{"content":{"namespace":"nested"}}`, + `{"namespace":"files","content":"` + strings.Repeat("y", 200) + `"}`, + `{"namespace":null}`, + `"literal"`, + `42`, + `null`, + } + prefixes := []string{ + `{"input":[`, + `{"tools":[{"type":"namespace"}],"input":[`, + `{"metadata":{"user_id":"u"},"input":[`, + } + + seed := uint64(0x243f6a8885a308d3) + next := func() uint64 { + seed ^= seed << 13 + seed ^= seed >> 7 + seed ^= seed << 17 + return seed + } + + for i := 0; i < 3000; i++ { + n := int(next()%5) + 1 + parts := make([]string, 0, n) + for j := 0; j < n; j++ { + parts = append(parts, items[int(next()%uint64(len(items)))]) + } + body := prefixes[int(next()%uint64(len(prefixes)))] + strings.Join(parts, ",") + `]}` + keep := next()%2 == 0 + + want, got := stripBoth(t, body, keep) + require.Equal(t, want, got, "iteration=%d keep=%v body=%s", i, keep, body) + } +} + +// 畸形输入的行为差异有明确用例固定,避免后续误改: +func TestStripOpenAIResponsesInputNamespacesMalformedRootIsConservative(t *testing.T) { + const malformed = `0{"input"[{ "namespace"00` + out, err := stripOpenAIResponsesInputNamespaces([]byte(malformed), true) + require.NoError(t, err) + require.Equal(t, malformed, string(out), "改写在无法解析的片段上必须放弃") +} + +func FuzzStripOpenAIResponsesInputNamespaces(f *testing.F) { + f.Add([]byte(`{"input":[{"namespace":"files"}]}`), false) + f.Add([]byte(`{"tools":[{"type":"namespace"}],"input":[{"type":"message"}]}`), true) + f.Add([]byte(`{"input":[{"type":"function_call","namespace":"files"}]}`), true) + f.Add([]byte(`{"input":"namespace"}`), false) + f.Fuzz(func(t *testing.T, body []byte, keep bool) { + legacyBody := append([]byte(nil), body...) + newBody := append([]byte(nil), body...) + legacyOut, legacyErr := legacyStripOpenAIResponsesInputNamespaces(legacyBody, keep) + newOut, newErr := stripOpenAIResponsesInputNamespaces(newBody, keep) + require.Equal(t, fmt.Sprint(legacyErr), fmt.Sprint(newErr), "body=%q", body) + if legacyErr != nil || !gjson.ValidBytes(body) { + // 畸形输入两个 gjson API 的取值区间不同,见表驱动测试里的说明。 + return + } + require.Equal(t, string(legacyOut), string(newOut), "body=%q keep=%v", body, keep) + }) +} diff --git a/backend/internal/service/openai_responses_tool_schema.go b/backend/internal/service/openai_responses_tool_schema.go index 166589d91d8a..440a1b0a9de2 100644 --- a/backend/internal/service/openai_responses_tool_schema.go +++ b/backend/internal/service/openai_responses_tool_schema.go @@ -2,6 +2,7 @@ package service import ( "bytes" + "encoding/binary" "encoding/json" "errors" "fmt" @@ -86,7 +87,7 @@ func sanitizeOpenAIResponsesToolSchemaPatterns(body []byte) ([]byte, bool, error // oneOf/anyOf. Other missing types and nested property schemas are left // unchanged. func sanitizeOpenAIResponsesToolParameterTypes(body []byte) ([]byte, bool, error) { - if len(body) == 0 { + if len(body) == 0 || !openAIResponsesBodyMayNeedToolParameterRepair(body) { return body, false, nil } return sanitizeOpenAIResponsesToolSchemas(body, openAIResponsesToolSchemaOptions{ @@ -96,31 +97,85 @@ func sanitizeOpenAIResponsesToolParameterTypes(body []byte) ([]byte, bool, error }) } +var ( + openAIResponsesNullLiteral = []byte("null") + // Short needles on purpose: bytes.Contains switches to a much slower + // algorithm for longer needles (a quoted 7-byte key costs ~12x a 5-byte one) + // and these run on every request. + openAIResponsesOneOfHint = []byte("oneOf") + openAIResponsesAnyOfHint = []byte("anyOf") + openAIResponsesRegexGroupBytes = []byte("(?") + openAIResponsesJSONUnicodeEscape = []byte(`\u`) + // Any escaped spelling of an ASCII letter is \u00XX, so this also stands in + // for a union keyword written that way. + openAIResponsesUnicodeLetterEscape = []byte(`\u00`) + openAIResponsesJSONBackslashPair = []byte(`\\`) +) + +// openAIResponsesBodyMayNeedToolParameterRepair is a necessary condition for +// sanitizeOpenAIResponsesToolParameterTypes to change anything. +// +// Every repair reads either a literal null value (type / required), which the +// JSON grammar cannot spell with escapes, or a oneOf/anyOf union. The union +// repair first accepts a parameters object that contains "oneOf", "anyOf" or +// any backslash at all, then decides on the decoded keys - so a union keyword +// written as "one\u004ff" also qualifies. Any escaped spelling of an ASCII +// letter is a \u00XX escape, which is what the last needle covers. +func openAIResponsesBodyMayNeedToolParameterRepair(body []byte) bool { + return bytes.Contains(body, openAIResponsesNullLiteral) || + bytes.Contains(body, openAIResponsesOneOfHint) || + bytes.Contains(body, openAIResponsesAnyOfHint) || + bytes.Contains(body, openAIResponsesUnicodeLetterEscape) +} + +// openAIResponsesBodyMayContainUnsupportedRegex is a necessary condition for +// sanitizeOpenAIResponsesToolSchemaPatterns to change anything. It is +// deliberately much narrower than "the body contains a parenthesis": prose, +// descriptions and code samples contain those constantly, so that test passed +// on nearly every request and made this pass walk every request body. func openAIResponsesBodyMayContainUnsupportedRegex(body []byte) bool { - // An opening parenthesis may be literal or encoded as JSON's canonical - // Unicode escape. A backslash inside a JSON string is escaped as \\, so the - // sequence \\ exposes the decoded regex escape without parsing. - if bytes.Contains(body, []byte("(")) || bytes.Contains(body, []byte(`\u0028`)) || - bytes.Contains(body, []byte(`\u005c`)) || bytes.Contains(body, []byte(`\u005C`)) { + // hasUnsupportedOpenAIRegexPattern 只有三种触发方式,这里逐一给出必要字节条件: + // + // 1. 一个反斜杠后跟了非白名单的字母; + // 2. 字符串以反斜杠结尾; + // 3. 分组语法 "(?"。 + // + // 前两种都需要解码后的反斜杠,而 JSON 里它只能写成 "\\" 或 \u005c。 + // 第三种里 "(" 和 "?" 各自都可能是转义写法。 + if bytes.Contains(body, openAIResponsesJSONBackslashPair) { return true } - for i := 0; i+2 < len(body); i++ { - if body[i] != '\\' || body[i+1] != '\\' { - continue - } - escaped := body[i+2] - if isASCIILetter(escaped) && !pythonRegexEscapeAllowed(escaped) { - return true - } + if bytes.Contains(body, openAIResponsesRegexGroupBytes) { + return true } - return false + if !bytes.Contains(body, openAIResponsesJSONUnicodeEscape) { + return false + } + // 任何 \u00XX 转义都可能写成上述三种形态里的括号、问号或反斜杠。 + return bytes.Contains(body, openAIResponsesUnicodeLetterEscape) +} + +// openAIResponsesJSONPatternIsUnsupported reports whether a JSON string span +// (quotes included) decodes to a pattern Python re rejects. Spans without an +// escape - the overwhelming majority - are checked in place, so the common +// "many tools, no bad patterns" body neither decodes nor allocates per pattern. +func openAIResponsesJSONPatternIsUnsupported(raw []byte) bool { + if len(raw) < 2 || raw[0] != '"' || raw[len(raw)-1] != '"' { + return false + } + inner := raw[1 : len(raw)-1] + if bytes.IndexByte(inner, '\\') < 0 { + return hasUnsupportedOpenAIRegexPattern(inner) + } + decoded, err := decodeOpenAIResponsesJSONString(raw) + return err == nil && hasUnsupportedOpenAIRegexPattern([]byte(decoded)) } // hasUnsupportedOpenAIRegexPattern reports whether Python re rejects pattern. // OpenAI validates tool-schema patterns with Python re, which supports neither // lookaround nor the .NET/Java (?...) and (?'name'...) group forms, and // reserves unknown ASCII-letter escapes such as \p and \R. -func hasUnsupportedOpenAIRegexPattern(pattern string) bool { +func hasUnsupportedOpenAIRegexPattern(pattern []byte) bool { inCharacterClass := false for i := 0; i < len(pattern); i++ { switch pattern[i] { @@ -231,10 +286,10 @@ func sanitizeOpenAIResponsesToolSchemas( if p.pos != len(body) { return nil, false, fmt.Errorf("sanitize OpenAI Responses tool schemas: trailing data at byte %d", p.pos) } - if !json.Valid(body) { - return nil, false, fmt.Errorf("sanitize OpenAI Responses tool schemas: invalid JSON") - } if len(p.edits) == 0 { + // The walk above already rejected everything encoding/json rejects, so a + // clean parse needs no second full-body validation. When there are edits + // the result is validated after patching. return body, false, nil } return applyOpenAIResponsesToolSchemaEdits(body, p.edits) @@ -269,7 +324,11 @@ func (p *openAIResponsesToolSchemaParser) parseValue( case "additional_tools": context = openAIResponsesToolSchemaToolCarrier default: - context = openAIResponsesToolSchemaSkip + // Nothing inside this item can be edited, so the probe walk is the + // whole job: reuse where it stopped instead of walking the item a + // second time just to skip it. Messages dominate input history. + p.pos = probe.pos + return nil } } switch p.body[p.pos] { @@ -319,7 +378,7 @@ func (p *openAIResponsesToolSchemaParser) parseObject( if err != nil { return err } - key := p.body[keyStart:keyEnd] + key := newOpenAIResponsesJSONKey(p.body[keyStart:keyEnd]) p.skipWhitespace() if !p.consume(':') { return p.syntaxError("expected colon") @@ -335,26 +394,26 @@ func (p *openAIResponsesToolSchemaParser) parseObject( p.skipWhitespace() deleteMember := false - if context == openAIResponsesToolSchemaTypeProbe && openAIResponsesJSONStringEquals(key, "type") { + if context == openAIResponsesToolSchemaTypeProbe && key.is("type") { if value, ok := decodeOpenAIResponsesJSONStringValue(p.body[valueStart:valueEnd]); ok { p.probeType = strings.TrimSpace(value) } } if (context == openAIResponsesToolSchemaTool || context == openAIResponsesToolSchemaFunction) && - openAIResponsesJSONStringEquals(key, "parameters") { + key.is("parameters") { parameterCount++ parameterValueStart = valueStart parameterValueEnd = valueEnd } if p.options.removeUnsupportedRegexPatterns { - if context == openAIResponsesToolSchema && openAIResponsesJSONStringEquals(key, "patternProperties") { + if context == openAIResponsesToolSchema && key.is("patternProperties") { // The child parser records how many keys it had to remove. A // closed sibling object must be reopened in that case. if p.patternPropertiesDrops[valueStart] > 0 { lostPatternProperty = true } } - if context == openAIResponsesToolSchema && openAIResponsesJSONStringEquals(key, "additionalProperties") && + if context == openAIResponsesToolSchema && key.is("additionalProperties") && !bytes.Equal(p.body[valueStart:valueEnd], []byte("true")) { // Defer the edit: patternProperties may appear after this // member, and only actual key removal requires reopening. @@ -364,15 +423,14 @@ func (p *openAIResponsesToolSchemaParser) parseObject( replacement: "true", }) } - if context == openAIResponsesToolSchema && openAIResponsesJSONStringEquals(key, "pattern") { - if pattern, ok := decodeOpenAIResponsesJSONStringValue(p.body[valueStart:valueEnd]); ok && hasUnsupportedOpenAIRegexPattern(pattern) { + if context == openAIResponsesToolSchema && key.is("pattern") { + if openAIResponsesJSONPatternIsUnsupported(p.body[valueStart:valueEnd]) { deleteMember = true } } - if context == openAIResponsesToolSchemaPatternPropertiesMap { - if pattern, ok := decodeOpenAIResponsesJSONStringValue(key); ok && hasUnsupportedOpenAIRegexPattern(pattern) { - deleteMember = true - } + if context == openAIResponsesToolSchemaPatternPropertiesMap && + openAIResponsesJSONPatternIsUnsupported(key.raw) { + deleteMember = true } } // JSON Schema requires "required" to be an array. Clients occasionally emit @@ -380,11 +438,11 @@ func (p *openAIResponsesToolSchemaParser) parseObject( // "required" is the semantic equivalent of an empty one, so dropping the // member preserves the client's intent while satisfying strict validators. if context == openAIResponsesToolSchema && p.options.dropNullRequired && - openAIResponsesJSONStringEquals(key, "required") && + key.is("required") && bytes.Equal(p.body[valueStart:valueEnd], []byte("null")) { deleteMember = true } - if context == openAIResponsesToolSchema && schemaRoot && openAIResponsesJSONStringEquals(key, "type") { + if context == openAIResponsesToolSchema && schemaRoot && key.is("type") { // Duplicate JSON keys have parser-dependent effective values. Repair a // root type only when it is unique rather than choosing a winner and // potentially changing the client's effective schema. @@ -570,52 +628,95 @@ func (p *openAIResponsesToolSchemaParser) parseArray( } } +// openAIResponsesJSONKey is one object member name, prepared for repeated +// comparison. parseObject tests the same key against a dozen candidate names, +// so the escape question is answered once here instead of rescanning the span +// on every comparison. +type openAIResponsesJSONKey struct { + raw []byte + inner []byte + plain bool +} + +func newOpenAIResponsesJSONKey(raw []byte) openAIResponsesJSONKey { + key := openAIResponsesJSONKey{raw: raw} + if len(raw) < 2 || raw[0] != '"' || raw[len(raw)-1] != '"' { + return key + } + key.inner = raw[1 : len(raw)-1] + key.plain = bytes.IndexByte(key.inner, '\\') < 0 + return key +} + +// is reports whether the member name equals want. A key carrying an escape +// decodes to fewer bytes than it occupies, so an escape-free span can be +// compared in place; only escaped spellings need to be decoded. +func (k openAIResponsesJSONKey) is(want string) bool { + if k.inner == nil { + return false + } + if k.plain { + return len(k.inner) == len(want) && string(k.inner) == want + } + decoded, err := decodeOpenAIResponsesJSONString(k.raw) + return err == nil && decoded == want +} + +func (k openAIResponsesJSONKey) isAny(candidates ...string) bool { + for _, candidate := range candidates { + if k.is(candidate) { + return true + } + } + return false +} + func openAIResponsesToolSchemaChildContext( - context openAIResponsesToolSchemaContext, key []byte, + context openAIResponsesToolSchemaContext, key openAIResponsesJSONKey, ) (openAIResponsesToolSchemaContext, bool) { switch context { case openAIResponsesToolSchemaDocument: switch { - case openAIResponsesJSONStringEquals(key, "tools"): + case key.is("tools"): return openAIResponsesToolSchemaTools, false - case openAIResponsesJSONStringEquals(key, "input"): + case key.is("input"): return openAIResponsesToolSchemaInput, false } case openAIResponsesToolSchemaTool: switch { // Anthropic Messages carries the same JSON Schema under input_schema, so // /v1/messages tools must reach the sanitizer too. - case openAIResponsesJSONStringMatchesAny(key, "parameters", "input_schema"): + case key.isAny("parameters", "input_schema"): return openAIResponsesToolSchema, true - case openAIResponsesJSONStringEquals(key, "function"): + case key.is("function"): return openAIResponsesToolSchemaFunction, false - case openAIResponsesJSONStringEquals(key, "tools"): + case key.is("tools"): return openAIResponsesToolSchemaTools, false } case openAIResponsesToolSchemaToolCarrier: - if openAIResponsesJSONStringEquals(key, "tools") { + if key.is("tools") { return openAIResponsesToolSchemaTools, false } case openAIResponsesToolSchemaFunction: switch { - case openAIResponsesJSONStringEquals(key, "parameters"): + case key.is("parameters"): return openAIResponsesToolSchema, true - case openAIResponsesJSONStringEquals(key, "tools"): + case key.is("tools"): return openAIResponsesToolSchemaTools, false } case openAIResponsesToolSchema: switch { - case openAIResponsesJSONStringMatchesAny(key, + case key.isAny( "additionalProperties", "additionalItems", "contains", "not", "if", "then", "else", "propertyNames", "unevaluatedProperties", "unevaluatedItems", "contentSchema"): return openAIResponsesToolSchema, false - case openAIResponsesJSONStringEquals(key, "items"): + case key.is("items"): return openAIResponsesToolSchemaOrArray, false - case openAIResponsesJSONStringMatchesAny(key, "anyOf", "oneOf", "allOf", "prefixItems"): + case key.isAny("anyOf", "oneOf", "allOf", "prefixItems"): return openAIResponsesToolSchemaArray, false - case openAIResponsesJSONStringEquals(key, "patternProperties"): + case key.is("patternProperties"): return openAIResponsesToolSchemaPatternPropertiesMap, false - case openAIResponsesJSONStringMatchesAny(key, + case key.isAny( "properties", "$defs", "definitions", "dependentSchemas", "dependencies"): return openAIResponsesToolSchemaMap, false } @@ -631,14 +732,14 @@ func (p *openAIResponsesToolSchemaParser) parseString() (int, int, error) { } start := p.pos p.pos++ - const special = "\"\\\x00\x01\x02\x03\x04\x05\x06\x07\x08\x09\x0a\x0b\x0c\x0d\x0e\x0f\x10\x11\x12\x13\x14\x15\x16\x17\x18\x19\x1a\x1b\x1c\x1d\x1e\x1f" - for p.pos < len(p.body) { - next := bytes.IndexAny(p.body[p.pos:], special) - if next < 0 { - p.pos = len(p.body) - break + for { + // Skip the plain run in word-sized steps: string payloads dominate large + // request bodies, and a byte-at-a-time walk here was the bulk of the + // cost of the whole sanitizer. + p.pos += openAIResponsesJSONPlainStringRun(p.body[p.pos:]) + if p.pos >= len(p.body) { + return 0, 0, p.syntaxError("unterminated string") } - p.pos += next switch p.body[p.pos] { case '"': p.pos++ @@ -659,17 +760,51 @@ func (p *openAIResponsesToolSchemaParser) parseString() (int, int, error) { } } p.pos += 5 - continue case '"', '\\', '/', 'b', 'f', 'n', 'r', 't': p.pos++ default: return 0, 0, p.syntaxError("invalid string escape") } default: + // Everything else that ends the plain run is a control byte. return 0, 0, p.syntaxError("control character in string") } } - return 0, 0, p.syntaxError("unterminated string") +} + +const ( + openAIResponsesSWARByteOnes = 0x0101010101010101 + openAIResponsesSWARHighBits = 0x8080808080808080 +) + +// openAIResponsesJSONWordHasZeroByte reports whether any byte of word is 0x00. +func openAIResponsesJSONWordHasZeroByte(word uint64) bool { + return (word-openAIResponsesSWARByteOnes)&^word&openAIResponsesSWARHighBits != 0 +} + +// openAIResponsesJSONPlainStringRun returns the length of the leading run of +// bytes in bulk that can be copied through a JSON string verbatim: no closing +// quote, no escape backslash and no control byte. Those three are exactly the +// bytes parseString has to stop at. +func openAIResponsesJSONPlainStringRun(bulk []byte) int { + offset := 0 + for ; offset+8 <= len(bulk); offset += 8 { + word := binary.LittleEndian.Uint64(bulk[offset:]) + // '"' and '\\' are found by zero-byte detection on the XOR, which flags + // a whole word at once; (value & 0xE0) == 0 means value < 0x20. + if openAIResponsesJSONWordHasZeroByte(word^0x2222222222222222) || + openAIResponsesJSONWordHasZeroByte(word^0x5c5c5c5c5c5c5c5c) || + openAIResponsesJSONWordHasZeroByte(word&0xe0e0e0e0e0e0e0e0) { + break + } + } + for ; offset < len(bulk); offset++ { + value := bulk[offset] + if value == '"' || value == '\\' || value < 0x20 { + break + } + } + return offset } func isOpenAIResponsesJSONHexDigit(value byte) bool { @@ -771,26 +906,6 @@ func decodeOpenAIResponsesJSONString(raw []byte) (string, error) { return decoded, nil } -func openAIResponsesJSONStringEquals(raw []byte, want string) bool { - if len(raw) < 2 || raw[0] != '"' || raw[len(raw)-1] != '"' { - return false - } - if !bytes.Contains(raw, []byte{'\\'}) { - return bytes.Equal(raw[1:len(raw)-1], []byte(want)) - } - decoded, err := decodeOpenAIResponsesJSONString(raw) - return err == nil && decoded == want -} - -func openAIResponsesJSONStringMatchesAny(raw []byte, candidates ...string) bool { - for _, candidate := range candidates { - if openAIResponsesJSONStringEquals(raw, candidate) { - return true - } - } - return false -} - func decodeOpenAIResponsesJSONStringValue(raw []byte) (string, bool) { if len(raw) < 2 || raw[0] != '"' || raw[len(raw)-1] != '"' { return "", false diff --git a/backend/internal/service/openai_responses_tool_schema_benchmark_test.go b/backend/internal/service/openai_responses_tool_schema_benchmark_test.go new file mode 100644 index 000000000000..9d775d22c2d8 --- /dev/null +++ b/backend/internal/service/openai_responses_tool_schema_benchmark_test.go @@ -0,0 +1,129 @@ +package service + +import ( + "fmt" + "strings" + "testing" +) + +// buildToolSchemaBenchmarkBody 造一份贴近真实 Codex 请求的 body:小 tools 数组 + +// 大 input 历史。description 里带括号,因为真实工具的说明几乎都有。 +func buildToolSchemaBenchmarkBody(targetBytes, tools int, withLookaround bool) []byte { + var sb strings.Builder + sb.Grow(targetBytes + 4096) + write := func(s string) { _, _ = sb.WriteString(s) } + write(`{"model":"gpt-5.6","stream":true,"instructions":"You are Codex, a coding agent.","tools":[`) + for i := 0; i < tools; i++ { + if i > 0 { + write(",") + } + pattern := "" + if withLookaround && i == 0 { + pattern = `,"pattern":"(?=x).*"` + } + write(fmt.Sprintf( + `{"type":"function","name":"tool_%d","description":"Runs a shell command (supports pipes).","parameters":{"type":"object","properties":{"query":{"type":"string"%s},"limit":{"type":"integer","minimum":1}},"required":["query"]}}`, + i, pattern)) + } + write(`],"input":[`) + item := `{"type":"message","role":"user","content":[{"type":"input_text","text":"` + strings.Repeat("x", 4000) + `"}]}` + for i := 0; sb.Len() < targetBytes; i++ { + if i > 0 { + write(",") + } + write(item) + } + write(`]}`) + return []byte(sb.String()) +} + +// ungated 是改动前入口在这类 body 上的实际走向:旧的预检查是「body 里有 (」, +// 而工具说明几乎都带括号,所以请求无一例外走整趟解析。 +func benchmarkToolSchemaEntry( + b *testing.B, body []byte, + ungated func([]byte) ([]byte, bool, error), + gated func([]byte) ([]byte, bool, error), +) { + b.Helper() + b.Run("ungated", func(b *testing.B) { + b.SetBytes(int64(len(body))) + b.ReportAllocs() + for range b.N { + _, _, _ = ungated(body) + } + }) + b.Run("gated", func(b *testing.B) { + b.SetBytes(int64(len(body))) + b.ReportAllocs() + for range b.N { + _, _, _ = gated(body) + } + }) +} + +func BenchmarkSanitizeOpenAIResponsesToolSchemaPatternsClean1MiB(b *testing.B) { + body := buildToolSchemaBenchmarkBody(1<<20, 30, false) + benchmarkToolSchemaEntry(b, body, + func(in []byte) ([]byte, bool, error) { + return sanitizeOpenAIResponsesToolSchemas(in, openAIResponsesToolSchemaOptions{removeUnsupportedRegexPatterns: true}) + }, + sanitizeOpenAIResponsesToolSchemaPatterns, + ) +} + +func BenchmarkSanitizeOpenAIResponsesToolParameterTypesClean1MiB(b *testing.B) { + body := buildToolSchemaBenchmarkBody(1<<20, 30, false) + benchmarkToolSchemaEntry(b, body, + func(in []byte) ([]byte, bool, error) { + return sanitizeOpenAIResponsesToolSchemas(in, openAIResponsesToolSchemaOptions{ + replaceNullParameterTypes: true, + injectObjectUnionRootObjectType: true, + dropNullRequired: true, + }) + }, + sanitizeOpenAIResponsesToolParameterTypes, + ) +} + +func BenchmarkOpenAIResponsesToolSchemaGates(b *testing.B) { + body := buildToolSchemaBenchmarkBody(1<<20, 30, false) + b.Run("unsupported_regex", func(b *testing.B) { + b.SetBytes(int64(len(body))) + for range b.N { + _ = openAIResponsesBodyMayContainUnsupportedRegex(body) + } + }) + b.Run("parameter_repair", func(b *testing.B) { + b.SetBytes(int64(len(body))) + for range b.N { + _ = openAIResponsesBodyMayNeedToolParameterRepair(body) + } + }) +} + +// 字符串扫描是解析里最重的一段:请求体的大头是长内容字符串。 +func BenchmarkOpenAIResponsesJSONStringScan(b *testing.B) { + body := []byte(`"` + strings.Repeat("abcdefgh", 1<<14) + `"`) + b.Run("legacy", func(b *testing.B) { + b.SetBytes(int64(len(body))) + for range b.N { + _, _, _, _ = legacyParseOpenAIResponsesJSONString(body, 0) + } + }) + b.Run("current", func(b *testing.B) { + b.SetBytes(int64(len(body))) + for range b.N { + _ = currentParseOpenAIResponsesJSONString(body, 0) + } + }) +} + +// 平台入口就是三个调用点(HTTP 转发、WS 归一化、/v1/messages 转换)实际走的路径。 +func BenchmarkSanitizeOpenAIResponsesToolSchemasForPlatformClean1MiB(b *testing.B) { + body := buildToolSchemaBenchmarkBody(1<<20, 30, false) + b.SetBytes(int64(len(body))) + b.ReportAllocs() + for range b.N { + _, _, _ = sanitizeOpenAIResponsesToolSchemasForPlatform(body, PlatformOpenAI) + } +} diff --git a/backend/internal/service/openai_responses_tool_schema_scan_test.go b/backend/internal/service/openai_responses_tool_schema_scan_test.go new file mode 100644 index 000000000000..f98a80b4d7b0 --- /dev/null +++ b/backend/internal/service/openai_responses_tool_schema_scan_test.go @@ -0,0 +1,334 @@ +package service + +import ( + "encoding/json" + "fmt" + "strings" + "testing" + "unicode/utf8" + + "github.com/stretchr/testify/require" +) + +// legacyParseOpenAIResponsesJSONString is the byte-at-a-time scanner this file +// replaced. It stays here as the differential baseline for parseString. +func legacyParseOpenAIResponsesJSONString(body []byte, pos int) (int, int, string, int) { + if pos >= len(body) || body[pos] != '"' { + return 0, 0, "expected string", pos + } + start := pos + pos++ + for pos < len(body) { + switch body[pos] { + case '"': + pos++ + return start, pos, "", 0 + case '\\': + pos++ + if pos >= len(body) { + return 0, 0, "unterminated string escape", pos + } + switch body[pos] { + case 'u': + if pos+4 >= len(body) { + return 0, 0, "short unicode escape", pos + } + for _, digit := range body[pos+1 : pos+5] { + if !isOpenAIResponsesJSONHexDigit(digit) { + return 0, 0, "invalid unicode escape", pos + } + } + pos += 5 + continue + case '"', '\\', '/', 'b', 'f', 'n', 'r', 't': + pos++ + default: + return 0, 0, "invalid string escape", pos + } + default: + if body[pos] < 0x20 { + return 0, 0, "control character in string", pos + } + pos++ + } + } + return 0, 0, "unterminated string", pos +} + +type stringScanResult struct { + start, end int + err string + errPos int +} + +func currentParseOpenAIResponsesJSONString(body []byte, pos int) stringScanResult { + p := openAIResponsesToolSchemaParser{body: body, pos: pos} + start, end, err := p.parseString() + if err != nil { + message, errPos := splitOpenAIResponsesToolSchemaError(err) + return stringScanResult{err: message, errPos: errPos} + } + return stringScanResult{start: start, end: end} +} + +func splitOpenAIResponsesToolSchemaError(err error) (string, int) { + text := err.Error() + const prefix = "sanitize OpenAI Responses tool schemas: " + text = strings.TrimPrefix(text, prefix) + at := strings.LastIndex(text, " at byte ") + if at < 0 { + return text, -1 + } + var pos int + if _, scanErr := fmt.Sscanf(text[at+len(" at byte "):], "%d", &pos); scanErr != nil { + return text, -1 + } + return text[:at], pos +} + +func TestOpenAIResponsesToolSchemaParseStringMatchesLegacy(t *testing.T) { + escape := string(rune(92)) + cases := []string{ + `""`, + `"abc"`, + `"a b c"`, + `"` + strings.Repeat("x", 64) + `"`, + `"` + strings.Repeat("x", 63) + `"`, // exercises the 8-byte tail + `"` + strings.Repeat("x", 65) + `"`, + `"a\"b"`, + `"a\\b"`, + `"a\/b"`, + `"` + escape + `u00e9"`, + `"` + escape + `uD83D` + escape + `uDE00"`, + `"` + escape + `u00E9"`, + // 控制字符 + "\"a\nb\"", + "\"a\tb\"", + "\"a\x00b\"", + "\"a\x1fb\"", + "\"a\x7fb\"", // DEL 是合法 JSON + // 非法转义 / 截断 + `"a\qb"`, + `"a\u12"`, + `"a\u12zz"`, + `"a\u`, + `"a\`, + `"unterminated`, + `"`, + ``, + `abc`, + // 多字节 UTF-8 + `"中文 😀"`, + `"` + strings.Repeat("中", 40) + `"`, + } + + for _, tc := range cases { + for _, pos := range []int{0, 1} { + body := []byte(tc) + if pos == 1 { + body = append([]byte("x"), body...) + } + wantStart, wantEnd, wantErr, wantErrPos := legacyParseOpenAIResponsesJSONString(body, pos) + got := currentParseOpenAIResponsesJSONString(body, pos) + require.Equal(t, stringScanResult{start: wantStart, end: wantEnd, err: wantErr, errPos: wantErrPos}, got, + "input=%q pos=%d", tc, pos) + } + } +} + +func FuzzOpenAIResponsesToolSchemaParseString(f *testing.F) { + f.Add([]byte(`"abc"`), 0) + f.Add([]byte(`"a\"b"`), 0) + f.Add([]byte{'"', 'a', '\n', '"'}, 0) + f.Add([]byte(`"`), 0) + f.Add([]byte(`x"aé"`), 1) + f.Fuzz(func(t *testing.T, body []byte, pos int) { + if pos < 0 || pos > len(body) { + return + } + wantStart, wantEnd, wantErr, wantErrPos := legacyParseOpenAIResponsesJSONString(body, pos) + got := currentParseOpenAIResponsesJSONString(body, pos) + require.Equal(t, stringScanResult{start: wantStart, end: wantEnd, err: wantErr, errPos: wantErrPos}, got, + "body=%q pos=%d", body, pos) + }) +} + +// 探测走完的终点必须与「跳过」走完的终点一致,探针结果才能被当作跳过复用。 +func TestOpenAIResponsesToolSchemaInputItemSkipMatchesProbe(t *testing.T) { + values := []string{ + `{"type":"message","role":"user","content":[{"type":"input_text","text":"hi"}]}`, + `{"type":"function","name":"x","parameters":{"type":"object"}}`, + `{"type":"function_call","arguments":"{}"}`, + `{"type":"custom","name":"x"}`, + `{"type":"tool_search"}`, + `{"type":"namespace","tools":[]}`, + `{"type":"additional_tools","tools":[{"type":"namespace"}]}`, + `{"type":"\\u0066unction","parameters":{"type":"null"}}`, + `{"type": "message" , "content" : [ 1 , 2 , {"a":null} ] }`, + `{}`, + `{"a":[{"b":[{"c":"d"}]}]}`, + `{"type":"message","content":"\\u0000\\u001f"}`, + } + for _, value := range values { + body := []byte(value) + probe := openAIResponsesToolSchemaParser{body: body, pos: 0} + require.NoError(t, probe.parseValue(openAIResponsesToolSchemaTypeProbe, false, 0), "value=%s", value) + + skip := openAIResponsesToolSchemaParser{body: body, pos: 0} + require.NoError(t, skip.parseValue(openAIResponsesToolSchemaSkip, false, 0), "value=%s", value) + + require.Equal(t, skip.pos, probe.pos, "value=%s", value) + require.Equal(t, len(body), probe.pos, "value=%s", value) + } +} + +// 解析器接受的 body 必须也是 encoding/json 认可的有效 JSON——否则去掉改写前的 +// json.Valid 预检查就会放过畸形请求。 +func TestOpenAIResponsesToolSchemaParserAcceptsOnlyValidJSON(t *testing.T) { + corpus := append(openAIResponsesToolSchemaGateCorpus(), []string{ + `{}`, `[]`, `null`, `0`, `""`, `{"a":1}`, `[1,2,3]`, + }...) + for _, body := range corpus { + p := openAIResponsesToolSchemaParser{body: []byte(body)} + err := p.parseValue(openAIResponsesToolSchemaDocument, false, 0) + if err != nil { + continue + } + p.skipWhitespace() + if p.pos != len(body) { + continue + } + require.True(t, json.Valid([]byte(body)), "解析器接受了 encoding/json 拒绝的输入: %q", body) + } +} + +func FuzzOpenAIResponsesToolSchemaParserAcceptsOnlyValidJSON(f *testing.F) { + for _, seed := range []string{ + `{"tools":[{"type":"function","parameters":{"type":"null"}}]}`, + `{"a":1,"b":[true,null,"x"]}`, + `0{"input"[{ "namespace"00`, + `{"a":01}`, + `{"a":"\u12zz"}`, + `{"a":1} trailing`, + } { + f.Add([]byte(seed)) + } + f.Fuzz(func(t *testing.T, body []byte) { + if !utf8.Valid(body) { + return // 入口先做 utf8 校验,这里只看解析器本身 + } + p := openAIResponsesToolSchemaParser{body: body} + if err := p.parseValue(openAIResponsesToolSchemaDocument, false, 0); err != nil { + return + } + p.skipWhitespace() + if p.pos != len(body) { + return + } + require.True(t, json.Valid(body), "解析器接受了 encoding/json 拒绝的输入: %q", body) + }) +} + +// openAIResponsesToolSchemaGateCorpus 覆盖两个门控必须放行的每一种写法。 +func openAIResponsesToolSchemaGateCorpus() []string { + escape := string(rune(92)) + pattern := func(p string) string { + return `{"tools":[{"type":"function","name":"f","parameters":{"type":"object","properties":{"q":{"type":"string","pattern":"` + p + `"}}}}]}` + } + return []string{ + // —— 非法正则 —— + pattern(`(?=x)`), + pattern(`(?!x)`), + pattern(`(?<=x)`), + pattern(`(?x)`), + pattern(`(?'name'x)`), + pattern(`a` + escape + escape + `p{L}`), + pattern(`a` + escape + escape + `R`), + pattern(`a` + escape + `u005cp`), + pattern(`a` + escape + `u0028` + escape + `u003f=x)`), + pattern(`a` + escape + `u0028?=x)`), + pattern(`a(` + escape + `u003f=x)`), + pattern(`a` + escape + escape + escape + escape + `d`), + // patternProperties 的键 + `{"tools":[{"type":"function","parameters":{"type":"object","patternProperties":{"(?=x)":{"type":"string"}}}}]}`, + `{"tools":[{"type":"function","parameters":{"type":"object","patternProperties":{"` + escape + `u0028` + escape + `u003f=x)":{"type":"string"}}}}]}`, + // —— 参数类型修复 —— + `{"tools":[{"type":"function","parameters":{"type":null}}]}`, + `{"tools":[{"type":"function","parameters":{"required":null}}]}`, + `{"tools":[{"type":"function","parameters":{"oneOf":[{"type":"object"},{"type":"object"}]}}]}`, + `{"tools":[{"type":"function","parameters":{"anyOf":[{"properties":{}}]}}]}`, + // union 关键字用 \u004f / \u0066 转义写出:字面 needle 不命中,但 + // openAIMissingRootObjectUnionTypeEdit 会因为 raw 里有反斜杠而继续解析。 + `{"tools":[{"type":"function","name":"other","parameters":{"one` + escape + `u004ff":[{"type":"object"}]}}]}`, + `{"tools":[{"type":"function","name":"other","parameters":{"anyO` + escape + `u0066":[{"type":"object"}]}}]}`, + `{"messages":[{"role":"user","content":"x","input_schema":{"type":null}}]}`, + // —— 合法正则不应触发修复,但门控允许放行 —— + pattern(`^a+$`), + pattern(`a` + escape + escape + `d{3}`), + `{"input":[{"type":"message","content":"a null mention (and parens)"}]}`, + } +} + +// 门控必须是「会改写」的必要条件:只要消毒真的改了 body,门控就必须放行。 +// 反向不成立——门控故意留了余量(例如 body 里出现任何 \\ 就放行),因为算出 +// 精确条件比放行一两次解析更贵也更易错。 +func requireOpenAIResponsesToolSchemaPatternGateCovers(t *testing.T, body []byte) { + t.Helper() + _, changed, err := sanitizeOpenAIResponsesToolSchemas(body, + openAIResponsesToolSchemaOptions{removeUnsupportedRegexPatterns: true}) + if err != nil { + return // 解析失败的 body 不会被改写,错误本身交给既有用例覆盖 + } + if changed { + require.True(t, openAIResponsesBodyMayContainUnsupportedRegex(body), + "改写已发生但正则门控放过了: %q", body) + } +} + +// 类型修复原本没有门控,同样用绝对不变量:只要真的改了 body,门控就必须放行。 +func requireOpenAIResponsesToolParameterGateCovers(t *testing.T, body []byte) { + t.Helper() + _, changed, err := sanitizeOpenAIResponsesToolSchemas(body, openAIResponsesToolSchemaOptions{ + replaceNullParameterTypes: true, + injectObjectUnionRootObjectType: true, + dropNullRequired: true, + }) + if err != nil { + return + } + if changed { + require.True(t, openAIResponsesBodyMayNeedToolParameterRepair(body), + "改写已发生但类型门控放过了: %q", body) + } +} + +// 门控必须真的能挡住普通请求,否则上面那条不变量会被「永远返回 true」蒙混过关。 +func TestOpenAIResponsesToolSchemaGatesSkipOrdinaryTraffic(t *testing.T) { + clean := buildToolSchemaBenchmarkBody(1<<20, 30, false) + require.False(t, openAIResponsesBodyMayContainUnsupportedRegex(clean), + "普通的 1 MiB 请求不该进入正则 pattern 消毒") + require.False(t, openAIResponsesBodyMayNeedToolParameterRepair(clean), + "普通的 1 MiB 请求不该进入参数类型修复") +} + +func TestOpenAIResponsesToolSchemaGatesAreNecessary(t *testing.T) { + for _, body := range openAIResponsesToolSchemaGateCorpus() { + raw := []byte(body) + requireOpenAIResponsesToolSchemaPatternGateCovers(t, raw) + requireOpenAIResponsesToolParameterGateCovers(t, raw) + } +} + +func FuzzOpenAIResponsesToolSchemaGatesAreNecessary(f *testing.F) { + for _, seed := range openAIResponsesToolSchemaGateCorpus() { + f.Add([]byte(seed)) + } + f.Fuzz(func(t *testing.T, body []byte) { + if len(body) == 0 { + return + } + requireOpenAIResponsesToolSchemaPatternGateCovers(t, body) + requireOpenAIResponsesToolParameterGateCovers(t, body) + }) +} diff --git a/backend/internal/service/openai_ws_forwarder_ingress.go b/backend/internal/service/openai_ws_forwarder_ingress.go index c8dc75aac4fa..a180f7104a31 100644 --- a/backend/internal/service/openai_ws_forwarder_ingress.go +++ b/backend/internal/service/openai_ws_forwarder_ingress.go @@ -14,6 +14,7 @@ import ( "time" "github.com/Wei-Shaw/sub2api/internal/pkg/openai" + "github.com/Wei-Shaw/sub2api/internal/pkg/requestmodel" "github.com/Wei-Shaw/sub2api/internal/pkg/requesttiming" "github.com/Wei-Shaw/sub2api/internal/requestcapture" coderws "github.com/coder/websocket" @@ -906,6 +907,11 @@ func (s *OpenAIGatewayService) ProxyResponsesWebSocketFromClient( if !gjson.ValidBytes(trimmed) { return openAIWSClientPayload{}, NewOpenAIWSClientCloseError(coderws.StatusPolicyViolation, "invalid websocket request payload", errors.New("invalid json")) } + // 帧内重复字段会让这里 gjson 读到的首个值与后续重编码/上游读到的值分叉 + // (GHSA-p3r4-jcm3-2hph),在读取任何字段之前拒绝。 + if field, conflict := requestmodel.ConflictingField("application/json", trimmed); conflict { + return openAIWSClientPayload{}, NewOpenAIWSClientCloseError(coderws.StatusPolicyViolation, fmt.Sprintf("websocket request payload declares field %.64q more than once", field), nil) + } // Keep the client's per-frame window separate from handshake/account identity // normalization. A handshake window can initialize the session, but must @@ -1102,7 +1108,9 @@ func (s *OpenAIGatewayService) ProxyResponsesWebSocketFromClient( normalized = stripped logOpenAIWSModeInfo("ingress_ws_codex_spark_image_tool_stripped account_id=%d", account.ID) } - imageIntent := IsImageGenerationIntentForPlatform(openAIResponsesEndpoint, originalModel, normalized, account.Platform) + // normalized 由 parseClientPayload 中已通过 gjson.ValidBytes 校验的字节派生, + // 后续改写只走 sjson 或 decode→json.Marshal,合法性保持,因此跳过重复校验。 + imageIntent := IsImageGenerationIntentForPlatformValidated(openAIResponsesEndpoint, originalModel, normalized, account.Platform) if imageIntent && !imageGenerationAllowed { return openAIWSClientPayload{}, NewOpenAIWSClientCloseError(coderws.StatusPolicyViolation, ImageGenerationPermissionMessage(), nil) } @@ -1522,6 +1530,10 @@ func (s *OpenAIGatewayService) ProxyResponsesWebSocketFromClient( if bridgeErr != nil && isOpenAIWSSessionPreempted(ctx) { return errOpenAIWSSessionPreempted } + if result != nil { + // The HTTP payload can contain a policy rewrite or replayed configuration from an earlier turn. + result.RequestedReasoningEffort = currentBridgePayload.requestedReasoningEffort + } if bridgeErr != nil && ctx.Err() != nil { bridgeErr = clientReader.closeForControl(ctx) } else if errors.Is(bridgeErr, errOpenAIWSUsageDrainExpired) && clientReader.disconnected() { diff --git a/backend/internal/service/openai_ws_forwarder_ingress_session_test.go b/backend/internal/service/openai_ws_forwarder_ingress_session_test.go index 953fb66a2f30..5ae899d6ac13 100644 --- a/backend/internal/service/openai_ws_forwarder_ingress_session_test.go +++ b/backend/internal/service/openai_ws_forwarder_ingress_session_test.go @@ -4074,7 +4074,7 @@ func TestOpenAIGatewayService_ProxyResponsesWebSocketFromClient_StoreDisabledStr require.Equal(t, "world", gjson.Get(secondWrite, "input.1.text").String()) } -func TestOpenAIGatewayService_ProxyResponsesWebSocketFromClient_PreviousResponseNotFoundRecoveryRemovesDuplicatePrevID(t *testing.T) { +func TestOpenAIGatewayService_ProxyResponsesWebSocketFromClient_RejectsDuplicatePrevIDBeforeRecovery(t *testing.T) { gin.SetMode(gin.TestMode) cfg := &config.Config{} @@ -4197,32 +4197,27 @@ func TestOpenAIGatewayService_ProxyResponsesWebSocketFromClient_PreviousResponse firstTurn := readMessage() require.Equal(t, "resp_turn_prev_once_1", gjson.GetBytes(firstTurn, "response.id").String()) - // duplicate previous_response_id: 恢复重试时应删除所有重复键,避免再次 previous_response_not_found。 + // 重复的 previous_response_id:网关 gjson 读首个、上游可能读末个,帧在读取 + // 任何字段之前即被拒绝(GHSA-p3r4-jcm3-2hph),不会进入恢复重试,也不会发往上游。 writeMessage(`{"type":"response.create","model":"gpt-5.1","stream":false,"previous_response_id":"resp_turn_prev_once_1","input":[],"previous_response_id":"resp_turn_prev_duplicate"}`) - secondTurn := readMessage() - require.Equal(t, "resp_turn_prev_once_2", gjson.GetBytes(secondTurn, "response.id").String()) - - require.NoError(t, clientConn.Close(coderws.StatusNormalClosure, "done")) select { case serverErr := <-serverErrCh: - require.NoError(t, serverErr) + var closeErr *OpenAIWSClientCloseError + require.ErrorAs(t, serverErr, &closeErr) + require.Equal(t, coderws.StatusPolicyViolation, closeErr.StatusCode()) + require.Contains(t, closeErr.Reason(), `declares field "previous_response_id" more than once`) case <-time.After(5 * time.Second): t.Fatal("等待 ingress websocket 结束超时") } - require.Equal(t, 2, dialer.DialCount(), "previous_response_not_found 恢复应只重试一次") - + require.Equal(t, 1, dialer.DialCount(), "被拒绝的帧不应触发恢复重连") firstConn.mu.Lock() firstWrites := append([]map[string]any(nil), firstConn.writes...) firstConn.mu.Unlock() - require.Len(t, firstWrites, 2) - require.True(t, gjson.Get(requestToJSONString(firstWrites[1]), "previous_response_id").Exists()) - + require.Len(t, firstWrites, 1, "被拒绝的帧不应发往上游") secondConn.mu.Lock() - secondWrites := append([]map[string]any(nil), secondConn.writes...) + require.Empty(t, secondConn.writes) secondConn.mu.Unlock() - require.Len(t, secondWrites, 1) - require.False(t, gjson.Get(requestToJSONString(secondWrites[0]), "previous_response_id").Exists(), "重复键场景恢复重试后不应保留 previous_response_id") } func TestOpenAIGatewayService_ProxyResponsesWebSocketFromClient_RejectsMessageIDAsPreviousResponseID(t *testing.T) { diff --git a/backend/internal/service/openai_ws_http_bridge.go b/backend/internal/service/openai_ws_http_bridge.go index 32705266d724..cebfecb28e6a 100644 --- a/backend/internal/service/openai_ws_http_bridge.go +++ b/backend/internal/service/openai_ws_http_bridge.go @@ -874,7 +874,6 @@ func (s *OpenAIGatewayService) proxyOpenAIWSHTTPBridgeTurn( UpstreamResponseServiceTier: responseModelObserver.ServiceTier(), ServiceTier: resolvedOpenAIUpstreamServiceTierFromObserver(responseModelObserver, extractOpenAIServiceTierFromBody(body)), ReasoningEffort: ApplyThinkingEnabledFallback(extractOpenAIReasoningEffortFromBody(body, mappedModel, originalModel), body, mappedModel), - RequestedReasoningEffort: CanonicalRequestedReasoningEffort(body, originalModel, mappedModel), Stream: reqStream, OpenAIWSMode: true, UpstreamTerminalEvent: upstreamTerminalEvent, diff --git a/backend/internal/service/openai_ws_http_bridge_test.go b/backend/internal/service/openai_ws_http_bridge_test.go index 7e66491b532b..79a44fb579c8 100644 --- a/backend/internal/service/openai_ws_http_bridge_test.go +++ b/backend/internal/service/openai_ws_http_bridge_test.go @@ -2363,6 +2363,15 @@ func TestOpenAIWSHTTPBridgeKeepsContinuationFramesOnHTTPWithoutPreviousResponseI Schedulable: true, } + var requestedEfforts []string + hooks := &OpenAIWSIngressHooks{ + MaxReasoningEffort: "medium", + AfterTurn: func(_ int, result *OpenAIForwardResult, _ error) { + if result != nil { + requestedEfforts = append(requestedEfforts, optionalStringValue(result.RequestedReasoningEffort)) + } + }, + } errCh := make(chan error, 1) wsServer := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { conn, err := coderws.Accept(w, r, &coderws.AcceptOptions{CompressionMode: coderws.CompressionContextTakeover}) @@ -2391,7 +2400,7 @@ func TestOpenAIWSHTTPBridgeKeepsContinuationFramesOnHTTPWithoutPreviousResponseI req.Header.Set("User-Agent", "codex_cli_rs/0.135.0") ginCtx.Request = req - errCh <- svc.ProxyResponsesWebSocketFromClient(r.Context(), ginCtx, conn, account, "sk-test", firstMessage, nil) + errCh <- svc.ProxyResponsesWebSocketFromClient(r.Context(), ginCtx, conn, account, "sk-test", firstMessage, hooks) })) defer wsServer.Close() @@ -2415,12 +2424,12 @@ func TestOpenAIWSHTTPBridgeKeepsContinuationFramesOnHTTPWithoutPreviousResponseI return event } - writeMessage(`{"type":"response.create","model":"gpt-5.1","stream":true,"input":"first"}`) + writeMessage(`{"type":"response.create","model":"gpt-5.1","stream":true,"reasoning":{"effort":"high"},"input":"first"}`) firstTurnEvent := readMessage() require.Equal(t, "response.completed", gjson.GetBytes(firstTurnEvent, "type").String()) require.Equal(t, "resp_bridge_first", gjson.GetBytes(firstTurnEvent, "response.id").String()) - writeMessage(`{"type":"response.create","model":"gpt-5.1","stream":false,"previous_response_id":"resp_bridge_first","input":[{"type":"function_call_output","call_id":"call_bridge_1","output":"ok"}]}`) + writeMessage(`{"type":"response.create","model":"gpt-5.1","stream":false,"reasoning":{"effort":"xhigh"},"previous_response_id":"resp_bridge_first","input":[{"type":"function_call_output","call_id":"call_bridge_1","output":"ok"}]}`) secondTurnEvent := readMessage() require.Equal(t, "response.completed", gjson.GetBytes(secondTurnEvent, "type").String()) require.Equal(t, "resp_bridge_second", gjson.GetBytes(secondTurnEvent, "response.id").String()) @@ -2443,6 +2452,11 @@ func TestOpenAIWSHTTPBridgeKeepsContinuationFramesOnHTTPWithoutPreviousResponseI require.Equal(t, "call_bridge_1", secondInput[1].Get("call_id").String()) require.Equal(t, "function_call_output", secondInput[2].Get("type").String()) require.Equal(t, "call_bridge_1", secondInput[2].Get("call_id").String()) + // The bridge sends capped efforts while usage records each turn's own inbound selection. + for _, body := range upstream.bodies { + require.Equal(t, "medium", gjson.GetBytes(body, "reasoning.effort").String()) + } + require.Equal(t, []string{"high", "xhigh"}, requestedEfforts) require.Equal(t, 0, captureDialer.DialCount()) require.Empty(t, captureConn.writes) } diff --git a/backend/internal/service/openai_ws_v2_passthrough_adapter.go b/backend/internal/service/openai_ws_v2_passthrough_adapter.go index e2bdbb1321fb..60e44c242911 100644 --- a/backend/internal/service/openai_ws_v2_passthrough_adapter.go +++ b/backend/internal/service/openai_ws_v2_passthrough_adapter.go @@ -15,6 +15,7 @@ import ( "github.com/Wei-Shaw/sub2api/internal/pkg/logger" "github.com/Wei-Shaw/sub2api/internal/pkg/openai" + "github.com/Wei-Shaw/sub2api/internal/pkg/requestmodel" "github.com/Wei-Shaw/sub2api/internal/pkg/requesttiming" "github.com/Wei-Shaw/sub2api/internal/pkg/upstreamroute" openaiwsv2 "github.com/Wei-Shaw/sub2api/internal/service/openai_ws_v2" @@ -1104,6 +1105,12 @@ func (s *OpenAIGatewayService) proxyResponsesWebSocketV2Passthrough( if msgType != coderws.MessageText && msgType != coderws.MessageBinary { return payload, nil, nil } + // passthrough 原样转发 session.update 等所有客户端事件;任何帧内的重复 + // 字段都会让网关(gjson 取首个、sjson 只改首个)与上游读到不同的值 + // (GHSA-p3r4-jcm3-2hph),在读取任何字段之前拒绝。 + if field, conflict := requestmodel.ConflictingField("application/json", payload); conflict { + return payload, nil, NewOpenAIWSClientCloseError(coderws.StatusPolicyViolation, fmt.Sprintf("websocket request payload declares field %.64q more than once", field), nil) + } eventType := strings.TrimSpace(gjson.GetBytes(payload, "type").String()) isResponseCreate := eventType == "response.create" responseCreateAt := time.Time{} diff --git a/backend/internal/service/testdata/fuzz/FuzzOpenAIResponsesToolSchemaGatesAreNecessary/19981bffc2abbaf1 b/backend/internal/service/testdata/fuzz/FuzzOpenAIResponsesToolSchemaGatesAreNecessary/19981bffc2abbaf1 new file mode 100644 index 000000000000..ecbe8afb9b65 --- /dev/null +++ b/backend/internal/service/testdata/fuzz/FuzzOpenAIResponsesToolSchemaGatesAreNecessary/19981bffc2abbaf1 @@ -0,0 +1,2 @@ +go test fuzz v1 +[]byte("A") diff --git a/backend/internal/service/testdata/fuzz/FuzzOpenAIResponsesToolSchemaGatesAreNecessary/430233b3de39cf96 b/backend/internal/service/testdata/fuzz/FuzzOpenAIResponsesToolSchemaGatesAreNecessary/430233b3de39cf96 new file mode 100644 index 000000000000..41376806e28b --- /dev/null +++ b/backend/internal/service/testdata/fuzz/FuzzOpenAIResponsesToolSchemaGatesAreNecessary/430233b3de39cf96 @@ -0,0 +1,2 @@ +go test fuzz v1 +[]byte("{\"tools\":[{\"parameters\":{\"properties\":{\"\":{\"\":\"(\",\"pattern\":\"\\\\\"}}}}]}") diff --git a/backend/internal/service/testdata/fuzz/FuzzOpenAIResponsesToolSchemaGatesAreNecessary/6c31f0fa5746a2cd b/backend/internal/service/testdata/fuzz/FuzzOpenAIResponsesToolSchemaGatesAreNecessary/6c31f0fa5746a2cd new file mode 100644 index 000000000000..f9d7f69b336f --- /dev/null +++ b/backend/internal/service/testdata/fuzz/FuzzOpenAIResponsesToolSchemaGatesAreNecessary/6c31f0fa5746a2cd @@ -0,0 +1,2 @@ +go test fuzz v1 +[]byte("0\\\\") diff --git a/backend/internal/service/testdata/fuzz/FuzzOpenAIResponsesToolSchemaGatesAreNecessary/e90985907f88433e b/backend/internal/service/testdata/fuzz/FuzzOpenAIResponsesToolSchemaGatesAreNecessary/e90985907f88433e new file mode 100644 index 000000000000..3a4d1d4e1fcf --- /dev/null +++ b/backend/internal/service/testdata/fuzz/FuzzOpenAIResponsesToolSchemaGatesAreNecessary/e90985907f88433e @@ -0,0 +1,2 @@ +go test fuzz v1 +[]byte("{\"tools\":[{\"parameters\":{\"properties\":{\"\":{\"pattern\":\"\\\\\"}}}}]}") diff --git a/backend/internal/service/token_refresh_service.go b/backend/internal/service/token_refresh_service.go index a75c72b86830..29a22effc82f 100644 --- a/backend/internal/service/token_refresh_service.go +++ b/backend/internal/service/token_refresh_service.go @@ -911,7 +911,17 @@ func (s *TokenRefreshService) refreshWithRetryWithRateGate( releaseRate() } attemptTimedOut := errors.Is(refreshContextErr(attemptCtx), context.DeadlineExceeded) && refreshContextErr(ctx) == nil - if err == nil && newCredentials != nil && !attemptTimedOut && refreshContextErr(ctx) == nil { + if err == nil && hasOpenAIRefreshCredentials(attemptedAccount, newCredentials) { + var durableAccount *Account + durableAccount, credentialsPersisted, err = persistOpenAIRefreshCredentials(attemptCtx, s.accountRepo, attemptedAccount, newCredentials) + if err == nil { + account = durableAccount + if !credentialsPersisted { + err = errRefreshSkipped + shortCircuit = true + } + } + } else if err == nil && newCredentials != nil && !attemptTimedOut && refreshContextErr(ctx) == nil { newCredentials["_token_version"] = time.Now().UnixMilli() current, applied, saveErr := persistOAuthRefreshedCredentials(attemptCtx, s.accountRepo, account, attemptedAccount, newCredentials) if saveErr != nil { @@ -930,7 +940,7 @@ func (s *TokenRefreshService) refreshWithRetryWithRateGate( cancelAttempt() releaseAttempt() persistedAfterAttemptDeadline := attemptTimedOut && credentialsPersisted && err == nil - if attemptTimedOut && !persistedAfterAttemptDeadline && !isProviderScopedTerminalRefreshError(err) { + if attemptTimedOut && !shortCircuit && !persistedAfterAttemptDeadline && !isProviderScopedTerminalRefreshError(err) { cause := err if cause == nil { cause = context.DeadlineExceeded diff --git a/backend/internal/service/token_refresh_service_candidates_test.go b/backend/internal/service/token_refresh_service_candidates_test.go index ba382bd2dc79..46b3dacc53ab 100644 --- a/backend/internal/service/token_refresh_service_candidates_test.go +++ b/backend/internal/service/token_refresh_service_candidates_test.go @@ -3,6 +3,7 @@ package service import ( "context" "errors" + "reflect" "strings" "sync" "testing" @@ -69,6 +70,17 @@ func (r *tokenRefreshCandidateRepo) ListOAuthRefreshCandidatePage(_ context.Cont return page, nil } +func (r *tokenRefreshCandidateRepo) GetByID(_ context.Context, id int64) (*Account, error) { + r.mu.Lock() + defer r.mu.Unlock() + for i := range r.accounts { + if r.accounts[i].ID == id { + return snapshotOAuthRefreshAccount(&r.accounts[i]), nil + } + } + return nil, errors.New("account not found") +} + func (r *tokenRefreshCandidateRepo) UpdateCredentials(_ context.Context, id int64, _ map[string]any) error { r.mu.Lock() defer r.mu.Unlock() @@ -76,6 +88,32 @@ func (r *tokenRefreshCandidateRepo) UpdateCredentials(_ context.Context, id int6 return nil } +func (r *tokenRefreshCandidateRepo) UpdateOpenAIOAuthCredentialsIfUnchanged( + _ context.Context, + id int64, + expectedCredentials map[string]any, + expectedProxyID *int64, + credentials map[string]any, +) (bool, error) { + r.mu.Lock() + defer r.mu.Unlock() + for i := range r.accounts { + account := &r.accounts[i] + if account.ID != id { + continue + } + if account.Platform != PlatformOpenAI || account.Type != AccountTypeOAuth || + account.IsCredentialShadow() || !reflect.DeepEqual(account.Credentials, expectedCredentials) || + !reflect.DeepEqual(account.ProxyID, expectedProxyID) { + return false, nil + } + account.Credentials = shallowCopyMap(credentials) + r.updatedCredentialIDs = append(r.updatedCredentialIDs, id) + return true, nil + } + return false, nil +} + func (r *tokenRefreshCandidateRepo) SetError(context.Context, int64, string) error { r.mu.Lock() defer r.mu.Unlock() diff --git a/backend/internal/service/token_refresh_service_test.go b/backend/internal/service/token_refresh_service_test.go index 75a84bfbccd3..37911d8ac702 100644 --- a/backend/internal/service/token_refresh_service_test.go +++ b/backend/internal/service/token_refresh_service_test.go @@ -5,6 +5,7 @@ package service import ( "context" "errors" + "fmt" "reflect" "testing" "time" @@ -46,6 +47,9 @@ type tokenRefreshAccountRepo struct { setErrorErr error setTempUnschedErr error beforeConditionalState func() + openAISuccessCASCalls int + openAIPersistCtxErr error + openAIPersistDeadline time.Time } func (r *tokenRefreshAccountRepo) Update(ctx context.Context, account *Account) error { @@ -252,6 +256,35 @@ func (r *tokenRefreshAccountRepo) UpdateGrokOAuthCredentialsIfUnchanged( return true, nil } +func (r *tokenRefreshAccountRepo) UpdateOpenAIOAuthCredentialsIfUnchanged( + ctx context.Context, + id int64, + expectedCredentials map[string]any, + expectedProxyID *int64, + credentials map[string]any, +) (bool, error) { + r.openAISuccessCASCalls++ + r.openAIPersistCtxErr = ctx.Err() + r.openAIPersistDeadline, _ = ctx.Deadline() + if err := ctx.Err(); err != nil { + return false, err + } + if r.conditionalSuccessErr != nil { + return false, r.conditionalSuccessErr + } + account := r.accountsByID[id] + if account == nil || account.Platform != PlatformOpenAI || account.Type != AccountTypeOAuth || + account.IsCredentialShadow() || !reflect.DeepEqual(account.Credentials, expectedCredentials) || + !reflect.DeepEqual(account.ProxyID, expectedProxyID) { + return false, nil + } + r.updateCalls++ + r.updateCredentialsCalls++ + account.Credentials = shallowCopyMap(credentials) + r.lastAccount = account + return true, nil +} + func (r *tokenRefreshAccountRepo) SetGrokOAuthRefreshTempUnschedulableIfCredentialsUnchanged( _ context.Context, id int64, @@ -1210,6 +1243,124 @@ func TestTokenRefreshService_PersistedSuccessCrossingAttemptDeadlineStaysSuccess require.Equal(t, 1, scheduler.setAccountCalls) } +func TestTokenRefreshService_OpenAIRotationSurvivesAttemptDeadline(t *testing.T) { + for _, unified := range []bool{false, true} { + name := "fallback" + if unified { + name = "unified" + } + t.Run(name, func(t *testing.T) { + account := openAIRefreshTestAccount() + repo := &tokenRefreshAccountRepo{snapshotReads: true, respectReadContext: true} + repo.accountsByID = map[int64]*Account{account.ID: account} + invalidator := &tokenCacheInvalidatorStub{} + svc := &TokenRefreshService{ + accountRepo: repo, + cfg: &config.TokenRefreshConfig{MaxRetries: 3}, + refreshPolicy: DefaultBackgroundRefreshPolicy(), + cacheInvalidator: invalidator, + attemptTimeoutOverride: 10 * time.Millisecond, + } + if unified { + svc.refreshAPI = NewOAuthRefreshAPI(repo, nil) + } + executor := &refreshAPIExecutorStub{ + needsRefresh: true, + credentials: map[string]any{"access_token": "rotated-access", "refresh_token": "rotated-refresh"}, + onRefreshContext: func(ctx context.Context) { <-ctx.Done() }, + } + + err := svc.refreshWithRetry(context.Background(), account, executor, executor, time.Hour) + + require.NoError(t, err) + require.Equal(t, 1, executor.refreshCalls, "received rotation must not be retried after the attempt deadline") + require.Equal(t, 1, repo.openAISuccessCASCalls) + require.NoError(t, repo.openAIPersistCtxErr) + require.False(t, repo.openAIPersistDeadline.IsZero()) + require.LessOrEqual(t, time.Until(repo.openAIPersistDeadline), 10*time.Second) + require.Equal(t, "rotated-refresh", repo.accountsByID[account.ID].GetOpenAIRefreshToken()) + require.Equal(t, 1, invalidator.calls) + require.NoError(t, invalidator.ctxErr) + require.Zero(t, repo.setErrorCalls) + require.Zero(t, repo.setTempUnschedCalls) + }) + } +} + +func TestTokenRefreshService_OpenAIPersistenceFailureDoesNotRetryUpstream(t *testing.T) { + for _, unified := range []bool{false, true} { + for _, expireAttempt := range []bool{false, true} { + name := fmt.Sprintf("unified=%t/expired=%t", unified, expireAttempt) + t.Run(name, func(t *testing.T) { + account := openAIRefreshTestAccount() + repo := &tokenRefreshAccountRepo{snapshotReads: true, respectReadContext: true, conditionalSuccessErr: errors.New("database unavailable")} + repo.accountsByID = map[int64]*Account{account.ID: account} + svc := &TokenRefreshService{ + accountRepo: repo, + cfg: &config.TokenRefreshConfig{MaxRetries: 3}, + refreshPolicy: DefaultBackgroundRefreshPolicy(), + attemptTimeoutOverride: 10 * time.Millisecond, + } + if unified { + svc.refreshAPI = NewOAuthRefreshAPI(repo, nil) + } + executor := &refreshAPIExecutorStub{ + needsRefresh: true, + credentials: map[string]any{"access_token": "rotated-access", "refresh_token": "rotated-refresh"}, + } + if expireAttempt { + executor.onRefreshContext = func(ctx context.Context) { <-ctx.Done() } + } + + err := svc.refreshWithRetry(context.Background(), account, executor, executor, time.Hour) + + var containment *providerCycleContainmentRefreshError + require.ErrorAs(t, err, &containment) + require.Equal(t, 1, executor.refreshCalls, "a failed save must not reuse the consumed refresh token") + require.Equal(t, 1, repo.openAISuccessCASCalls) + require.NoError(t, repo.openAIPersistCtxErr) + require.Equal(t, "old-refresh", account.GetOpenAIRefreshToken()) + require.Zero(t, repo.setErrorCalls) + require.Zero(t, repo.setTempUnschedCalls) + }) + } + } +} + +func TestTokenRefreshService_OpenAIParentCancellationStillPersists(t *testing.T) { + for _, unified := range []bool{false, true} { + t.Run(fmt.Sprintf("unified=%t", unified), func(t *testing.T) { + account := openAIRefreshTestAccount() + repo := &tokenRefreshAccountRepo{snapshotReads: true, respectReadContext: true} + repo.accountsByID = map[int64]*Account{account.ID: account} + invalidator := &tokenCacheInvalidatorStub{} + svc := &TokenRefreshService{ + accountRepo: repo, cfg: &config.TokenRefreshConfig{MaxRetries: 3}, + refreshPolicy: DefaultBackgroundRefreshPolicy(), cacheInvalidator: invalidator, + } + if unified { + svc.refreshAPI = NewOAuthRefreshAPI(repo, nil) + } + ctx, cancel := context.WithCancel(context.Background()) + defer cancel() + executor := &refreshAPIExecutorStub{ + needsRefresh: true, onRefresh: cancel, + credentials: map[string]any{"access_token": "rotated-access", "refresh_token": "rotated-refresh"}, + } + + err := svc.refreshWithRetry(ctx, account, executor, executor, time.Hour) + + require.ErrorIs(t, err, context.Canceled) + require.Equal(t, 1, executor.refreshCalls) + require.Equal(t, 1, repo.openAISuccessCASCalls) + require.NoError(t, repo.openAIPersistCtxErr) + require.Equal(t, "rotated-refresh", repo.accountsByID[account.ID].GetOpenAIRefreshToken()) + require.Equal(t, 1, invalidator.calls) + require.NoError(t, invalidator.ctxErr) + }) + } +} + func TestPathA_ParentCancellationAfterPersistStillSynchronizesCacheState(t *testing.T) { account := &Account{ ID: 109, diff --git a/backend/internal/service/upstream_models.go b/backend/internal/service/upstream_models.go index 624b20df1ce6..2d0ad2e3f03a 100644 --- a/backend/internal/service/upstream_models.go +++ b/backend/internal/service/upstream_models.go @@ -712,7 +712,10 @@ func upstreamModelRegistryBaseURL(account *Account) string { case account.IsGemini(): return account.GetGeminiBaseURL(geminicli.AIStudioBaseURL) case account.IsAnthropic(): - return account.GetBaseURL() + if baseURL := strings.TrimSpace(account.GetCredential("base_url")); baseURL != "" { + return baseURL + } + return "https://api.anthropic.com" case account.Platform == PlatformAntigravity: return account.GetGeminiBaseURL(geminicli.AIStudioBaseURL) default: @@ -763,6 +766,8 @@ func matchModelsDevProviderByKnownHost(registry map[string]modelsDevProvider, ac } providerID := "" switch host { + case "api.anthropic.com": + providerID = "anthropic" case "api.openai.com", "chatgpt.com": providerID = "openai" case "opencode.ai": @@ -1761,7 +1766,7 @@ func normalizeCodexInputModalities(modalities []string) []string { normalized := make([]string, 0, len(modalities)) for _, modality := range modalities { modality = strings.ToLower(strings.TrimSpace(modality)) - if modality != "text" && modality != "image" { + if modality != "text" && modality != "image" && modality != "audio" { continue } if _, exists := seen[modality]; exists { diff --git a/backend/internal/service/upstream_models_test.go b/backend/internal/service/upstream_models_test.go index 8d023f03837e..be5aeb02764b 100644 --- a/backend/internal/service/upstream_models_test.go +++ b/backend/internal/service/upstream_models_test.go @@ -15,6 +15,52 @@ import ( "github.com/stretchr/testify/require" ) +func TestAnthropicModelRegistryBaseURLAndProvider(t *testing.T) { + registry := map[string]modelsDevProvider{ + "anthropic": {Models: map[string]modelsDevModel{"claude-test": {}}}, + "gateway": {ID: "gateway", API: "https://gateway.example/v1", Models: map[string]modelsDevModel{"custom": {}}}, + } + for _, accountType := range []string{AccountTypeOAuth, AccountTypeSetupToken, AccountTypeAPIKey} { + for _, test := range []struct { + name, credential, wantURL, wantProvider string + }{ + {"default", "", "https://api.anthropic.com", "anthropic"}, + {"blank", " \t ", "https://api.anthropic.com", "anthropic"}, + {"official", " https://api.anthropic.com/v1/ ", "https://api.anthropic.com/v1/", "anthropic"}, + {"custom", " https://gateway.example/v1 ", "https://gateway.example/v1", "gateway"}, + {"unknown", "https://unknown.example/v1", "https://unknown.example/v1", ""}, + } { + t.Run(accountType+"/"+test.name, func(t *testing.T) { + account := &Account{Platform: PlatformAnthropic, Type: accountType, + Credentials: map[string]any{"base_url": test.credential}} + baseURL := upstreamModelRegistryBaseURL(account) + require.Equal(t, test.wantURL, baseURL) + provider, ok := matchModelsDevProvider(registry, baseURL) + require.Equal(t, test.wantProvider != "", ok) + require.Equal(t, test.wantProvider, provider.ID) + }) + } + } +} + +func TestFetchModelsDevMetadataAnthropicOAuthAndSetupToken(t *testing.T) { + for _, accountType := range []string{AccountTypeOAuth, AccountTypeSetupToken} { + t.Run(accountType, func(t *testing.T) { + upstream := &httpUpstreamRecorder{responses: []*http.Response{{ + StatusCode: http.StatusOK, + Header: http.Header{"Content-Type": []string{"application/json"}}, + Body: io.NopCloser(strings.NewReader(`{"anthropic":{"models":{"claude-test":{"id":"claude-test","limit":{"context":1000000}}}}}`)), + }}} + svc := &AccountTestService{httpUpstream: upstream, cfg: upstreamModelSyncTestConfig()} + metadata, err := svc.fetchModelsDevMetadata(context.Background(), &Account{ + Platform: PlatformAnthropic, Type: accountType, + }, []string{"claude-test"}) + require.NoError(t, err) + require.Equal(t, int64(1_000_000), metadata["claude-test"].ContextWindow) + }) + } +} + type upstreamModelMetadataRepoStub struct { AccountRepository accountID int64 diff --git a/backend/internal/service/user_platform_quota_defaults.go b/backend/internal/service/user_platform_quota_defaults.go new file mode 100644 index 000000000000..f60a28bbff16 --- /dev/null +++ b/backend/internal/service/user_platform_quota_defaults.go @@ -0,0 +1,34 @@ +package service + +import ( + "context" + + dbent "github.com/Wei-Shaw/sub2api/ent" +) + +// snapshotUserPlatformQuotaDefaults initializes configured limits for a new user. +// Callers keep failures best-effort and log them without failing user creation. +func snapshotUserPlatformQuotaDefaults(ctx context.Context, repo UserPlatformQuotaRepository, userID int64, quotas map[string]*DefaultPlatformQuotaSetting) error { + if repo == nil || userID <= 0 || len(quotas) == 0 { + return nil + } + // Missing rows mean unlimited; explicit zero is a configured limit. + records := make([]UserPlatformQuotaRecord, 0, len(quotas)) + for platform, quota := range quotas { + if !quota.HasAnyLimit() { + continue + } + records = append(records, UserPlatformQuotaRecord{ + UserID: userID, + Platform: platform, + DailyLimitUSD: quota.DailyLimitUSD, + WeeklyLimitUSD: quota.WeeklyLimitUSD, + MonthlyLimitUSD: quota.MonthlyLimitUSD, + }) + } + if len(records) == 0 { + return nil + } + // A failed best-effort write must not abort the caller's transaction. + return repo.BulkInsertInitial(dbent.WithoutTx(ctx), records) +} diff --git a/backend/internal/service/websearch_config.go b/backend/internal/service/websearch_config.go index b0157ca41599..3a24c1ce784e 100644 --- a/backend/internal/service/websearch_config.go +++ b/backend/internal/service/websearch_config.go @@ -20,9 +20,9 @@ type WebSearchEmulationConfig struct { Providers []WebSearchProviderConfig `json:"providers"` } -// WebSearchProviderConfig describes a single search provider (Brave, Tavily, or DeepSeek). +// WebSearchProviderConfig describes a single search provider (Brave, Tavily, DeepSeek, or Exa). type WebSearchProviderConfig struct { - Type string `json:"type"` // websearch.ProviderTypeBrave | Tavily | DeepSeek + Type string `json:"type"` // websearch.ProviderTypeBrave | Tavily | DeepSeek | Exa APIKey string `json:"api_key,omitempty"` // secret — omitted in API responses APIKeyConfigured bool `json:"api_key_configured"` // read-only mask QuotaLimit *int64 `json:"quota_limit"` // nil = unlimited, >0 = limited @@ -40,6 +40,7 @@ var validProviderTypes = map[string]bool{ websearch.ProviderTypeBrave: true, websearch.ProviderTypeTavily: true, websearch.ProviderTypeDeepSeek: true, + websearch.ProviderTypeExa: true, } func validateWebSearchConfig(cfg *WebSearchEmulationConfig) error { diff --git a/backend/internal/service/websearch_config_exa_test.go b/backend/internal/service/websearch_config_exa_test.go new file mode 100644 index 000000000000..427f3fd01afd --- /dev/null +++ b/backend/internal/service/websearch_config_exa_test.go @@ -0,0 +1,17 @@ +//go:build unit + +package service + +import ( + "testing" + + "github.com/stretchr/testify/require" +) + +func TestValidateWebSearchConfig_AcceptsExa(t *testing.T) { + cfg := &WebSearchEmulationConfig{ + Enabled: true, + Providers: []WebSearchProviderConfig{{Type: "exa", QuotaLimit: int64Ptr(1000)}}, + } + require.NoError(t, validateWebSearchConfig(cfg)) +} diff --git a/frontend/src/api/admin/settings.ts b/frontend/src/api/admin/settings.ts index ea490385ed03..79f4f693e2f2 100644 --- a/frontend/src/api/admin/settings.ts +++ b/frontend/src/api/admin/settings.ts @@ -1682,7 +1682,7 @@ export async function updateBetaPolicySettings( // --- Web Search Emulation Config --- export interface WebSearchProviderConfig { - type: "brave" | "tavily" | "deepseek"; + type: "brave" | "tavily" | "deepseek" | "exa"; api_key: string; api_key_configured: boolean; quota_limit: number | null; diff --git a/frontend/src/components/account/AccountUsageCell.vue b/frontend/src/components/account/AccountUsageCell.vue index 6850c2d0e0ba..364d7dfc3f8c 100644 --- a/frontend/src/components/account/AccountUsageCell.vue +++ b/frontend/src/components/account/AccountUsageCell.vue @@ -41,6 +41,7 @@
{{ usageInfo.error }}
+ - + @@ -778,7 +782,7 @@ import { NEW_FEATURE_NOTICES } from '@/constants/newFeatureNotices' import { useI18n } from 'vue-i18n' import { adminAPI } from '@/api/admin' import type { Account, AccountUsageInfo, GeminiCredentials, WindowStats } from '@/types' -import { buildOpenAIUsageRefreshKey } from '@/utils/accountUsageRefresh' +import { buildAccountUsageRefreshKey } from '@/utils/accountUsageRefresh' import { enqueueUsageRequest } from '@/utils/usageLoadQueue' import { formatCompactNumber, formatDateTime } from '@/utils/format' import { isOfficialGeminiBaseUrl } from '@/utils/geminiExplicitCache' @@ -798,7 +802,7 @@ import { import OpenCodeGoUsageCell from './OpenCodeGoUsageCell.vue' // Module-level cache shared across all AccountUsageCell instances -const _usageCache = new Map() +const _usageCache = new Map() const USAGE_CACHE_TTL = 5 * 60 * 1000 // 5 minutes const props = withDefaults( @@ -957,12 +961,11 @@ const hasOpenAIQuotaObservation = computed(() => { return windows.some(window => window && !window.utilization_unknown) }) -const openAISevenDayEstimatedTotalCost = computed(() => { - const sevenDay = usageInfo.value?.seven_day - const utilization = sevenDay?.utilization - const currentCost = sevenDay?.window_stats?.cost +function estimateWindowTotalCost(window?: AccountUsageInfo['seven_day']) { + const utilization = window?.utilization + const currentCost = window?.window_stats?.cost if ( - sevenDay?.utilization_unknown || + window?.utilization_unknown || typeof utilization !== 'number' || typeof currentCost !== 'number' || !Number.isFinite(utilization) || @@ -975,9 +978,13 @@ const openAISevenDayEstimatedTotalCost = computed(() => { const estimate = (currentCost * 100) / utilization return Number.isFinite(estimate) && estimate > 0 ? estimate : null -}) +} -const openAIUsageRefreshKey = computed(() => buildOpenAIUsageRefreshKey(props.account)) +const openAISevenDayEstimatedTotalCost = computed(() => + estimateWindowTotalCost(usageInfo.value?.seven_day) +) + +const usageRefreshKey = computed(() => buildAccountUsageRefreshKey(props.account)) const shouldAutoLoadUsageOnMount = computed(() => { return shouldFetchUsage.value @@ -1602,7 +1609,7 @@ const loadUsage = async (options?: { source?: 'passive' | 'active'; bypassCache? // Check cache if (!options?.bypassCache) { const cached = _usageCache.get(props.account.id) - if (cached && Date.now() - cached.ts < USAGE_CACHE_TTL) { + if (cached && cached.refreshKey === usageRefreshKey.value && Date.now() - cached.ts < USAGE_CACHE_TTL) { usageInfo.value = cached.data loading.value = false return @@ -1611,6 +1618,7 @@ const loadUsage = async (options?: { source?: 'passive' | 'active'; bypassCache? loading.value = true error.value = null + const refreshKey = usageRefreshKey.value try { const fetchFn = () => options?.source @@ -1619,7 +1627,7 @@ const loadUsage = async (options?: { source?: 'passive' | 'active'; bypassCache? const result = await enqueueUsageRequest(props.account, fetchFn) if (!unmounted.value) { usageInfo.value = result - _usageCache.set(props.account.id, { data: result, ts: Date.now() }) + _usageCache.set(props.account.id, { data: result, ts: Date.now(), refreshKey }) } } catch (e: any) { if (!unmounted.value) { @@ -1683,13 +1691,14 @@ const attachVisibilityObserver = () => { const loadActiveUsage = async () => { const accountID = props.account.id + const refreshKey = usageRefreshKey.value activeQueryLoading.value = true error.value = null try { const result = await adminAPI.accounts.getUsage(accountID, 'active', true) if (!unmounted.value && props.account.id === accountID) { usageInfo.value = result - _usageCache.set(accountID, { data: result, ts: Date.now() }) + _usageCache.set(accountID, { data: result, ts: Date.now(), refreshKey }) } } catch (e: any) { if (!unmounted.value && props.account.id === accountID) { @@ -1863,17 +1872,17 @@ watch( { flush: 'post' } ) -watch(openAIUsageRefreshKey, (nextKey, prevKey) => { +watch(usageRefreshKey, (nextKey, prevKey) => { if (!prevKey || nextKey === prevKey) return - if (props.account.platform !== 'openai' || props.account.type !== 'oauth') return + if (!shouldFetchUsage.value) return if (isBatchManaged.value) { - requestParentBatchUsage({ force: true }) + requestParentBatchUsage(props.account.platform === 'openai' ? { force: true } : undefined) return } _usageCache.delete(props.account.id) - requestAutoLoad() + requestAutoLoad(isAnthropicOAuthOrSetupToken.value ? 'passive' : undefined) }) watch( diff --git a/frontend/src/components/account/BulkEditAccountModal.vue b/frontend/src/components/account/BulkEditAccountModal.vue index a799e2c55eb4..01a71e21dff3 100644 --- a/frontend/src/components/account/BulkEditAccountModal.vue +++ b/frontend/src/components/account/BulkEditAccountModal.vue @@ -215,21 +215,51 @@ ]" /> -