fix(openai): fail over standalone alpha search on API-key upstream 400

Some OpenAI-compatible relays reject the standalone Codex search endpoint
with HTTP 400 while serving /v1/responses normally. The 400 was passed
straight to the client, so search failed even when another account in the
group could serve it.

For API-key accounts, a 400 from /v1/alpha/search now fails over to the
next eligible account without account-health side effects or same-account
retries. When failover is exhausted the last upstream status and body are
returned unchanged.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
r266-techandClaude Opus 5.5 committed 2026-11-29 11:24:35 +09:00
1 parent f53641e53c
commit df3c428142
5 files changed
+152 -14

No files matched your search

@@ -220,7 +220,9 @@ func (h *OpenAIGatewayHandler) AlphaSearch(c *gin.Context) {
return
}
h.gatewayService.ReportOpenAIAccountScheduleResult(account, openAIAccountScheduleModel(c, account, requestedModel, false, result), false, nil, err)
if failoverErr.Reason != service.OpenAIAlphaSearchRejectedReason {
h.gatewayService.ReportOpenAIAccountScheduleResult(account, openAIAccountScheduleModel(c, account, requestedModel, false, result), false, nil, err)
}
if c.Writer.Size() != writerSizeBeforeForward {
h.handleFailoverExhausted(c, failoverErr, true)
return
@@ -0,0 +1,107 @@
package handler
import (
"fmt"
"io"
"net/http"
"net/http/httptest"
"strings"
"testing"
"github.com/Wei-Shaw/sub2api/internal/config"
"github.com/Wei-Shaw/sub2api/internal/server/middleware"
"github.com/Wei-Shaw/sub2api/internal/service"
"github.com/gin-gonic/gin"
"github.com/stretchr/testify/require"
)
type alphaSearchUpstream struct {
service.HTTPUpstream
successAccount int64
calls []int64
}
const alphaSearchSuccess = `{"output":"search result"}`
func alphaSearchRejection(accountID int64) string {
return fmt.Sprintf(`{ "error": {"message": "rejected by %d"} }`+"\n", accountID)
}
func (u *alphaSearchUpstream) Do(_ *http.Request, _ string, accountID int64, _ int) (*http.Response, error) {
u.calls = append(u.calls, accountID)
status, contentType, body := http.StatusBadRequest, "application/problem+json", alphaSearchRejection(accountID)
if accountID == u.successAccount {
status, contentType, body = http.StatusOK, "application/json", alphaSearchSuccess
}
return &http.Response{
StatusCode: status,
Header: http.Header{"Content-Type": {contentType}},
Body: io.NopCloser(strings.NewReader(body)),
}, nil
}
func TestAlphaSearchBadRequestFailover(t *testing.T) {
gin.SetMode(gin.TestMode)
for _, tc := range []struct {
name string
accountCount int
successAccount int64
maxSwitches int
firstType string
wantCalls []int64
wantStatus int
wantBody string
}{
{"next account succeeds", 2, 2, 2, service.AccountTypeAPIKey, []int64{1, 2}, http.StatusOK, alphaSearchSuccess},
{"single account", 1, 0, 2, service.AccountTypeAPIKey, []int64{1}, http.StatusBadRequest, alphaSearchRejection(1)},
{"all accounts reject", 2, 0, 3, service.AccountTypeAPIKey, []int64{1, 2}, http.StatusBadRequest, alphaSearchRejection(2)},
{"switch limit", 3, 3, 1, service.AccountTypeAPIKey, []int64{1, 2}, http.StatusBadRequest, alphaSearchRejection(2)},
{"oauth passes through", 2, 2, 2, service.AccountTypeOAuth, []int64{1}, http.StatusBadRequest, alphaSearchRejection(1)},
} {
t.Run(tc.name, func(t *testing.T) {
repo := &openAIWSFailoverHandlerAccountRepoStub{}
for i := 1; i <= tc.accountCount; i++ {
account := newPinnedCodexAccount(int64(i), service.StatusActive, true, false)
account.Concurrency = 0
account.Credentials["pool_mode"] = true
account.Credentials["pool_mode_retry_status_codes"] = []any{400}
repo.accounts = append(repo.accounts, account)
}
if tc.firstType == service.AccountTypeOAuth {
repo.accounts[0].Type = tc.firstType
repo.accounts[0].Credentials = map[string]any{"access_token": "oauth-token", "chatgpt_account_id": "chatgpt-account"}
}
cfg := &config.Config{RunMode: config.RunModeSimple}
upstream := &alphaSearchUpstream{successAccount: tc.successAccount}
usage := &openAIWSUsageHandlerUsageLogRepoStub{created: make(chan *service.UsageLog, 4)}
billing := service.NewBillingCacheService(nil, nil, nil, nil, nil, nil, cfg, nil)
t.Cleanup(billing.Stop)
gateway := service.NewOpenAIGatewayService(repo, usage, nil, nil, nil, nil, nil, cfg,
nil, nil, service.NewBillingService(cfg, nil), service.NewRateLimitService(repo, nil, cfg, nil, nil), billing, upstream,
&service.DeferredService{}, nil, nil, nil, nil, nil, nil, nil)
h := NewOpenAIGatewayHandler(gateway, service.NewConcurrencyService(nil), billing, &service.APIKeyService{}, nil, nil, nil, nil, cfg)
h.maxAccountSwitches = tc.maxSwitches
rec := httptest.NewRecorder()
c, _ := gin.CreateTestContext(rec)
c.Request = httptest.NewRequest(http.MethodPost, "/v1/alpha/search", strings.NewReader(`{"model":"gpt-5.6-sol","commands":{"search_query":[{"q":"news"}]}}`))
group := &service.Group{ID: 42, Platform: service.PlatformOpenAI}
c.Set(string(middleware.ContextKeyAPIKey), &service.APIKey{ID: 1, GroupID: &group.ID, Group: group, User: &service.User{ID: 2}})
c.Set(string(middleware.ContextKeyUser), middleware.AuthSubject{UserID: 2})
h.AlphaSearch(c)
require.Equal(t, tc.wantCalls, upstream.calls)
require.Equal(t, tc.wantStatus, rec.Code)
require.Equal(t, tc.wantBody, rec.Body.String())
require.Empty(t, repo.rateLimitedIDs)
if tc.wantStatus == http.StatusOK {
require.Len(t, usage.created, 1)
require.Equal(t, tc.successAccount, (<-usage.created).AccountID)
require.Equal(t, "application/json", rec.Header().Get("Content-Type"))
} else {
require.Empty(t, usage.created)
require.Equal(t, "application/problem+json", rec.Header().Get("Content-Type"))
}
})
}
}
@@ -3640,6 +3640,10 @@ func (h *OpenAIGatewayHandler) handleFailoverExhausted(c *gin.Context, failoverE
h.handleFailoverExhaustedSimple(c, http.StatusBadGateway, streamStarted)
return
}
if failoverErr.Reason == service.OpenAIAlphaSearchRejectedReason && !streamStarted {
h.gatewayService.WriteAlphaSearchResponse(c, failoverErr.StatusCode, failoverErr.ResponseHeaders, failoverErr.ResponseBody)
return
}
if failoverErr.Reason == service.OpenAIResponsesToolsUnsupportedReason {
// No upstream request was sent for this local capability mismatch. Keep
// the original client error without attributing it to upstream health.
@@ -18,6 +18,8 @@ import (
const (
chatgptCodexAlphaSearchURL = "https://chatgpt.com/backend-api/codex/alpha/search"
openAIPlatformAlphaSearchURL = "https://api.openai.com/v1/alpha/search"
OpenAIAlphaSearchRejectedReason GatewayFailureReason = "openai_alpha_search_rejected"
)
// ForwardAlphaSearch proxies Codex standalone web search without binding the
@@ -89,6 +91,16 @@ func (s *OpenAIGatewayService) ForwardAlphaSearch(ctx context.Context, c *gin.Co
return nil, fmt.Errorf("read alpha search response: %w", err)
}
// API key 中转可能只拒绝独立搜索端点。直接换号,不重试同一账号,
// 也不把这次 400 计入账号健康;耗尽时仍透传最后一次上游响应。
if account.Type == AccountTypeAPIKey && resp.StatusCode == http.StatusBadRequest {
return nil, &UpstreamFailoverError{
StatusCode: resp.StatusCode,
ResponseBody: respBody,
ResponseHeaders: resp.Header,
Reason: OpenAIAlphaSearchRejectedReason,
}
}
if resp.StatusCode >= http.StatusBadRequest {
upstreamMessage := sanitizeUpstreamErrorMessage(strings.TrimSpace(extractUpstreamErrorMessage(respBody)))
if s.shouldFailoverOpenAIUpstreamResponse(account, resp.StatusCode, upstreamMessage, respBody) ||
@@ -117,12 +129,7 @@ func (s *OpenAIGatewayService) ForwardAlphaSearch(ctx context.Context, c *gin.Co
if !account.IsShadow() {
s.UpdateCodexUsageSnapshotFromHeaders(ctx, account.ID, resp.Header)
}
writeOpenAIPassthroughResponseHeaders(c.Writer.Header(), resp.Header, s.responseHeaderFilter)
contentType := resp.Header.Get("Content-Type")
if contentType == "" {
contentType = "application/json"
}
c.Data(resp.StatusCode, contentType, respBody)
s.WriteAlphaSearchResponse(c, resp.StatusCode, resp.Header, respBody)
if resp.StatusCode < http.StatusOK || resp.StatusCode >= http.StatusMultipleChoices {
// 非 2xx(错误/重定向)已原样透传给客户端:不是一次成功的搜索,不计费。
return nil, nil
@@ -137,6 +144,16 @@ func (s *OpenAIGatewayService) ForwardAlphaSearch(ctx context.Context, c *gin.Co
}, nil
}
// WriteAlphaSearchResponse forwards the selected standalone search response, including an exhausted upstream 400.
func (s *OpenAIGatewayService) WriteAlphaSearchResponse(c *gin.Context, status int, headers http.Header, body []byte) {
writeOpenAIPassthroughResponseHeaders(c.Writer.Header(), headers, s.responseHeaderFilter)
contentType := headers.Get("Content-Type")
if contentType == "" {
contentType = "application/json"
}
c.Data(status, contentType, body)
}
func (s *OpenAIGatewayService) forwardAlphaSearchViaResponsesWebSearch(
ctx context.Context,
c *gin.Context,
@@ -244,7 +244,7 @@ func TestForwardAlphaSearchPATBackfillsMissingChatGPTAccountMetadata(t *testing.
require.Equal(t, OpenAIAuthModePersonalAccessToken, account.Credentials["auth_mode"])
}
func TestForwardAlphaSearchAPIKeyMapsModelAndPassesThroughError(t *testing.T) {
func TestForwardAlphaSearchAPIKeyMapsModelAndFailsOverOnBadRequest(t *testing.T) {
gin.SetMode(gin.TestMode)
body := []byte(`{"id":"search-session","model":"gpt-5.6-sol","commands":{"search_query":[{"q":"news"}]}}`)
recorder := httptest.NewRecorder()
@@ -252,13 +252,18 @@ func TestForwardAlphaSearchAPIKeyMapsModelAndPassesThroughError(t *testing.T) {
c.Request = httptest.NewRequest(http.MethodPost, "/alpha/search", bytes.NewReader(body))
c.Request.Header.Set("Content-Type", "application/json")
upstreamBody := `{"error":{"type":"invalid_request_error","message":"bad search"}}`
upstreamBody := `{"error":{"type":"invalid_request_error","message":"organization has been disabled"}}`
upstream := &httpUpstreamRecorder{resp: &http.Response{
StatusCode: http.StatusBadRequest,
Header: http.Header{"Content-Type": []string{"application/json"}},
Body: io.NopCloser(strings.NewReader(upstreamBody)),
}}
service := &OpenAIGatewayService{cfg: &config.Config{}, httpUpstream: upstream}
repo := &alphaSearchAccountStateRepo{}
cfg := &config.Config{}
service := &OpenAIGatewayService{
cfg: cfg, httpUpstream: upstream, accountRepo: repo,
rateLimitService: NewRateLimitService(repo, nil, cfg, nil, nil),
}
account := &Account{
ID: 7,
Platform: PlatformOpenAI,
@@ -274,11 +279,14 @@ func TestForwardAlphaSearchAPIKeyMapsModelAndPassesThroughError(t *testing.T) {
result, err := service.ForwardAlphaSearch(context.Background(), c, account, body)
require.NoError(t, err)
// 上游错误透传不是一次成功的搜索:不返回 result、不产生按次计费。
var failoverErr *UpstreamFailoverError
require.ErrorAs(t, err, &failoverErr)
require.Nil(t, result)
require.Equal(t, http.StatusBadRequest, recorder.Code)
require.JSONEq(t, upstreamBody, recorder.Body.String())
require.Equal(t, OpenAIAlphaSearchRejectedReason, failoverErr.Reason)
require.Equal(t, http.StatusBadRequest, failoverErr.StatusCode)
require.Equal(t, upstreamBody, string(failoverErr.ResponseBody))
require.False(t, c.Writer.Written())
require.Zero(t, repo.setErrorCalls)
require.Equal(t, "https://compat.example/v4/alpha/search", upstream.lastReq.URL.String())
require.Equal(t, "Bearer sk-test", upstream.lastReq.Header.Get("Authorization"))
require.Equal(t, "upstream-5.6", gjson.GetBytes(upstream.lastBody, "model").String())