From 5e4e3863e8caec6aeac1a9e6bf77b9574186b7fb Mon Sep 17 00:00:00 2001 From: "github-actions[bot]" <41898282+github-actions[bot]@users.noreply.github.com> Date: Wed, 18 Nov 2026 03:51:52 +0000 Subject: [PATCH 01/87] chore: sync VERSION to 0.2.23 [skip ci] (cherry picked from commit 2af3f1e15c98c893a89255a037f551046883b8c0) --- backend/cmd/server/VERSION | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/backend/cmd/server/VERSION b/backend/cmd/server/VERSION index 62eccae33345..521eb3d6e6c3 100644 --- a/backend/cmd/server/VERSION +++ b/backend/cmd/server/VERSION @@ -1 +1 @@ -2.23.1 +0.2.23 From 7892c7a0608218b9a94dc5fa157f75c0a1aef7b3 Mon Sep 17 00:00:00 2001 From: shaw Date: Fri, 20 Nov 2026 14:22:44 +0800 Subject: [PATCH 02/87] fix(openai): stop alpha/search tool-level 403s from benching OAuth accounts A Codex literature search (gpt-6.2-astra with literature_search_query) on a plan without that capability gets 403 {"detail":"Literature search is unavailable."} from /alpha/search. The alpha/search side-effect gate only exempted 401/404/405, so the 403 went through the generic OpenAI 403 path: the first hit cools the account for 10 minutes and three hits within 3 hours mark it errored until an admin clears it. 403 is also a failover status, so one request replays across the pool. In production, one request paused all 9 OAuth accounts within 4 seconds. On alpha/search (and the PAT Responses fallback), a 403 now writes account state only when it is an account or workspace access-state error (deactivated, disabled, ...). Every other 403 is the search tool refusing the request: the request still fails over, since another account's plan may allow it, but no account is cooled, counted or errored. (cherry picked from commit fe5e7fa404055cf03880045b4c06d5e6548991e5) --- .../internal/service/openai_alpha_search.go | 13 ++- .../service/openai_alpha_search_test.go | 105 +++++++++++++++++- 2 files changed, 110 insertions(+), 8 deletions(-) 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) { From 1ccf30feb2b0ba359e0a1446eeba69583065251c Mon Sep 17 00:00:00 2001 From: xuemk <19485593+xuemk@users.noreply.github.com> Date: Wed, 11 Nov 2026 15:21:18 +0800 Subject: [PATCH 03/87] fix(openai): protect rotated oauth credentials from enrichment timeout and race conditions (cherry picked from commit fb52c6e136a9401d5c078bade0533b32715706f7) --- backend/internal/repository/account_repo.go | 26 +- .../account_repo_temp_unsched_test.go | 75 +++++ backend/internal/service/oauth_refresh_api.go | 99 ++++++ .../service/oauth_refresh_api_test.go | 281 +++++++++++++++++- .../internal/service/token_refresh_service.go | 14 +- .../token_refresh_service_candidates_test.go | 38 +++ .../service/token_refresh_service_test.go | 151 ++++++++++ 7 files changed, 671 insertions(+), 13 deletions(-) diff --git a/backend/internal/repository/account_repo.go b/backend/internal/repository/account_repo.go index 9a0e57c7a4d5..4558ee544baa 100644 --- a/backend/internal/repository/account_repo.go +++ b/backend/internal/repository/account_repo.go @@ -2047,6 +2047,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") @@ -2070,6 +2093,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) @@ -2077,7 +2101,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/service/oauth_refresh_api.go b/backend/internal/service/oauth_refresh_api.go index 9dade7235db8..88f90ab9f94d 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 = newCredentials + } + 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/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, From 9f92e0051f38507e2682b8c2828e1a5ecfb75322 Mon Sep 17 00:00:00 2001 From: Anankke Date: Sat, 14 Nov 2026 03:55:33 -0800 Subject: [PATCH 04/87] feat(gateway): write Claude Code compaction requests at 5m cache TTL With the 1h cache TTL injection on, every breakpoint of a compaction request was rewritten to 1h, although the conversation is replaced by the summary afterwards and nothing reads the tokens added since the last main-thread breakpoint again. A compaction request is recognised by the fixed preamble of the compact prompt in the last user message. Every breakpoint becomes 5m, including one the client already wrote as 1h. A 5m breakpoint still reads the prefix the main thread cached at 1h, and an all-5m request keeps the tools, system, messages TTL order Anthropic requires. The admin settings hint for the switch names the exception. (cherry picked from commit e2631bbb385a8fa04a7b006678417713600aa270) --- .../service/gateway_claude_oauth_body.go | 47 ++++++++++ .../gateway_compaction_cache_ttl_test.go | 87 +++++++++++++++++++ .../src/i18n/locales/en/admin/settings.ts | 2 +- .../src/i18n/locales/zh/admin/settings.ts | 2 +- 4 files changed, 136 insertions(+), 2 deletions(-) create mode 100644 backend/internal/service/gateway_compaction_cache_ttl_test.go diff --git a/backend/internal/service/gateway_claude_oauth_body.go b/backend/internal/service/gateway_claude_oauth_body.go index 62eb2fdb2bac..23cae4ad4ee2 100644 --- a/backend/internal/service/gateway_claude_oauth_body.go +++ b/backend/internal/service/gateway_claude_oauth_body.go @@ -1218,10 +1218,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/frontend/src/i18n/locales/en/admin/settings.ts b/frontend/src/i18n/locales/en/admin/settings.ts index 227ad3e71186..f4f0132a35b6 100644 --- a/frontend/src/i18n/locales/en/admin/settings.ts +++ b/frontend/src/i18n/locales/en/admin/settings.ts @@ -627,7 +627,7 @@ export default { cacheTTL5m: '5 minutes', cacheTTL1h: '1 hour', anthropicCacheTTL1hInjection: 'Anthropic Cache TTL Injection', - anthropicCacheTTL1hInjectionHint: 'When enabled, existing ephemeral cache_control blocks in Anthropic OAuth/Setup Token request bodies are forced to 1h; response usage is billed back as 5m by default, with account-level TTL billing override taking priority.', + anthropicCacheTTL1hInjectionHint: 'When enabled, existing ephemeral cache_control blocks in Anthropic OAuth/Setup Token request bodies are forced to 1h, except Claude Code compaction requests, which use 5m; response usage is billed back as 5m by default, with account-level TTL billing override taking priority.', rewriteMessageCacheControl: 'Rewrite Message Cache Breakpoints', rewriteMessageCacheControlHint: 'Default off: preserve client cache_control on message content blocks. When enabled, client breakpoints are stripped and proxy breakpoints are injected for clients that do not manage caching themselves.', clientDatelineNormalization: 'Client Dateline Normalization', diff --git a/frontend/src/i18n/locales/zh/admin/settings.ts b/frontend/src/i18n/locales/zh/admin/settings.ts index 90bd0d1b7576..f7db08568689 100644 --- a/frontend/src/i18n/locales/zh/admin/settings.ts +++ b/frontend/src/i18n/locales/zh/admin/settings.ts @@ -620,7 +620,7 @@ export default { cacheTTL5m: '5 分钟', cacheTTL1h: '1 小时', anthropicCacheTTL1hInjection: 'Anthropic 缓存 TTL 注入', - anthropicCacheTTL1hInjectionHint: '开启后,对 Anthropic OAuth/Setup Token 请求体中已有的 ephemeral 缓存块强制写入 1h;响应 usage 默认按 5m 回写计费,账号级 TTL 计费设置优先。', + anthropicCacheTTL1hInjectionHint: '开启后,对 Anthropic OAuth/Setup Token 请求体中已有的 ephemeral 缓存块强制写入 1h,Claude Code 压缩请求除外,写入 5m;响应 usage 默认按 5m 回写计费,账号级 TTL 计费设置优先。', rewriteMessageCacheControl: '改写消息缓存断点', rewriteMessageCacheControlHint: '默认关闭,保留客户端在 messages 内容块中的 cache_control。开启后会清除客户端断点并注入代理断点,适合不自行管理缓存策略的客户端。', clientDatelineNormalization: '客户端 dateline 归一化', From 11b246706847e9b91fa706eb0786dd9168536767 Mon Sep 17 00:00:00 2001 From: Anankke Date: Sat, 14 Nov 2026 02:54:25 -0800 Subject: [PATCH 05/87] feat(websearch): add Exa as a web search emulation provider The web search emulation answers a WebSearch tool call on accounts without native search by querying a configured provider. Only Brave and Tavily are available. This adds Exa as a third keyed provider, "exa", in the same place the others are registered. ExaProvider posts {query, numResults, contents: {highlights: true}} to https://api.exa.ai/search with the key in the x-api-key header. The search type and highlight length are left to Exa's defaults. Each result maps url and title as they are, publishedDate to page_age, and its highlights joined by newlines to the snippet. A result without highlights has no snippet. A non-200 answer is returned as an error with the status and the start of the body, as for Tavily. "exa" is accepted by the emulation config validator, built by the manager and offered in the admin settings provider dropdown. (cherry picked from commit bf292550a6d45088c46dd0792d9bffddb2c65e92) --- backend/internal/pkg/websearch/exa.go | 112 ++++++++++++++++++ backend/internal/pkg/websearch/exa_test.go | 91 ++++++++++++++ backend/internal/pkg/websearch/manager.go | 4 +- backend/internal/pkg/websearch/provider.go | 2 +- backend/internal/pkg/websearch/types.go | 1 + backend/internal/service/websearch_config.go | 5 +- .../service/websearch_config_exa_test.go | 17 +++ frontend/src/api/admin/settings.ts | 2 +- frontend/src/views/admin/SettingsView.vue | 1 + 9 files changed, 230 insertions(+), 5 deletions(-) create mode 100644 backend/internal/pkg/websearch/exa.go create mode 100644 backend/internal/pkg/websearch/exa_test.go create mode 100644 backend/internal/service/websearch_config_exa_test.go 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..18a38b9b2970 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/service/websearch_config.go b/backend/internal/service/websearch_config.go index b0157ca41599..59ea7162cb7e 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/views/admin/SettingsView.vue b/frontend/src/views/admin/SettingsView.vue index 271038fb9099..7098dccdaed0 100644 --- a/frontend/src/views/admin/SettingsView.vue +++ b/frontend/src/views/admin/SettingsView.vue @@ -6187,6 +6187,7 @@ { value: 'brave', label: 'Brave Search' }, { value: 'tavily', label: 'Tavily' }, { value: 'deepseek', label: 'DeepSeek' }, + { value: 'exa', label: 'Exa' }, ]" class="w-36" @click.stop From ca0c76bf72652f272048b604da0b111f1bd22c76 Mon Sep 17 00:00:00 2001 From: Anankke Date: Sat, 14 Nov 2026 02:54:30 -0800 Subject: [PATCH 06/87] feat(apicompat): return web_search sources in web_search_tool_result blocks The Messages bridge always answered an OpenAI web_search_call with an empty web_search_tool_result, so clients never saw the pages the search used. Bridge requests on the OpenAI platform that carry a web_search tool now ask for web_search_call.action.sources. Each call's sources, or the page a completed open_page opened, become that call's web_search_tool_result entries, in both the streaming and non-streaming paths. Sources are decoded entry by entry so a malformed entry cannot drop the terminal event. (cherry picked from commit aa5a020bd16bcac8c9c18f71040abfa50e2c9984) --- .../pkg/apicompat/responses_to_anthropic.go | 8 +- .../apicompat/responses_web_search_sources.go | 57 ++++++++ .../responses_web_search_sources_test.go | 110 ++++++++++++++++ backend/internal/pkg/apicompat/types.go | 4 + .../service/openai_gateway_messages.go | 3 + ...ateway_messages_web_search_sources_test.go | 123 ++++++++++++++++++ 6 files changed, 299 insertions(+), 6 deletions(-) create mode 100644 backend/internal/pkg/apicompat/responses_web_search_sources.go create mode 100644 backend/internal/pkg/apicompat/responses_web_search_sources_test.go create mode 100644 backend/internal/service/openai_gateway_messages_web_search_sources_test.go diff --git a/backend/internal/pkg/apicompat/responses_to_anthropic.go b/backend/internal/pkg/apicompat/responses_to_anthropic.go index 0acb60aa84f1..c459a952f471 100644 --- a/backend/internal/pkg/apicompat/responses_to_anthropic.go +++ b/backend/internal/pkg/apicompat/responses_to_anthropic.go @@ -68,11 +68,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), }) } } @@ -680,9 +679,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 +686,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_web_search_sources.go b/backend/internal/pkg/apicompat/responses_web_search_sources.go new file mode 100644 index 000000000000..39efc7370d70 --- /dev/null +++ b/backend/internal/pkg/apicompat/responses_web_search_sources.go @@ -0,0 +1,57 @@ +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 a completed open_page opened. +// Sources are decoded entry by entry, so one malformed entry 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" && item.Status == "completed" && action.URL != "" { + results = append(results, newWebSearchResult(action.URL)) + } + } + 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..07742de86c84 --- /dev/null +++ b/backend/internal/pkg/apicompat/responses_web_search_sources_test.go @@ -0,0 +1,110 @@ +//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{ + "in progress": `{"type":"web_search_call","id":"ws_1","status":"in_progress","action":{"type":"open_page","url":"https://docs.example/page"}}`, + "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"]) + }) + } +} diff --git a/backend/internal/pkg/apicompat/types.go b/backend/internal/pkg/apicompat/types.go index 5b79f7d4ce92..68240055f143 100644 --- a/backend/internal/pkg/apicompat/types.go +++ b/backend/internal/pkg/apicompat/types.go @@ -612,6 +612,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 string `json:"url,omitempty"` // open_page / find_in_page target + // Sources stays raw: a strictly typed entry of an unexpected shape would + // fail decoding the whole terminal event that carries this call. + Sources json.RawMessage `json:"sources,omitempty"` } // ResponsesSummary is a summary text block inside a reasoning output. diff --git a/backend/internal/service/openai_gateway_messages.go b/backend/internal/service/openai_gateway_messages.go index dc069c6238a5..619957462b06 100644 --- a/backend/internal/service/openai_gateway_messages.go +++ b/backend/internal/service/openai_gateway_messages.go @@ -257,6 +257,9 @@ 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) 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) +} From 4f4f15c3c0139571ded73ee6e99d554afaf2ede0 Mon Sep 17 00:00:00 2001 From: Anankke Date: Sat, 14 Nov 2026 07:09:38 -0800 Subject: [PATCH 07/87] fix(apicompat): tolerate non-string action.url and skip unfinished web_search calls WebSearchAction.URL was a strict string, so a web_search_call whose action.url was not a string failed decoding of the whole Responses event and the Messages stream lost its terminal event. It is now raw like Sources and read as a string only for open_page. The non-streaming converter also filled results for web_search_call items that had not completed, while the streaming one only handles completed items. Both now emit blocks for completed calls only. (cherry picked from commit 30152d1b16fb2fbc5d3d58a8ca71d2bd6fea8a89) --- .../pkg/apicompat/responses_to_anthropic.go | 3 +++ .../apicompat/responses_web_search_sources.go | 13 ++++++---- .../responses_web_search_sources_test.go | 24 +++++++++++++++++-- backend/internal/pkg/apicompat/types.go | 6 ++--- 4 files changed, 36 insertions(+), 10 deletions(-) diff --git a/backend/internal/pkg/apicompat/responses_to_anthropic.go b/backend/internal/pkg/apicompat/responses_to_anthropic.go index c459a952f471..68c128e3d1ee 100644 --- a/backend/internal/pkg/apicompat/responses_to_anthropic.go +++ b/backend/internal/pkg/apicompat/responses_to_anthropic.go @@ -56,6 +56,9 @@ func ResponsesToAnthropic(resp *ResponsesResponse, model string) *AnthropicRespo Input: sanitizeAnthropicToolUseInput(item.Name, item.Arguments), }) case "web_search_call": + if item.Status != "completed" { + continue + } toolUseID := "srvtoolu_" + item.ID query := "" if item.Action != nil { diff --git a/backend/internal/pkg/apicompat/responses_web_search_sources.go b/backend/internal/pkg/apicompat/responses_web_search_sources.go index 39efc7370d70..f6f0bf16a7bb 100644 --- a/backend/internal/pkg/apicompat/responses_web_search_sources.go +++ b/backend/internal/pkg/apicompat/responses_web_search_sources.go @@ -27,9 +27,9 @@ type webSearchResult struct { } // webSearchCallResults is the web_search_tool_result content for one call: a -// search's action.sources, or the single page a completed open_page opened. -// Sources are decoded entry by entry, so one malformed entry cannot fail the -// terminal event that carries the call. +// 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 { @@ -42,8 +42,11 @@ func webSearchCallResults(item *ResponsesOutput) json.RawMessage { results = append(results, newWebSearchResult(rawURL)) } } - } else if action.Type == "open_page" && item.Status == "completed" && action.URL != "" { - results = append(results, newWebSearchResult(action.URL)) + } 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) diff --git a/backend/internal/pkg/apicompat/responses_web_search_sources_test.go b/backend/internal/pkg/apicompat/responses_web_search_sources_test.go index 07742de86c84..3cf9c04f3e08 100644 --- a/backend/internal/pkg/apicompat/responses_web_search_sources_test.go +++ b/backend/internal/pkg/apicompat/responses_web_search_sources_test.go @@ -100,11 +100,31 @@ func TestWebSearchOpenPageReturnsSinglePage(t *testing.T) { func TestWebSearchOpenPageRequiresCompletedURL(t *testing.T) { for name, item := range map[string]string{ - "in progress": `{"type":"web_search_call","id":"ws_1","status":"in_progress","action":{"type":"open_page","url":"https://docs.example/page"}}`, - "empty url": `{"type":"web_search_call","id":"ws_1","status":"completed","action":{"type":"open_page","url":""}}`, + "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 68240055f143..16cadc978b3e 100644 --- a/backend/internal/pkg/apicompat/types.go +++ b/backend/internal/pkg/apicompat/types.go @@ -612,9 +612,9 @@ 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 string `json:"url,omitempty"` // open_page / find_in_page target - // Sources stays raw: a strictly typed entry of an unexpected shape would - // fail decoding the whole terminal event that carries this call. + // 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"` } From a5c8941f9c7c73a8e88163600fe77a8af6c811f5 Mon Sep 17 00:00:00 2001 From: Anankke Date: Sat, 14 Nov 2026 03:51:44 -0800 Subject: [PATCH 08/87] fix(apicompat): map ToolSearch to native tool_search for Codex OAuth The Messages to Responses bridge turned every ToolSearch tool_result made of tool_reference blocks into "(empty)" and sent every defer_loading tool as a top-level function. On ChatGPT/Codex accounts whose model reports supports_search_tool (Grok excluded, xAI has no tool_search) ToolSearch now maps to the native client-executed tool_search, history becomes tool_search_call and tool_search_output carrying the revealed definitions, and an upstream tool_search_call comes back as a ToolSearch tool_use on both the streaming and buffered paths. Deferred tools stay out of the top-level tools so the prompt cache prefix is the same before and after a reveal. Requests that do not declare ToolSearch are left untouched. (cherry picked from commit 5e322694e72ef39ffb59ec7b5920e206239eb895) --- .../pkg/apicompat/anthropic_tool_search.go | 191 ++++++++++++++++++ .../apicompat/anthropic_tool_search_test.go | 174 ++++++++++++++++ .../pkg/apicompat/responses_to_anthropic.go | 6 + .../apicompat/responses_to_chatcompletions.go | 9 +- backend/internal/pkg/apicompat/types.go | 7 + .../service/openai_gateway_messages.go | 10 + ...penai_gateway_messages_tool_search_test.go | 158 +++++++++++++++ 7 files changed, 554 insertions(+), 1 deletion(-) create mode 100644 backend/internal/pkg/apicompat/anthropic_tool_search.go create mode 100644 backend/internal/pkg/apicompat/anthropic_tool_search_test.go create mode 100644 backend/internal/service/openai_gateway_messages_tool_search_test.go 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..55518e0db4f1 --- /dev/null +++ b/backend/internal/pkg/apicompat/anthropic_tool_search.go @@ -0,0 +1,191 @@ +package apicompat + +import ( + "encoding/json" +) + +// 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" + +// 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 + for _, t := range req.Tools { + if t.Name == ToolSearchToolName && !t.DeferLoading { + declared = true + break + } + } + if !declared { + 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 + } + for i, raw := range items { + var item ResponsesInputItem + if err := json.Unmarshal(raw, &item); err != nil { + return err + } + names, isSearch := revealed[item.CallID] + if !isSearch { + 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, + } + default: + continue + } + encoded, err := json.Marshal(native) + if err != nil { + return err + } + items[i] = encoded + } + input, err := json.Marshal(items) + if err != nil { + return err + } + out.Input = input + return nil +} + +// 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..3729a16e8b41 --- /dev/null +++ b/backend/internal/pkg/apicompat/anthropic_tool_search_test.go @@ -0,0 +1,174 @@ +//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 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/responses_to_anthropic.go b/backend/internal/pkg/apicompat/responses_to_anthropic.go index 68c128e3d1ee..d11c17b1c492 100644 --- a/backend/internal/pkg/apicompat/responses_to_anthropic.go +++ b/backend/internal/pkg/apicompat/responses_to_anthropic.go @@ -55,6 +55,8 @@ func ResponsesToAnthropic(resp *ResponsesResponse, model string) *AnthropicRespo Name: item.Name, Input: sanitizeAnthropicToolUseInput(item.Name, item.Arguments), }) + case "tool_search_call": + blocks = append(blocks, toolSearchCallToolUse(item)) case "web_search_call": if item.Status != "completed" { continue @@ -635,6 +637,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" { diff --git a/backend/internal/pkg/apicompat/responses_to_chatcompletions.go b/backend/internal/pkg/apicompat/responses_to_chatcompletions.go index e024a6f20392..b81336cde914 100644 --- a/backend/internal/pkg/apicompat/responses_to_chatcompletions.go +++ b/backend/internal/pkg/apicompat/responses_to_chatcompletions.go @@ -530,6 +530,8 @@ type BufferedResponseAccumulator struct { // custom_tool_call that IsServerSideSearchCall is then rebuilt as that item // instead of as a client function_call. XAIServerSideSearch bool + // tool_search_call items arrive complete on output_item.done. + toolSearchCalls []ResponsesOutput } // NewBufferedResponseAccumulator returns an initialised accumulator. @@ -583,6 +585,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 +598,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 +652,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/types.go b/backend/internal/pkg/apicompat/types.go index 16cadc978b3e..4fecfd62f29b 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 字段。 @@ -428,6 +433,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"` diff --git a/backend/internal/service/openai_gateway_messages.go b/backend/internal/service/openai_gateway_messages.go index 619957462b06..df775684b1a0 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) 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..7effea4e0847 --- /dev/null +++ b/backend/internal/service/openai_gateway_messages_tool_search_test.go @@ -0,0 +1,158 @@ +//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") +} + +// 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") +} From 957d6851a1d4a09fe5ab38574901a8086da9ebcd Mon Sep 17 00:00:00 2001 From: Anankke Date: Sat, 14 Nov 2026 06:15:40 -0800 Subject: [PATCH 09/87] fix(apicompat): keep forced tools, result text and reserved names intact A revealed tool was declared in tool_search_output under its own name while its replayed function_call used the Codex reserved-name alias, so the two disagreed for python. Reserved-name collection now walks tool_search_output tools like additional_tools. The collector is shared with the /v1/responses passthrough entries, so they now alias tool_search_output definitions too. The Responses API has no tool_choice value that forces tool_search or a tool that only tool_search_output declares, so a request forcing ToolSearch or a deferred tool keeps the plain function mapping and its body is unchanged. tool_search_output has no field for the result text, so text and errors from a ToolSearch result ride in a separate input_text part of the user message after the tool outputs, ahead of the user's own parts. (cherry picked from commit 3f1a7c6d9d1906989a19aba330d477b8e72b80c1) --- .../pkg/apicompat/anthropic_tool_search.go | 92 +++++++++++++++++-- .../apicompat/anthropic_tool_search_test.go | 82 +++++++++++++++++ .../service/openai_codex_tool_names.go | 2 +- ...penai_gateway_messages_tool_search_test.go | 76 +++++++++++++++ 4 files changed, 245 insertions(+), 7 deletions(-) diff --git a/backend/internal/pkg/apicompat/anthropic_tool_search.go b/backend/internal/pkg/apicompat/anthropic_tool_search.go index 55518e0db4f1..b21636d0b77b 100644 --- a/backend/internal/pkg/apicompat/anthropic_tool_search.go +++ b/backend/internal/pkg/apicompat/anthropic_tool_search.go @@ -2,6 +2,7 @@ package apicompat import ( "encoding/json" + "strings" ) // ToolSearchToolName is Claude Code's client-executed tool-search tool. Under @@ -10,6 +11,10 @@ import ( // `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. @@ -19,13 +24,18 @@ const ToolSearchToolName = "ToolSearch" // 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.Name == ToolSearchToolName && !t.DeferLoading { + if t.DeferLoading { + deferred[t.Name] = true + } else if t.Name == ToolSearchToolName { declared = true - break } } - if !declared { + // 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 } @@ -60,13 +70,34 @@ func ApplyNativeToolSearch(req *AnthropicRequest, out *ResponsesRequest) error { if err := json.Unmarshal(out.Input, &items); err != nil { return err } - for i, raw := range items { + 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 @@ -102,16 +133,27 @@ func ApplyNativeToolSearch(req *AnthropicRequest, out *ResponsesRequest) error { "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 } - items[i] = encoded + 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(items) + input, err := json.Marshal(rewritten) if err != nil { return err } @@ -119,6 +161,44 @@ func ApplyNativeToolSearch(req *AnthropicRequest, out *ResponsesRequest) error { 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 { diff --git a/backend/internal/pkg/apicompat/anthropic_tool_search_test.go b/backend/internal/pkg/apicompat/anthropic_tool_search_test.go index 3729a16e8b41..76446588c6a3 100644 --- a/backend/internal/pkg/apicompat/anthropic_tool_search_test.go +++ b/backend/internal/pkg/apicompat/anthropic_tool_search_test.go @@ -118,6 +118,88 @@ func TestApplyNativeToolSearch_NoToolSearchDeclaredKeepsFunctionTools(t *testing 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":[ diff --git a/backend/internal/service/openai_codex_tool_names.go b/backend/internal/service/openai_codex_tool_names.go index 849a45e417ab..45b1af0ab317 100644 --- a/backend/internal/service/openai_codex_tool_names.go +++ b/backend/internal/service/openai_codex_tool_names.go @@ -132,7 +132,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" { diff --git a/backend/internal/service/openai_gateway_messages_tool_search_test.go b/backend/internal/service/openai_gateway_messages_tool_search_test.go index 7effea4e0847..27c22fea453f 100644 --- a/backend/internal/service/openai_gateway_messages_tool_search_test.go +++ b/backend/internal/service/openai_gateway_messages_tool_search_test.go @@ -112,6 +112,82 @@ func TestForwardAsAnthropic_CodexOAuthModelWithoutSearchSupportKeepsFunctionTool 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) { From 6bf8c25f1f0fe9674298edee9ce0ad8ba4db29fb Mon Sep 17 00:00:00 2001 From: ranxi2001 Date: Sat, 21 Nov 2026 02:45:28 +0800 Subject: [PATCH 10/87] fix: preserve upstream tool search accumulator merge resolution Upstream-merge: e5e1162f424b09d037af65160f56f0d2a0afc4d9 --- .../internal/pkg/apicompat/responses_to_chatcompletions.go | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/backend/internal/pkg/apicompat/responses_to_chatcompletions.go b/backend/internal/pkg/apicompat/responses_to_chatcompletions.go index b81336cde914..3bdc4d7c1f4c 100644 --- a/backend/internal/pkg/apicompat/responses_to_chatcompletions.go +++ b/backend/internal/pkg/apicompat/responses_to_chatcompletions.go @@ -520,6 +520,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 @@ -530,8 +533,6 @@ type BufferedResponseAccumulator struct { // custom_tool_call that IsServerSideSearchCall is then rebuilt as that item // instead of as a client function_call. XAIServerSideSearch bool - // tool_search_call items arrive complete on output_item.done. - toolSearchCalls []ResponsesOutput } // NewBufferedResponseAccumulator returns an initialised accumulator. From 39768f76a45f9d87387f105604f498f0bcf477de Mon Sep 17 00:00:00 2001 From: Anankke Date: Sat, 14 Nov 2026 06:18:52 -0800 Subject: [PATCH 11/87] fix(openai): keep hosted output items in buffered compat responses Non-streaming /v1/messages and /v1/chat/completions force an upstream stream and read it with readOpenAICompatBufferedTerminal, and the Codex OAuth backend ends that stream with an empty terminal output. The delta accumulator rebuilds only reasoning, message and function calls, so web_search_call, image_generation_call and other hosted items were dropped and /v1/messages lost its server_tool_use and web_search_tool_result blocks. The reader now collects the output_item.done items of every type the accumulator does not produce and adds them to an empty terminal output, after the leading reasoning item and ahead of the message and function calls. The accumulator's own items stay exactly as it builds them, so reasoning text, function call arguments and custom tool calls are unchanged, and a non-empty terminal output is untouched. (cherry picked from commit f72ef070975445fe077c6c267369f08e38ca52e7) --- .../openai_gateway_buffered_hosted_items.go | 102 ++++++ ...enai_gateway_buffered_hosted_items_test.go | 346 ++++++++++++++++++ .../service/openai_gateway_messages.go | 5 + 3 files changed, 453 insertions(+) create mode 100644 backend/internal/service/openai_gateway_buffered_hosted_items.go create mode 100644 backend/internal/service/openai_gateway_buffered_hosted_items_test.go 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..133ae6dc55c4 --- /dev/null +++ b/backend/internal/service/openai_gateway_buffered_hosted_items.go @@ -0,0 +1,102 @@ +package service + +import ( + "encoding/json" + "slices" + "sort" + "strings" + + "github.com/Wei-Shaw/sub2api/internal/pkg/apicompat" + "github.com/tidwall/gjson" +) + +// openAICompatAccumulatedItemTypes are the output item types that +// apicompat.BufferedResponseAccumulator rebuilds from deltas. Every other type +// can only be recovered from its response.output_item.done event. +var openAICompatAccumulatedItemTypes = map[string]struct{}{ + "reasoning": {}, + "message": {}, + "function_call": {}, + "custom_tool_call": {}, +} + +type openAICompatHostedItem struct { + index int64 + indexed bool + raw json.RawMessage +} + +// openAICompatHostedItems collects the response.output_item.done items of types +// the delta accumulator does not produce, such as web_search_call and +// image_generation_call. +type openAICompatHostedItems struct { + items []openAICompatHostedItem +} + +func (h *openAICompatHostedItems) Observe(payload []byte) { + if h == nil || strings.TrimSpace(gjson.GetBytes(payload, "type").String()) != "response.output_item.done" || !gjson.ValidBytes(payload) { + return + } + item := gjson.GetBytes(payload, "item") + if !item.IsObject() { + return + } + itemType := strings.TrimSpace(item.Get("type").String()) + if _, ok := openAICompatAccumulatedItemTypes[itemType]; ok || itemType == "" { + return + } + entry := openAICompatHostedItem{raw: json.RawMessage(item.Raw)} + if index := gjson.GetBytes(payload, "output_index"); index.Exists() { + entry.index, entry.indexed = index.Int(), true + for i := range h.items { + if h.items[i].indexed && h.items[i].index == entry.index { + h.items[i] = entry + return + } + } + } + h.items = append(h.items, entry) +} + +// fillTerminalOutput gives an empty terminal output the collected hosted items +// ahead of what the accumulator rebuilds, after its leading reasoning item. +// 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. +// Hosted items keep their output_index order; items reported without an +// output_index follow the indexed ones in arrival order. +func (h *openAICompatHostedItems) fillTerminalOutput(eventType string, response *apicompat.ResponsesResponse, acc *apicompat.BufferedResponseAccumulator) { + switch strings.TrimSpace(eventType) { + case "response.completed", "response.done", "response.incomplete": + default: + return + } + if h == nil || len(h.items) == 0 || response == nil || len(response.Output) > 0 { + return + } + sort.SliceStable(h.items, func(i, j int) bool { + a, b := h.items[i], h.items[j] + if a.indexed != b.indexed { + return a.indexed + } + return a.indexed && a.index < b.index + }) + hosted := make([]apicompat.ResponsesOutput, 0, len(h.items)) + for _, entry := range h.items { + var item apicompat.ResponsesOutput + if err := json.Unmarshal(entry.raw, &item); err == nil { + hosted = append(hosted, item) + } + } + if len(hosted) == 0 { + return + } + var output []apicompat.ResponsesOutput + if acc != nil && acc.HasContent() { + output = acc.BuildOutput() + } + at := 0 + for at < len(output) && output[at].Type == "reasoning" { + at++ + } + response.Output = slices.Insert(output, at, hosted...) +} 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..435d3fe6a3cc --- /dev/null +++ b/backend/internal/service/openai_gateway_buffered_hosted_items_test.go @@ -0,0 +1,346 @@ +//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 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}) + 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)) + }) + } +} diff --git a/backend/internal/service/openai_gateway_messages.go b/backend/internal/service/openai_gateway_messages.go index df775684b1a0..da20f741cc92 100644 --- a/backend/internal/service/openai_gateway_messages.go +++ b/backend/internal/service/openai_gateway_messages.go @@ -907,6 +907,7 @@ func (s *OpenAIGatewayService) readOpenAICompatBufferedTerminal( ) (*apicompat.ResponsesResponse, OpenAIUsage, *apicompat.BufferedResponseAccumulator, openAICompatPriorModelAudit, error) { acc := apicompat.NewBufferedResponseAccumulator() acc.XAIServerSideSearch = account != nil && account.IsGrok() + hostedItems := &openAICompatHostedItems{} var usage OpenAIUsage if resp == nil || resp.Body == nil { return nil, usage, acc, openAICompatPriorModelAudit{}, errors.New("upstream response body is nil") @@ -987,6 +988,7 @@ func (s *OpenAIGatewayService) readOpenAICompatBufferedTerminal( if frame, ok := parser.Finish(); ok { payload := openAICompatPayloadWithEventType(frame.Data, frame.EventType) payload = string(restoreCodexToolNamesFromContext(c, []byte(payload))) + hostedItems.Observe([]byte(payload)) var event apicompat.ResponsesStreamEvent if err := json.Unmarshal([]byte(payload), &event); err == nil { s.parseSSEUsageBytesWithType([]byte(payload), event.Type, &usage) @@ -1002,6 +1004,7 @@ func (s *OpenAIGatewayService) readOpenAICompatBufferedTerminal( if response.Usage != nil { usage = copyOpenAIUsageFromResponsesUsage(response.Usage, usage) } + hostedItems.fillTerminalOutput(event.Type, response, acc) return response, usage, acc, prior, nil } } @@ -1028,6 +1031,7 @@ func (s *OpenAIGatewayService) readOpenAICompatBufferedTerminal( } payload := openAICompatPayloadWithEventType(frame.Data, frame.EventType) payload = string(restoreCodexToolNamesFromContext(c, []byte(payload))) + hostedItems.Observe([]byte(payload)) var event apicompat.ResponsesStreamEvent if err := json.Unmarshal([]byte(payload), &event); err != nil { @@ -1052,6 +1056,7 @@ func (s *OpenAIGatewayService) readOpenAICompatBufferedTerminal( if response.Usage != nil { usage = copyOpenAIUsageFromResponsesUsage(response.Usage, usage) } + hostedItems.fillTerminalOutput(event.Type, response, acc) return response, usage, acc, prior, nil } From 564c9896d37019735d71cf3069943c0e972ccd20 Mon Sep 17 00:00:00 2001 From: Anankke Date: Sat, 14 Nov 2026 12:49:12 -0800 Subject: [PATCH 12/87] fix(openai): rebuild empty buffered terminal output from done items An empty terminal output was rebuilt from merged deltas, so reasoning lost its per-item signature and segmentation, and message and tool order followed the accumulator instead of output_index. The buffered reader now records every output item and rebuilds the terminal output from the output_item.done items in output_index order, taking deltas only for a field a done item left empty or for an item that never got a done event. Items merge by item id, so items sharing an output_index stay apart and a repeated item replaces its earlier copy; response.cancelled terminals are filled too. A non-empty terminal output is untouched. A new test compares /v1/messages and /v1/chat/completions with the streaming path on shapes taken from real Codex streams. (cherry picked from commit 00b09b892d7bbbf14c004b4246771ffe3e019ad0) --- .../openai_gateway_buffered_hosted_items.go | 338 ++++++++++++++--- ...enai_gateway_buffered_hosted_items_test.go | 61 +++ ...nai_gateway_buffered_stream_parity_test.go | 347 ++++++++++++++++++ .../service/openai_gateway_messages.go | 10 +- 4 files changed, 692 insertions(+), 64 deletions(-) create mode 100644 backend/internal/service/openai_gateway_buffered_stream_parity_test.go diff --git a/backend/internal/service/openai_gateway_buffered_hosted_items.go b/backend/internal/service/openai_gateway_buffered_hosted_items.go index 133ae6dc55c4..c0e74c4abf2f 100644 --- a/backend/internal/service/openai_gateway_buffered_hosted_items.go +++ b/backend/internal/service/openai_gateway_buffered_hosted_items.go @@ -2,7 +2,6 @@ package service import ( "encoding/json" - "slices" "sort" "strings" @@ -10,93 +9,314 @@ import ( "github.com/tidwall/gjson" ) -// openAICompatAccumulatedItemTypes are the output item types that -// apicompat.BufferedResponseAccumulator rebuilds from deltas. Every other type -// can only be recovered from its response.output_item.done event. -var openAICompatAccumulatedItemTypes = map[string]struct{}{ - "reasoning": {}, - "message": {}, - "function_call": {}, - "custom_tool_call": {}, +// 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. +type openAICompatOutputSlot struct { + index int64 + indexed bool + itemType string + added *apicompat.ResponsesOutput + done *apicompat.ResponsesOutput + reasoning strings.Builder + text strings.Builder + refusal strings.Builder + args strings.Builder + argsDone string } -type openAICompatHostedItem struct { - index int64 - indexed bool - raw json.RawMessage +// 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 } -// openAICompatHostedItems collects the response.output_item.done items of types -// the delta accumulator does not produce, such as web_search_call and -// image_generation_call. -type openAICompatHostedItems struct { - items []openAICompatHostedItem +func openAICompatIsToolCallType(itemType string) bool { + return itemType == "function_call" || itemType == "custom_tool_call" } -func (h *openAICompatHostedItems) Observe(payload []byte) { - if h == nil || strings.TrimSpace(gjson.GetBytes(payload, "type").String()) != "response.output_item.done" || !gjson.ValidBytes(payload) { +func (o *openAICompatOutputSlots) Observe(payload []byte) { + if o == nil { return } - item := gjson.GetBytes(payload, "item") - if !item.IsObject() { - 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, false, true) + slot.added = &item + } + case "response.output_item.done": + if item, ok := openAICompatEventItem(payload); ok { + slot := o.slot(payload, item.Type, item.ID, true, true) + slot.done = &item + } + case "response.output_text.delta": + if delta := gjson.GetBytes(payload, "delta").String(); delta != "" { + _, _ = o.slot(payload, "message", "", false, true).text.WriteString(delta) + } + case "response.refusal.delta": + if delta := gjson.GetBytes(payload, "delta").String(); delta != "" { + _, _ = o.slot(payload, "message", "", false, true).refusal.WriteString(delta) + } + case "response.reasoning_summary_text.delta", "response.reasoning_text.delta": + if delta := gjson.GetBytes(payload, "delta").String(); delta != "" { + _, _ = o.slot(payload, "reasoning", "", false, true).reasoning.WriteString(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", "", false, false); slot != nil { + _, _ = slot.args.WriteString(delta) + } + } + case "response.function_call_arguments.done": + if slot := o.slot(payload, "function_call", "", 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", "", false, false); slot != nil { + if completed := gjson.GetBytes(payload, "input").String(); completed != "" { + slot.argsDone = completed + } + } } - itemType := strings.TrimSpace(item.Get("type").String()) - if _, ok := openAICompatAccumulatedItemTypes[itemType]; ok || itemType == "" { - return +} + +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 } - entry := openAICompatHostedItem{raw: json.RawMessage(item.Raw)} - if index := gjson.GetBytes(payload, "output_index"); index.Exists() { - entry.index, entry.indexed = index.Int(), true - for i := range h.items { - if h.items[i].indexed && h.items[i].index == entry.index { - h.items[i] = entry - return + item.Type = strings.TrimSpace(item.Type) + return item, item.Type != "" +} + +// slot finds the slot an event belongs to. 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 and items that merely share an output_index stay +// apart. Otherwise an event with an output_index belongs to the newest slot of +// that index (an added event: the newest one that has none yet; a done event +// without an id replaces the done item of that slot). An event without an +// output_index belongs to the newest unindexed slot of its kind (a done event: +// the oldest one still 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 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) + } + 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 { + switch { + case index.Exists(): + atIndex := func(slot *openAICompatOutputSlot) bool { return slot.indexed && slot.index == index.Int() } + 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 }) + default: + found = newest(atIndex) } + case added: + case done: + for _, slot := range o.slots { + if !slot.indexed && slot.done == nil && slot.itemType == kind { + found = slot + break + } + } + default: + found = newest(func(slot *openAICompatOutputSlot) bool { return !slot.indexed && matches(slot) }) + } + } + if found == nil { + if !create { + return nil + } + found = &openAICompatOutputSlot{} + if index.Exists() { + found.index, found.indexed = index.Int(), true } + o.slots = append(o.slots, found) } - h.items = append(h.items, entry) + if found.itemType == "" || done || added { + found.itemType = kind + } + return found } -// fillTerminalOutput gives an empty terminal output the collected hosted items -// ahead of what the accumulator rebuilds, after its leading reasoning item. -// 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. -// Hosted items keep their output_index order; items reported without an -// output_index follow the indexed ones in arrival order. -func (h *openAICompatHostedItems) fillTerminalOutput(eventType string, response *apicompat.ResponsesResponse, acc *apicompat.BufferedResponseAccumulator) { +// 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; 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": + case "response.completed", "response.done", "response.incomplete", "response.cancelled", "response.canceled": default: return } - if h == nil || len(h.items) == 0 || response == nil || len(response.Output) > 0 { + if o == nil || response == nil || len(response.Output) > 0 { return } - sort.SliceStable(h.items, func(i, j int) bool { - a, b := h.items[i], h.items[j] + 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 }) - hosted := make([]apicompat.ResponsesOutput, 0, len(h.items)) - for _, entry := range h.items { - var item apicompat.ResponsesOutput - if err := json.Unmarshal(entry.raw, &item); err == nil { - hosted = append(hosted, item) + for _, slot := range slots { + if item, ok := slot.build(); ok { + response.Output = append(response.Output, item) } } - if len(hosted) == 0 { - return +} + +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 openAICompatReasoningItemText(item apicompat.ResponsesOutput) string { + var text strings.Builder + for _, part := range item.Summary { + if part.Type == "summary_text" { + _, _ = text.WriteString(part.Text) + } + } + if text.Len() == 0 { + for _, part := range item.Content { + if part.Type == "reasoning_text" { + _, _ = text.WriteString(part.Text) + } + } + } + return text.String() +} + +func (s *openAICompatOutputSlot) buildReasoning() (apicompat.ResponsesOutput, bool) { + item := apicompat.ResponsesOutput{Type: "reasoning"} + if s.done != nil { + item = *s.done + } + if s.reasoning.Len() > 0 && openAICompatReasoningItemText(item) == "" { + item.Summary = []apicompat.ResponsesSummary{{Type: "summary_text", Text: s.reasoning.String()}} + item.Content = nil + } + return item, s.done != nil || s.reasoning.Len() > 0 +} + +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...) + } + if s.text.Len() > 0 { + filled := false + hasText := false + for i := range item.Content { + part := &item.Content[i] + if part.Type != "output_text" { + continue + } + if strings.TrimSpace(part.Text) != "" { + hasText = true + break + } + if !filled { + part.Text, filled = s.text.String(), true + } + } + if !hasText && !filled { + item.Content = append(item.Content, apicompat.ResponsesContentPart{Type: "output_text", Text: s.text.String()}) + } + } + if s.refusal.Len() > 0 { + hasRefusal := false + for _, part := range item.Content { + if part.Type == "refusal" && part.Refusal != "" { + hasRefusal = true + } + } + if !hasRefusal { + item.Content = append(item.Content, apicompat.ResponsesContentPart{Type: "refusal", Refusal: s.refusal.String()}) + } + } + return item, s.done != nil || s.text.Len() > 0 || s.refusal.Len() > 0 +} + +// buildToolCall returns a function_call item. A custom_tool_call is returned in +// that form as well, with its input as the arguments, because that is the shape +// the Chat Completions and Messages converters render as a tool call. +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 } - var output []apicompat.ResponsesOutput - if acc != nil && acc.HasContent() { - output = acc.BuildOutput() + if arguments == "" { + arguments = s.argsDone } - at := 0 - for at < len(output) && output[at].Type == "reasoning" { - at++ + if arguments == "" { + arguments = s.args.String() } - response.Output = slices.Insert(output, at, hosted...) + item.Type, item.Input, item.Arguments = "function_call", "", 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 index 435d3fe6a3cc..87159ed762a3 100644 --- a/backend/internal/service/openai_gateway_buffered_hosted_items_test.go +++ b/backend/internal/service/openai_gateway_buffered_hosted_items_test.go @@ -8,6 +8,7 @@ import ( "io" "net/http" "net/http/httptest" + "strconv" "strings" "testing" @@ -344,3 +345,63 @@ func TestBufferedCompat_FailedTerminalKeepsErrorPayload(t *testing.T) { }) } } + +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) +} 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..455c5e5875b5 --- /dev/null +++ b/backend/internal/service/openai_gateway_buffered_stream_parity_test.go @@ -0,0 +1,347 @@ +//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) + }) + } +} diff --git a/backend/internal/service/openai_gateway_messages.go b/backend/internal/service/openai_gateway_messages.go index da20f741cc92..dc9127bef203 100644 --- a/backend/internal/service/openai_gateway_messages.go +++ b/backend/internal/service/openai_gateway_messages.go @@ -907,7 +907,7 @@ func (s *OpenAIGatewayService) readOpenAICompatBufferedTerminal( ) (*apicompat.ResponsesResponse, OpenAIUsage, *apicompat.BufferedResponseAccumulator, openAICompatPriorModelAudit, error) { acc := apicompat.NewBufferedResponseAccumulator() acc.XAIServerSideSearch = account != nil && account.IsGrok() - hostedItems := &openAICompatHostedItems{} + outputSlots := &openAICompatOutputSlots{} var usage OpenAIUsage if resp == nil || resp.Body == nil { return nil, usage, acc, openAICompatPriorModelAudit{}, errors.New("upstream response body is nil") @@ -988,7 +988,7 @@ func (s *OpenAIGatewayService) readOpenAICompatBufferedTerminal( if frame, ok := parser.Finish(); ok { payload := openAICompatPayloadWithEventType(frame.Data, frame.EventType) payload = string(restoreCodexToolNamesFromContext(c, []byte(payload))) - hostedItems.Observe([]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) @@ -1004,7 +1004,7 @@ func (s *OpenAIGatewayService) readOpenAICompatBufferedTerminal( if response.Usage != nil { usage = copyOpenAIUsageFromResponsesUsage(response.Usage, usage) } - hostedItems.fillTerminalOutput(event.Type, response, acc) + outputSlots.fillTerminalOutput(event.Type, response) return response, usage, acc, prior, nil } } @@ -1031,7 +1031,7 @@ func (s *OpenAIGatewayService) readOpenAICompatBufferedTerminal( } payload := openAICompatPayloadWithEventType(frame.Data, frame.EventType) payload = string(restoreCodexToolNamesFromContext(c, []byte(payload))) - hostedItems.Observe([]byte(payload)) + outputSlots.Observe([]byte(payload)) var event apicompat.ResponsesStreamEvent if err := json.Unmarshal([]byte(payload), &event); err != nil { @@ -1056,7 +1056,7 @@ func (s *OpenAIGatewayService) readOpenAICompatBufferedTerminal( if response.Usage != nil { usage = copyOpenAIUsageFromResponsesUsage(response.Usage, usage) } - hostedItems.fillTerminalOutput(event.Type, response, acc) + outputSlots.fillTerminalOutput(event.Type, response) return response, usage, acc, prior, nil } From 00c890480808ff172576172c158f4f3f3a00d9d6 Mon Sep 17 00:00:00 2001 From: Anankke Date: Sat, 14 Nov 2026 12:56:42 -0800 Subject: [PATCH 13/87] fix(apicompat): keep tool_use input a JSON object in buffered responses A tool call whose arguments were not a JSON object (truncated by max_output_tokens, empty, or the free-form input of a custom_tool_call) made json.Marshal fail, so /v1/messages answered 200 with an empty body. ResponsesToAnthropic now keeps an object as it is, uses {} for a function_call with anything else, and wraps a custom_tool_call input as {"input": ...}, the shape extractCustomToolCallInput reads back. Both converters now render custom_tool_call items, which were dropped when the terminal output carried them. The streaming converter is unchanged: it forwards the argument deltas as the upstream sent them. (cherry picked from commit fbe8c39a90e8b2b3153f418cc828dc6f97281ed9) --- .../pkg/apicompat/responses_to_anthropic.go | 28 +++++++- .../responses_to_anthropic_tool_input_test.go | 68 +++++++++++++++++++ .../apicompat/responses_to_chatcompletions.go | 9 +++ .../openai_gateway_buffered_hosted_items.go | 11 +-- ...enai_gateway_buffered_hosted_items_test.go | 31 +++++++++ 5 files changed, 142 insertions(+), 5 deletions(-) create mode 100644 backend/internal/pkg/apicompat/responses_to_anthropic_tool_input_test.go diff --git a/backend/internal/pkg/apicompat/responses_to_anthropic.go b/backend/internal/pkg/apicompat/responses_to_anthropic.go index d11c17b1c492..01b0329bff38 100644 --- a/backend/internal/pkg/apicompat/responses_to_anthropic.go +++ b/backend/internal/pkg/apicompat/responses_to_anthropic.go @@ -53,7 +53,14 @@ 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": + 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)) @@ -146,6 +153,25 @@ 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. +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" { + 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) 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..1e64c11c5c2d --- /dev/null +++ b/backend/internal/pkg/apicompat/responses_to_anthropic_tool_input_test.go @@ -0,0 +1,68 @@ +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 wrapped", "custom_tool_call", "", "{\"input\":\"\"}"}, + {"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"}, + }} + 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"}, + }} + 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) +} diff --git a/backend/internal/pkg/apicompat/responses_to_chatcompletions.go b/backend/internal/pkg/apicompat/responses_to_chatcompletions.go index 3bdc4d7c1f4c..b01fee4302a5 100644 --- a/backend/internal/pkg/apicompat/responses_to_chatcompletions.go +++ b/backend/internal/pkg/apicompat/responses_to_chatcompletions.go @@ -56,6 +56,15 @@ func ResponsesToChatCompletions(resp *ResponsesResponse, model string) *ChatComp Arguments: item.Arguments, }, }) + case "custom_tool_call": + 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": diff --git a/backend/internal/service/openai_gateway_buffered_hosted_items.go b/backend/internal/service/openai_gateway_buffered_hosted_items.go index c0e74c4abf2f..396d26af4ca2 100644 --- a/backend/internal/service/openai_gateway_buffered_hosted_items.go +++ b/backend/internal/service/openai_gateway_buffered_hosted_items.go @@ -280,9 +280,8 @@ func (s *openAICompatOutputSlot) buildMessage() (apicompat.ResponsesOutput, bool return item, s.done != nil || s.text.Len() > 0 || s.refusal.Len() > 0 } -// buildToolCall returns a function_call item. A custom_tool_call is returned in -// that form as well, with its input as the arguments, because that is the shape -// the Chat Completions and Messages converters render as a tool call. +// 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 @@ -317,6 +316,10 @@ func (s *openAICompatOutputSlot) buildToolCall() (apicompat.ResponsesOutput, boo if arguments == "" { arguments = s.args.String() } - item.Type, item.Input, item.Arguments = "function_call", "", arguments + 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 index 87159ed762a3..8792b57a63c7 100644 --- a/backend/internal/service/openai_gateway_buffered_hosted_items_test.go +++ b/backend/internal/service/openai_gateway_buffered_hosted_items_test.go @@ -405,3 +405,34 @@ func TestForwardAsAnthropic_CancelledTerminalKeepsHostedOutputItems(t *testing.T 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) +} From e95f9083b14c7f6476169efb3214e86509297d04 Mon Sep 17 00:00:00 2001 From: Anankke Date: Sat, 14 Nov 2026 17:40:48 -0800 Subject: [PATCH 14/87] fix(openai): render custom tool calls only from rebuilt buffered output A custom_tool_call in an output the upstream delivered is not a client tool call; 250deb70e5 rendered it on that path too, which turns xAI server-side searches into tool_use. ResponsesResponse.RenderCustomToolCalls is set only when the buffered reader rebuilds an empty output, so a delivered output behaves as before the rework. A reasoning done item that carries both a summary and raw reasoning_text content now takes its text from the deltas again, as the streaming path shows it. (cherry picked from commit 49ef5f6909661a2c0dfc88b586d83568fd3cde70) --- .../pkg/apicompat/responses_to_anthropic.go | 3 ++ .../responses_to_anthropic_tool_input_test.go | 16 ++++++- .../apicompat/responses_to_chatcompletions.go | 3 ++ backend/internal/pkg/apicompat/types.go | 5 +++ .../openai_gateway_buffered_hosted_items.go | 43 +++++++++---------- ...enai_gateway_buffered_hosted_items_test.go | 14 ++++++ 6 files changed, 60 insertions(+), 24 deletions(-) diff --git a/backend/internal/pkg/apicompat/responses_to_anthropic.go b/backend/internal/pkg/apicompat/responses_to_anthropic.go index 01b0329bff38..3a28d057a988 100644 --- a/backend/internal/pkg/apicompat/responses_to_anthropic.go +++ b/backend/internal/pkg/apicompat/responses_to_anthropic.go @@ -56,6 +56,9 @@ func ResponsesToAnthropic(resp *ResponsesResponse, model string) *AnthropicRespo Input: anthropicToolUseInput(item.Type, item.Name, item.Arguments), }) case "custom_tool_call": + if !resp.RenderCustomToolCalls { + continue + } blocks = append(blocks, AnthropicContentBlock{ Type: "tool_use", ID: fromResponsesCallID(item.CallID), 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 index 1e64c11c5c2d..3c6f819bcea5 100644 --- a/backend/internal/pkg/apicompat/responses_to_anthropic_tool_input_test.go +++ b/backend/internal/pkg/apicompat/responses_to_anthropic_tool_input_test.go @@ -46,7 +46,7 @@ func TestResponsesToAnthropicInvalidToolInputStillMarshals(t *testing.T) { {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) @@ -60,9 +60,21 @@ func TestResponsesToAnthropicInvalidToolInputStillMarshals(t *testing.T) { 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 b01fee4302a5..e4753ac65ddc 100644 --- a/backend/internal/pkg/apicompat/responses_to_chatcompletions.go +++ b/backend/internal/pkg/apicompat/responses_to_chatcompletions.go @@ -57,6 +57,9 @@ func ResponsesToChatCompletions(resp *ResponsesResponse, model string) *ChatComp }, }) case "custom_tool_call": + if !resp.RenderCustomToolCalls { + continue + } toolCalls = append(toolCalls, ChatToolCall{ ID: item.CallID, Type: "function", diff --git a/backend/internal/pkg/apicompat/types.go b/backend/internal/pkg/apicompat/types.go index 4fecfd62f29b..6ea416028a0a 100644 --- a/backend/internal/pkg/apicompat/types.go +++ b/backend/internal/pkg/apicompat/types.go @@ -485,6 +485,11 @@ 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:"-"` } // ResponsesError describes an error in a failed response. diff --git a/backend/internal/service/openai_gateway_buffered_hosted_items.go b/backend/internal/service/openai_gateway_buffered_hosted_items.go index 396d26af4ca2..e2c787dd6910 100644 --- a/backend/internal/service/openai_gateway_buffered_hosted_items.go +++ b/backend/internal/service/openai_gateway_buffered_hosted_items.go @@ -166,8 +166,8 @@ func (o *openAICompatOutputSlots) slot(payload []byte, kind, id string, done, cr // 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 +// 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; 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 @@ -192,6 +192,9 @@ func (o *openAICompatOutputSlots) fillTerminalOutput(eventType string, response for _, slot := range slots { if item, ok := slot.build(); ok { response.Output = append(response.Output, item) + if item.Type == "custom_tool_call" { + response.RenderCustomToolCalls = true + } } } } @@ -211,31 +214,27 @@ func (s *openAICompatOutputSlot) build() (apicompat.ResponsesOutput, bool) { return *s.done, true } -func openAICompatReasoningItemText(item apicompat.ResponsesOutput) string { - var text strings.Builder - for _, part := range item.Summary { - if part.Type == "summary_text" { - _, _ = text.WriteString(part.Text) - } - } - if text.Len() == 0 { - for _, part := range item.Content { - if part.Type == "reasoning_text" { - _, _ = text.WriteString(part.Text) - } - } - } - return text.String() -} - func (s *openAICompatOutputSlot) buildReasoning() (apicompat.ResponsesOutput, bool) { item := apicompat.ResponsesOutput{Type: "reasoning"} if s.done != nil { item = *s.done } - if s.reasoning.Len() > 0 && openAICompatReasoningItemText(item) == "" { - item.Summary = []apicompat.ResponsesSummary{{Type: "summary_text", Text: s.reasoning.String()}} - item.Content = nil + // 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 != "") + } + if summary == content { + item.Summary = []apicompat.ResponsesSummary{{Type: "summary_text", Text: s.reasoning.String()}} + item.Content = nil + } } return item, s.done != nil || s.reasoning.Len() > 0 } diff --git a/backend/internal/service/openai_gateway_buffered_hosted_items_test.go b/backend/internal/service/openai_gateway_buffered_hosted_items_test.go index 8792b57a63c7..e3fc5c14d731 100644 --- a/backend/internal/service/openai_gateway_buffered_hosted_items_test.go +++ b/backend/internal/service/openai_gateway_buffered_hosted_items_test.go @@ -436,3 +436,17 @@ func TestForwardAsAnthropic_BufferedNonObjectToolInput(t *testing.T) { 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) +} From e59f34cf08d289c9296006da63bf77bf323c2b08 Mon Sep 17 00:00:00 2001 From: Anankke Date: Sun, 15 Nov 2026 02:35:40 -0800 Subject: [PATCH 15/87] fix(openai): complete buffered item parts by their own index A message or reasoning item with several parts lost or doubled text when its done item left only some of them empty and the terminal output was empty. Observe now keeps the deltas per content_index or summary_index, apart for output_text, refusal, summary_text and reasoning_text. buildMessage and buildReasoning fill only the blank part whose own index has deltas and keep the parts with text and their order as the done item has them. Deltas of an index the done item has no part for follow its parts. (cherry picked from commit 5279823757cc8d836316243e5f37a13715ce4b81) --- .../openai_gateway_buffered_hosted_items.go | 191 ++++++++++++++---- ...enai_gateway_buffered_hosted_items_test.go | 140 +++++++++++++ ...nai_gateway_buffered_stream_parity_test.go | 90 +++++++++ 3 files changed, 377 insertions(+), 44 deletions(-) diff --git a/backend/internal/service/openai_gateway_buffered_hosted_items.go b/backend/internal/service/openai_gateway_buffered_hosted_items.go index e2c787dd6910..da592bffd248 100644 --- a/backend/internal/service/openai_gateway_buffered_hosted_items.go +++ b/backend/internal/service/openai_gateway_buffered_hosted_items.go @@ -2,6 +2,7 @@ package service import ( "encoding/json" + "math" "sort" "strings" @@ -9,20 +10,69 @@ import ( "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 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 - added *apicompat.ResponsesOutput - done *apicompat.ResponsesOutput - reasoning strings.Builder - text strings.Builder - refusal strings.Builder - args strings.Builder - argsDone string + index int64 + indexed bool + itemType 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 @@ -52,15 +102,23 @@ func (o *openAICompatOutputSlots) Observe(payload []byte) { } case "response.output_text.delta": if delta := gjson.GetBytes(payload, "delta").String(); delta != "" { - _, _ = o.slot(payload, "message", "", false, true).text.WriteString(delta) + o.slot(payload, "message", "", 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", "", false, true).refusal.WriteString(delta) + o.slot(payload, "message", "", 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", "", false, true) + _, _ = slot.reasoning.WriteString(delta) + slot.summaryText.write(gjson.GetBytes(payload, "summary_index").Int(), delta) } - case "response.reasoning_summary_text.delta", "response.reasoning_text.delta": + case "response.reasoning_text.delta": if delta := gjson.GetBytes(payload, "delta").String(); delta != "" { - _, _ = o.slot(payload, "reasoning", "", false, true).reasoning.WriteString(delta) + slot := o.slot(payload, "reasoning", "", 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 != "" { @@ -168,8 +226,8 @@ func (o *openAICompatOutputSlots) slot(payload []byte, kind, id string, done, cr // 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; an item that never received it is rebuilt from its -// deltas. Only terminals that carry a result are filled; the output of +// 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) { @@ -231,9 +289,40 @@ func (s *openAICompatOutputSlot) buildReasoning() (apicompat.ResponsesOutput, bo for _, part := range item.Content { content = content || (part.Type == "reasoning_text" && part.Text != "") } - if summary == content { + 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 @@ -245,38 +334,52 @@ func (s *openAICompatOutputSlot) buildMessage() (apicompat.ResponsesOutput, bool item = *s.done item.Content = append([]apicompat.ResponsesContentPart(nil), item.Content...) } - if s.text.Len() > 0 { - filled := false - hasText := false - for i := range item.Content { - part := &item.Content[i] - if part.Type != "output_text" { - continue - } - if strings.TrimSpace(part.Text) != "" { - hasText = true - break - } - if !filled { - part.Text, filled = s.text.String(), true - } + 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 !hasText && !filled { - item.Content = append(item.Content, apicompat.ResponsesContentPart{Type: "output_text", Text: s.text.String()}) + } + 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}) } } - if s.refusal.Len() > 0 { - hasRefusal := false - for _, part := range item.Content { - if part.Type == "refusal" && part.Refusal != "" { - hasRefusal = true - } + 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 } - if !hasRefusal { - item.Content = append(item.Content, apicompat.ResponsesContentPart{Type: "refusal", Refusal: s.refusal.String()}) + 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 item, s.done != nil || s.text.Len() > 0 || s.refusal.Len() > 0 + return deltas.unclaimed(claimed, from) } // buildToolCall returns the function_call or custom_tool_call item of the slot, diff --git a/backend/internal/service/openai_gateway_buffered_hosted_items_test.go b/backend/internal/service/openai_gateway_buffered_hosted_items_test.go index e3fc5c14d731..da05eb1ec81a 100644 --- a/backend/internal/service/openai_gateway_buffered_hosted_items_test.go +++ b/backend/internal/service/openai_gateway_buffered_hosted_items_test.go @@ -450,3 +450,143 @@ func TestForwardAsAnthropic_BufferedReasoningSummaryAndContentKeepBoth(t *testin 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) + }) + } + } +} diff --git a/backend/internal/service/openai_gateway_buffered_stream_parity_test.go b/backend/internal/service/openai_gateway_buffered_stream_parity_test.go index 455c5e5875b5..322798f09cad 100644 --- a/backend/internal/service/openai_gateway_buffered_stream_parity_test.go +++ b/backend/internal/service/openai_gateway_buffered_stream_parity_test.go @@ -345,3 +345,93 @@ func TestBufferedCompat_MatchesStreamingPathOnRealStreamShapes(t *testing.T) { }) } } + +// 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) + }) + } + } + } +} From 706f998dd1fcd51fa45f252a1cf0e36ce71770ea Mon Sep 17 00:00:00 2001 From: Anankke Date: Sun, 15 Nov 2026 04:10:53 -0800 Subject: [PATCH 16/87] fix(openai): follow the streaming path for rebuilt buffered items A rebuilt output skips a web search that is not completed, gives an empty custom tool input as {} and keeps a reasoning signature that only the added event carries. Deltas without an output_index join their item by item_id or as the newest open item of their kind, and deltas that came before the item was added belong to it. Items that share an output_index or have none keep their own events: an item of another kind, a done item that is already closed and a different call_id each get their own slot. (cherry picked from commit 7f1ecfaa2dab996e39165ffbeadb71c0fb371927) --- .../pkg/apicompat/responses_to_anthropic.go | 5 +- .../responses_to_anthropic_tool_input_test.go | 2 +- .../openai_gateway_buffered_hosted_items.go | 99 +++++++--- ...enai_gateway_buffered_hosted_items_test.go | 185 ++++++++++++++++++ 4 files changed, 260 insertions(+), 31 deletions(-) diff --git a/backend/internal/pkg/apicompat/responses_to_anthropic.go b/backend/internal/pkg/apicompat/responses_to_anthropic.go index 3a28d057a988..8ee66e8e1612 100644 --- a/backend/internal/pkg/apicompat/responses_to_anthropic.go +++ b/backend/internal/pkg/apicompat/responses_to_anthropic.go @@ -161,12 +161,13 @@ func containsAnthropicToolUseBlock(blocks []AnthropicContentBlock) bool { // 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. +// 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" { + if itemType == "custom_tool_call" && raw != "" { wrapped, err := json.Marshal(map[string]string{"input": raw}) if err == nil { return wrapped 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 index 3c6f819bcea5..a0a99d3798cd 100644 --- a/backend/internal/pkg/apicompat/responses_to_anthropic_tool_input_test.go +++ b/backend/internal/pkg/apicompat/responses_to_anthropic_tool_input_test.go @@ -20,7 +20,7 @@ func TestAnthropicToolUseInput(t *testing.T) { {"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 wrapped", "custom_tool_call", "", "{\"input\":\"\"}"}, + {"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 { diff --git a/backend/internal/service/openai_gateway_buffered_hosted_items.go b/backend/internal/service/openai_gateway_buffered_hosted_items.go index da592bffd248..772f0bc1affd 100644 --- a/backend/internal/service/openai_gateway_buffered_hosted_items.go +++ b/backend/internal/service/openai_gateway_buffered_hosted_items.go @@ -64,6 +64,7 @@ type openAICompatOutputSlot struct { index int64 indexed bool itemType string + id string added *apicompat.ResponsesOutput done *apicompat.ResponsesOutput reasoning strings.Builder @@ -92,48 +93,48 @@ func (o *openAICompatOutputSlots) Observe(payload []byte) { 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, false, true) + 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, true, true) + 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", "", false, true).text.write(gjson.GetBytes(payload, "content_index").Int(), 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", "", false, true).refusal.write(gjson.GetBytes(payload, "content_index").Int(), 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", "", false, true) + 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", "", false, true) + 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", "", false, false); slot != nil { + 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", "", false, false); slot != nil { + 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", "", false, false); slot != nil { + 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 } @@ -151,17 +152,24 @@ func openAICompatEventItem(payload []byte) (apicompat.ResponsesOutput, bool) { return item, item.Type != "" } -// slot finds the slot an event belongs to. A done event whose item has an id +// 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 and items that merely share an output_index stay -// apart. Otherwise an event with an output_index belongs to the newest slot of -// that index (an added event: the newest one that has none yet; a done event -// without an id replaces the done item of that slot). An event without an -// output_index belongs to the newest unindexed slot of its kind (a done event: -// the oldest one still 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 string, done, create bool) *openAICompatOutputSlot { +// 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 { @@ -170,6 +178,9 @@ func (o *openAICompatOutputSlots) slot(payload []byte, kind, id string, done, cr } 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]) { @@ -182,40 +193,64 @@ func (o *openAICompatOutputSlots) slot(payload []byte, kind, id string, done, cr 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() } + 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 }) + 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 !slot.indexed && slot.done == nil && slot.itemType == kind { + if found == nil && !slot.indexed && slot.done == nil && slot.itemType == kind { found = slot - break } } default: - found = newest(func(slot *openAICompatOutputSlot) bool { return !slot.indexed && matches(slot) }) + 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{} - if index.Exists() { - found.index, found.indexed = index.Int(), true - } 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 } @@ -249,6 +284,10 @@ func (o *openAICompatOutputSlots) fillTerminalOutput(eventType string, response }) 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 @@ -277,6 +316,10 @@ func (s *openAICompatOutputSlot) buildReasoning() (apicompat.ResponsesOutput, bo 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 @@ -325,7 +368,7 @@ func (s *openAICompatOutputSlot) buildReasoning() (apicompat.ResponsesOutput, bo } } } - return item, s.done != nil || s.reasoning.Len() > 0 + return item, s.done != nil || s.reasoning.Len() > 0 || strings.TrimSpace(item.EncryptedContent) != "" } func (s *openAICompatOutputSlot) buildMessage() (apicompat.ResponsesOutput, bool) { diff --git a/backend/internal/service/openai_gateway_buffered_hosted_items_test.go b/backend/internal/service/openai_gateway_buffered_hosted_items_test.go index da05eb1ec81a..d137fe14e7f1 100644 --- a/backend/internal/service/openai_gateway_buffered_hosted_items_test.go +++ b/backend/internal/service/openai_gateway_buffered_hosted_items_test.go @@ -590,3 +590,188 @@ func TestBufferedCompat_PartialReasoningParts(t *testing.T) { } } } + +// 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) + } +} From ff662d8df43e7458e5c8b78e8a75e3f7721b0034 Mon Sep 17 00:00:00 2001 From: Anankke Date: Mon, 16 Nov 2026 00:43:36 -0800 Subject: [PATCH 17/87] fix(openai): keep xAI server-side search out of rebuilt buffered tool calls A buffered request on a Grok account rebuilds an empty terminal output from the done items and renders its custom_tool_call items as tool_use or tool_calls. An item that apicompat.IsServerSideSearchCall accepts is a search xAI ran itself, so it is no longer rendered as a client tool call. The item stays in the output, so Grok SearchCount still counts it, and stop_reason and finish_reason follow the remaining content. A new test covers an empty terminal on /v1/messages and /v1/chat/completions, with and without a client tool next to the search. (cherry picked from commit 413f1cb08a449d855aaa5220b12940c93704bd88) --- .../pkg/apicompat/responses_to_anthropic.go | 2 +- .../apicompat/responses_to_chatcompletions.go | 2 +- backend/internal/pkg/apicompat/types.go | 5 ++ .../openai_gateway_buffered_hosted_items.go | 4 ++ ...ateway_buffered_server_side_search_test.go | 65 +++++++++++++++++++ .../service/openai_gateway_messages.go | 2 +- 6 files changed, 77 insertions(+), 3 deletions(-) create mode 100644 backend/internal/service/openai_gateway_buffered_server_side_search_test.go diff --git a/backend/internal/pkg/apicompat/responses_to_anthropic.go b/backend/internal/pkg/apicompat/responses_to_anthropic.go index 8ee66e8e1612..43b64b9d02ef 100644 --- a/backend/internal/pkg/apicompat/responses_to_anthropic.go +++ b/backend/internal/pkg/apicompat/responses_to_anthropic.go @@ -56,7 +56,7 @@ func ResponsesToAnthropic(resp *ResponsesResponse, model string) *AnthropicRespo Input: anthropicToolUseInput(item.Type, item.Name, item.Arguments), }) case "custom_tool_call": - if !resp.RenderCustomToolCalls { + if !resp.RenderCustomToolCalls || (resp.XAIServerSideSearch && IsServerSideSearchCall(item.Type, item.CallID)) { continue } blocks = append(blocks, AnthropicContentBlock{ diff --git a/backend/internal/pkg/apicompat/responses_to_chatcompletions.go b/backend/internal/pkg/apicompat/responses_to_chatcompletions.go index e4753ac65ddc..5bd60f3f5f05 100644 --- a/backend/internal/pkg/apicompat/responses_to_chatcompletions.go +++ b/backend/internal/pkg/apicompat/responses_to_chatcompletions.go @@ -57,7 +57,7 @@ func ResponsesToChatCompletions(resp *ResponsesResponse, model string) *ChatComp }, }) case "custom_tool_call": - if !resp.RenderCustomToolCalls { + if !resp.RenderCustomToolCalls || (resp.XAIServerSideSearch && IsServerSideSearchCall(item.Type, item.CallID)) { continue } toolCalls = append(toolCalls, ChatToolCall{ diff --git a/backend/internal/pkg/apicompat/types.go b/backend/internal/pkg/apicompat/types.go index 6ea416028a0a..13f5c4973bd7 100644 --- a/backend/internal/pkg/apicompat/types.go +++ b/backend/internal/pkg/apicompat/types.go @@ -490,6 +490,11 @@ type ResponsesResponse struct { // 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. diff --git a/backend/internal/service/openai_gateway_buffered_hosted_items.go b/backend/internal/service/openai_gateway_buffered_hosted_items.go index 772f0bc1affd..69ac8f6205da 100644 --- a/backend/internal/service/openai_gateway_buffered_hosted_items.go +++ b/backend/internal/service/openai_gateway_buffered_hosted_items.go @@ -80,6 +80,9 @@ type openAICompatOutputSlot struct { // 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 { @@ -291,6 +294,7 @@ func (o *openAICompatOutputSlots) fillTerminalOutput(eventType string, response response.Output = append(response.Output, item) if item.Type == "custom_tool_call" { response.RenderCustomToolCalls = true + response.XAIServerSideSearch = o.xaiServerSideSearch } } } 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_messages.go b/backend/internal/service/openai_gateway_messages.go index dc9127bef203..957638cd4e5f 100644 --- a/backend/internal/service/openai_gateway_messages.go +++ b/backend/internal/service/openai_gateway_messages.go @@ -907,7 +907,7 @@ func (s *OpenAIGatewayService) readOpenAICompatBufferedTerminal( ) (*apicompat.ResponsesResponse, OpenAIUsage, *apicompat.BufferedResponseAccumulator, openAICompatPriorModelAudit, error) { acc := apicompat.NewBufferedResponseAccumulator() acc.XAIServerSideSearch = account != nil && account.IsGrok() - outputSlots := &openAICompatOutputSlots{} + 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") From 3890d8ce4b0deb3a0cf89f97f94a5576efffc5ed Mon Sep 17 00:00:00 2001 From: r266-tech Date: Mon, 16 Nov 2026 15:00:05 +0800 Subject: [PATCH 18/87] perf(scheduler): omit expanded groups from account cache (cherry picked from commit 18c42a29d2edb2e314eef5115021fe33b7fa5af6) --- .../internal/repository/scheduler_cache.go | 4 + .../scheduler_cache_integration_test.go | 9 +- .../scheduler_cache_payload_unit_test.go | 116 ++++++++++++++++++ .../repository/scheduler_cache_unit_test.go | 1 - 4 files changed, 128 insertions(+), 2 deletions(-) create mode 100644 backend/internal/repository/scheduler_cache_payload_unit_test.go diff --git a/backend/internal/repository/scheduler_cache.go b/backend/internal/repository/scheduler_cache.go index 4f9995feb1e4..568995904e79 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, From b3735bd2e879686b5c49fbf2d18328295e354041 Mon Sep 17 00:00:00 2001 From: wucm667 Date: Mon, 16 Nov 2026 20:52:14 +0800 Subject: [PATCH 19/87] fix(accounts): refresh Claude and Gemini usage snapshots (cherry picked from commit fa796b309a613785396a0c658b710ba8c13b3a1f) --- .../components/account/AccountUsageCell.vue | 22 ++++--- .../__tests__/AccountUsageCell.spec.ts | 62 +++++++++++++++++++ .../__tests__/accountUsageRefresh.spec.ts | 27 +++++++- frontend/src/utils/accountUsageRefresh.ts | 26 ++++++++ frontend/src/views/admin/AccountsView.vue | 11 ++-- .../admin/__tests__/AccountsView.lite.spec.ts | 48 +++++++++++++- 6 files changed, 178 insertions(+), 18 deletions(-) diff --git a/frontend/src/components/account/AccountUsageCell.vue b/frontend/src/components/account/AccountUsageCell.vue index 6850c2d0e0ba..7c34578cb239 100644 --- a/frontend/src/components/account/AccountUsageCell.vue +++ b/frontend/src/components/account/AccountUsageCell.vue @@ -778,7 +778,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 +798,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( @@ -977,7 +977,7 @@ const openAISevenDayEstimatedTotalCost = computed(() => { return Number.isFinite(estimate) && estimate > 0 ? estimate : null }) -const openAIUsageRefreshKey = computed(() => buildOpenAIUsageRefreshKey(props.account)) +const usageRefreshKey = computed(() => buildAccountUsageRefreshKey(props.account)) const shouldAutoLoadUsageOnMount = computed(() => { return shouldFetchUsage.value @@ -1602,7 +1602,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 +1611,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 +1620,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 +1684,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 +1865,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/__tests__/AccountUsageCell.spec.ts b/frontend/src/components/account/__tests__/AccountUsageCell.spec.ts index 300024b2baab..76a0c2b3e2c1 100644 --- a/frontend/src/components/account/__tests__/AccountUsageCell.spec.ts +++ b/frontend/src/components/account/__tests__/AccountUsageCell.spec.ts @@ -116,6 +116,68 @@ const cnUsageCellStubs = { } describe('AccountUsageCell', () => { + it.each([ + ['anthropic', 'oauth'], ['anthropic', 'setup-token'], ['gemini', 'oauth'], ['gemini', 'apikey'] + ] as const)('refreshes %s %s snapshots without forcing upstream reads and reuses the new cache', async (platform, type) => { + const account = makeAccount({ id: 98200 + (platform === 'gemini' ? 10 : 0) + (type === 'oauth' ? 1 : 2), platform, type, extra: {} }) + getUsage.mockResolvedValue({ five_hour: { utilization: 21 }, seven_day: { utilization: 31 }, gemini_shared_daily: { utilization: 31 } }) + const wrapper = mount(AccountUsageCell, { props: { account } }) + await flushPromises() + expect(getUsage).toHaveBeenCalledTimes(1) + getUsage.mockResolvedValue({ five_hour: { utilization: 44 }, seven_day: { utilization: 54 }, gemini_shared_daily: { utilization: 54 } }) + const next = { ...account, last_used_at: platform === 'gemini' ? '2026-11-16T10:00:00Z' : null, extra: { passive_usage_7d_utilization: 0.54 } } + await wrapper.setProps({ account: next }) + await flushPromises() + expect(getUsage).toHaveBeenCalledTimes(2) + expect(getUsage).toHaveBeenLastCalledWith(...(platform === 'anthropic' ? [account.id, 'passive', false] : [account.id])) + expect(wrapper.text()).toContain('54') + await wrapper.setProps({ account: { ...next, updated_at: 'unrelated', current_concurrency: 3 } }) + await flushPromises() + expect(getUsage).toHaveBeenCalledTimes(2) + wrapper.unmount() + }) + + it.each(['anthropic', 'gemini'] as const)('asks the desktop batch manager to refresh %s without force', async (platform) => { + const account = makeAccount({ id: 98301, platform, extra: {} }) + const requestBatchedUsage = vi.fn() + const wrapper = mount(AccountUsageCell, { props: { account, requestBatchedUsage } }) + await flushPromises() + requestBatchedUsage.mockClear() + await wrapper.setProps({ account: { ...account, last_used_at: '2026-11-16T10:00:00Z' } }) + expect(requestBatchedUsage).toHaveBeenCalledTimes(1) + expect(requestBatchedUsage).toHaveBeenCalledWith(expect.objectContaining({ id: account.id }), undefined) + expect(getUsage).not.toHaveBeenCalled() + wrapper.unmount() + }) + + it.each(['anthropic', 'gemini'] as const)('defers mobile %s snapshot refresh until visible', async (platform) => { + vi.mocked(window.matchMedia).mockReturnValue({ matches: false, addEventListener: vi.fn(), removeEventListener: vi.fn() } as unknown as MediaQueryList) + let notify: IntersectionObserverCallback = () => {} + vi.stubGlobal('IntersectionObserver', class { + constructor(callback: IntersectionObserverCallback) { notify = callback } + observe() {} + disconnect() {} + }) + const account = makeAccount({ id: 98401, platform, extra: {} }) + getUsage.mockResolvedValue({ five_hour: { utilization: 44 }, gemini_shared_daily: { utilization: 44 } }) + const wrapper = mount(AccountUsageCell, { props: { account } }) + try { + await flushPromises() + await wrapper.setProps({ account: { ...account, last_used_at: '2026-11-16T10:00:00Z' } }) + expect(getUsage).not.toHaveBeenCalled() + notify([{ isIntersecting: true }] as IntersectionObserverEntry[], {} as IntersectionObserver) + await flushPromises() + expect(getUsage).toHaveBeenCalledTimes(1) + expect(getUsage).toHaveBeenLastCalledWith(...(platform === 'anthropic' ? [account.id, 'passive', false] : [account.id])) + await wrapper.setProps({ account: { ...account, last_used_at: '2026-11-16T10:01:00Z' } }) + await flushPromises() + expect(getUsage).toHaveBeenCalledTimes(2) + } finally { + wrapper.unmount() + vi.unstubAllGlobals() + } + }) + beforeEach(() => { getUsage.mockReset() Object.defineProperty(window, 'matchMedia', { diff --git a/frontend/src/utils/__tests__/accountUsageRefresh.spec.ts b/frontend/src/utils/__tests__/accountUsageRefresh.spec.ts index f9559697e11b..f2d21a421247 100644 --- a/frontend/src/utils/__tests__/accountUsageRefresh.spec.ts +++ b/frontend/src/utils/__tests__/accountUsageRefresh.spec.ts @@ -1,5 +1,30 @@ import { describe, expect, it } from 'vitest' -import { buildGrokUsageRefreshKey, buildOpenAIUsageRefreshKey } from '../accountUsageRefresh' +import { buildAccountUsageRefreshKey, buildGrokUsageRefreshKey, buildOpenAIUsageRefreshKey } from '../accountUsageRefresh' + +describe('buildAccountUsageRefreshKey', () => { + it.each(['oauth', 'setup-token'])('tracks every Claude %s passive snapshot input', (type) => { + const base = { id: 1, platform: 'anthropic', type, extra: {} } as any + for (const field of ['last_used_at', 'session_window_start', 'session_window_end', 'session_window_status']) { + expect(buildAccountUsageRefreshKey({ ...base, [field]: 'new' })).not.toBe(buildAccountUsageRefreshKey(base)) + } + for (const field of ['session_window_utilization', 'passive_usage_sampled_at', 'passive_usage_7d_utilization', 'passive_usage_7d_reset', 'passive_usage_7d_oi_utilization', 'passive_usage_7d_oi_reset']) { + expect(buildAccountUsageRefreshKey({ ...base, extra: { [field]: 1 } })).not.toBe(buildAccountUsageRefreshKey(base)) + } + }) + + it.each(['anthropic', 'gemini'])('ignores unrelated %s changes and extra key ordering', (platform) => { + const base = { id: 1, platform, type: 'oauth', extra: { session_window_utilization: 0, other: 1 } } as any + expect(buildAccountUsageRefreshKey({ ...base, updated_at: 'new', current_concurrency: 5, extra: { other: 2, session_window_utilization: 0 } } as any)).toBe(buildAccountUsageRefreshKey(base)) + expect(buildAccountUsageRefreshKey({ ...base, last_used_at: 'new' })).not.toBe(buildAccountUsageRefreshKey(base)) + }) + + it('retains OpenAI keys and excludes unsupported platforms/types', () => { + const base = { id: 1, platform: 'openai', type: 'oauth', extra: {} } as any + expect(buildAccountUsageRefreshKey(base)).toBe(buildOpenAIUsageRefreshKey(base)) + expect(buildAccountUsageRefreshKey({ ...base, platform: 'anthropic', type: 'apikey' })).toBe('') + expect(buildAccountUsageRefreshKey({ ...base, platform: 'antigravity' })).toBe('') + }) +}) describe('buildOpenAIUsageRefreshKey', () => { it('会在 codex 快照变化时生成不同 key', () => { diff --git a/frontend/src/utils/accountUsageRefresh.ts b/frontend/src/utils/accountUsageRefresh.ts index 121dae253ae9..4d64ee789971 100644 --- a/frontend/src/utils/accountUsageRefresh.ts +++ b/frontend/src/utils/accountUsageRefresh.ts @@ -69,3 +69,29 @@ export const buildGrokUsageRefreshKey = (account: Pick): string => { + if (account.platform === 'openai') return buildOpenAIUsageRefreshKey(account) + + const isClaude = account.platform === 'anthropic' && (account.type === 'oauth' || account.type === 'setup-token') + if (!isClaude && account.platform !== 'gemini') return '' + + const extra = account.extra ?? {} + return serializeSnapshotRefreshValue([ + account.id, + account.platform, + account.type, + account.last_used_at ?? null, + account.session_window_start ?? null, + account.session_window_end ?? null, + ...(isClaude ? [ + account.session_window_status ?? null, + extra.session_window_utilization ?? null, + extra.passive_usage_sampled_at ?? null, + extra.passive_usage_7d_utilization ?? null, + extra.passive_usage_7d_reset ?? null, + extra.passive_usage_7d_oi_utilization ?? null, + extra.passive_usage_7d_oi_reset ?? null + ] : []) + ]) +} diff --git a/frontend/src/views/admin/AccountsView.vue b/frontend/src/views/admin/AccountsView.vue index c9462d18e1d9..2ef45c7c45c2 100644 --- a/frontend/src/views/admin/AccountsView.vue +++ b/frontend/src/views/admin/AccountsView.vue @@ -607,7 +607,7 @@ import Icon from '@/components/icons/Icon.vue' import ErrorPassthroughRulesModal from '@/components/admin/ErrorPassthroughRulesModal.vue' import TLSFingerprintProfilesModal from '@/components/admin/TLSFingerprintProfilesModal.vue' import { fetchAllAccountIds } from '@/utils/accountSelection' -import { buildGrokUsageRefreshKey, buildOpenAIUsageRefreshKey } from '@/utils/accountUsageRefresh' +import { buildGrokUsageRefreshKey, buildAccountUsageRefreshKey } from '@/utils/accountUsageRefresh' import { formatDateTime, formatRelativeTime } from '@/utils/format' import { proxyExpiryBadgeClass, proxyExpiryLabelKey } from '@/utils/proxyExpiry' import { extractApiErrorMessage } from '@/utils/apiError' @@ -897,7 +897,7 @@ const usageBatchByAccountId = ref>({}) const usageBatchErrorByAccountId = ref>({}) const usageBatchLoadingByAccountId = ref>({}) const usageBatchRequestTokenByAccountId = ref>({}) -const usageBatchCache = new Map() +const usageBatchCache = new Map() const USAGE_BATCH_CACHE_TTL = 5 * 60 * 1000 const pendingUsageBatchIds = new Set() let usageBatchFlushTimer: ReturnType | null = null @@ -951,6 +951,7 @@ const flushQueuedUsageBatch = async () => { usageBatchFlushTimer = null const accountIDs = Array.from(pendingUsageBatchIds) const force = queuedUsageBatchForce + const refreshKeys = new Map(accounts.value.map(account => [account.id, buildAccountUsageRefreshKey(account)])) pendingUsageBatchIds.clear() queuedUsageBatchForce = false @@ -981,7 +982,7 @@ const flushQueuedUsageBatch = async () => { nextErrors[key] = errorMap[key] ?? null nextLoading[key] = false if (usage) { - usageBatchCache.set(accountID, { data: usage, ts: now }) + usageBatchCache.set(accountID, { data: usage, ts: now, refreshKey: refreshKeys.get(accountID) ?? '' }) } else { usageBatchCache.delete(accountID) } @@ -1019,7 +1020,7 @@ const queueBatchedUsage = (account: Account, options?: { force?: boolean }) => { usageBatchCache.delete(cacheKey) } else { const cached = usageBatchCache.get(cacheKey) - if (cached && Date.now() - cached.ts < USAGE_BATCH_CACHE_TTL) { + if (cached && cached.refreshKey === buildAccountUsageRefreshKey(account) && Date.now() - cached.ts < USAGE_BATCH_CACHE_TTL) { setUsageBatchState(cacheKey, cached.data, null) setUsageBatchLoading(cacheKey, false) return @@ -1690,7 +1691,7 @@ const shouldReplaceAutoRefreshRow = (current: Account, next: Account) => { current.rate_limit_reset_at !== next.rate_limit_reset_at || current.overload_until !== next.overload_until || current.temp_unschedulable_until !== next.temp_unschedulable_until || - buildOpenAIUsageRefreshKey(current) !== buildOpenAIUsageRefreshKey(next) || + buildAccountUsageRefreshKey(current) !== buildAccountUsageRefreshKey(next) || buildGrokUsageRefreshKey(current) !== buildGrokUsageRefreshKey(next) ) } diff --git a/frontend/src/views/admin/__tests__/AccountsView.lite.spec.ts b/frontend/src/views/admin/__tests__/AccountsView.lite.spec.ts index 618834f18989..55e5a30089ee 100644 --- a/frontend/src/views/admin/__tests__/AccountsView.lite.spec.ts +++ b/frontend/src/views/admin/__tests__/AccountsView.lite.spec.ts @@ -13,6 +13,7 @@ const { getPerformance, getBatchTodayStats, getManagementCapabilities, + getBatchUsage, getUpstreamBillingProbeSettings, getUpstreamBillingRatesWithEtag, probeUpstreamBilling, @@ -28,6 +29,7 @@ const { getPerformance: vi.fn(), getBatchTodayStats: vi.fn(), getManagementCapabilities: vi.fn(), + getBatchUsage: vi.fn(), getUpstreamBillingProbeSettings: vi.fn(), getUpstreamBillingRatesWithEtag: vi.fn(), probeUpstreamBilling: vi.fn(), @@ -47,6 +49,7 @@ vi.mock('@/api/admin', () => ({ getPerformance, listWithEtag, getBatchTodayStats, + getBatchUsage, getUpstreamBillingProbeSettings, getUpstreamBillingRatesWithEtag, probeUpstreamBilling, @@ -84,6 +87,7 @@ const DataTableStub = defineComponent({ + @@ -110,7 +114,7 @@ const AccountStatsModalStub = defineComponent({ template: '
{{ show ? account?.name : "" }}
' }) -function mountView(stubActionMenu = true) { +function mountView(stubActionMenu = true, realUsageCell = false) { return mount(AccountsView, { attachTo: document.body, global: { @@ -142,7 +146,7 @@ function mountView(stubActionMenu = true) { AccountStatusIndicator: true, AccountTodayStatsCell: true, AccountGroupsCell: AccountGroupsCellStub, - AccountUsageCell: true, + AccountUsageCell: !realUsageCell, UpstreamBillingRateCell: true, HelpTooltip: true, Icon: true, @@ -183,6 +187,7 @@ describe('admin AccountsView lite account list', () => { getPerformance.mockReset().mockResolvedValue({}) getBatchTodayStats.mockReset().mockResolvedValue({ stats: {} }) getManagementCapabilities.mockReset().mockResolvedValue({ concurrency_upgrade_enabled: false }) + getBatchUsage.mockReset().mockResolvedValue({ usage: { '42': { five_hour: { utilization: 21 }, seven_day: { utilization: 31 } } }, errors: {} }) getUpstreamBillingProbeSettings.mockReset().mockResolvedValue({ enabled: true }) getAllProxies.mockReset().mockResolvedValue([]) getAllGroups.mockReset().mockResolvedValue([{ id: 7, name: 'codex', platform: 'openai' }]) @@ -229,6 +234,45 @@ describe('admin AccountsView lite account list', () => { wrapper.unmount() }) + it.each([ + ['anthropic', 'oauth'], ['anthropic', 'setup-token'], ['gemini', 'oauth'] + ])('updates %s %s usage on auto-refresh without force or unrelated probes', async (platform, type) => { + vi.useFakeTimers() + vi.spyOn(document, 'hidden', 'get').mockReturnValue(false) + vi.spyOn(window, 'matchMedia').mockImplementation(() => ({ + matches: true, addEventListener: vi.fn(), removeEventListener: vi.fn() + }) as unknown as MediaQueryList) + localStorage.setItem('account-auto-refresh', JSON.stringify({ enabled: true, interval_seconds: 5 })) + const account = { ...listRow, platform, type } + listAccounts.mockResolvedValue({ items: [account], total: 1, page: 1, page_size: 20, pages: 1 }) + const wrapper = mountView(true, true) + await flushPromises() + await vi.advanceTimersByTimeAsync(1) + await flushPromises() + expect(getBatchUsage).toHaveBeenCalledTimes(1) + expect(getBatchUsage).toHaveBeenCalledWith([42], false) + + const next = { ...account, extra: { session_window_utilization: 0.44, passive_usage_7d_utilization: 0.54 }, last_used_at: platform === 'gemini' ? '2026-11-16T10:00:00Z' : null } + getBatchUsage.mockResolvedValue({ usage: { '42': { five_hour: { utilization: 44 }, seven_day: { utilization: 54 } } }, errors: {} }) + listWithEtag.mockResolvedValue({ notModified: false, etag: 'new', data: { items: [next], total: 1, pages: 1 } }) + await vi.advanceTimersByTimeAsync(6000) + await flushPromises() + expect(getBatchUsage).toHaveBeenCalledTimes(2) + expect(getBatchUsage).toHaveBeenLastCalledWith([42], false) + const cell = wrapper.findComponent({ name: 'AccountUsageCell' }) + expect(cell.props('account').last_used_at).toBe(next.last_used_at) + expect(cell.props('batchedUsage').seven_day.utilization).toBe(54) + cell.props('requestBatchedUsage')(cell.props('account')) + await vi.advanceTimersByTimeAsync(1) + expect(getBatchUsage).toHaveBeenCalledTimes(2) + + listWithEtag.mockResolvedValue({ notModified: false, etag: 'unrelated', data: { items: [{ ...next, updated_at: 'new', current_concurrency: 2, extra: { ...next.extra, unrelated: true } }], total: 1, pages: 1 } }) + await vi.advanceTimersByTimeAsync(6000) + await flushPromises() + expect(getBatchUsage).toHaveBeenCalledTimes(2) + wrapper.unmount() + }) + it('keeps lite=1 on the initial list request', async () => { const wrapper = mountView() await flushPromises() From 448bb3e97dc1ba80308a02195dae907b35b5be56 Mon Sep 17 00:00:00 2001 From: wucm667 Date: Tue, 17 Nov 2026 11:22:55 +0800 Subject: [PATCH 20/87] ci: rerun checks after allocation guard failure (cherry picked from commit d0c232401fb1ad977682602ab2d8af4c1b8ace26) From fae1d7e00142b6fd8e0b4ded866b99769640417f Mon Sep 17 00:00:00 2001 From: wucm667 Date: Thu, 19 Nov 2026 09:49:44 +0800 Subject: [PATCH 21/87] fix(i18n): clarify Ultra Fast service tier hints (cherry picked from commit 155b83badbbe4bad3b7ba42f7a4a5c38fec88aa3) --- frontend/src/i18n/locales/en/admin/overview.ts | 2 +- frontend/src/i18n/locales/zh/admin/overview.ts | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/frontend/src/i18n/locales/en/admin/overview.ts b/frontend/src/i18n/locales/en/admin/overview.ts index 55589c4527f6..24db79fec6a2 100644 --- a/frontend/src/i18n/locales/en/admin/overview.ts +++ b/frontend/src/i18n/locales/en/admin/overview.ts @@ -1338,7 +1338,7 @@ export default { force: 'Force Fast (priority)', hint: 'Forces service_tier=priority on OpenAI requests in this group. The global Fast/Flex policy can still filter or block it. New requests update immediately after saving; existing WebSocket sessions must reconnect.', forceUltrafast: 'Force Ultra Fast (ultrafast)', - ultrafastHint: 'Forces service_tier=ultrafast on supported models. Pro 200 includes GPT-6.2 Sol Ultrafast; Pro 500 includes Sol and Astra. Other subscriptions use their advertised tiers. If unavailable, Force Fast takes precedence over the client tier. GPT-6.2 Sol/Astra cost 3× Standard before March 1, 2027 00:00 Pacific, then 6×; GPT-6 Astra and GPT-6.1 Sol cost 6×. Channels can override the Ultra Fast multiplier. Free Fast excludes Ultra Fast; Free UltraFast is a separate setting.', + ultrafastHint: 'Forces Ultra Fast (service_tier=ultrafast) on supported models. Pro 200 includes GPT-6.2 Sol Ultrafast. Pro 500 includes both Sol and Astra Ultrafast. Other subscriptions use the tiers advertised by their account. If unavailable, Force Fast takes precedence over the client tier. GPT-6.2 Sol and Astra cost 3× Standard through February 28, 2027 (Pacific time), then 6×. GPT-6 Astra and GPT-6.1 Sol cost 6×. Channels can override the Ultra Fast multiplier. Free Fast excludes Ultra Fast; Free UltraFast is a separate setting.', free: 'Free Fast', freeUltrafast: 'Free UltraFast', freeUltrafastHint: 'Bill requests settled at the ultrafast tier to customers at Standard prices, including cache reads and writes. Independent of Free Fast; does not force UltraFast upstream, and preserves actual-tier account cost statistics.', diff --git a/frontend/src/i18n/locales/zh/admin/overview.ts b/frontend/src/i18n/locales/zh/admin/overview.ts index e88352ae2d5c..9faa36eaba9a 100644 --- a/frontend/src/i18n/locales/zh/admin/overview.ts +++ b/frontend/src/i18n/locales/zh/admin/overview.ts @@ -1336,7 +1336,7 @@ export default { force: '强制使用 Fast(priority)', hint: '开启后,此分组的 OpenAI 请求会强制写入 service_tier=priority;全局 Fast/Flex 策略仍可过滤或拦截。保存后新请求立即生效,已建立的 WebSocket 会话需重连。', forceUltrafast: '强制使用 Ultra Fast(ultrafast)', - ultrafastHint: '对支持的模型强制设置 service_tier=ultrafast。GPT-6.2 订阅档位按套餐补全:Pro 200 支持 Sol,Pro 500 支持 Sol 和 Astra;其他账号使用其目录明确提供的档位。不可用时,若同时开启强制 Fast 则使用 Fast,否则跟随客户端。GPT-6.2 Sol/Astra 在 2027-03-01 00:00(太平洋时间)前按标准价 3 倍计费,之后恢复 6 倍;GPT-6 Astra 和 GPT-6.1 Sol 为 6 倍。渠道可单独设置 Ultra Fast 倍率。免费 Fast 不包含 Ultra Fast,免费 UltraFast 由独立开关控制。', + ultrafastHint: '对支持的模型强制使用 Ultra Fast(service_tier=ultrafast)。GPT-6.2 订阅档位按套餐补全:Pro 200 支持 Sol,Pro 500 支持 Sol 和 Astra;其他账号使用其目录明确提供的档位。不可用时,若同时开启强制 Fast 则使用 Fast,否则跟随客户端。6.2 Sol 和 Astra 在太平洋时间 2027 年 2 月 28 日及之前按标准价 3 倍计费,之后为 6 倍。GPT-6 Astra 和 GPT-6.1 Sol 为 6 倍。渠道可单独设置 Ultra Fast 倍率。免费 Fast 不包含 Ultra Fast,免费 UltraFast 由独立开关控制。', free: '免费 Fast', freeUltrafast: '免费 UltraFast', freeUltrafastHint: '开启后,最终按 ultrafast 档位结算的请求向用户按 Standard 价格计费(含缓存读写)。独立于免费 Fast;不强制上游使用 UltraFast,账号成本统计仍保留实际档位。', From a2ffac674abfd496306e3cbe7051b3385cdabbef Mon Sep 17 00:00:00 2001 From: Anankke Date: Mon, 16 Nov 2026 01:28:35 -0800 Subject: [PATCH 22/87] fix(composite): adapt thinking to the Claude 5.5 model a route rewrites to A composite route that rewrites the request model left the client's thinking untouched, so a route from claude-sonnet-5 to claude-opus-5-5 forwarded thinking.type=enabled with budget_tokens and validateClaude55Request answered 400 before the request reached the upstream. The route middleware now rewrites the model through RewriteCompositeRequestModel, which replaces a thinking mode that validateClaude55Request rejects for the new model with the nearest mode it accepts: enabled becomes adaptive without budget_tokens, and disabled becomes between_tools on Sonnet 5.5. The mapping is shared with the Bedrock Sonnet 5.5 sanitizer, whose behavior is unchanged. Modes the target still rejects stay with validateClaude55Request, and a request whose model the route does not rewrite keeps its thinking as sent. (cherry picked from commit f42dad9b7113ad26dfcfc59b4ce1bfe3352c9493) --- .../server/routes/composite_platform_test.go | 80 ++++++++++++++++++ backend/internal/server/routes/gateway.go | 5 +- backend/internal/service/bedrock_request.go | 9 +- backend/internal/service/claude55_thinking.go | 27 ++++++ .../internal/service/composite_platform.go | 12 +++ .../composite_platform_thinking_test.go | 82 +++++++++++++++++++ 6 files changed, 203 insertions(+), 12 deletions(-) create mode 100644 backend/internal/service/claude55_thinking.go create mode 100644 backend/internal/service/composite_platform_thinking_test.go 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/gateway.go b/backend/internal/server/routes/gateway.go index 7d454a7f73d0..a235fb0a50d9 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 兼容) @@ -739,9 +738,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/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) +} From 5033d18decb145c5bf8ba8e7f899016dfdee1986 Mon Sep 17 00:00:00 2001 From: lishuangqiang <142634204+lishuangqiang@users.noreply.github.com> Date: Mon, 16 Nov 2026 21:30:06 +0800 Subject: [PATCH 23/87] perf(gateway): skip the cache_control TTL walk when no 1h breakpoint exists The byte-level precheck added for #8668 still runs both cache_control walks for any body containing a "thinking" literal, because the thinking-block cleanup cannot be skipped by that check alone. Claude Code enables extended thinking by default, so that is the dominant shape: the precheck pays its own scan and then falls through to the unconditional normalizeCacheControlTTLOrder(enforceCacheControlBlockLimit(body)). On the 32KB Claude Code benchmark body with thinking, this made the optimized path slightly slower than the pre-fix code (112us vs 104us). Skip the second collectCacheControlPaths pass when the body has no "1h" literal. The walk is provably a no-op there: last1h stays -1 and nothing is rewritten. Escaped bodies returned earlier, so the byte check is exact, and the block-limit deletions only remove cache_control keys, which cannot introduce a 1h breakpoint. Benchmark (Apple M5 Pro, -benchtime 2s -count 3): thinking, no 1h: 112us / 21 allocs -> 52us / 8 allocs common, no 1h: 21.6us / 0 allocs -> 21.3us / 0 allocs 1h bodies: unchanged (within noise) The benchmark gains two thinking cases so future work cannot regress this shape unnoticed. Equivalence tests compare against the verbatim legacy implementation. Fixes #8861 Refs #8668 (cherry picked from commit 833cfcc2fb49ea35f2191b009cd2dc35a2784234) --- .../service/gateway_claude_oauth_body.go | 10 +++++- .../gateway_request_json_bench_test.go | 34 +++++++++++++++++-- 2 files changed, 41 insertions(+), 3 deletions(-) diff --git a/backend/internal/service/gateway_claude_oauth_body.go b/backend/internal/service/gateway_claude_oauth_body.go index 23cae4ad4ee2..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 个) 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) { From 739da575b8198aba9c185d855392a3370f16a32f Mon Sep 17 00:00:00 2001 From: Anankke Date: Mon, 16 Nov 2026 04:06:12 -0800 Subject: [PATCH 24/87] fix(grok): bill search calls from xAI usage success counts When a Grok response usage carries server_side_tool_usage_details, take SearchCount from web_search_calls, x_search_calls and document_search_calls instead of counting output items. xAI documents server_side_tool_usage as the successful calls that determine billing, so failed calls and server-side tools that return nothing are no longer billed. Classes the item counter does not count and the x_posts_fetched / x_users_fetched item counts are not read. Without server_side_tool_usage_details the existing item counting is unchanged. The usage is read from the JSON body, the SSE body and the terminal stream event, for /v1/responses, /v1/messages and /v1/chat/completions, streaming and not. ResponsesUsage keeps the raw object so the buffered paths, which count from a decoded response, can read it. (cherry picked from commit 2c587f78b07e35f23e79ac63d180a06234bee050) --- backend/internal/pkg/apicompat/types.go | 4 + backend/internal/service/grok_search_count.go | 45 ++++++ .../service/grok_search_usage_billing_test.go | 147 ++++++++++++++++++ .../openai_gateway_chat_completions.go | 1 + .../service/openai_gateway_messages.go | 1 + .../openai_gateway_response_handling.go | 1 + 6 files changed, 199 insertions(+) create mode 100644 backend/internal/service/grok_search_usage_billing_test.go diff --git a/backend/internal/pkg/apicompat/types.go b/backend/internal/pkg/apicompat/types.go index 13f5c4973bd7..b941f5b3edf4 100644 --- a/backend/internal/pkg/apicompat/types.go +++ b/backend/internal/pkg/apicompat/types.go @@ -651,6 +651,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/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/openai_gateway_chat_completions.go b/backend/internal/service/openai_gateway_chat_completions.go index 78a384c6e034..44f5d836d041 100644 --- a/backend/internal/service/openai_gateway_chat_completions.go +++ b/backend/internal/service/openai_gateway_chat_completions.go @@ -999,6 +999,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_messages.go b/backend/internal/service/openai_gateway_messages.go index 957638cd4e5f..3d87259a3e85 100644 --- a/backend/internal/service/openai_gateway_messages.go +++ b/backend/internal/service/openai_gateway_messages.go @@ -1186,6 +1186,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_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 { From 7b0038e3b16eb69e58dbc70974ca0d28e586da0a Mon Sep 17 00:00:00 2001 From: lishuangqiang <142634204+lishuangqiang@users.noreply.github.com> Date: Mon, 16 Nov 2026 22:52:36 +0800 Subject: [PATCH 25/87] perf(openai): skip the image-intent body scan when a request cannot declare one Every /v1/responses request runs IsImageGenerationIntentForPlatform to decide whether to mark the context as image generation (capability routing and image billing). After the two O(1) checks (dedicated image endpoint, image model) the function unconditionally runs gjson.ValidBytes over the whole body and then walks the root object with a ForEach. Both steps are pure overhead for requests that cannot match. Every branch that can set the intent requires one of two things in the body: the literal "image_gen" (image_generation tools carry that prefix, and the namespace, tool_choice and function-reference checks all use image_gen), or an image model name (gpt-image-*, grok-imagine*) as the "model" value. The same body is also validated by the handler and again by ParseGatewayRequest, so this pass is a third redundant validation of the same bytes. Add a byte-level necessary condition ahead of gjson.ValidBytes: bytes.Contains(body, "image_gen") || containsASCIIFold(body, "imag") // image model names || bytes.Contains(body, "\\u") // unicode-escaped literal All three are required: - "image_gen" alone misses the model branch. {"model":"gpt-image-2"} returns true today and does not contain "image_gen"; dropping it would let image model requests bypass the group image-generation gate and image billing. - isOpenAIImageGenerationModel lowercases its argument while bytes.Contains does not, so the model token is matched case-insensitively. - JSON strings may spell any byte as a unicode escape, so a body containing "image_generation" only reveals the literal after decoding. Escaped bodies therefore fall back to the full scan. None of the target literals contain a character JSON escapes, so a "\u" probe is exhaustive. containsASCIIFold had to be rewritten as well. It compared byte by byte, which is a full body scan on its own, and a first-byte memchr variant that re-probes both cases of the first byte per candidate degrades quadratically. The new implementation keeps one cursor per case and advances only the cursor it just consumed, so it stays linear. Without this the precheck would cost more than the scan it replaces (~930us vs 783us on a 1MiB body). The three scan bodies collapse into two root walkers plus one entry point; the grok and explicit rules were byte-identical copies. Codex clients advertise the image_gen namespace on ordinary requests, so those bodies still take the full scan. Skipping the duplicate validation for callers that already validated the same bytes is a separate change. Benchmark (Apple M5 Pro, 1MiB body, 0 allocs): no image declarations 783us -> 48us codex namespace 560us -> 564us (gate cannot fire, unchanged) Fixes #8865 (cherry picked from commit 59645b7bea035d4f43072a2c0b62360eaa6e45fe) --- .../service/image_generation_intent.go | 165 +++++++++--------- ...eration_intent_prefilter_benchmark_test.go | 92 ++++++++++ .../image_generation_intent_prefilter_test.go | 140 +++++++++++++++ .../service/openai_codex_tool_names.go | 55 ++++-- 4 files changed, 353 insertions(+), 99 deletions(-) create mode 100644 backend/internal/service/image_generation_intent_prefilter_benchmark_test.go create mode 100644 backend/internal/service/image_generation_intent_prefilter_test.go diff --git a/backend/internal/service/image_generation_intent.go b/backend/internal/service/image_generation_intent.go index 76e6f6f325a1..252622530927 100644 --- a/backend/internal/service/image_generation_intent.go +++ b/backend/internal/service/image_generation_intent.go @@ -37,21 +37,93 @@ 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) +} + +// 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) +} + +// 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 openAIImageGenerationIntent(endpoint, requestedModel, body, false) } - if isOpenAIImageGenerationModel(requestedModel) { + // Grok removes namespace catalogs before forwarding. Native image_generation + // remains an explicit capability request. + return openAIImageGenerationIntent(endpoint, requestedModel, body, true) +} + +// openAIImageGenerationIntent 统一入口:先做 O(1) 端点/模型判断,再用字节级预检查 +// 挡住不可能命中扫描的 body,最后才校验并遍历根对象。 +func openAIImageGenerationIntent(endpoint string, requestedModel string, body []byte, explicit bool) bool { + if IsImageGenerationEndpoint(endpoint) || isOpenAIImageGenerationModel(requestedModel) { return true } - if len(body) == 0 || !gjson.ValidBytes(body) { + if !openAIBodyMayDeclareImageGeneration(body) { + return false + } + if !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 +152,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 +167,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": 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..8658bda1b07e --- /dev/null +++ b/backend/internal/service/image_generation_intent_prefilter_benchmark_test.go @@ -0,0 +1,92 @@ +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(见 IsImageGenerationIntentForPlatform + // 注释),预检查必然放行,这类流量仍需完整扫描,本项用于跟踪它的成本。 + 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") + } + } + }) +} 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..beb12d259fc0 --- /dev/null +++ b/backend/internal/service/image_generation_intent_prefilter_test.go @@ -0,0 +1,140 @@ +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) + } + }) +} + +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/openai_codex_tool_names.go b/backend/internal/service/openai_codex_tool_names.go index 45b1af0ab317..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" @@ -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 } From 395aace2eaba4216e110b8ee260af06cb51a8dc4 Mon Sep 17 00:00:00 2001 From: lishuangqiang <142634204+lishuangqiang@users.noreply.github.com> Date: Mon, 16 Nov 2026 23:02:17 +0800 Subject: [PATCH 26/87] perf(openai): reuse an already-validated body when classifying image intent The handler validates the request body at gateway_handler_responses.go:66 and ParseGatewayRequest validates it again at gateway_request.go:240. For bodies that do carry image declarations the byte-level precheck cannot fire, so the intent classifier still ran gjson.ValidBytes over the same bytes a third time. That is the dominant remaining cost for Codex traffic, because Codex advertises the image_gen namespace on ordinary responses requests. Add IsImageGenerationIntentForPlatformValidated for callers that have already established the body is valid JSON, and use it at the two call sites where that holds: - gateway_handler_responses.go: the body is validated at the top of the handler, and afterwards it is only rewritten through sjson (applyOpenAIReasoningEffortPolicyForRequest), which preserves validity. - openai_ws_forwarder_ingress.go: the payload is validated in parseClientPayload, and every later rewrite is sjson, a decode/re-marshal round trip, or a no-op. Both call sites carry the reasoning in a comment. The validating entry points are unchanged, so invalid-JSON semantics stay exactly as they were for every other caller. Benchmark (Apple M5 Pro, 1MiB Codex body, 0 allocs): intent classifier: 562us -> 50us Refs #8865 (cherry picked from commit 487d42c9645d3e259e42a99a29edc9d1a9311e4c) --- .../handler/gateway_handler_responses.go | 5 +++- .../service/image_generation_intent.go | 26 ++++++++++++++----- ...eration_intent_prefilter_benchmark_test.go | 14 ++++++++-- .../image_generation_intent_prefilter_test.go | 7 +++++ .../service/openai_ws_forwarder_ingress.go | 4 ++- 5 files changed, 45 insertions(+), 11 deletions(-) diff --git a/backend/internal/handler/gateway_handler_responses.go b/backend/internal/handler/gateway_handler_responses.go index 1f3ce43a046d..4f50dea58e43 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) diff --git a/backend/internal/service/image_generation_intent.go b/backend/internal/service/image_generation_intent.go index 252622530927..ab435522c211 100644 --- a/backend/internal/service/image_generation_intent.go +++ b/backend/internal/service/image_generation_intent.go @@ -72,14 +72,14 @@ func openAIBodyMayDeclareImageGeneration(body []byte) bool { // IsImageGenerationIntent classifies requests that can produce generated images. func IsImageGenerationIntent(endpoint string, requestedModel string, body []byte) bool { - return openAIImageGenerationIntent(endpoint, requestedModel, body, false) + 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) + return openAIImageGenerationIntent(endpoint, requestedModel, body, true, true) } // IsImageGenerationIntentForPlatform applies platform-specific intent rules. @@ -91,24 +91,36 @@ func IsExplicitImageGenerationIntent(endpoint string, requestedModel string, bod // 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) + return openAIImageGenerationIntent(endpoint, requestedModel, body, false, validate) } // Grok removes namespace catalogs before forwarding. Native image_generation // remains an explicit capability request. - return openAIImageGenerationIntent(endpoint, requestedModel, body, true) + return openAIImageGenerationIntent(endpoint, requestedModel, body, true, validate) } // openAIImageGenerationIntent 统一入口:先做 O(1) 端点/模型判断,再用字节级预检查 -// 挡住不可能命中扫描的 body,最后才校验并遍历根对象。 -func openAIImageGenerationIntent(endpoint string, requestedModel string, body []byte, explicit bool) bool { +// 挡住不可能命中扫描的 body,最后才按需校验并遍历根对象。 +func openAIImageGenerationIntent(endpoint string, requestedModel string, body []byte, explicit bool, validate bool) bool { if IsImageGenerationEndpoint(endpoint) || isOpenAIImageGenerationModel(requestedModel) { return true } if !openAIBodyMayDeclareImageGeneration(body) { return false } - if !gjson.ValidBytes(body) { + if validate && !gjson.ValidBytes(body) { return false } root := parseRawJSONView(body) diff --git a/backend/internal/service/image_generation_intent_prefilter_benchmark_test.go b/backend/internal/service/image_generation_intent_prefilter_benchmark_test.go index 8658bda1b07e..3136faab9701 100644 --- a/backend/internal/service/image_generation_intent_prefilter_benchmark_test.go +++ b/backend/internal/service/image_generation_intent_prefilter_benchmark_test.go @@ -78,8 +78,8 @@ func BenchmarkImageGenerationIntentPrefilter(b *testing.B) { } }) - // Codex 在普通请求里就带 image_gen namespace(见 IsImageGenerationIntentForPlatform - // 注释),预检查必然放行,这类流量仍需完整扫描,本项用于跟踪它的成本。 + // Codex 在普通请求里就带 image_gen namespace,预检查必然放行, + // 这类流量只能靠「已校验」变体省掉重复的全量校验。 b.Run("intent/codex_namespace", func(b *testing.B) { b.SetBytes(int64(len(codex))) b.ReportAllocs() @@ -89,4 +89,14 @@ func BenchmarkImageGenerationIntentPrefilter(b *testing.B) { } } }) + + 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 index beb12d259fc0..0b9b8413c089 100644 --- a/backend/internal/service/image_generation_intent_prefilter_test.go +++ b/backend/internal/service/image_generation_intent_prefilter_test.go @@ -104,6 +104,13 @@ func FuzzImageGenerationIntentPrefilter(f *testing.F) { 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) + } }) } diff --git a/backend/internal/service/openai_ws_forwarder_ingress.go b/backend/internal/service/openai_ws_forwarder_ingress.go index c8dc75aac4fa..14be31aaeda0 100644 --- a/backend/internal/service/openai_ws_forwarder_ingress.go +++ b/backend/internal/service/openai_ws_forwarder_ingress.go @@ -1102,7 +1102,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) } From c568a7b1d6ee996e4b944843d58444c8a842ddac Mon Sep 17 00:00:00 2001 From: lishuangqiang <142634204+lishuangqiang@users.noreply.github.com> Date: Mon, 16 Nov 2026 23:03:38 +0800 Subject: [PATCH 27/87] perf(openai): apply the image-intent precheck to the declaration scanners openAIRequestBodyHasImageGenerationDeclaration and openAIRequestBodyImageGenerationToolNeedsNormalization each validate the whole body up front before looking at tools/input/tool_choice. Both branches only match image_gen literals, so the same byte-level necessary condition applies and lets them skip the validation for bodies that cannot match. Refs #8865 (cherry picked from commit 62765bb4e761ec89f91aa7d409d4103f7075154e) --- backend/internal/service/image_generation_intent.go | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/backend/internal/service/image_generation_intent.go b/backend/internal/service/image_generation_intent.go index ab435522c211..5ec0dbe1b88f 100644 --- a/backend/internal/service/image_generation_intent.go +++ b/backend/internal/service/image_generation_intent.go @@ -301,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")) || @@ -310,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") From ad8da3813cc980ed5255f30fc6ffd27ecc30a8a6 Mon Sep 17 00:00:00 2001 From: lishuangqiang <142634204+lishuangqiang@users.noreply.github.com> Date: Mon, 16 Nov 2026 23:23:13 +0800 Subject: [PATCH 28/87] perf(service): parse the gateway request body with a single root walk parseGatewayRequestCurrentBody looked up eight fields with separate gjson.Get calls. A lookup for a key that is not present still has to scan the whole body to prove absence, and for a typical Responses request six of those keys are absent (metadata.user_id, thinking.type, output_config.effort, max_tokens, system, messages). On a 1MiB body that is six full passes at about 142us each, while a single root walk over the same body costs about 220us. Collect every field the parser needs in one ForEach over the root and derive the raw ranges from the same results. Nested paths keep gjson semantics: each path segment resolves to the first duplicate key that actually yields the child, not simply the first key with that name. {"metadata":"x","metadata":{"user_id":"u"}} resolves to "u", and the walk reproduces that by retrying while the collected child does not exist. Duplicate scalar keys keep first-occurrence-wins. The Anthropic [1m] model normalization rewrites the body mid-parse, so the walk is repeated after the rewrite. That path only runs when the client leaks the suffix. Benchmark (Apple M5 Pro, 3 allocs unchanged): responses 128KiB: 208us -> 96us responses 1MiB: 1.59ms -> 735us anthropic 1MiB: 1.43ms -> 723us Equivalence tests keep a verbatim copy of the previous implementation as legacy* and compare every field (model, stream, metadata user id, thinking, effort, speed, max tokens, system/messages/input ranges, protocol, body after parsing) across 4 protocols and 44 bodies, plus 3000 deterministic random combinations. A fuzz target does the same for arbitrary input. (cherry picked from commit 0c571e9e271ebc295e505424700e9213d2401388) --- backend/internal/service/gateway_request.go | 155 +++++++-- .../gateway_request_scan_benchmark_test.go | 81 +++++ .../gateway_request_scan_equivalence_test.go | 293 ++++++++++++++++++ 3 files changed, 495 insertions(+), 34 deletions(-) create mode 100644 backend/internal/service/gateway_request_scan_benchmark_test.go create mode 100644 backend/internal/service/gateway_request_scan_equivalence_test.go diff --git a/backend/internal/service/gateway_request.go b/backend/internal/service/gateway_request.go index c0d1abea6403..f7cabd1edcc1 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,8 +261,8 @@ func normalizeClaudeCodeLongContextModel(model string) string { return model } -// parseGatewayRequestCurrentBody 只做标量和 raw range 轻量解析,不恢复 system/messages 对象图。 -func parseGatewayRequestCurrentBody(parsed *ParsedRequest, protocol string) error { +// parseGatewayRequestBody 只做标量和 raw range 轻量解析,不恢复 system/messages 对象图。 +func parseGatewayRequestBody(parsed *ParsedRequest, protocol string) error { if parsed == nil || parsed.Body == nil { return fmt.Errorf("empty request body") } @@ -186,17 +272,19 @@ func parseGatewayRequestCurrentBody(parsed *ParsedRequest, protocol string) erro 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 +294,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) } // DescribeInvalidJSON returns a diagnostic error for a request body that @@ -353,7 +440,7 @@ func normalizeSessionUserAgentFallback(raw string) string { // 不同协议使用不同的 system/messages 字段名。 func ParseGatewayRequest(body *RequestBodyRef, protocol string) (*ParsedRequest, error) { parsed := &ParsedRequest{Body: body} - if err := parseGatewayRequestCurrentBody(parsed, protocol); err != nil { + if err := parseGatewayRequestBody(parsed, protocol); err != nil { return nil, err } return parsed, nil 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..0b09668d7036 --- /dev/null +++ b/backend/internal/service/gateway_request_scan_benchmark_test.go @@ -0,0 +1,81 @@ +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) + item := `{"type":"message","role":"user","content":[{"type":"input_text","text":"` + strings.Repeat("x", 4000) + `"}]}` + if anthropic { + sb.WriteString(`{"model":"claude-sonnet-5-5","stream":true,"system":[{"type":"text","text":"`) + sb.WriteString(strings.Repeat("z", targetBytes/8)) + sb.WriteString(`"}],"tools":[{"name":"shell","description":"`) + sb.WriteString(strings.Repeat("y", targetBytes/16)) + sb.WriteString(`"}],"messages":[`) + msg := `{"role":"user","content":[{"type":"text","text":"` + strings.Repeat("x", 4000) + `"}]}` + for i := 0; sb.Len() < targetBytes; i++ { + if i > 0 { + sb.WriteString(`,`) + } + sb.WriteString(msg) + } + sb.WriteString(`]}`) + return []byte(sb.String()) + } + sb.WriteString(`{"model":"gpt-5.5","stream":true,"instructions":"`) + sb.WriteString(strings.Repeat("z", targetBytes/8)) + sb.WriteString(`","tools":[{"type":"function","name":"shell","description":"`) + sb.WriteString(strings.Repeat("y", targetBytes/16)) + sb.WriteString(`"}],"input":[`) + for i := 0; sb.Len() < targetBytes; i++ { + if i > 0 { + sb.WriteString(`,`) + } + sb.WriteString(item) + } + sb.WriteString(`]}`) + 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); 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..ca35784c0c24 --- /dev/null +++ b/backend/internal/service/gateway_request_scan_equivalence_test.go @@ -0,0 +1,293 @@ +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") + } + parsed.Body.parsed = nil + + 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) + parsed.saveBodyState() + 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) + + 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) + } +} + +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) + + }) +} From 9bb0c442902bca18191c44b795c5a9f25bdc4f64 Mon Sep 17 00:00:00 2001 From: lishuangqiang <142634204+lishuangqiang@users.noreply.github.com> Date: Mon, 16 Nov 2026 23:24:26 +0800 Subject: [PATCH 29/87] perf(openai): skip the redundant body validation when parsing responses requests The /v1/responses handler validates the request body with gjson.ValidBytes before doing anything else, then hands the same bytes to ParseGatewayRequest, which validates them a second time. After the single-root-walk change the validation is the majority of what that call does: at 1MiB it is about 510us of the remaining 730us. Add ParseGatewayRequestValidated for callers that have already established the body is valid JSON, and use it in the handler, where the only rewrite between the two points is applyOpenAIReasoningEffortPolicyForRequest (sjson, which preserves validity). The validating entry point is unchanged, so invalid JSON keeps producing a clean error everywhere else. ReplaceBody / CloneForBody keep validating as well, because their bytes can differ from the ones a caller validated. Equivalence tests assert the trusted variant produces identical results to the validating one on valid JSON, and the fuzz target checks the same for every input that parses. Benchmark (Apple M5 Pro, 3 allocs unchanged): responses 1MiB: 735us -> 239us anthropic 1MiB: 723us -> 207us (not yet wired: that handler has no earlier validation, so it keeps the validating path) (cherry picked from commit 844459e78595acb63dc4d97e0394106cfd9dbfa1) --- .../handler/gateway_handler_responses.go | 4 ++- backend/internal/service/gateway_request.go | 21 ++++++++--- .../gateway_request_scan_benchmark_test.go | 13 ++++++- .../gateway_request_scan_equivalence_test.go | 35 ++++++++++++++++++- 4 files changed, 66 insertions(+), 7 deletions(-) diff --git a/backend/internal/handler/gateway_handler_responses.go b/backend/internal/handler/gateway_handler_responses.go index 4f50dea58e43..d6f338de8d8c 100644 --- a/backend/internal/handler/gateway_handler_responses.go +++ b/backend/internal/handler/gateway_handler_responses.go @@ -184,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/service/gateway_request.go b/backend/internal/service/gateway_request.go index f7cabd1edcc1..85d9930fc4b0 100644 --- a/backend/internal/service/gateway_request.go +++ b/backend/internal/service/gateway_request.go @@ -262,13 +262,14 @@ func normalizeClaudeCodeLongContextModel(model string) string { } // parseGatewayRequestBody 只做标量和 raw range 轻量解析,不恢复 system/messages 对象图。 -func parseGatewayRequestBody(parsed *ParsedRequest, protocol string) error { +// 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) } @@ -332,7 +333,7 @@ func parseGatewayRequestBody(parsed *ParsedRequest, protocol string) error { } func refreshGatewayRequestRanges(parsed *ParsedRequest, protocol string) error { - return parseGatewayRequestBody(parsed, protocol) + return parseGatewayRequestBody(parsed, protocol, true) } // DescribeInvalidJSON returns a diagnostic error for a request body that @@ -439,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 := parseGatewayRequestBody(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_scan_benchmark_test.go b/backend/internal/service/gateway_request_scan_benchmark_test.go index 0b09668d7036..82e5634cccd8 100644 --- a/backend/internal/service/gateway_request_scan_benchmark_test.go +++ b/backend/internal/service/gateway_request_scan_benchmark_test.go @@ -72,7 +72,18 @@ func BenchmarkParseGatewayRequestScan(b *testing.B) { b.ReportAllocs() for range b.N { parsed := &ParsedRequest{Body: NewRequestBodyRef(body)} - if err := parseGatewayRequestBody(parsed, tc.protocol); err != nil { + 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 index ca35784c0c24..ffe43ec9e9e7 100644 --- a/backend/internal/service/gateway_request_scan_equivalence_test.go +++ b/backend/internal/service/gateway_request_scan_equivalence_test.go @@ -165,7 +165,7 @@ func parseBoth(t *testing.T, protocol string, body []byte) (parsedSnapshot, pars // 直接调被重构的这一步:ParseGatewayRequest 在失败时返回 nil,无法比较错误路径上的中间状态。 newBody := NewRequestBodyRef(append([]byte(nil), body...)) newParsed := &ParsedRequest{Body: newBody} - newErr := parseGatewayRequestBody(newParsed, protocol) + newErr := parseGatewayRequestBody(newParsed, protocol, true) return snapshotOf(legacyParsed, legacyErr), snapshotOf(newParsed, newErr) } @@ -275,6 +275,30 @@ func TestParseGatewayRequestMatchesLegacyRandomized(t *testing.T) { } } +// 已校验变体只允许在「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) @@ -289,5 +313,14 @@ func FuzzParseGatewayRequestMatchesLegacy(f *testing.F) { 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) + } }) } From e087eaee918fb1cb0cb1b98f7805fc3a72781f6d Mon Sep 17 00:00:00 2001 From: lishuangqiang <142634204+lishuangqiang@users.noreply.github.com> Date: Mon, 16 Nov 2026 23:34:25 +0800 Subject: [PATCH 30/87] perf(openai): use the validated parse path for chat completions too Same shape as the responses handler: the body is validated at the top of ChatCompletions, the only later rewrite is applyOpenAIReasoningEffortPolicyForRequest (sjson), and the parse error was already being ignored. Nothing between the two points mutates the bytes: parseOpenAICompatibleStream, checkSecurityAudit and tokenInflightEstimate only read them. (cherry picked from commit 8d962ba494ae0adcd745629b1e4bcec1dc839b0e) --- backend/internal/handler/gateway_handler_chat_completions.go | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/backend/internal/handler/gateway_handler_chat_completions.go b/backend/internal/handler/gateway_handler_chat_completions.go index 582511403bca..742027edaeb4 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} } From 98c0ec3cf0ef853a90c54750610fd1c0ceec63a2 Mon Sep 17 00:00:00 2001 From: lishuangqiang <142634204+lishuangqiang@users.noreply.github.com> Date: Tue, 17 Nov 2026 00:14:52 +0800 Subject: [PATCH 31/87] test(gateway): stop ignoring strings.Builder errors in the scan benchmark The benchmark body builder discarded the results of strings.Builder.WriteString, which errcheck rejects (the repo enables errcheck with check-blank off, so a plain call is flagged even though Builder never returns an error). Route the writes through one helper that assigns the result. (cherry picked from commit 09840b8027a308b46ed62268151d6de71877e09f) --- .../gateway_request_scan_benchmark_test.go | 34 ++++++++++--------- 1 file changed, 18 insertions(+), 16 deletions(-) diff --git a/backend/internal/service/gateway_request_scan_benchmark_test.go b/backend/internal/service/gateway_request_scan_benchmark_test.go index 82e5634cccd8..f74bf099370d 100644 --- a/backend/internal/service/gateway_request_scan_benchmark_test.go +++ b/backend/internal/service/gateway_request_scan_benchmark_test.go @@ -11,35 +11,37 @@ import ( 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 { - sb.WriteString(`{"model":"claude-sonnet-5-5","stream":true,"system":[{"type":"text","text":"`) - sb.WriteString(strings.Repeat("z", targetBytes/8)) - sb.WriteString(`"}],"tools":[{"name":"shell","description":"`) - sb.WriteString(strings.Repeat("y", targetBytes/16)) - sb.WriteString(`"}],"messages":[`) + 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 { - sb.WriteString(`,`) + write(`,`) } - sb.WriteString(msg) + write(msg) } - sb.WriteString(`]}`) + write(`]}`) return []byte(sb.String()) } - sb.WriteString(`{"model":"gpt-5.5","stream":true,"instructions":"`) - sb.WriteString(strings.Repeat("z", targetBytes/8)) - sb.WriteString(`","tools":[{"type":"function","name":"shell","description":"`) - sb.WriteString(strings.Repeat("y", targetBytes/16)) - sb.WriteString(`"}],"input":[`) + 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 { - sb.WriteString(`,`) + write(`,`) } - sb.WriteString(item) + write(item) } - sb.WriteString(`]}`) + write(`]}`) return []byte(sb.String()) } From 9f3e348fbd2ee391735231da9e8ea3df16f6dbc4 Mon Sep 17 00:00:00 2001 From: lishuangqiang <142634204+lishuangqiang@users.noreply.github.com> Date: Tue, 17 Nov 2026 00:10:26 +0800 Subject: [PATCH 32/87] perf(openai): stop copying the whole input array when stripping namespaces stripOpenAIResponsesInputNamespaces runs on every OpenAI OAuth / API-key HTTP forward attempt. Its entry check only proves that the *body* contains a namespace literal, and Codex clients advertise the image_gen namespace tool on ordinary requests, so the check passes for most traffic and the function runs even when there is nothing to strip. Three avoidable copies showed up in that path: 1. gjson.GetBytes(body, "input") materialises the input array. On a 1MiB body that is a 1MiB allocation on every request, including the no-op case. Use the zero-copy parse view (parseRawJSONView) instead. 2. The rewrite built the new input array in a buffer and then handed it to sjson.SetRawBytes, which allocates a second full body copy. Assemble the output directly instead: prefix + rewritten array + suffix in one buffer sized to the body. 3. sjson.DeleteBytes([]byte(item.Raw), ...) converted each changed item to a byte slice first. Use the string form. hasOpenAIResponsesNamespaceToolDeclaration reads input the same way and gets the same treatment; it runs for API-key accounts on every request. Benchmark (Apple M5 Pro, -benchmem), legacy = the previous implementation: 1MiB tools_only 545us / 1056768 B / 1 alloc -> 495us / 0 B / 0 alloc 1MiB strip_first 882us / 3170624 B / 8 allocs -> 548us / 1056936 B / 4 1MiB strip_last 841us / 3170624 B / 8 allocs -> 556us / 1056928 B / 4 8MiB strip_first 5.95ms / 25190720 B / 8 -> 4.30ms / 8396960 B / 4 So the no-op path stops allocating entirely and the rewriting path copies one body instead of three. Behaviour is unchanged for valid JSON: equivalence tests keep the previous implementation as legacy* and compare output bytes, errors and whether the input slice was returned untouched, across 36 bodies (duplicate keys, escaped keys, nested namespace fields, non-object items, keep-tool-call mode, missing or non-array input) plus 3000 randomized combinations and a fuzz target. One deliberate difference, pinned by a test: on input that is not valid JSON, gjson.GetBytes and gjson.Parse return different spans for the same key, and the new implementation refuses to rewrite an unparseable fragment instead of truncating it. The only caller forwards a body that the handler has already validated, so this path is not reachable in production. (cherry picked from commit 049e0f41b863b0e81527de088fb144db0a60e5d3) --- .../service/openai_responses_namespace.go | 49 ++-- ...enai_responses_namespace_benchmark_test.go | 19 +- ...ai_responses_namespace_equivalence_test.go | 241 ++++++++++++++++++ 3 files changed, 284 insertions(+), 25 deletions(-) create mode 100644 backend/internal/service/openai_responses_namespace_equivalence_test.go 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..3e8f0600fe18 --- /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) + }) +} From beb67770e3f574d5516b659f29bf217037d3bc08 Mon Sep 17 00:00:00 2001 From: lishuangqiang <142634204+lishuangqiang@users.noreply.github.com> Date: Tue, 17 Nov 2026 00:29:48 +0800 Subject: [PATCH 33/87] style(openai): gofmt the namespace strip equivalence test (cherry picked from commit 596696356e2fb4a62d3e4797dc5cdcf71553cfdb) --- .../service/openai_responses_namespace_equivalence_test.go | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/backend/internal/service/openai_responses_namespace_equivalence_test.go b/backend/internal/service/openai_responses_namespace_equivalence_test.go index 3e8f0600fe18..52f766d7dab3 100644 --- a/backend/internal/service/openai_responses_namespace_equivalence_test.go +++ b/backend/internal/service/openai_responses_namespace_equivalence_test.go @@ -60,8 +60,8 @@ func legacyStripOpenAIResponsesInputNamespaces(body []byte, keepToolCallNamespac } type stripSnapshot struct { - err string - output string + err string + output string unchanged bool // 是否原样返回了传入的 slice(两个实现都应如此) } From b27ceb904e6e23eb5401e362e45745f03e0910e2 Mon Sep 17 00:00:00 2001 From: lishuangqiang <142634204+lishuangqiang@users.noreply.github.com> Date: Tue, 17 Nov 2026 01:39:42 +0800 Subject: [PATCH 34/87] perf(openai): stop walking every request body in the tool-schema sanitizer sanitizeOpenAIResponsesToolSchemasForPlatform runs on every OpenAI Responses forward attempt, on WS normalization and on /v1/messages conversion, and its two passes both ran far more often than they need to: * the regex-pattern pass was gated on "the body contains '('", and tool descriptions, code samples and user messages contain parentheses constantly, so the gate let essentially everything through; * the parameter-type pass had no gate at all and ran for OpenAI, Anthropic, Grok and every CN platform. A 1MiB Codex request therefore walked its body twice with the hand-written parser before reaching the upstream. Profiling put 92% of that in parseString, which scanned strings byte by byte while long content strings are most of a request body. Changes: 1. parseString skips the plain run of a string eight bytes at a time (SWAR), stopping only on '"', '\\' or a control byte - exactly the three bytes it has to stop at. 2.2 GB/s -> 10.5 GB/s. 2. An input item is no longer walked twice. The type probe walked the whole item and then the item was walked again just to skip it; the probe's end position is now reused. Messages dominate input history. 3. json.Valid(body) only runs when the walk actually produced an edit. With no edits the body is returned untouched, so that second full-body validation proved nothing; patches are still validated after they are applied. 4. Both gates are now necessary conditions that can be proven complete. hasUnsupportedOpenAIRegexPattern only fires on an unsupported backslash escape, a trailing backslash, or group syntax "(?"; the first two need a decoded backslash, which JSON can only spell "\\\\" or \\u005c, and the third can have either character escaped. The parameter pass only edits a literal null value or a oneOf/anyOf union, and the union repair accepts any parameters object containing a backslash, so an escaped keyword such as "one\\u004ff" counts too - hence the \\u00XX needle. 5. Patterns are checked in place when the JSON span carries no escape, instead of strconv.Unquote per pattern, and object member names are parsed once into openAIResponsesJSONKey rather than rescanning the span for every candidate name. Benchmark (Apple M5 Pro, 1MiB Codex-shaped body: 30 tools + 1MiB input): platform entry, OpenAI 7.48ms / 512 allocs -> 96us / 0 allocs platform entry, Anthropic 3.75ms / 256 allocs -> 66us / 0 allocs patterns pass 3.71ms / 256 allocs -> 30us / 0 allocs parameter-types pass 3.69ms / 256 allocs -> 66us / 0 allocs Existing benchmarks: ..._Patterns_ByteSpanPatch 1586609ns / 2017 allocs -> 915199ns / 17 ..._ParameterTypes_ByteSpanPatch 1011697ns / 17 allocs -> 647160ns / 17 Correctness: parseString keeps the previous byte-at-a-time scanner as legacy* and compares return values and error positions across a corpus plus fuzzing; the probe reuse asserts that the probe and the skip walk stop at the same byte; the gates are pinned by the invariant "if the sanitizer changed the body, the gate must have let it through", over a corpus that spells out every unsupported pattern shape and fuzzing; dropping the pre-edit json.Valid relies on "the parser accepts implies encoding/json accepts", which is fuzzed too. Fuzzing found two bugs in this change, both fixed and kept as regression seeds under testdata/fuzz: an out-of-range read when a body ended in "\\\\", and a gate that was narrower than the necessary condition for a pattern whose value is a lone backslash. The second means such patterns are now cleaned up where the old gate only caught them by accident, when the body happened to contain a parenthesis elsewhere. (cherry picked from commit e7c587e14de55c286edc816fda2f18e550d58492) --- .../service/openai_responses_tool_schema.go | 267 ++++++++++---- ...ai_responses_tool_schema_benchmark_test.go | 129 +++++++ .../openai_responses_tool_schema_scan_test.go | 334 ++++++++++++++++++ .../19981bffc2abbaf1 | 2 + .../430233b3de39cf96 | 2 + .../6c31f0fa5746a2cd | 2 + .../e90985907f88433e | 2 + 7 files changed, 662 insertions(+), 76 deletions(-) create mode 100644 backend/internal/service/openai_responses_tool_schema_benchmark_test.go create mode 100644 backend/internal/service/openai_responses_tool_schema_scan_test.go create mode 100644 backend/internal/service/testdata/fuzz/FuzzOpenAIResponsesToolSchemaGatesAreNecessary/19981bffc2abbaf1 create mode 100644 backend/internal/service/testdata/fuzz/FuzzOpenAIResponsesToolSchemaGatesAreNecessary/430233b3de39cf96 create mode 100644 backend/internal/service/testdata/fuzz/FuzzOpenAIResponsesToolSchemaGatesAreNecessary/6c31f0fa5746a2cd create mode 100644 backend/internal/service/testdata/fuzz/FuzzOpenAIResponsesToolSchemaGatesAreNecessary/e90985907f88433e 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/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\":\"\\\\\"}}}}]}") From 31764c84c37538ec46c7cf292b5e59429540c401 Mon Sep 17 00:00:00 2001 From: zhanghuaxiang <870255124@qq.com> Date: Mon, 16 Nov 2026 13:22:54 +0800 Subject: [PATCH 35/87] fix(openai): stop pinning large request bodies after the handler Clone the few request-view strings that outlive the handler instead of aliasing the request body, drop the converted Responses input once it is marshaled, and avoid pointing usage logs at the forward input. Async prompt audit checks its scope before copying the body and no longer clones twice, splits and trims prompts without full []rune copies, and skips redaction rewrites that cannot match. Co-authored-by: Cursor (cherry picked from commit bcb22d4de855635ffb2827a610ecde0c846461f0) --- backend/internal/securityaudit/coordinator.go | 4 +- .../prompt_memory_optimization_test.go | 225 ++++++++++++++++++ .../internal/securityaudit/prompt_scanner.go | 23 +- .../internal/securityaudit/prompt_service.go | 15 ++ .../internal/securityaudit/prompt_snapshot.go | 51 ++-- .../openai_gateway_chat_completions.go | 3 + .../service/openai_gateway_messages.go | 3 + .../service/openai_gateway_request_body.go | 17 +- .../openai_gateway_service_hotpath_test.go | 15 ++ .../internal/service/openai_gateway_usage.go | 13 +- 10 files changed, 335 insertions(+), 34 deletions(-) create mode 100644 backend/internal/securityaudit/prompt_memory_optimization_test.go 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/service/openai_gateway_chat_completions.go b/backend/internal/service/openai_gateway_chat_completions.go index 44f5d836d041..677892555513 100644 --- a/backend/internal/service/openai_gateway_chat_completions.go +++ b/backend/internal/service/openai_gateway_chat_completions.go @@ -292,6 +292,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{ diff --git a/backend/internal/service/openai_gateway_messages.go b/backend/internal/service/openai_gateway_messages.go index 3d87259a3e85..8e78ef95a8fe 100644 --- a/backend/internal/service/openai_gateway_messages.go +++ b/backend/internal/service/openai_gateway_messages.go @@ -276,6 +276,9 @@ func (s *OpenAIGatewayService) forwardAsAnthropic( 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 diff --git a/backend/internal/service/openai_gateway_request_body.go b/backend/internal/service/openai_gateway_request_body.go index e5f6bace497e..2690a50774fe 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 } } 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_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) From ce37b72b51ed5daf2f4e46b17e72e39910ebaba8 Mon Sep 17 00:00:00 2001 From: wucm667 Date: Tue, 17 Nov 2026 15:13:03 +0800 Subject: [PATCH 36/87] fix(anthropic): expose metadata-backed long-context models (cherry picked from commit 570d59e9ac0f32bf5caa51f0a1a72c60f40fbc01) --- backend/internal/handler/gateway_handler.go | 16 ++++ .../internal/handler/gateway_models_test.go | 76 +++++++++++++++++++ .../internal/service/anthropic_models_list.go | 47 ++++++++++++ backend/internal/service/upstream_models.go | 7 +- .../internal/service/upstream_models_test.go | 46 +++++++++++ 5 files changed, 191 insertions(+), 1 deletion(-) create mode 100644 backend/internal/service/anthropic_models_list.go diff --git a/backend/internal/handler/gateway_handler.go b/backend/internal/handler/gateway_handler.go index 59ae41723109..e7a7428964ea 100644 --- a/backend/internal/handler/gateway_handler.go +++ b/backend/internal/handler/gateway_handler.go @@ -1223,6 +1223,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 = modelListingSource(platform, availableModels, defaultModelIDsForPlatform(platform)) + } else if len(source) == 0 { + source = 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)) diff --git a/backend/internal/handler/gateway_models_test.go b/backend/internal/handler/gateway_models_test.go index 100166a022bb..eb0a2cdd0fc7 100644 --- a/backend/internal/handler/gateway_models_test.go +++ b/backend/internal/handler/gateway_models_test.go @@ -23,6 +23,82 @@ 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) + } + require.Len(t, mergeModelIDs(ids, nil), len(ids)) + }) + } +} + type gatewayModelsRouteRepoStub struct { service.CompositeModelRouteRepository routes []service.CompositeModelRoute diff --git a/backend/internal/service/anthropic_models_list.go b/backend/internal/service/anthropic_models_list.go new file mode 100644 index 000000000000..e3376935942a --- /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 := cloneStringSlice(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/upstream_models.go b/backend/internal/service/upstream_models.go index 624b20df1ce6..d98a01bbf858 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": 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 From b0dad124d5eaa448a0c63508eb181163137c864a Mon Sep 17 00:00:00 2001 From: SipengXie2024 <184713193+SipengXie2024@users.noreply.github.com> Date: Tue, 17 Nov 2026 09:50:16 +0000 Subject: [PATCH 37/87] fix(openai): skip foreign-vendor models on ChatGPT OAuth accounts, passthrough included Empty-mapping OpenAI OAuth accounts accepted claude-* models, and OAuth or setup-token accounts with openai_passthrough accepted every model. Both send requests to chatgpt.com/backend-api/codex, which answers foreign models with a non-retryable 400 ("not supported when using Codex with a ChatGPT account"), so mixed groups handed claude-* requests from Codex clients to the OAuth account instead of the API-key account that serves them. - Add "claude-" to openAIOAuthForeignModelPrefixes. - Apply the foreign-prefix check to OAuth and setup-token passthrough too; API-key passthrough keeps allowing every model. - Schedule /v1/messages by the channel-mapped model, as Responses, Chat Completions and the Responses WebSocket already do, so a channel mapping a claude-* alias to a GPT model still lands on OAuth accounts. (cherry picked from commit 77ba3346d1ae9aa3930dc1b347d05582e1bae93d) --- .../handler/openai_gateway_handler.go | 5 ++- backend/internal/service/account.go | 10 ++++- .../internal/service/openai_model_mapping.go | 7 +-- .../openai_oauth_model_support_test.go | 44 ++++++++++++++++--- 4 files changed, 53 insertions(+), 13 deletions(-) diff --git a/backend/internal/handler/openai_gateway_handler.go b/backend/internal/handler/openai_gateway_handler.go index e1788f518c61..75d063dc520c 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 { diff --git a/backend/internal/service/account.go b/backend/internal/service/account.go index 35f2cd5881bc..204cfd135945 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。 @@ -1177,6 +1177,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/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..cce75a4eb0d8 100644 --- a/backend/internal/service/openai_oauth_model_support_test.go +++ b/backend/internal/service/openai_oauth_model_support_test.go @@ -28,9 +28,7 @@ func TestIsModelSupported_OpenAIOAuthEmptyMapping_ServableModels(t *testing.T) { "gpt-5", "codex-mini-latest", "gpt5.3codexspark", // 别名拼写 - "gpt-image-1", // 图像生成模型 - "claude-sonnet-4-6", // /v1/messages 调度默认映射兜底 - "claude-3-opus-20240229", + "gpt-image-1", // 图像生成模型 "gpt-4o", // 保守 fail-open:非黑名单模型保持允许 "my-custom-alias", // 自定义别名可能由渠道级映射在转发前改写,保持允许 } @@ -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")) From b30320feeeba75056046b4b098522d2d3c62c43e Mon Sep 17 00:00:00 2001 From: r266-tech Date: Tue, 17 Nov 2026 21:46:58 +0800 Subject: [PATCH 38/87] fix(accounts): opt in to bulk passthrough model filter changes (cherry picked from commit 3b95559788e2538450c6c06765ae508b9f146a7e) --- .../account/BulkEditAccountModal.vue | 58 ++++++-- .../__tests__/BulkEditAccountModal.spec.ts | 133 ++++++++++++++++-- 2 files changed, 173 insertions(+), 18 deletions(-) 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 @@ ]" /> -