From f34df0e313b1a5e3ae8a929aaeca237c9062ee21 Mon Sep 17 00:00:00 2001 From: ninedrunk Date: Sat, 28 Nov 2026 12:52:13 +0800 Subject: [PATCH 01/11] =?UTF-8?q?feat(accounts):=20=E8=AE=A9=E6=89=80?= =?UTF-8?q?=E6=9C=89=E5=8F=97=E6=94=AF=E6=8C=81=E5=B9=B3=E5=8F=B0=E9=83=BD?= =?UTF-8?q?=E8=83=BD=E9=85=8D=E7=BD=AE=E8=B4=A6=E5=8F=B7=E7=BA=A7=E8=87=AA?= =?UTF-8?q?=E5=8A=A8=E5=81=9C=E8=B0=83=E9=98=88=E5=80=BC?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 后端已对 AllowedSchedulingThresholdPlatforms 中所有平台支持账号级 account_scheduling_threshold 覆盖,系统设置页也通过 SCHEDULING_THRESHOLD_PLATFORMS 展示了完整清单。 但账号编辑弹窗把 override 支持平台硬编码为 openai / anthropic / grok, 导致 Kimi / Zhipu GLM / MiniMax / OpenCode Go / Command Code 账号 即使后端完全支持,也没有 UI 可以配置账号级阈值。 创建账号弹窗则完全没有该选项。 改动: - 编辑弹窗改为从 SCHEDULING_THRESHOLD_PLATFORMS 派生支持平台, 消除前后端清单漂移; - 创建账号弹窗新增同样的账号级阈值覆盖入口; - 沿用 credentials.account_scheduling_threshold 键及原有语义。 不改动后端逻辑,不影响现有平台行为。 --- .../components/account/CreateAccountModal.vue | 54 +++++ .../components/account/EditAccountModal.vue | 6 +- ...itAccountModal.schedulingThreshold.spec.ts | 189 ++++++++++++++++++ .../src/i18n/locales/en/admin/accounts.ts | 1 + .../src/i18n/locales/zh/admin/accounts.ts | 1 + 5 files changed, 250 insertions(+), 1 deletion(-) create mode 100644 frontend/src/components/account/__tests__/EditAccountModal.schedulingThreshold.spec.ts diff --git a/frontend/src/components/account/CreateAccountModal.vue b/frontend/src/components/account/CreateAccountModal.vue index 24ba7aed1c..8478f2056c 100644 --- a/frontend/src/components/account/CreateAccountModal.vue +++ b/frontend/src/components/account/CreateAccountModal.vue @@ -581,6 +581,40 @@ + +
+
+
+ +

+ {{ t('admin.accounts.cnProviders.schedulingThresholdCreateHint') }} +

+
+ +
+
+ + +

{{ t('admin.accounts.accountSchedulingThresholdOverrideDisabledHint') }}

+
+
+
@@ -4164,6 +4198,7 @@ import { isValidWildcardPattern } from '@/composables/useModelWhitelist' import { adminAPI } from '@/api/admin' +import { SCHEDULING_THRESHOLD_PLATFORMS } from '@/api/admin/settings' import { useQuotaNotifyState } from '@/composables/useQuotaNotifyState' import { useAccountOAuth, @@ -4479,6 +4514,14 @@ const isGenericMultiProtocolPlatform = computed( const extraMultiProtocolPlatforms = computed(() => listPlatforms().filter(spec => !!spec.multi_protocol && !isCNProviderPlatform(spec.id) && spec.id !== 'opencode_go') ) +// 账号级自动停调阈值覆盖(创建时可选):写入 credentials.account_scheduling_threshold。 +// 仅对后端白名单平台显示;关闭/留空 = 跟随系统平台阈值。 +const ACCOUNT_SCHEDULING_THRESHOLD_CREDENTIAL_KEY = 'account_scheduling_threshold' +const createSchedulingThresholdOverrideEnabled = ref(false) +const createSchedulingThresholdOverrideValue = ref(100) +const supportsCreateSchedulingThresholdOverride = computed(() => + (SCHEDULING_THRESHOLD_PLATFORMS as readonly string[]).includes(form.platform) +) const genericAccountModes = computed(() => providerAccountModes(form.platform)) // 按模型分流的供应商(OpenCode 等):adaptive 账号携带 protocol_rules。 const routesByModel = computed(() => providerRoutesByModel(form.platform)) @@ -6241,6 +6284,17 @@ const handleSubmit = async () => { } } + // 账号级自动停调阈值覆盖:仅白名单平台、勾选且值在 1..99 时写入 + // (100 = 禁用当前账号自动停调,不写则跟随系统平台阈值)。 + if ( + supportsCreateSchedulingThresholdOverride.value && + createSchedulingThresholdOverrideEnabled.value + ) { + const numeric = Math.trunc(Number(createSchedulingThresholdOverrideValue.value) || 100) + const clamped = Math.min(100, Math.max(1, numeric)) + credentials[ACCOUNT_SCHEDULING_THRESHOLD_CREDENTIAL_KEY] = clamped + } + // Add model mapping if configured(OpenAI 开启自动透传时不应用) if (!isOpenAIModelRestrictionDisabled.value) { const modelMapping = buildModelMappingObject(modelRestrictionMode.value, allowedModels.value, modelMappings.value) diff --git a/frontend/src/components/account/EditAccountModal.vue b/frontend/src/components/account/EditAccountModal.vue index e1e50ec52a..15a1836ef0 100644 --- a/frontend/src/components/account/EditAccountModal.vue +++ b/frontend/src/components/account/EditAccountModal.vue @@ -3422,6 +3422,7 @@ import { useI18n } from 'vue-i18n' import { useAppStore } from '@/stores/app' import { adminAPI } from '@/api/admin' +import { SCHEDULING_THRESHOLD_PLATFORMS } from '@/api/admin/settings' import { useQuotaNotifyState } from '@/composables/useQuotaNotifyState' import type { Account, @@ -5353,7 +5354,10 @@ const applyTempUnschedConfig = (credentials: Record) => { function supportsAccountSchedulingThresholdOverridePlatform(platform: Account['platform'] | undefined) { - return platform === 'openai' || platform === 'anthropic' || platform === 'grok' + // 与后端 AllowedSchedulingThresholdPlatforms 共用同一清单(系统设置页也用这份), + // 避免前端入口与后端白名单再次漂移。 + if (!platform) return false + return (SCHEDULING_THRESHOLD_PLATFORMS as readonly string[]).includes(platform) } function normalizeAccountSchedulingThresholdOverride(value: unknown): number | null { diff --git a/frontend/src/components/account/__tests__/EditAccountModal.schedulingThreshold.spec.ts b/frontend/src/components/account/__tests__/EditAccountModal.schedulingThreshold.spec.ts new file mode 100644 index 0000000000..db6052eaa5 --- /dev/null +++ b/frontend/src/components/account/__tests__/EditAccountModal.schedulingThreshold.spec.ts @@ -0,0 +1,189 @@ +import { beforeEach, describe, expect, it, vi } from 'vitest' +import { defineComponent } from 'vue' +import { flushPromises, mount } from '@vue/test-utils' + +// 账号级自动停调阈值覆盖:GLM / MiniMax / OpenCode / Command Code 等 +// 套餐平台现在都能在账号编辑页设置该覆盖(此前仅 openai/anthropic/grok)。 + +const { updateAccountMock, checkMixedChannelRiskMock, authIsSimpleMode } = vi.hoisted(() => ({ + updateAccountMock: vi.fn(), + checkMixedChannelRiskMock: vi.fn(), + authIsSimpleMode: { value: true } +})) + +vi.mock('@/stores/app', () => ({ + useAppStore: () => ({ + showError: vi.fn(), + showSuccess: vi.fn(), + showInfo: vi.fn() + }) +})) + +vi.mock('@/stores/auth', () => ({ + useAuthStore: () => ({ + get isSimpleMode() { + return authIsSimpleMode.value + } + }) +})) + +vi.mock('@/api/admin', () => ({ + adminAPI: { + accounts: { + update: updateAccountMock, + checkMixedChannelRisk: checkMixedChannelRiskMock, + previewUpstreamGroup: vi.fn() + }, + settings: { + getWebSearchEmulationConfig: vi.fn().mockResolvedValue({ enabled: false, providers: [] }), + getSettings: vi.fn().mockResolvedValue({}) + }, + tlsFingerprintProfiles: { + list: vi.fn().mockResolvedValue([]) + } + } +})) + +vi.mock('@/api/admin/accounts', () => ({ + getAntigravityDefaultModelMapping: vi.fn() +})) + +vi.mock('vue-i18n', async () => { + const actual = await vi.importActual('vue-i18n') + return { + ...actual, + useI18n: () => ({ t: (key: string) => key }) + } +}) + +import EditAccountModal from '../EditAccountModal.vue' + +const BaseDialogStub = defineComponent({ + name: 'BaseDialog', + props: { show: { type: Boolean, default: false } }, + template: '
' +}) + +const GroupSelectorStub = defineComponent({ + name: 'GroupSelector', + props: { modelValue: { type: Array, default: () => [] } }, + emits: ['update:modelValue'], + template: '
' +}) + +const ModelWhitelistSelectorStub = defineComponent({ + name: 'ModelWhitelistSelector', + props: { modelMappings: { type: Array, default: () => [] }, modelValue: { type: Array, default: () => [] } }, + emits: ['update:modelValue'], + template: '
' +}) + +const SelectStub = defineComponent({ + name: 'SelectStub', + props: { + modelValue: { type: [String, Number, Boolean, null], default: '' }, + options: { type: Array, default: () => [] } + }, + emits: ['update:modelValue'], + template: ` + + ` +}) + +function buildAccount(platform: string, credentials: Record = {}) { + return { + id: 1, + name: `account-${platform}`, + notes: '', + platform, + type: 'apikey', + credentials: { api_key: 'key-test', base_url: '', ...credentials }, + extra: {}, + proxy_id: null, + concurrency: 1, + priority: 1, + rate_multiplier: 1, + status: 'active', + group_ids: [], + expires_at: null, + auto_pause_on_expired: false + } as any +} + +function mountModal(account: any) { + return mount(EditAccountModal, { + props: { show: true, account, proxies: [], groups: [] }, + global: { + stubs: { + BaseDialog: BaseDialogStub, + Select: SelectStub, + Icon: true, + ProxySelector: true, + GroupSelector: GroupSelectorStub, + ModelWhitelistSelector: ModelWhitelistSelectorStub + } + } + }) +} + +describe('EditAccountModal 账号自动停调阈值覆盖(套餐平台)', () => { + beforeEach(() => { + authIsSimpleMode.value = true + updateAccountMock.mockReset() + checkMixedChannelRiskMock.mockReset().mockResolvedValue({ has_risk: false }) + }) + + it.each(['zhipu', 'minimax', 'opencode_go', 'command_code'])( + '%s 账号显示阈值覆盖区块并能提交 account_scheduling_threshold', + async (platform) => { + const account = buildAccount(platform, { + account_mode: platform === 'zhipu' ? 'coding' : 'payg' + }) + updateAccountMock.mockResolvedValue(account) + const wrapper = mountModal(account) + + expect(wrapper.find('[data-testid="account-scheduling-threshold-section"]').exists()).toBe(true) + + await wrapper.get('[data-testid="account-scheduling-threshold-override-enabled"]').setValue(true) + await wrapper.get('[data-testid="account-scheduling-threshold-override-value"]').setValue('50') + await wrapper.get('form#edit-account-form').trigger('submit.prevent') + await flushPromises() + + expect(updateAccountMock).toHaveBeenCalledTimes(1) + expect(updateAccountMock.mock.calls[0]?.[1]?.credentials?.account_scheduling_threshold).toBe(50) + wrapper.unmount() + } + ) + + it('deepseek(余额型)不显示阈值覆盖区块', async () => { + const account = buildAccount('deepseek', { account_mode: 'payg' }) + updateAccountMock.mockResolvedValue(account) + const wrapper = mountModal(account) + expect(wrapper.find('[data-testid="account-scheduling-threshold-section"]').exists()).toBe(false) + wrapper.unmount() + }) + + it('关闭覆盖后把 account_scheduling_threshold 置空(回退系统阈值)', async () => { + const account = buildAccount('zhipu', { + account_mode: 'coding', + account_scheduling_threshold: 50 + }) + updateAccountMock.mockResolvedValue(account) + const wrapper = mountModal(account) + + const enabled = wrapper.get('[data-testid="account-scheduling-threshold-override-enabled"]') + expect(enabled.element.checked).toBe(true) + const value = wrapper.get('[data-testid="account-scheduling-threshold-override-value"]') + expect(value.element.value).toBe('50') + + await enabled.setValue(false) + await wrapper.get('form#edit-account-form').trigger('submit.prevent') + await flushPromises() + + expect(updateAccountMock).toHaveBeenCalledTimes(1) + expect(updateAccountMock.mock.calls[0]?.[1]?.credentials?.account_scheduling_threshold).toBeNull() + wrapper.unmount() + }) +}) diff --git a/frontend/src/i18n/locales/en/admin/accounts.ts b/frontend/src/i18n/locales/en/admin/accounts.ts index bfdfec7f55..6da92454f7 100644 --- a/frontend/src/i18n/locales/en/admin/accounts.ts +++ b/frontend/src/i18n/locales/en/admin/accounts.ts @@ -154,6 +154,7 @@ export default { example: 'Example: …/organization/org-0610bE2D…/projects/proj_0798F20…/api_keys → org-0610bE2D… goes into "Organization ID", proj_0798F20… into "Project ID"', }, }, + schedulingThresholdCreateHint: 'Optional: override the platform auto-pause threshold for this account (upstream usage-window percent). Leave unchecked to follow the system setting.', balance: 'Balance --', window5h: '5h', windowWeekly: '7d', diff --git a/frontend/src/i18n/locales/zh/admin/accounts.ts b/frontend/src/i18n/locales/zh/admin/accounts.ts index 0d35c23776..4cb68a4bb7 100644 --- a/frontend/src/i18n/locales/zh/admin/accounts.ts +++ b/frontend/src/i18n/locales/zh/admin/accounts.ts @@ -367,6 +367,7 @@ export default { example: '示例:…/organization/org-0610bE2D…/projects/proj_0798F20…/api_keys → org-0610bE2D… 填「组织 ID」,proj_0798F20… 填「项目 ID」', }, }, + schedulingThresholdCreateHint: '可选:为该账号覆盖平台级自动停调阈值(按上游原生窗口百分比)。不勾选则跟随系统设置。', balance: '余额 --', window5h: '5h', windowWeekly: '7d', From df3c428142fcf6874dbafe2e9ec7d91aea3fac9c Mon Sep 17 00:00:00 2001 From: r266-tech Date: Sun, 29 Nov 2026 11:24:35 +0900 Subject: [PATCH 02/11] 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 --- .../internal/handler/openai_alpha_search.go | 4 +- .../handler/openai_alpha_search_test.go | 107 ++++++++++++++++++ .../handler/openai_gateway_handler.go | 4 + .../internal/service/openai_alpha_search.go | 29 ++++- .../service/openai_alpha_search_test.go | 22 ++-- 5 files changed, 152 insertions(+), 14 deletions(-) create mode 100644 backend/internal/handler/openai_alpha_search_test.go diff --git a/backend/internal/handler/openai_alpha_search.go b/backend/internal/handler/openai_alpha_search.go index 8a76f6b23c..f7322b398c 100644 --- a/backend/internal/handler/openai_alpha_search.go +++ b/backend/internal/handler/openai_alpha_search.go @@ -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 diff --git a/backend/internal/handler/openai_alpha_search_test.go b/backend/internal/handler/openai_alpha_search_test.go new file mode 100644 index 0000000000..394447e4f3 --- /dev/null +++ b/backend/internal/handler/openai_alpha_search_test.go @@ -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")) + } + }) + } +} diff --git a/backend/internal/handler/openai_gateway_handler.go b/backend/internal/handler/openai_gateway_handler.go index 0e8c94b9f4..20132b0ea8 100644 --- a/backend/internal/handler/openai_gateway_handler.go +++ b/backend/internal/handler/openai_gateway_handler.go @@ -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. diff --git a/backend/internal/service/openai_alpha_search.go b/backend/internal/service/openai_alpha_search.go index e52183ab22..1b1b3e7834 100644 --- a/backend/internal/service/openai_alpha_search.go +++ b/backend/internal/service/openai_alpha_search.go @@ -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, diff --git a/backend/internal/service/openai_alpha_search_test.go b/backend/internal/service/openai_alpha_search_test.go index 0de2fe3394..64199e617b 100644 --- a/backend/internal/service/openai_alpha_search_test.go +++ b/backend/internal/service/openai_alpha_search_test.go @@ -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()) From e7f32da0a80d721bd631d7a9c6f8dbebac7ef41a Mon Sep 17 00:00:00 2001 From: debug-zhang <34176152+debug-zhang@users.noreply.github.com> Date: Tue, 1 Dec 2026 23:19:41 +0800 Subject: [PATCH 03/11] fix(gateway): return Retry-After on rate-limit and pool-cooldown errors Root cause: downstream 429/503 responses carried no Retry-After. The no-account classifier had no recovery time at all; the earliest account cooldown only existed inside scheduler log lines; and upstream error paths either dropped the provider's response headers (shouldDisable failures, final compat write) or copied Retry-After verbatim, including capacity-shed windows that clients would honor by sleeping for minutes. Change: - Diagnose the earliest cooldown among model-capable accounts (account rate limit, overload, temporary unschedulable, and per-model rate limit) and expose it as ModelAvailabilityDiagnosis.RetryAfterSeconds, capped by the new gateway.retry_after_max_seconds option (default 300s). - Emit Retry-After for 429/503 no-account classifications only when a recovery time is known; 404 model_not_found and unknown values omit it. - Forward upstream Retry-After / retry-after-ms (header or body) only for explicit 429 rate limits, converting to integer seconds with a ceiling and the same cap. Capacity-shed/server_is_overloaded and generic 5xx hints stay dropped to stay compatible with #8560/#8938. - Preserve upstream response headers on failover errors and route every failover-exhaustion path through the gated helper instead of copying arbitrary Retry-After values. - Status codes, error types, and messages are unchanged. Tests: - service: retry-after parsing (header, retry-after-ms rounding, body fields), cap/default/config override, capacity-shed rejection, non-429 statuses ignored, cooldown computation and unknown recovery. - handler: no-account 429/503 emit the diagnosed value, unknown recovery and model_not_found omit it, failover exhaustion forwards upstream 429 hints (including body retry-after-ms) and omits capacity-shed hints. --- backend/internal/config/config.go | 4 + .../gateway_handler_chat_completions.go | 2 +- .../handler/gateway_handler_responses.go | 2 +- backend/internal/handler/no_account_error.go | 26 ++- .../internal/handler/no_account_error_test.go | 58 ++++++ ...openai_gateway_credential_failover_test.go | 45 ++++- .../handler/openai_gateway_handler.go | 37 +--- .../handler/openai_images_balance_test.go | 5 +- .../service/gateway_model_availability.go | 44 ++++- .../openai_gateway_model_availability.go | 9 +- .../service/openai_gateway_upstream_errors.go | 7 + backend/internal/service/retry_after.go | 137 ++++++++++++++ backend/internal/service/retry_after_test.go | 178 ++++++++++++++++++ deploy/config.example.yaml | 3 + 14 files changed, 516 insertions(+), 41 deletions(-) create mode 100644 backend/internal/service/retry_after.go create mode 100644 backend/internal/service/retry_after_test.go diff --git a/backend/internal/config/config.go b/backend/internal/config/config.go index 6dad5c9722..4ba5e58f08 100644 --- a/backend/internal/config/config.go +++ b/backend/internal/config/config.go @@ -1179,6 +1179,9 @@ type GatewayConfig struct { LogUpstreamErrorBody bool `mapstructure:"log_upstream_error_body"` // 上游错误响应体记录最大字节数(超过会截断) LogUpstreamErrorBodyMaxBytes int `mapstructure:"log_upstream_error_body_max_bytes"` + // RetryAfterMaxSeconds 限制下发给客户端的 Retry-After 秒数(默认 300): + // 上游或账号池给出的恢复时间可能长达数小时,客户端按原值冷却会长时间挂起。 + RetryAfterMaxSeconds int `mapstructure:"retry_after_max_seconds"` // API-key 账号在客户端未提供 anthropic-beta 时,是否按需自动补齐(默认关闭以保持兼容) InjectBetaForAPIKey bool `mapstructure:"inject_beta_for_apikey"` @@ -2526,6 +2529,7 @@ func setDefaults() { viper.SetDefault("gateway.openai_high_effort_first_output_timeout_seconds", 0) viper.SetDefault("gateway.log_upstream_error_body", true) viper.SetDefault("gateway.log_upstream_error_body_max_bytes", 2048) + viper.SetDefault("gateway.retry_after_max_seconds", 300) viper.SetDefault("gateway.inject_beta_for_apikey", false) viper.SetDefault("gateway.failover_on_400", false) viper.SetDefault("gateway.max_account_switches", 10) diff --git a/backend/internal/handler/gateway_handler_chat_completions.go b/backend/internal/handler/gateway_handler_chat_completions.go index ef54220177..0f5ba738c4 100644 --- a/backend/internal/handler/gateway_handler_chat_completions.go +++ b/backend/internal/handler/gateway_handler_chat_completions.go @@ -427,7 +427,7 @@ func (h *GatewayHandler) handleCCFailoverExhausted(c *gin.Context, lastErr *serv return } if lastErr != nil { - copyFailoverRetryAfter(c, lastErr.ResponseHeaders) + applyRateLimitRetryAfter(c, lastErr, h.cfg) } if lastErr != nil && lastErr.IsCredentialFailure() { status, message := credentialFailoverClientResponse(lastErr) diff --git a/backend/internal/handler/gateway_handler_responses.go b/backend/internal/handler/gateway_handler_responses.go index 103a8fa2b7..c1cf1170b9 100644 --- a/backend/internal/handler/gateway_handler_responses.go +++ b/backend/internal/handler/gateway_handler_responses.go @@ -412,7 +412,7 @@ func (h *GatewayHandler) responsesErrorResponse(c *gin.Context, status int, code // handleResponsesFailoverExhausted writes a failover-exhausted error in Responses format. func (h *GatewayHandler) handleResponsesFailoverExhausted(c *gin.Context, lastErr *service.UpstreamFailoverError, streamStarted bool) { if lastErr != nil { - copyFailoverRetryAfter(c, lastErr.ResponseHeaders) + applyRateLimitRetryAfter(c, lastErr, h.cfg) } statusCode := http.StatusBadGateway if lastErr != nil && lastErr.StatusCode > 0 { diff --git a/backend/internal/handler/no_account_error.go b/backend/internal/handler/no_account_error.go index 4614d13e5e..c9f2e87f11 100644 --- a/backend/internal/handler/no_account_error.go +++ b/backend/internal/handler/no_account_error.go @@ -32,6 +32,10 @@ type noAccountErrorClassification struct { ErrType string Message string ModelNotFound bool // true when this is a 404 model_not_found classification + // RetryAfterSeconds carries the earliest recovery time the gateway could + // determine for a temporary availability failure. Zero means unknown; no + // Retry-After header is emitted in that case. + RetryAfterSeconds int } var selectionModelRateLimitedPattern = regexp.MustCompile(`(?:model_rate_limited|rate_limited)=(\d+)`) @@ -68,9 +72,10 @@ func classifySelectionFailureError(err error, fallback noAccountErrorClassificat return fallback } return noAccountErrorClassification{ - Status: http.StatusTooManyRequests, - ErrType: "rate_limit_error", - Message: "All available accounts are currently rate-limited. Please retry later.", + Status: http.StatusTooManyRequests, + ErrType: "rate_limit_error", + Message: "All available accounts are currently rate-limited. Please retry later.", + RetryAfterSeconds: fallback.RetryAfterSeconds, } } @@ -134,6 +139,7 @@ func classifyNoAccountError( ModelNotFound: true, } } + fallback.RetryAfterSeconds = result.RetryAfterSeconds return fallback } @@ -153,12 +159,26 @@ func classifyNoAccountErrorFromGin( ctx = c.Request.Context() } classification := classifyNoAccountError(ctx, diag, apiKey, routingModel, displayModel, platform) + classification.applyRetryAfter(c) if classification.ModelNotFound { service.MarkOpsClientBusinessLimited(c, service.OpsClientBusinessLimitedReasonLocalModelConfiguration) } return classification } +// applyRetryAfter publishes the scheduler-derived recovery hint for temporary +// availability failures. It never adds the header to a 404 model_not_found or +// when the recovery time is unknown. +func (classification noAccountErrorClassification) applyRetryAfter(c *gin.Context) { + if c == nil || classification.RetryAfterSeconds <= 0 { + return + } + switch classification.Status { + case http.StatusTooManyRequests, http.StatusServiceUnavailable, 529: + c.Header("Retry-After", strconv.Itoa(classification.RetryAfterSeconds)) + } +} + func classifyOpenAICompatibleNoAccountErrorFromGin( c *gin.Context, diag service.ModelAvailabilityDiagnoser, diff --git a/backend/internal/handler/no_account_error_test.go b/backend/internal/handler/no_account_error_test.go index e46b98bb21..6fa32ebb97 100644 --- a/backend/internal/handler/no_account_error_test.go +++ b/backend/internal/handler/no_account_error_test.go @@ -322,3 +322,61 @@ func TestGPT55RetirementEmptyListingDoesNotUseDefaults(t *testing.T) { require.Empty(t, modelListingSource(service.PlatformOpenAI, []string{}, []string{"gpt-5.5"})) require.Equal(t, []string{"gpt-5.5"}, modelListingSource(service.PlatformOpenAI, nil, []string{"gpt-5.5"})) } + +// The scheduler publishes the earliest cooldown among model-capable accounts; +// the classifier must turn it into Retry-After on both the 503 fallback and the +// 429 rate-limit verdict. +func TestClassifyNoAccountError_RateLimitedPoolCarriesRetryAfter(t *testing.T) { + c := newTestGinContextWithRequest() + fd := &fakeDiagnoser{resp: service.ModelAvailabilityDiagnosis{ + HasAccountsInPool: true, + HasModelSupport: true, + RetryAfterSeconds: 59, + }} + apiKey := &service.APIKey{GroupID: ptrInt64(7)} + + cls := classifyNoAccountErrorFromGin(c, fd, apiKey, "gpt-5.6-sol", "gpt-5.6-sol", service.PlatformOpenAI) + require.Equal(t, http.StatusServiceUnavailable, cls.Status) + require.Equal(t, 59, cls.RetryAfterSeconds) + require.Equal(t, "59", c.Writer.Header().Get("Retry-After")) + + cls = classifySelectionFailureError( + fmt.Errorf("no available OpenAI accounts supporting model: gpt-5.6-sol (pool=3, filtered: model_rate_limited=3)"), + cls, + ) + require.Equal(t, http.StatusTooManyRequests, cls.Status) + require.Equal(t, "rate_limit_error", cls.ErrType) + require.Equal(t, 59, cls.RetryAfterSeconds, "the 429 upgrade must keep the recovery hint") + require.Equal(t, "59", c.Writer.Header().Get("Retry-After")) +} + +func TestClassifyNoAccountError_UnknownRecoveryOmitsRetryAfter(t *testing.T) { + c := newTestGinContextWithRequest() + fd := &fakeDiagnoser{resp: service.ModelAvailabilityDiagnosis{HasAccountsInPool: true, HasModelSupport: true}} + apiKey := &service.APIKey{GroupID: ptrInt64(7)} + + cls := classifyNoAccountErrorFromGin(c, fd, apiKey, "gpt-5", "gpt-5", service.PlatformOpenAI) + + require.Equal(t, http.StatusServiceUnavailable, cls.Status) + require.Zero(t, cls.RetryAfterSeconds) + require.Empty(t, c.Writer.Header().Get("Retry-After"), + "an unknown recovery time must not be invented") +} + +func TestClassifyNoAccountError_ModelNotFoundOmitsRetryAfter(t *testing.T) { + c := newTestGinContextWithRequest() + fd := &fakeDiagnoser{resp: service.ModelAvailabilityDiagnosis{ + HasAccountsInPool: true, + HasModelSupport: false, + RetryAfterSeconds: 59, + }} + apiKey := &service.APIKey{GroupID: ptrInt64(7)} + + cls := classifyNoAccountErrorFromGin(c, fd, apiKey, "gpt-5.9-unknown", "gpt-5.9-unknown", service.PlatformOpenAI) + + require.Equal(t, http.StatusNotFound, cls.Status) + require.True(t, cls.ModelNotFound) + require.Zero(t, cls.RetryAfterSeconds) + require.Empty(t, c.Writer.Header().Get("Retry-After"), + "a permanent model configuration error has no recovery time") +} diff --git a/backend/internal/handler/openai_gateway_credential_failover_test.go b/backend/internal/handler/openai_gateway_credential_failover_test.go index 4fd5df01d0..a1c6bf539b 100644 --- a/backend/internal/handler/openai_gateway_credential_failover_test.go +++ b/backend/internal/handler/openai_gateway_credential_failover_test.go @@ -277,7 +277,7 @@ func TestFailoverExhaustionRejectsSecretBearingRetryAfter(t *testing.T) { require.NotContains(t, recorder.Body.String(), "must-not-leak") } -func TestFailoverExhaustionRejectsFarFutureRetryAfterDate(t *testing.T) { +func TestFailoverExhaustionCapsFarFutureRetryAfterDate(t *testing.T) { gin.SetMode(gin.TestMode) recorder := httptest.NewRecorder() c, _ := gin.CreateTestContext(recorder) @@ -291,10 +291,11 @@ func TestFailoverExhaustionRejectsFarFutureRetryAfterDate(t *testing.T) { }, false) require.Equal(t, http.StatusTooManyRequests, recorder.Code) - require.Empty(t, recorder.Header().Get("Retry-After")) + require.Equal(t, "300", recorder.Header().Get("Retry-After"), + "absurd upstream windows must be capped instead of forwarded verbatim") } -func TestFailoverExhaustionAllowsBoundedRetryAfterDate(t *testing.T) { +func TestFailoverExhaustionConvertsRetryAfterDateToSeconds(t *testing.T) { gin.SetMode(gin.TestMode) recorder := httptest.NewRecorder() c, _ := gin.CreateTestContext(recorder) @@ -307,7 +308,8 @@ func TestFailoverExhaustionAllowsBoundedRetryAfterDate(t *testing.T) { }, false) require.Equal(t, http.StatusTooManyRequests, recorder.Code) - require.Equal(t, retryAfter, recorder.Header().Get("Retry-After")) + require.Equal(t, "300", recorder.Header().Get("Retry-After"), + "dates are converted to integer seconds and capped") } func TestOpsClassificationTreatsCredentialFailureAsAuthNotInference(t *testing.T) { @@ -438,3 +440,38 @@ func TestOpsWebSocketCredentialFailoverExhaustedIsRecorded(t *testing.T) { require.Equal(t, http.StatusServiceUnavailable, job.entry.StatusCode) require.Equal(t, service.GrokCredentialUnavailableClientMessage, job.entry.ErrorMessage) } + +func TestFailoverExhaustionUsesBodyRetryAfterMs(t *testing.T) { + gin.SetMode(gin.TestMode) + recorder := httptest.NewRecorder() + c, _ := gin.CreateTestContext(recorder) + h := &OpenAIGatewayHandler{} + + h.handleFailoverExhausted(c, &service.UpstreamFailoverError{ + StatusCode: http.StatusTooManyRequests, + ResponseBody: []byte(`{"error":{"headers":{"retry-after-ms":"1500"}}}`), + }, false) + + require.Equal(t, http.StatusTooManyRequests, recorder.Code) + require.Equal(t, "2", recorder.Header().Get("Retry-After"), + "body-provided millisecond hints are converted to whole seconds") +} + +func TestFailoverExhaustionCapacityShedOmitsRetryAfter(t *testing.T) { + gin.SetMode(gin.TestMode) + recorder := httptest.NewRecorder() + c, _ := gin.CreateTestContext(recorder) + h := &OpenAIGatewayHandler{} + + h.handleFailoverExhausted(c, &service.UpstreamFailoverError{ + StatusCode: http.StatusTooManyRequests, + RequestScopedTransient: true, + ResponseHeaders: http.Header{"Retry-After": []string{"480"}}, + ResponseBody: []byte(`{"error":{"type":"server_error","code":"server_is_overloaded",` + + `"message":"Our servers are currently overloaded. Please try again later."}}`), + }, false) + + require.NotEmpty(t, recorder.Body.String()) + require.Empty(t, recorder.Header().Get("Retry-After"), + "capacity-shed windows must not be forwarded; clients would sleep through a transient blip") +} diff --git a/backend/internal/handler/openai_gateway_handler.go b/backend/internal/handler/openai_gateway_handler.go index 0e8c94b9f4..3d0c27285b 100644 --- a/backend/internal/handler/openai_gateway_handler.go +++ b/backend/internal/handler/openai_gateway_handler.go @@ -1656,7 +1656,7 @@ func (h *OpenAIGatewayHandler) anthropicStreamingAwareError(c *gin.Context, stat // handleAnthropicFailoverExhausted maps upstream failover errors to Anthropic format. func (h *OpenAIGatewayHandler) handleAnthropicFailoverExhausted(c *gin.Context, failoverErr *service.UpstreamFailoverError, streamStarted bool) { if failoverErr != nil { - copyFailoverRetryAfter(c, failoverErr.ResponseHeaders) + applyRateLimitRetryAfter(c, failoverErr, h.cfg) } if failoverErr != nil && failoverErr.IsCredentialFailure() { status, message := credentialFailoverClientResponse(failoverErr) @@ -3646,7 +3646,7 @@ func (h *OpenAIGatewayHandler) handleFailoverExhausted(c *gin.Context, failoverE h.handleStreamingAwareError(c, failoverErr.ClientStatusCode, "invalid_request_error", failoverErr.ClientMessage, streamStarted) return } - copyFailoverRetryAfter(c, failoverErr.ResponseHeaders) + applyRateLimitRetryAfter(c, failoverErr, h.cfg) if failoverErr.IsOpenAIRequestBodyTooLarge() { // An operator-configured passthrough rule wins over the built-in body // limit mapping below. Failover on 413 exists because different @@ -3784,34 +3784,15 @@ func credentialFailoverClientResponse(failoverErr *service.UpstreamFailoverError return http.StatusServiceUnavailable, service.GrokCredentialUnavailableClientMessage } -func copyFailoverRetryAfter(c *gin.Context, headers http.Header) { - if c == nil || headers == nil { +// applyRateLimitRetryAfter forwards an upstream rate-limit cooldown hint to the +// downstream error response. Only explicit upstream 429s qualify: capacity-shed +// and generic 5xx responses advertise long windows that clients would honor by +// sleeping through a transient blip (#8560, #8938). +func applyRateLimitRetryAfter(c *gin.Context, failoverErr *service.UpstreamFailoverError, cfg *config.Config) { + if c == nil || failoverErr == nil || failoverErr.IsOpenAICapacityShed() { return } - retryAfter := strings.TrimSpace(headers.Get("Retry-After")) - if retryAfter == "" || len(retryAfter) > 128 || strings.ContainsAny(retryAfter, "\r\n") || !isSafeRetryAfter(retryAfter) { - return - } - c.Header("Retry-After", retryAfter) -} - -func isSafeRetryAfter(value string) bool { - digitsOnly := true - for _, char := range value { - if char < '0' || char > '9' { - digitsOnly = false - break - } - } - if digitsOnly { - seconds, err := strconv.ParseUint(value, 10, 32) - return err == nil && seconds <= uint64((7*24*time.Hour)/time.Second) - } - retryAt, err := http.ParseTime(value) - if err != nil { - return false - } - return !retryAt.After(time.Now().Add(7 * 24 * time.Hour)) + service.SetUpstreamRateLimitRetryAfter(c, failoverErr.StatusCode, failoverErr.ResponseHeaders, failoverErr.ResponseBody, cfg) } // handleFailoverExhaustedSimple 简化版本,用于没有响应体的情况 diff --git a/backend/internal/handler/openai_images_balance_test.go b/backend/internal/handler/openai_images_balance_test.go index dc6014f469..e085f68bc0 100644 --- a/backend/internal/handler/openai_images_balance_test.go +++ b/backend/internal/handler/openai_images_balance_test.go @@ -26,7 +26,10 @@ func TestOpenAIImagesBalanceExhaustionPreservesMachineReadableCause(t *testing.T ClientMessage: service.OpenAIImagesInsufficientBalanceMessage, ResponseHeaders: http.Header{"Retry-After": []string{"23"}, "X-Request-Id": []string{"req-images-balance"}}, }, streamStarted) - require.Equal(t, "23", recorder.Header().Get("Retry-After")) + // A Retry-After on a non-rate-limit upstream failure (502 mapped to 402 + // here) is intentionally not forwarded: only explicit upstream 429 rate + // limits carry a usable cooldown (#8560, #8938). + require.Empty(t, recorder.Header().Get("Retry-After")) if streamStarted { require.Contains(t, recorder.Body.String(), `"code":"insufficient_balance"`) diff --git a/backend/internal/service/gateway_model_availability.go b/backend/internal/service/gateway_model_availability.go index 1edc1d809a..fbe727c886 100644 --- a/backend/internal/service/gateway_model_availability.go +++ b/backend/internal/service/gateway_model_availability.go @@ -3,6 +3,7 @@ package service import ( "context" "strings" + "time" "github.com/Wei-Shaw/sub2api/internal/config" ) @@ -24,6 +25,11 @@ type ModelAvailabilityDiagnosis struct { // HasRetiredSubscriptionModel records a ChatGPT upstream blocked by model // retirement, so an unsupported request can include migration guidance. HasRetiredSubscriptionModel bool + // RetryAfterSeconds is the shortest known cooldown among model-capable + // accounts, rounded up and capped by gateway.retry_after_max_seconds. Zero + // means no recovery time could be determined, in which case handlers must + // omit the Retry-After header rather than guess. + RetryAfterSeconds int } // ModelAvailabilityDiagnoser is implemented by gateway services that can @@ -43,7 +49,9 @@ type ModelAvailabilityDiagnoser interface { // by persistent configuration and returns whether the requested model is // configured to be served by any of them. The dedicated repository query // bypasses scheduler snapshots and deliberately ignores transient rate-limit, -// overload, temporary-unschedulable, expiry, quota, and runtime-block state. +// overload, temporary-unschedulable, expiry, quota, and runtime-block state when +// deciding persistent eligibility; those transient cooldowns are instead +// reported as the earliest recovery time callers can turn into Retry-After. // // Safe to call on the error path: returns {true,true} on any internal failure // or when the inputs preclude meaningful diagnosis (empty model, etc.), so @@ -100,6 +108,7 @@ func (s *GatewayService) DiagnoseModelAvailabilityForPlatform( } diag := ModelAvailabilityDiagnosis{} + var earliestRecovery time.Duration for i := range accounts { if useMixed && accounts[i].Platform == PlatformAntigravity && !accounts[i].IsMixedSchedulingEnabled() { continue @@ -107,8 +116,39 @@ func (s *GatewayService) DiagnoseModelAvailabilityForPlatform( diag.HasAccountsInPool = true if s.isModelSupportedByAccountWithContext(ctx, &accounts[i], requestedModel) { diag.HasModelSupport = true - return diag + if remaining := accountCooldownRemaining(ctx, &accounts[i], requestedModel); remaining > 0 { + if earliestRecovery == 0 || remaining < earliestRecovery { + earliestRecovery = remaining + } + } } } + diag.RetryAfterSeconds = ceilRetryAfterSeconds(earliestRecovery, DownstreamRetryAfterMaxSeconds(s.cfg)) return diag } + +// accountCooldownRemaining reports how long an account stays unschedulable +// because of persisted cooldown state: account-level rate limit, overload, or +// temporary unschedulability windows plus per-model rate limits. Returns 0 when +// the account is not cooling down. When several windows overlap, the latest +// end wins because the account becomes schedulable only after all of them. +func accountCooldownRemaining(ctx context.Context, account *Account, requestedModel string) time.Duration { + if account == nil { + return 0 + } + remaining := account.GetModelRateLimitRemainingTimeWithContext(ctx, requestedModel) + now := time.Now() + for _, until := range []*time.Time{ + account.RateLimitResetAt, + account.OverloadUntil, + account.TempUnschedulableUntil, + } { + if until == nil { + continue + } + if wait := until.Sub(now); wait > remaining { + remaining = wait + } + } + return remaining +} diff --git a/backend/internal/service/openai_gateway_model_availability.go b/backend/internal/service/openai_gateway_model_availability.go index 21693a4d23..b253ef1764 100644 --- a/backend/internal/service/openai_gateway_model_availability.go +++ b/backend/internal/service/openai_gateway_model_availability.go @@ -3,6 +3,7 @@ package service import ( "context" "strings" + "time" "github.com/Wei-Shaw/sub2api/internal/config" ) @@ -54,6 +55,7 @@ func (s *OpenAIGatewayService) DiagnoseModelAvailabilityForPlatform( } diag := ModelAvailabilityDiagnosis{} + var earliestRecovery time.Duration for i := range accounts { diag.HasAccountsInPool = true if isRetiredOpenAISubscriptionModel(&accounts[i], resolveOpenAIAccountUpstreamModelForRequest(&accounts[i], requestedModel, false)) { @@ -65,8 +67,13 @@ func (s *OpenAIGatewayService) DiagnoseModelAvailabilityForPlatform( // mapping must match. if accounts[i].IsModelSupported(requestedModel) { diag.HasModelSupport = true - return diag + if remaining := accountCooldownRemaining(ctx, &accounts[i], requestedModel); remaining > 0 { + if earliestRecovery == 0 || remaining < earliestRecovery { + earliestRecovery = remaining + } + } } } + diag.RetryAfterSeconds = ceilRetryAfterSeconds(earliestRecovery, DownstreamRetryAfterMaxSeconds(s.cfg)) return diag } diff --git a/backend/internal/service/openai_gateway_upstream_errors.go b/backend/internal/service/openai_gateway_upstream_errors.go index ae620ec283..503fabe728 100644 --- a/backend/internal/service/openai_gateway_upstream_errors.go +++ b/backend/internal/service/openai_gateway_upstream_errors.go @@ -757,6 +757,7 @@ func (s *OpenAIGatewayService) handleErrorResponse( return nil, &UpstreamFailoverError{ StatusCode: resp.StatusCode, ResponseBody: body, + ResponseHeaders: resp.Header.Clone(), RetryableOnSameAccount: false, } } @@ -811,6 +812,10 @@ func (s *OpenAIGatewayService) handleErrorResponse( errMsg = upstreamMsg } + // Explicit upstream rate limits are the only status where the provider's + // own cooldown hint is safe to forward (see UpstreamRateLimitRetryAfterSeconds). + SetUpstreamRateLimitRetryAfter(c, resp.StatusCode, resp.Header, body, s.cfg) + c.JSON(statusCode, gin.H{ "error": gin.H{ "type": errType, @@ -956,6 +961,7 @@ func (s *OpenAIGatewayService) handleCompatErrorResponse( return nil, &UpstreamFailoverError{ StatusCode: resp.StatusCode, ResponseBody: body, + ResponseHeaders: resp.Header.Clone(), RetryableOnSameAccount: false, } } @@ -975,6 +981,7 @@ func (s *OpenAIGatewayService) handleCompatErrorResponse( errType = "api_error" } + SetUpstreamRateLimitRetryAfter(c, resp.StatusCode, resp.Header, body, s.cfg) writeError(c, resp.StatusCode, errType, upstreamMsg) return nil, fmt.Errorf("upstream error: %d %s", resp.StatusCode, upstreamMsg) } diff --git a/backend/internal/service/retry_after.go b/backend/internal/service/retry_after.go new file mode 100644 index 0000000000..0f98280cbf --- /dev/null +++ b/backend/internal/service/retry_after.go @@ -0,0 +1,137 @@ +package service + +import ( + "math" + "net/http" + "strconv" + "strings" + "time" + + "github.com/Wei-Shaw/sub2api/internal/config" + "github.com/gin-gonic/gin" + "github.com/tidwall/gjson" +) + +// defaultRetryAfterMaxSeconds is the safe default for the downstream +// Retry-After header. Upstream cooldown windows can be hours long; a client +// that sleeps that long after a transient failure is effectively down. +const defaultRetryAfterMaxSeconds = 300 + +// DownstreamRetryAfterMaxSeconds resolves the configured Retry-After cap, +// falling back to the built-in default when the config is missing or invalid. +func DownstreamRetryAfterMaxSeconds(cfg *config.Config) int { + if cfg != nil && cfg.Gateway.RetryAfterMaxSeconds > 0 { + return cfg.Gateway.RetryAfterMaxSeconds + } + return defaultRetryAfterMaxSeconds +} + +// UpstreamRateLimitRetryAfterSeconds derives an integer Retry-After value from +// an explicit upstream rate-limit response (HTTP 429). The value is rounded up +// to whole seconds and capped at maxSeconds. +// +// The policy is deliberately narrow: only a 429 that is not capacity shedding +// qualifies. Providers advertise multi-minute retry windows for +// server_is_overloaded / capacity-shed responses, and clients that honor them +// sleep through what is usually a short blip (#8560, #8938). Generic 5xx +// responses are ignored for the same reason. +func UpstreamRateLimitRetryAfterSeconds(statusCode int, headers http.Header, body []byte, maxSeconds int) (int, bool) { + if statusCode != http.StatusTooManyRequests { + return 0, false + } + if isOpenAIRequestScopedCapacityShed(ExtractUpstreamErrorMessage(body), body) { + return 0, false + } + delay, ok := parseUpstreamRetryAfterDelay(headers, body) + if !ok || delay <= 0 { + return 0, false + } + if maxSeconds <= 0 { + maxSeconds = defaultRetryAfterMaxSeconds + } + seconds := int(math.Ceil(delay.Seconds())) + if seconds < 1 { + seconds = 1 + } + if seconds > maxSeconds { + seconds = maxSeconds + } + return seconds, true +} + +// SetUpstreamRateLimitRetryAfter mirrors an upstream rate-limit hint onto the +// downstream response headers. It is a no-op for non-rate-limit statuses and +// for capacity-shed responses. +func SetUpstreamRateLimitRetryAfter(c *gin.Context, statusCode int, headers http.Header, body []byte, cfg *config.Config) { + if c == nil { + return + } + if seconds, ok := UpstreamRateLimitRetryAfterSeconds(statusCode, headers, body, DownstreamRetryAfterMaxSeconds(cfg)); ok { + c.Header("Retry-After", strconv.Itoa(seconds)) + } +} + +// parseUpstreamRetryAfterDelay reads the first usable retry hint from the +// response headers, then from the response body (some OpenAI-compatible +// upstreams only expose it there). Both second and millisecond variants are +// supported. +func parseUpstreamRetryAfterDelay(headers http.Header, body []byte) (time.Duration, bool) { + type retryAfterValue struct { + raw string + milliseconds bool + } + values := make([]retryAfterValue, 0, 6) + if headers != nil { + values = append(values, + retryAfterValue{raw: headers.Get("Retry-After")}, + retryAfterValue{raw: headers.Get("Retry-After-Ms"), milliseconds: true}, + ) + } + values = append(values, + retryAfterValue{raw: gjson.GetBytes(body, "error.headers.retry-after").String()}, + retryAfterValue{raw: gjson.GetBytes(body, "response.error.headers.retry-after").String()}, + retryAfterValue{raw: gjson.GetBytes(body, "error.headers.retry-after-ms").String(), milliseconds: true}, + retryAfterValue{raw: gjson.GetBytes(body, "response.error.headers.retry-after-ms").String(), milliseconds: true}, + ) + for _, value := range values { + raw := strings.TrimSpace(value.raw) + if raw == "" { + continue + } + if value.milliseconds { + if millis, err := strconv.ParseFloat(raw, 64); err == nil && millis > 0 { + return time.Duration(millis * float64(time.Millisecond)), true + } + continue + } + if seconds, err := strconv.ParseFloat(raw, 64); err == nil && seconds > 0 { + return time.Duration(seconds * float64(time.Second)), true + } + if resetAt, err := http.ParseTime(raw); err == nil { + if delay := time.Until(resetAt); delay > 0 { + return delay, true + } + } + } + return 0, false +} + +// ceilRetryAfterSeconds converts a recovery duration into whole seconds, +// applying the downstream cap. It returns 0 when the duration is unknown or +// already elapsed, so callers can omit the header instead of guessing. +func ceilRetryAfterSeconds(delay time.Duration, maxSeconds int) int { + if delay <= 0 { + return 0 + } + if maxSeconds <= 0 { + maxSeconds = defaultRetryAfterMaxSeconds + } + seconds := int(math.Ceil(delay.Seconds())) + if seconds < 1 { + seconds = 1 + } + if seconds > maxSeconds { + seconds = maxSeconds + } + return seconds +} diff --git a/backend/internal/service/retry_after_test.go b/backend/internal/service/retry_after_test.go new file mode 100644 index 0000000000..685129688b --- /dev/null +++ b/backend/internal/service/retry_after_test.go @@ -0,0 +1,178 @@ +package service + +import ( + "context" + "net/http" + "testing" + "time" + + "github.com/Wei-Shaw/sub2api/internal/config" + "github.com/stretchr/testify/require" +) + +func TestUpstreamRateLimitRetryAfterSeconds_Header(t *testing.T) { + seconds, ok := UpstreamRateLimitRetryAfterSeconds( + http.StatusTooManyRequests, + http.Header{"Retry-After": []string{"17"}}, + nil, + 300, + ) + require.True(t, ok) + require.Equal(t, 17, seconds) +} + +func TestUpstreamRateLimitRetryAfterSeconds_HeaderMillisecondsRoundsUp(t *testing.T) { + seconds, ok := UpstreamRateLimitRetryAfterSeconds( + http.StatusTooManyRequests, + http.Header{"Retry-After-Ms": []string{"1500"}}, + nil, + 300, + ) + require.True(t, ok) + require.Equal(t, 2, seconds, "sub-second hints must round up, never to zero") +} + +func TestUpstreamRateLimitRetryAfterSeconds_BodyMilliseconds(t *testing.T) { + body := []byte(`{"error":{"headers":{"retry-after-ms":"1500"}}}`) + + seconds, ok := UpstreamRateLimitRetryAfterSeconds(http.StatusTooManyRequests, nil, body, 300) + require.True(t, ok) + require.Equal(t, 2, seconds) +} + +func TestUpstreamRateLimitRetryAfterSeconds_BodySeconds(t *testing.T) { + body := []byte(`{"response":{"error":{"headers":{"retry-after":"12"}}}}`) + + seconds, ok := UpstreamRateLimitRetryAfterSeconds(http.StatusTooManyRequests, nil, body, 300) + require.True(t, ok) + require.Equal(t, 12, seconds) +} + +func TestUpstreamRateLimitRetryAfterSeconds_CapsAtConfiguredMaximum(t *testing.T) { + seconds, ok := UpstreamRateLimitRetryAfterSeconds( + http.StatusTooManyRequests, + http.Header{"Retry-After": []string{"600"}}, + nil, + 300, + ) + require.True(t, ok) + require.Equal(t, 300, seconds) +} + +func TestUpstreamRateLimitRetryAfterSeconds_DefaultCapWhenUnset(t *testing.T) { + seconds, ok := UpstreamRateLimitRetryAfterSeconds( + http.StatusTooManyRequests, + http.Header{"Retry-After": []string{"3600"}}, + nil, + 0, + ) + require.True(t, ok) + require.Equal(t, defaultRetryAfterMaxSeconds, seconds) +} + +func TestUpstreamRateLimitRetryAfterSeconds_RejectsCapacityShed(t *testing.T) { + body := []byte(`{"error":{"type":"server_error","code":"server_is_overloaded","message":"Our servers are currently overloaded. Please try again later.","headers":{"retry-after":"480"}}}`) + + seconds, ok := UpstreamRateLimitRetryAfterSeconds(http.StatusTooManyRequests, nil, body, 300) + require.False(t, ok, "capacity-shed windows are intentionally not forwarded (#8560, #8938)") + require.Zero(t, seconds) +} + +func TestUpstreamRateLimitRetryAfterSeconds_IgnoresNonRateLimitStatuses(t *testing.T) { + for _, status := range []int{ + http.StatusOK, + http.StatusBadRequest, + http.StatusServiceUnavailable, + http.StatusBadGateway, + http.StatusGatewayTimeout, + 529, + } { + seconds, ok := UpstreamRateLimitRetryAfterSeconds( + status, + http.Header{"Retry-After": []string{"30"}}, + nil, + 300, + ) + require.False(t, ok, "status %d must not forward Retry-After", status) + require.Zero(t, seconds) + } +} + +func TestUpstreamRateLimitRetryAfterSeconds_NoHint(t *testing.T) { + seconds, ok := UpstreamRateLimitRetryAfterSeconds( + http.StatusTooManyRequests, + http.Header{}, + []byte(`{"error":{"message":"rate limit exceeded"}}`), + 300, + ) + require.False(t, ok, "unknown recovery time must not be invented") + require.Zero(t, seconds) +} + +func TestUpstreamRateLimitRetryAfterSeconds_HTTPDate(t *testing.T) { + header := http.Header{"Retry-After": []string{time.Now().Add(30 * time.Second).UTC().Format(http.TimeFormat)}} + + seconds, ok := UpstreamRateLimitRetryAfterSeconds(http.StatusTooManyRequests, header, nil, 300) + require.True(t, ok) + require.GreaterOrEqual(t, seconds, 27) + require.LessOrEqual(t, seconds, 30) +} + +func TestCeilRetryAfterSeconds(t *testing.T) { + require.Zero(t, ceilRetryAfterSeconds(0, 300)) + require.Zero(t, ceilRetryAfterSeconds(-time.Second, 300)) + require.Equal(t, 1, ceilRetryAfterSeconds(200*time.Millisecond, 300)) + require.Equal(t, 2, ceilRetryAfterSeconds(1500*time.Millisecond, 300)) + require.Equal(t, 300, ceilRetryAfterSeconds(10*time.Minute, 300)) +} + +func TestAccountCooldownRemaining_OverlappingWindowsUseLatestEnd(t *testing.T) { + now := time.Now() + rateLimitResetAt := now.Add(30 * time.Second) + tempUnschedulableUntil := now.Add(90 * time.Second) + account := &Account{ + RateLimitResetAt: &rateLimitResetAt, + TempUnschedulableUntil: &tempUnschedulableUntil, + } + + remaining := accountCooldownRemaining(context.Background(), account, "gpt-5") + require.GreaterOrEqual(t, remaining, 89*time.Second) + require.LessOrEqual(t, remaining, 90*time.Second) +} + +func TestAccountCooldownRemaining_ModelRateLimit(t *testing.T) { + resetAt := time.Now().Add(2 * time.Minute).UTC().Format(time.RFC3339) + account := &Account{ + Extra: map[string]any{ + modelRateLimitsKey: map[string]any{ + "gpt-5": map[string]any{"rate_limit_reset_at": resetAt}, + }, + }, + } + + remaining := accountCooldownRemaining(context.Background(), account, "gpt-5") + require.GreaterOrEqual(t, remaining, 119*time.Second) + require.LessOrEqual(t, remaining, 120*time.Second) +} + +func TestAccountCooldownRemaining_NoCooldown(t *testing.T) { + require.Zero(t, accountCooldownRemaining(context.Background(), nil, "gpt-5")) + require.Zero(t, accountCooldownRemaining(context.Background(), &Account{}, "gpt-5")) +} + +func TestDownstreamRetryAfterMaxSeconds(t *testing.T) { + require.Equal(t, 300, DownstreamRetryAfterMaxSeconds(nil)) + require.Equal(t, 300, DownstreamRetryAfterMaxSeconds(&config.Config{})) + + cfg := &config.Config{Gateway: config.GatewayConfig{RetryAfterMaxSeconds: 60}} + require.Equal(t, 60, DownstreamRetryAfterMaxSeconds(cfg)) + + seconds, ok := UpstreamRateLimitRetryAfterSeconds( + http.StatusTooManyRequests, + http.Header{"Retry-After": []string{"600"}}, + nil, + DownstreamRetryAfterMaxSeconds(cfg), + ) + require.True(t, ok) + require.Equal(t, 60, seconds) +} diff --git a/deploy/config.example.yaml b/deploy/config.example.yaml index 66cac12786..d9129a9d7f 100644 --- a/deploy/config.example.yaml +++ b/deploy/config.example.yaml @@ -577,6 +577,9 @@ gateway: # Max bytes to log from upstream error body # 记录上游错误响应体的最大字节数 log_upstream_error_body_max_bytes: 2048 + # Cap for the downstream Retry-After header in seconds (default: 300) + # 下发 Retry-After 的最大秒数,避免客户端按超长上游恢复时间长时间挂起(默认:300) + retry_after_max_seconds: 300 # Auto inject anthropic-beta header for API-key accounts when needed (default: off) # 需要时自动为 API-key 账户注入 anthropic-beta 头(默认:关闭) inject_beta_for_apikey: false From 56e27df2d7c7f48406da3f62e8ab9d4ccfbb72fd Mon Sep 17 00:00:00 2001 From: magisk-k <363574826+magisk-k@users.noreply.github.com> Date: Tue, 1 Dec 2026 15:35:35 +0000 Subject: [PATCH 04/11] fix(openai): keep Codex catalog ETag in sync with codex.response.metadata Codex caches the /models catalog together with its ETag and, on every Responses WebSocket turn, compares that ETag with the x-models-etag header of the codex.response.metadata event. Upstream reports the ETag of its own catalog, but the gateway serves a group-specific manifest whose ETag changes as soon as group policy adjusts it, so Codex re-downloaded the full catalog on every turn. Record, per group, which served ETag corresponds to each upstream catalog ETag, and translate the metadata header when relaying WebSocket events in both ctx_pool and passthrough modes. Unknown values are removed so clients fall back to their regular catalog cache TTL. Pinned manifests keep the upstream ETags of every merged account, and generated manifests now use weak ETags so the value still matches behind a compressing reverse proxy. --- .../internal/handler/gateway_models_test.go | 4 +- .../handler/openai_codex_models_handler.go | 16 +- .../service/openai_codex_models_etag.go | 223 ++++++++++++++++++ .../service/openai_codex_models_etag_test.go | 160 +++++++++++++ .../openai_codex_models_etag_ws_test.go | 179 ++++++++++++++ .../service/openai_codex_models_pinned.go | 12 +- .../service/openai_codex_models_service.go | 22 +- .../openai_codex_models_service_test.go | 5 +- .../service/openai_ws_forwarder_ingress.go | 1 + .../openai_ws_v2_passthrough_adapter.go | 9 + 10 files changed, 619 insertions(+), 12 deletions(-) create mode 100644 backend/internal/service/openai_codex_models_etag.go create mode 100644 backend/internal/service/openai_codex_models_etag_test.go create mode 100644 backend/internal/service/openai_codex_models_etag_ws_test.go diff --git a/backend/internal/handler/gateway_models_test.go b/backend/internal/handler/gateway_models_test.go index 0d5b9b2fc7..043edc00cb 100644 --- a/backend/internal/handler/gateway_models_test.go +++ b/backend/internal/handler/gateway_models_test.go @@ -527,7 +527,9 @@ func TestGatewayCodexModels_GeneratedManifestUsesFinalBodyETag(t *testing.T) { second := httptest.NewRecorder() secondContext, _ := gin.CreateTestContext(second) secondContext.Request = httptest.NewRequest(http.MethodGet, "/models?client_version=0.147.0", nil) - secondContext.Request.Header.Set("If-None-Match", "W/"+etag) + // The generated ETag is weak; its strong form must still revalidate. + require.True(t, strings.HasPrefix(etag, "W/")) + secondContext.Request.Header.Set("If-None-Match", strings.TrimPrefix(etag, "W/")) secondContext.Set(string(middleware2.ContextKeyAPIKey), &service.APIKey{Group: group}) h.CodexModels(secondContext) diff --git a/backend/internal/handler/openai_codex_models_handler.go b/backend/internal/handler/openai_codex_models_handler.go index 777eeebdb1..6c17bee83b 100644 --- a/backend/internal/handler/openai_codex_models_handler.go +++ b/backend/internal/handler/openai_codex_models_handler.go @@ -67,7 +67,7 @@ func (h *OpenAIGatewayHandler) CodexModels(c *gin.Context) { if c.Request.Context().Err() != nil { return } - writeOpenAIModelsResponse(c, pinnedManifest) + h.writeCodexModelsResponse(c, apiKey.Group, pinnedManifest) return } } @@ -86,7 +86,7 @@ func (h *OpenAIGatewayHandler) CodexModels(c *gin.Context) { return } if configured { - writeOpenAIModelsResponse(c, configuredManifest) + h.writeCodexModelsResponse(c, apiKey.Group, configuredManifest) return } } @@ -147,7 +147,17 @@ func (h *OpenAIGatewayHandler) CodexModels(c *gin.Context) { return } - writeOpenAIModelsResponse(c, manifest) + h.writeCodexModelsResponse(c, apiKey.Group, manifest) return } } + +// writeCodexModelsResponse records the ETag the group's manifest is served with, +// so codex.response.metadata events can be translated to it, and writes the +// manifest response. +func (h *OpenAIGatewayHandler) writeCodexModelsResponse(c *gin.Context, group *service.Group, manifest *service.OpenAIModelsResponse) { + if group != nil && h.gatewayService != nil { + h.gatewayService.RecordCodexModelsManifestETag(group.ID, manifest) + } + writeOpenAIModelsResponse(c, manifest) +} diff --git a/backend/internal/service/openai_codex_models_etag.go b/backend/internal/service/openai_codex_models_etag.go new file mode 100644 index 0000000000..550bdc2fb5 --- /dev/null +++ b/backend/internal/service/openai_codex_models_etag.go @@ -0,0 +1,223 @@ +package service + +import ( + "bytes" + "strings" + "sync" + "time" + + "github.com/tidwall/gjson" + "github.com/tidwall/sjson" +) + +// Codex keeps the catalog returned by GET /models together with its ETag. On +// every Responses WebSocket turn it compares that ETag with the x-models-etag +// header carried by the codex.response.metadata event, and downloads the whole +// catalog again whenever the two differ. +// +// Upstream reports the ETag of its own catalog, while the gateway serves a +// group-specific manifest: once group policy adjusts the manifest, its ETag no +// longer matches the upstream value and every turn triggers a full catalog +// download. The registry remembers, per group, which served ETag corresponds +// to each upstream catalog ETag so the metadata event can be translated. When +// no mapping is known (for example after a restart, or on another instance) +// the header is removed instead, and Codex falls back to its regular catalog +// cache TTL. + +const ( + codexResponseMetadataEventType = "codex.response.metadata" + codexModelsETagHeader = "x-models-etag" + + codexModelsETagRegistryMaxEntries = 4096 + codexModelsETagRegistryTTL = 24 * time.Hour +) + +type codexModelsETagKey struct { + groupID int64 + upstream string +} + +type codexModelsETagEntry struct { + served string + recordedAt time.Time +} + +// codexModelsETagRegistry maps (group, upstream catalog ETag) to the ETag of the +// manifest the gateway served for that group. It is bounded and entries expire, +// so a stale mapping can only ever cause a fallback to the client's cache TTL. +type codexModelsETagRegistry struct { + mu sync.Mutex + entries map[codexModelsETagKey]codexModelsETagEntry + maxEntries int + ttl time.Duration +} + +func newCodexModelsETagRegistry(maxEntries int, ttl time.Duration) *codexModelsETagRegistry { + return &codexModelsETagRegistry{ + entries: make(map[codexModelsETagKey]codexModelsETagEntry), + maxEntries: maxEntries, + ttl: ttl, + } +} + +var codexModelsETags = newCodexModelsETagRegistry(codexModelsETagRegistryMaxEntries, codexModelsETagRegistryTTL) + +// normalizeCodexModelsETag returns the opaque part of an entity tag so weak and +// strong forms, with or without quotes, compare equal. +func normalizeCodexModelsETag(etag string) string { + etag = strings.TrimSpace(etag) + if len(etag) >= 2 && strings.EqualFold(etag[:2], "W/") { + etag = strings.TrimSpace(etag[2:]) + } + if len(etag) >= 2 && etag[0] == '"' && etag[len(etag)-1] == '"' { + etag = etag[1 : len(etag)-1] + } + return etag +} + +func (r *codexModelsETagRegistry) record(groupID int64, upstreamETags []string, served string, now time.Time) { + served = strings.TrimSpace(served) + if r == nil || groupID <= 0 || served == "" { + return + } + r.mu.Lock() + defer r.mu.Unlock() + for _, upstream := range upstreamETags { + upstream = normalizeCodexModelsETag(upstream) + if upstream == "" { + continue + } + r.entries[codexModelsETagKey{groupID: groupID, upstream: upstream}] = codexModelsETagEntry{served: served, recordedAt: now} + } + r.evictLocked(now) +} + +func (r *codexModelsETagRegistry) lookup(groupID int64, upstream string, now time.Time) (string, bool) { + upstream = normalizeCodexModelsETag(upstream) + if r == nil || groupID <= 0 || upstream == "" { + return "", false + } + r.mu.Lock() + defer r.mu.Unlock() + key := codexModelsETagKey{groupID: groupID, upstream: upstream} + entry, ok := r.entries[key] + if !ok { + return "", false + } + if r.ttl > 0 && now.Sub(entry.recordedAt) > r.ttl { + delete(r.entries, key) + return "", false + } + return entry.served, true +} + +func (r *codexModelsETagRegistry) evictLocked(now time.Time) { + if r.maxEntries <= 0 || len(r.entries) <= r.maxEntries { + return + } + if r.ttl > 0 { + for key, entry := range r.entries { + if now.Sub(entry.recordedAt) > r.ttl { + delete(r.entries, key) + } + } + } + for len(r.entries) > r.maxEntries { + var oldestKey codexModelsETagKey + var oldest time.Time + first := true + for key, entry := range r.entries { + if first || entry.recordedAt.Before(oldest) { + oldestKey, oldest, first = key, entry.recordedAt, false + } + } + delete(r.entries, oldestKey) + } +} + +// upstreamCatalogETags lists the upstream catalog ETags a manifest was built +// from. Manifests generated locally have none. +func (r *OpenAIModelsResponse) upstreamCatalogETags() []string { + if r == nil { + return nil + } + if len(r.sourceETags) > 0 { + return r.sourceETags + } + if strings.TrimSpace(r.upstreamETag) != "" { + return []string{r.upstreamETag} + } + return nil +} + +// RecordCodexModelsManifestETag remembers which ETag a group's Codex manifest +// was served with for every upstream catalog ETag it was derived from. The +// mapping lets codex.response.metadata events carry an ETag the client +// recognizes. Verbatim manifests are recorded too, so their ETag is kept. +func (s *OpenAIGatewayService) RecordCodexModelsManifestETag(groupID int64, manifest *OpenAIModelsResponse) { + if manifest == nil { + return + } + codexModelsETags.record(groupID, manifest.upstreamCatalogETags(), manifest.ETag, time.Now()) +} + +// rewriteCodexResponseMetadataModelsETag translates the x-models-etag header of +// a codex.response.metadata event into the ETag the gateway served for the +// group, or removes it when no mapping is known. Other messages are returned +// unchanged. +func rewriteCodexResponseMetadataModelsETag(groupID int64, message []byte) []byte { + return rewriteCodexResponseMetadataModelsETagWith(codexModelsETags, groupID, message, time.Now()) +} + +func rewriteCodexResponseMetadataModelsETagWith(registry *codexModelsETagRegistry, groupID int64, message []byte, now time.Time) []byte { + if len(message) == 0 || !bytes.Contains(message, []byte(codexResponseMetadataEventType)) { + return message + } + if gjson.GetBytes(message, "type").String() != codexResponseMetadataEventType { + return message + } + headers := gjson.GetBytes(message, "headers") + if !headers.IsObject() { + return message + } + var headerKey string + var upstream gjson.Result + headers.ForEach(func(key, value gjson.Result) bool { + if strings.EqualFold(strings.TrimSpace(key.String()), codexModelsETagHeader) { + headerKey, upstream = key.String(), value + return false + } + return true + }) + if headerKey == "" { + return message + } + path := "headers." + escapeCodexMetadataHeaderPath(headerKey) + upstreamValue := upstream.String() + if upstream.IsArray() { + upstreamValue = upstream.Get("0").String() + } + if served, ok := registry.lookup(groupID, upstreamValue, now); ok { + if upstream.Type == gjson.String && upstreamValue == served { + return message + } + if updated, err := sjson.SetBytes(message, path, served); err == nil { + return updated + } + return message + } + if updated, err := sjson.DeleteBytes(message, path); err == nil { + return updated + } + return message +} + +var codexMetadataHeaderPathEscaper = strings.NewReplacer( + `\`, `\\`, `.`, `\.`, `*`, `\*`, `?`, `\?`, `|`, `\|`, + `#`, `\#`, `@`, `\@`, `!`, `\!`, `:`, `\:`, +) + +// escapeCodexMetadataHeaderPath escapes gjson/sjson path syntax in a header name. +func escapeCodexMetadataHeaderPath(key string) string { + return codexMetadataHeaderPathEscaper.Replace(key) +} diff --git a/backend/internal/service/openai_codex_models_etag_test.go b/backend/internal/service/openai_codex_models_etag_test.go new file mode 100644 index 0000000000..1a918a2125 --- /dev/null +++ b/backend/internal/service/openai_codex_models_etag_test.go @@ -0,0 +1,160 @@ +package service + +import ( + "testing" + "time" + + "github.com/stretchr/testify/require" + "github.com/tidwall/gjson" +) + +func TestNormalizeCodexModelsETag(t *testing.T) { + t.Parallel() + + for input, want := range map[string]string{ + `W/"abc"`: "abc", + `w/"abc"`: "abc", + `"abc"`: "abc", + `abc`: "abc", + ` W/"abc" `: "abc", + ``: "", + } { + require.Equal(t, want, normalizeCodexModelsETag(input), input) + } +} + +func TestCodexModelsETagRegistryLookupAndExpiry(t *testing.T) { + t.Parallel() + + now := time.Unix(1_800_000_000, 0) + registry := newCodexModelsETagRegistry(16, time.Hour) + registry.record(7, []string{`W/"upstream-a"`, `"upstream-b"`}, `W/"served"`, now) + + served, ok := registry.lookup(7, `"upstream-a"`, now) + require.True(t, ok) + require.Equal(t, `W/"served"`, served) + served, ok = registry.lookup(7, `W/"upstream-b"`, now) + require.True(t, ok) + require.Equal(t, `W/"served"`, served) + + _, ok = registry.lookup(8, `"upstream-a"`, now) + require.False(t, ok, "mappings are group-scoped") + _, ok = registry.lookup(7, `"upstream-a"`, now.Add(2*time.Hour)) + require.False(t, ok, "expired mappings are not used") +} + +func TestCodexModelsETagRegistryIgnoresIncompleteRecords(t *testing.T) { + t.Parallel() + + now := time.Unix(1_800_000_000, 0) + registry := newCodexModelsETagRegistry(16, time.Hour) + registry.record(0, []string{`"upstream"`}, `"served"`, now) + registry.record(1, nil, `"served"`, now) + registry.record(1, []string{`"upstream"`}, "", now) + require.Empty(t, registry.entries) +} + +func TestCodexModelsETagRegistryEvictsOldestBeyondCapacity(t *testing.T) { + t.Parallel() + + now := time.Unix(1_800_000_000, 0) + registry := newCodexModelsETagRegistry(2, time.Hour) + registry.record(1, []string{`"a"`}, `"served-a"`, now) + registry.record(1, []string{`"b"`}, `"served-b"`, now.Add(time.Second)) + registry.record(1, []string{`"c"`}, `"served-c"`, now.Add(2*time.Second)) + + require.Len(t, registry.entries, 2) + _, ok := registry.lookup(1, `"a"`, now.Add(2*time.Second)) + require.False(t, ok) + _, ok = registry.lookup(1, `"c"`, now.Add(2*time.Second)) + require.True(t, ok) +} + +func TestRewriteCodexResponseMetadataModelsETag(t *testing.T) { + t.Parallel() + + now := time.Unix(1_800_000_000, 0) + const groupID int64 = 9 + registry := newCodexModelsETagRegistry(16, time.Hour) + registry.record(groupID, []string{`W/"upstream-catalog"`}, `W/"gateway-manifest"`, now) + registry.record(groupID, []string{`W/"verbatim"`}, `W/"verbatim"`, now) + + t.Run("translates known upstream ETag", func(t *testing.T) { + message := []byte(`{"type":"codex.response.metadata","headers":{"x-models-etag":"W/\"upstream-catalog\"","x-other":"kept"}}`) + out := rewriteCodexResponseMetadataModelsETagWith(registry, groupID, message, now) + require.Equal(t, `W/"gateway-manifest"`, gjson.GetBytes(out, "headers.x-models-etag").String()) + require.Equal(t, "kept", gjson.GetBytes(out, "headers.x-other").String()) + }) + + t.Run("keeps an ETag that already matches", func(t *testing.T) { + message := []byte(`{"type":"codex.response.metadata","headers":{"x-models-etag":"W/\"verbatim\""}}`) + out := rewriteCodexResponseMetadataModelsETagWith(registry, groupID, message, now) + require.Equal(t, message, out) + }) + + t.Run("removes an unknown ETag", func(t *testing.T) { + message := []byte(`{"type":"codex.response.metadata","headers":{"x-models-etag":"W/\"unknown\"","x-other":"kept"}}`) + out := rewriteCodexResponseMetadataModelsETagWith(registry, groupID, message, now) + require.False(t, gjson.GetBytes(out, "headers.x-models-etag").Exists()) + require.Equal(t, "kept", gjson.GetBytes(out, "headers.x-other").String()) + }) + + t.Run("removes the ETag for another group", func(t *testing.T) { + message := []byte(`{"type":"codex.response.metadata","headers":{"x-models-etag":"W/\"upstream-catalog\""}}`) + out := rewriteCodexResponseMetadataModelsETagWith(registry, groupID+1, message, now) + require.False(t, gjson.GetBytes(out, "headers.x-models-etag").Exists()) + }) + + t.Run("matches the header name case-insensitively", func(t *testing.T) { + message := []byte(`{"type":"codex.response.metadata","headers":{"X-Models-ETag":"W/\"upstream-catalog\""}}`) + out := rewriteCodexResponseMetadataModelsETagWith(registry, groupID, message, now) + require.Equal(t, `W/"gateway-manifest"`, gjson.GetBytes(out, "headers.X-Models-ETag").String()) + }) + + t.Run("handles array header values", func(t *testing.T) { + message := []byte(`{"type":"codex.response.metadata","headers":{"x-models-etag":["W/\"upstream-catalog\""]}}`) + out := rewriteCodexResponseMetadataModelsETagWith(registry, groupID, message, now) + require.Equal(t, `W/"gateway-manifest"`, gjson.GetBytes(out, "headers.x-models-etag").String()) + }) + + t.Run("leaves other messages untouched", func(t *testing.T) { + for _, message := range [][]byte{ + []byte(`{"type":"response.output_text.delta","delta":"codex.response.metadata"}`), + []byte(`{"type":"codex.response.metadata"}`), + []byte(`{"type":"codex.response.metadata","headers":"x-models-etag"}`), + []byte(`{"type":"codex.response.metadata","headers":{"x-other":"value"}}`), + []byte(`not json`), + } { + require.Equal(t, message, rewriteCodexResponseMetadataModelsETagWith(registry, groupID, message, now), string(message)) + } + }) +} + +func TestRecordCodexModelsManifestETagUsesEveryUpstreamSource(t *testing.T) { + t.Parallel() + + const groupID int64 = 77_001 + svc := &OpenAIGatewayService{} + merged := &OpenAIModelsResponse{ + Body: []byte(`{"models":[]}`), + ETag: `W/"merged"`, + sourceETags: []string{`W/"account-1"`, `W/"account-2"`}, + } + svc.RecordCodexModelsManifestETag(groupID, merged) + + now := time.Now() + for _, upstream := range []string{`W/"account-1"`, `W/"account-2"`} { + served, ok := codexModelsETags.lookup(groupID, upstream, now) + require.True(t, ok, upstream) + require.Equal(t, `W/"merged"`, served) + } + + single := &OpenAIModelsResponse{ETag: `W/"single"`, upstreamETag: `W/"single"`} + svc.RecordCodexModelsManifestETag(groupID, single) + served, ok := codexModelsETags.lookup(groupID, `W/"single"`, now) + require.True(t, ok) + require.Equal(t, `W/"single"`, served) + + local := &OpenAIModelsResponse{ETag: `W/"local-only"`} + require.Empty(t, local.upstreamCatalogETags()) +} diff --git a/backend/internal/service/openai_codex_models_etag_ws_test.go b/backend/internal/service/openai_codex_models_etag_ws_test.go new file mode 100644 index 0000000000..c1eaecaec9 --- /dev/null +++ b/backend/internal/service/openai_codex_models_etag_ws_test.go @@ -0,0 +1,179 @@ +package service + +import ( + "context" + "net/http" + "net/http/httptest" + "strings" + "testing" + "time" + + "github.com/Wei-Shaw/sub2api/internal/config" + coderws "github.com/coder/websocket" + "github.com/gin-gonic/gin" + "github.com/stretchr/testify/require" + "github.com/tidwall/gjson" +) + +// runCodexMetadataWSTurn relays one upstream turn to a WebSocket client and +// returns the events the client received up to response.completed. +func runCodexMetadataWSTurn(t *testing.T, passthrough bool, groupID int64, upstreamEvents [][]byte) [][]byte { + t.Helper() + gin.SetMode(gin.TestMode) + + cfg := &config.Config{} + cfg.Security.URLAllowlist.Enabled = false + cfg.Security.URLAllowlist.AllowInsecureHTTP = true + cfg.Gateway.OpenAIWS.Enabled = true + cfg.Gateway.OpenAIWS.OAuthEnabled = true + cfg.Gateway.OpenAIWS.APIKeyEnabled = true + cfg.Gateway.OpenAIWS.ResponsesWebsocketsV2 = true + cfg.Gateway.OpenAIWS.MaxConnsPerAccount = 1 + cfg.Gateway.OpenAIWS.MaxIdlePerAccount = 1 + cfg.Gateway.OpenAIWS.QueueLimitPerConn = 8 + cfg.Gateway.OpenAIWS.DialTimeoutSeconds = 3 + cfg.Gateway.OpenAIWS.ReadTimeoutSeconds = 3 + cfg.Gateway.OpenAIWS.WriteTimeoutSeconds = 3 + + upstreamConn := &openAIWSCaptureConn{events: upstreamEvents} + dialer := &openAIWSCaptureDialer{conn: upstreamConn} + svc := &OpenAIGatewayService{ + cfg: cfg, + httpUpstream: &httpUpstreamRecorder{}, + cache: &stubGatewayCache{}, + openaiWSResolver: NewOpenAIWSProtocolResolver(cfg), + toolCorrector: NewCodexToolCorrector(), + } + extra := map[string]any{"responses_websockets_v2_enabled": true} + if passthrough { + cfg.Gateway.OpenAIWS.ModeRouterV2Enabled = true + cfg.Gateway.OpenAIWS.IngressModeDefault = OpenAIWSIngressModeCtxPool + svc.openaiWSPassthroughDialer = dialer + extra = map[string]any{"openai_apikey_responses_websockets_v2_mode": OpenAIWSIngressModePassthrough} + } else { + pool := newOpenAIWSConnPool(cfg) + pool.setClientDialerForTest(dialer) + svc.openaiWSPool = pool + } + account := &Account{ + ID: 9_601, + Name: "codex-metadata-etag", + Platform: PlatformOpenAI, + Type: AccountTypeAPIKey, + Status: StatusActive, + Schedulable: true, + Concurrency: 1, + Credentials: map[string]any{"api_key": "sk-test"}, + Extra: extra, + } + + serverErrCh := make(chan error, 1) + wsServer := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + conn, err := coderws.Accept(w, r, &coderws.AcceptOptions{CompressionMode: coderws.CompressionContextTakeover}) + if err != nil { + serverErrCh <- err + return + } + defer func() { _ = conn.CloseNow() }() + + ginCtx, _ := gin.CreateTestContext(httptest.NewRecorder()) + ginCtx.Request = r.Clone(r.Context()) + ginCtx.Set("api_key", &APIKey{GroupID: &groupID}) + + readCtx, cancel := context.WithTimeout(r.Context(), 3*time.Second) + _, firstMessage, readErr := conn.Read(readCtx) + cancel() + if readErr != nil { + serverErrCh <- readErr + return + } + serverErrCh <- svc.ProxyResponsesWebSocketFromClient(r.Context(), ginCtx, conn, account, "sk-test", firstMessage, &OpenAIWSIngressHooks{}) + })) + defer wsServer.Close() + + dialCtx, cancelDial := context.WithTimeout(context.Background(), 3*time.Second) + clientConn, _, err := coderws.Dial(dialCtx, "ws"+strings.TrimPrefix(wsServer.URL, "http"), nil) + cancelDial() + require.NoError(t, err) + defer func() { _ = clientConn.CloseNow() }() + + writeCtx, cancelWrite := context.WithTimeout(context.Background(), 3*time.Second) + require.NoError(t, clientConn.Write(writeCtx, coderws.MessageText, []byte(`{"type":"response.create","model":"gpt-5.1","stream":false}`))) + cancelWrite() + + var received [][]byte + for { + readCtx, cancelRead := context.WithTimeout(context.Background(), 3*time.Second) + _, event, readErr := clientConn.Read(readCtx) + cancelRead() + require.NoError(t, readErr) + received = append(received, event) + if gjson.GetBytes(event, "type").String() == "response.completed" { + break + } + } + _ = clientConn.Close(coderws.StatusNormalClosure, "done") + select { + case <-serverErrCh: + case <-time.After(5 * time.Second): + t.Fatal("timed out waiting for the websocket session to end") + } + return received +} + +func codexMetadataEvent(t *testing.T, events [][]byte) []byte { + t.Helper() + for _, event := range events { + if gjson.GetBytes(event, "type").String() == codexResponseMetadataEventType { + return event + } + } + t.Fatalf("client did not receive %s", codexResponseMetadataEventType) + return nil +} + +func TestCodexResponseMetadataModelsETagIsTranslatedOverWebSocket(t *testing.T) { + for _, tc := range []struct { + name string + passthrough bool + groupID int64 + }{ + {name: "ctx_pool", passthrough: false, groupID: 96_011}, + {name: "passthrough", passthrough: true, groupID: 96_012}, + } { + t.Run(tc.name, func(t *testing.T) { + (&OpenAIGatewayService{}).RecordCodexModelsManifestETag(tc.groupID, &OpenAIModelsResponse{ + ETag: `W/"gateway-manifest"`, + upstreamETag: `W/"upstream-catalog"`, + }) + events := runCodexMetadataWSTurn(t, tc.passthrough, tc.groupID, [][]byte{ + []byte(`{"type":"codex.response.metadata","headers":{"x-models-etag":"W/\"upstream-catalog\"","x-codex-other":"kept"}}`), + []byte(`{"type":"response.completed","response":{"id":"resp_metadata_etag","model":"gpt-5.1","usage":{"input_tokens":1,"output_tokens":1}}}`), + }) + metadata := codexMetadataEvent(t, events) + require.Equal(t, `W/"gateway-manifest"`, gjson.GetBytes(metadata, "headers.x-models-etag").String()) + require.Equal(t, "kept", gjson.GetBytes(metadata, "headers.x-codex-other").String()) + }) + } +} + +func TestCodexResponseMetadataUnknownModelsETagIsRemovedOverWebSocket(t *testing.T) { + for _, tc := range []struct { + name string + passthrough bool + groupID int64 + }{ + {name: "ctx_pool", passthrough: false, groupID: 96_021}, + {name: "passthrough", passthrough: true, groupID: 96_022}, + } { + t.Run(tc.name, func(t *testing.T) { + events := runCodexMetadataWSTurn(t, tc.passthrough, tc.groupID, [][]byte{ + []byte(`{"type":"codex.response.metadata","headers":{"x-models-etag":"W/\"never-served\"","x-codex-other":"kept"}}`), + []byte(`{"type":"response.completed","response":{"id":"resp_metadata_unknown","model":"gpt-5.1","usage":{"input_tokens":1,"output_tokens":1}}}`), + }) + metadata := codexMetadataEvent(t, events) + require.False(t, gjson.GetBytes(metadata, "headers.x-models-etag").Exists()) + require.Equal(t, "kept", gjson.GetBytes(metadata, "headers.x-codex-other").String()) + }) + } +} diff --git a/backend/internal/service/openai_codex_models_pinned.go b/backend/internal/service/openai_codex_models_pinned.go index 16faefd068..1020dbe0fc 100644 --- a/backend/internal/service/openai_codex_models_pinned.go +++ b/backend/internal/service/openai_codex_models_pinned.go @@ -150,7 +150,17 @@ func (s *OpenAIGatewayService) FetchPinnedCodexModelsManifest(ctx context.Contex if len(results) == 1 && bytes.Equal(merged, results[0].response.Body) { return results[0].response, results[0].account, nil } - return &OpenAIModelsResponse{Body: merged, ETag: codexModelsManifestBodyETag(merged)}, results[0].account, nil + // Keep every pinned account's upstream catalog ETag: a turn served by any + // of them reports that account's ETag in codex.response.metadata. + var sourceETags []string + for _, result := range results { + sourceETags = append(sourceETags, result.response.upstreamCatalogETags()...) + } + return &OpenAIModelsResponse{ + Body: merged, + ETag: codexModelsManifestBodyETag(merged), + sourceETags: sourceETags, + }, results[0].account, nil } type pinnedOpenAIModelsResult struct { diff --git a/backend/internal/service/openai_codex_models_service.go b/backend/internal/service/openai_codex_models_service.go index d557500d01..c4eb37709d 100644 --- a/backend/internal/service/openai_codex_models_service.go +++ b/backend/internal/service/openai_codex_models_service.go @@ -110,9 +110,12 @@ func codexProviderQualifiedModelID(modelID string) string { // OpenAIModelsResponse carries either an OpenAI model list or a Codex manifest // together with upstream and client caching metadata. type OpenAIModelsResponse struct { - Body []byte - ETag string - upstreamETag string + Body []byte + ETag string + upstreamETag string + // sourceETags lists the upstream catalog ETags of every manifest merged + // into this one; empty when the manifest comes from a single upstream. + sourceETags []string upstreamSourceBody []byte convertedFromOpenAIModelList bool NotModified bool @@ -2164,13 +2167,17 @@ func (s *OpenAIGatewayService) fetchCodexModelsManifestUpstream(ctx context.Cont return manifest, nil } +// codexModelsManifestBodyETag returns a weak ETag for a gateway-built catalog. +// The tag only needs semantic equivalence, and a weak tag survives reverse +// proxies that compress responses: they rewrite strong tags to weak ones, which +// would otherwise stop matching the value echoed in x-models-etag. func codexModelsManifestBodyETag(body []byte) string { sum := sha256.Sum256(body) - return fmt.Sprintf(`"%x"`, sum) + return fmt.Sprintf(`W/"%x"`, sum) } -// CodexModelsManifestETag returns the strong ETag for a generated client -// catalog. It is based on the final JSON body after local filtering. +// CodexModelsManifestETag returns the ETag for a generated client catalog. It +// is based on the final JSON body after local filtering. func CodexModelsManifestETag(body []byte) string { return codexModelsManifestBodyETag(body) } @@ -2701,6 +2708,9 @@ func cloneOpenAIModelsResponse(manifest *OpenAIModelsResponse) *OpenAIModelsResp if manifest.upstreamSourceBody != nil { cloned.upstreamSourceBody = append([]byte(nil), manifest.upstreamSourceBody...) } + if manifest.sourceETags != nil { + cloned.sourceETags = append([]string(nil), manifest.sourceETags...) + } return &cloned } diff --git a/backend/internal/service/openai_codex_models_service_test.go b/backend/internal/service/openai_codex_models_service_test.go index 198f27e582..5413a184b3 100644 --- a/backend/internal/service/openai_codex_models_service_test.go +++ b/backend/internal/service/openai_codex_models_service_test.go @@ -1388,10 +1388,13 @@ func TestBuildGroupConfiguredCodexModelsManifestUsesAdministratorConfiguration(t require.EqualValues(t, 1_000_000, models[0]["context_window"]) require.Equal(t, codexModelsManifestBodyETag(manifest.Body), manifest.ETag) + // Generated manifests carry a weak ETag; the strong form of the same tag + // must still revalidate. + require.True(t, strings.HasPrefix(manifest.ETag, "W/")) notModified, configured, err := svc.BuildGroupConfiguredCodexModelsManifest( context.Background(), group, - "W/"+manifest.ETag, + strings.TrimPrefix(manifest.ETag, "W/"), ) require.NoError(t, err) require.True(t, configured) diff --git a/backend/internal/service/openai_ws_forwarder_ingress.go b/backend/internal/service/openai_ws_forwarder_ingress.go index e97faa44ed..50451a015e 100644 --- a/backend/internal/service/openai_ws_forwarder_ingress.go +++ b/backend/internal/service/openai_ws_forwarder_ingress.go @@ -495,6 +495,7 @@ func (s *OpenAIGatewayService) ProxyResponsesWebSocketFromClient( writeCtx, cancel := newOpenAIWSDownstreamWriteContext(ctx, hooks, s.openAIWSWriteTimeout()) defer cancel() message = restoreCodexToolNamesFromContext(c, message) + message = rewriteCodexResponseMetadataModelsETag(getOpenAIGroupIDFromContext(c), message) return clientConn.Write(writeCtx, coderws.MessageText, message) } diff --git a/backend/internal/service/openai_ws_v2_passthrough_adapter.go b/backend/internal/service/openai_ws_v2_passthrough_adapter.go index e4c4bac0a5..8531292782 100644 --- a/backend/internal/service/openai_ws_v2_passthrough_adapter.go +++ b/backend/internal/service/openai_ws_v2_passthrough_adapter.go @@ -30,6 +30,9 @@ type openAIWSClientFrameConn struct { // model identifier they supplied for the current turn. restoreResponseModel func([]byte) []byte restoreToolNames func([]byte) []byte + // Upstream reports its own catalog ETag; clients compare it with the ETag + // of the manifest the gateway served them. + rewriteModelsETag func([]byte) []byte } // openAIWSPolicyEnforcingFrameConn wraps a client-side FrameConn and runs @@ -651,6 +654,9 @@ func (c *openAIWSClientFrameConn) WriteFrame(ctx context.Context, msgType coderw if c.restoreToolNames != nil { payload = c.restoreToolNames(payload) } + if c.rewriteModelsETag != nil { + payload = c.rewriteModelsETag(payload) + } } return c.conn.Write(ctx, msgType, payload) } @@ -970,6 +976,9 @@ func (s *OpenAIGatewayService) proxyResponsesWebSocketV2Passthrough( restoreToolNames: func(payload []byte) []byte { return restoreCodexToolNamesFromContext(c, payload) }, + rewriteModelsETag: func(payload []byte) []byte { + return rewriteCodexResponseMetadataModelsETag(getOpenAIGroupIDFromContext(c), payload) + }, } policyClientConn := &openAIWSPolicyEnforcingFrameConn{ inner: clientFrameConn, From c5b12503bbd3991a853c40815102a3b42687eb01 Mon Sep 17 00:00:00 2001 From: HuntercodeT <61233559+HuntercodeT@users.noreply.github.com> Date: Wed, 2 Dec 2026 09:28:53 +0800 Subject: [PATCH 05/11] fix(openai): bound WebSocket HTTP bridge replay history --- .../handler/openai_gateway_handler.go | 3 +- .../service/grok_upstream_errors_test.go | 1 + .../service/openai_gateway_grok_test.go | 3 + .../openai_responses_created_at_test.go | 3 +- .../internal/service/openai_ws_forwarder.go | 1 + .../service/openai_ws_forwarder_ingress.go | 112 ++++++++---- .../internal/service/openai_ws_http_bridge.go | 95 +++++++--- .../service/openai_ws_http_bridge_history.go | 149 ++++++++++++++++ .../openai_ws_http_bridge_history_test.go | 164 ++++++++++++++++++ .../openai_ws_http_bridge_resume_test.go | 2 + .../service/openai_ws_http_bridge_test.go | 30 +++- 11 files changed, 492 insertions(+), 71 deletions(-) create mode 100644 backend/internal/service/openai_ws_http_bridge_history.go create mode 100644 backend/internal/service/openai_ws_http_bridge_history_test.go diff --git a/backend/internal/handler/openai_gateway_handler.go b/backend/internal/handler/openai_gateway_handler.go index 0e8c94b9f4..58ebfa6ef9 100644 --- a/backend/internal/handler/openai_gateway_handler.go +++ b/backend/internal/handler/openai_gateway_handler.go @@ -81,7 +81,8 @@ func newOpenAIWSUnsupportedModelSwitchError(model string) error { } func shouldReportOpenAIWSProxyAccountFailure(err error) bool { - return err != nil && !errors.Is(err, errOpenAIWSUnsupportedModelSwitch) && !service.IsOpenAIWSSessionPreemptedError(err) + return err != nil && !errors.Is(err, errOpenAIWSUnsupportedModelSwitch) && + !errors.Is(err, service.ErrResponsesWSBridgeHistoryLimit) && !service.IsOpenAIWSSessionPreemptedError(err) } // openAIWSIngressEndedByClient reports whether a finished ingress WebSocket turn diff --git a/backend/internal/service/grok_upstream_errors_test.go b/backend/internal/service/grok_upstream_errors_test.go index 3bd5ad3e73..799c1a7c95 100644 --- a/backend/internal/service/grok_upstream_errors_test.go +++ b/backend/internal/service/grok_upstream_errors_test.go @@ -279,6 +279,7 @@ func TestGrokContentPolicySSEErrorDoesNotMutateOrFailover(t *testing.T) { result, err := svc.proxyOpenAIWSHTTPBridgeTurn( context.Background(), c, account, "access-token", payload, len(payload), "grok-4.5", "", "", "", "cache-id", 1, + nil, func(message []byte) error { writes = append(writes, append([]byte(nil), message...)) return nil diff --git a/backend/internal/service/openai_gateway_grok_test.go b/backend/internal/service/openai_gateway_grok_test.go index 3abfa7eefb..1382139fbb 100644 --- a/backend/internal/service/openai_gateway_grok_test.go +++ b/backend/internal/service/openai_gateway_grok_test.go @@ -3606,6 +3606,7 @@ func TestOpenAIWSHTTPBridgeGrok429PersistsRateLimit(t *testing.T) { context.Background(), nil, account, "token", []byte(`{"type":"response.create","model":"grok-4.3","input":"hi"}`), 64, "grok-4.3", "", "", "", "cache-id", 1, + nil, func([]byte) error { return nil }, ) @@ -3649,6 +3650,7 @@ func TestOpenAIWSHTTPBridgeSSEErrorSideEffectsRunOncePerPlatform(t *testing.T) { result, err := svc.proxyOpenAIWSHTTPBridgeTurn( context.Background(), c, account, "sk-test", payload, len(payload), "gpt-5", "", "", "", "", 1, + nil, func([]byte) error { writes++ return nil @@ -3680,6 +3682,7 @@ func TestOpenAIWSHTTPBridgeGrokExhaustedSuccessPersistsRateLimit(t *testing.T) { context.Background(), nil, account, "token", []byte(`{"type":"response.create","model":"grok-4.3","input":"hi"}`), 64, "grok-4.3", "", "", "", "cache-id", 1, + nil, func([]byte) error { return nil }, ) diff --git a/backend/internal/service/openai_responses_created_at_test.go b/backend/internal/service/openai_responses_created_at_test.go index b4aaac3dff..7aa37cffdc 100644 --- a/backend/internal/service/openai_responses_created_at_test.go +++ b/backend/internal/service/openai_responses_created_at_test.go @@ -264,6 +264,7 @@ func TestProxyOpenAIWSHTTPBridgeTurn_GrokStampsMissingCreatedAt(t *testing.T) { result, err := svc.proxyOpenAIWSHTTPBridgeTurn( context.Background(), c, account, "access-token", payload, len(payload), "grok-4.5", "", "", "", "", 1, + nil, func(message []byte) error { events = append(events, append([]byte(nil), message...)) return nil @@ -292,7 +293,7 @@ func TestProxyOpenAIWSHTTPBridgeTurn_BareErrorSynthesizedFailedCarriesCreatedAt( payload := []byte(`{"type":"response.create","model":"gpt-5","input":"hi"}`) var writes [][]byte - _, err := svc.proxyOpenAIWSHTTPBridgeTurn(context.Background(), c, account, "sk-test", payload, len(payload), "gpt-5", "", "", "", "", 2, func(message []byte) error { + _, err := svc.proxyOpenAIWSHTTPBridgeTurn(context.Background(), c, account, "sk-test", payload, len(payload), "gpt-5", "", "", "", "", 2, nil, func(message []byte) error { writes = append(writes, append([]byte(nil), message...)) return nil }) diff --git a/backend/internal/service/openai_ws_forwarder.go b/backend/internal/service/openai_ws_forwarder.go index b5a466949f..0aa12e035e 100644 --- a/backend/internal/service/openai_ws_forwarder.go +++ b/backend/internal/service/openai_ws_forwarder.go @@ -243,6 +243,7 @@ func (e *OpenAIWSClientCloseError) Reason() string { // OpenAIWSIngressHooks 定义入站 WS 每个 turn 的生命周期回调。 type OpenAIWSIngressHooks struct { + BridgeHistory *ResponsesWSBridgeHistory // ClientLifecycleContext is the request context before an ingress lease // adds its independent cancellation signal. Downstream writes bind to it // so shutdown and disconnect cancellation remain direct during lease loss. diff --git a/backend/internal/service/openai_ws_forwarder_ingress.go b/backend/internal/service/openai_ws_forwarder_ingress.go index e97faa44ed..267cb40b48 100644 --- a/backend/internal/service/openai_ws_forwarder_ingress.go +++ b/backend/internal/service/openai_ws_forwarder_ingress.go @@ -587,6 +587,12 @@ func (s *OpenAIGatewayService) ProxyResponsesWebSocketFromClient( // is resolved again for each turn below so an in-connection model switch // cannot reuse another model's upstream cache identity. grokCacheSeedPayload := firstPayload.payloadRaw + history := openAIWSLegacyBridgeHistory{budget: &ResponsesWSBridgeHistory{}} + if hooks != nil && hooks.BridgeHistory != nil { + history.budget = hooks.BridgeHistory + } + defer history.close() + historyLost := false var bridgeReplayInput []json.RawMessage bridgeReplayInputExists := false var bridgeAccountFailoverInput []json.RawMessage @@ -630,27 +636,46 @@ func (s *OpenAIGatewayService) ProxyResponsesWebSocketFromClient( toolOutputCoverage := AnalyzeToolCallOutputContextCoverageBytes(currentBridgePayload.payloadRaw) needsBridgeReplay := currentBridgePayload.previousResponseID != "" || (toolOutputCoverage.HasFunctionCallOutput && !toolOutputCoverage.ContextCoversAllCallIDs) - // 一次解析当前 input,正常 replay 与 account-failover 两份序列共享同一批正文。 - bridgeCurrentItems, bridgeCurrentItemsExist, extractErr := openAIWSExtractNormalizedInputSequence( - currentBridgePayload.payloadRaw, - ) - if extractErr != nil { - return fmt.Errorf("build websocket http bridge replay input: %w", extractErr) + if needsBridgeReplay && historyLost { + return NewResponsesWSBridgeHistoryCloseError() + } + if !needsBridgeReplay { + // A self-contained request replaces the previous replay chain. + bridgeReplayInput, bridgeAccountFailoverInput = nil, nil + bridgeReplayInputExists, bridgeAccountFailoverInputExists = false, false + history.resize(0) + } + var turnReplayInput, turnAccountFailoverInput []json.RawMessage + var turnReplayInputExists, turnAccountFailoverInputExists bool + cacheTurn := ResponsesWSBridgeReplayInputFits(currentBridgePayload.payloadRaw, ResponsesWSBridgeHistoryLimit) + if cacheTurn { + items, exists, extractErr := openAIWSExtractNormalizedInputSequence(currentBridgePayload.payloadRaw) + if extractErr != nil { + return fmt.Errorf("build websocket http bridge replay input: %w", extractErr) + } + cacheTurn = history.reserve(ResponsesWSBridgeReplayItemsBytes(items)) + if cacheTurn { + items = CloneResponsesWSBridgeReplayItems(items) + turnReplayInput, turnReplayInputExists = buildOpenAIWSReplayInputSequenceFromItems( + bridgeReplayInput, bridgeReplayInputExists, items, exists, needsBridgeReplay, + ) + turnAccountFailoverInput, turnAccountFailoverInputExists = buildOpenAIWSReplayInputSequenceFromItems( + bridgeAccountFailoverInput, bridgeAccountFailoverInputExists, items, exists, needsBridgeReplay, + ) + turnBytes := ResponsesWSBridgeReplayItemsBytes(turnReplayInput) + ResponsesWSBridgeReplayItemsBytes(turnAccountFailoverInput) + cacheTurn = history.resize(turnBytes) + } + } else { + history.budget.LogLimit(openAIWSLegacyBridgeHistoryPath, "connection") + } + if !cacheTurn { + if needsBridgeReplay { + return NewResponsesWSBridgeHistoryCloseError() + } + turnReplayInput, turnAccountFailoverInput = nil, nil + turnReplayInputExists, turnAccountFailoverInputExists = false, false + history.resize(0) } - turnReplayInput, turnReplayInputExists := buildOpenAIWSReplayInputSequenceFromItems( - bridgeReplayInput, - bridgeReplayInputExists, - bridgeCurrentItems, - bridgeCurrentItemsExist, - needsBridgeReplay, - ) - turnAccountFailoverInput, turnAccountFailoverInputExists := buildOpenAIWSReplayInputSequenceFromItems( - bridgeAccountFailoverInput, - bridgeAccountFailoverInputExists, - bridgeCurrentItems, - bridgeCurrentItemsExist, - needsBridgeReplay, - ) if needsBridgeReplay && turnReplayInputExists { updatedPayload, setInputErr := setOpenAIWSPayloadInputSequence( currentBridgePayload.payloadRaw, @@ -684,6 +709,11 @@ func (s *OpenAIGatewayService) ProxyResponsesWebSocketFromClient( return fmt.Errorf("resolve Grok websocket cache identity: %w", err) } } + collector := &openAIWSToolCallReplayCollector{ + all: openAIWSReplayOutput{reserve: history.reserve}, + reserve: history.reserve, + disabled: !cacheTurn, + } result, bridgeErr := s.proxyOpenAIWSHTTPBridgeTurn( ctx, c, @@ -697,6 +727,7 @@ func (s *OpenAIGatewayService) ProxyResponsesWebSocketFromClient( currentBridgePayload.imageInputSize, grokCacheIdentity, turn, + collector, writeClientMessage, ) if bridgeErr != nil && isOpenAIWSSessionPreempted(ctx) { @@ -731,23 +762,32 @@ func (s *OpenAIGatewayService) ProxyResponsesWebSocketFromClient( if result == nil { return errors.New("websocket http bridge turn result is nil") } - // turnReplayInput/turnAccountFailoverInput 可能共享同一头数组(转移自 - // bridgeCurrentItems),保存历史必须经 combine 新建头,禁止就地 append。 - bridgeReplayInput = turnReplayInput - bridgeReplayInputExists = turnReplayInputExists - if result.wsReplayInputExists { - bridgeReplayInput = combineOpenAIWSReplayItems(bridgeReplayInput, result.wsReplayInput) - bridgeReplayInputExists = true - } - bridgeAccountFailoverInput = turnAccountFailoverInput - bridgeAccountFailoverInputExists = turnAccountFailoverInputExists - if len(result.wsAccountFailoverReplayInput) > 0 { - bridgeAccountFailoverInput = combineOpenAIWSReplayItems( - bridgeAccountFailoverInput, - result.wsAccountFailoverReplayInput, - ) - bridgeAccountFailoverInputExists = true + historyLost = !cacheTurn || collector.overflow + if historyLost { + bridgeReplayInput, bridgeAccountFailoverInput = nil, nil + bridgeReplayInputExists, bridgeAccountFailoverInputExists = false, false + history.resize(0) + } else { + // turnReplayInput/turnAccountFailoverInput 可能共享同一头数组(转移自 + // bridgeCurrentItems),保存历史必须经 combine 新建头,禁止就地 append。 + bridgeReplayInput = turnReplayInput + bridgeReplayInputExists = turnReplayInputExists + if result.wsReplayInputExists { + bridgeReplayInput = combineOpenAIWSReplayItems(bridgeReplayInput, result.wsReplayInput) + bridgeReplayInputExists = true + } + bridgeAccountFailoverInput = turnAccountFailoverInput + bridgeAccountFailoverInputExists = turnAccountFailoverInputExists + if len(result.wsAccountFailoverReplayInput) > 0 { + bridgeAccountFailoverInput = combineOpenAIWSReplayItems( + bridgeAccountFailoverInput, + result.wsAccountFailoverReplayInput, + ) + bridgeAccountFailoverInputExists = true + } + history.resize(ResponsesWSBridgeReplayItemsBytes(bridgeReplayInput) + ResponsesWSBridgeReplayItemsBytes(bridgeAccountFailoverInput)) } + history.budget.LogSize(openAIWSLegacyBridgeHistoryPath) if bridgeTurnState := strings.TrimSpace(result.ResponseHeaders.Get(openAIWSTurnStateHeader)); bridgeTurnState != "" { // Follow-up turns on this bridge retain their own upstream state; // publishing it by session hash would leak it to independent bridges. diff --git a/backend/internal/service/openai_ws_http_bridge.go b/backend/internal/service/openai_ws_http_bridge.go index ce7a7dfaec..efdb281763 100644 --- a/backend/internal/service/openai_ws_http_bridge.go +++ b/backend/internal/service/openai_ws_http_bridge.go @@ -261,40 +261,65 @@ func prepareOpenAIWSHTTPBridgeBody(account *Account, payload []byte) ([]byte, er type openAIWSToolCallReplayCollector struct { items []json.RawMessage seen map[string]struct{} - allItems []json.RawMessage - allSeen map[string]struct{} + all openAIWSReplayOutput + reserve func(int) bool + disabled bool + overflow bool } func (c *openAIWSToolCallReplayCollector) AddEvent(eventType string, message []byte) { + if c.disabled || c.overflow { + return + } + forEachOpenAIWSReplayOutputItem(eventType, message, func(item gjson.Result) bool { + c.all.addItem(item) + if !c.all.overflow { + c.addItem(item) + } + c.overflow = c.overflow || c.all.overflow + if c.overflow { + c.all = openAIWSReplayOutput{} + c.items, c.seen = nil, nil + } + return !c.overflow + }) +} + +func forEachOpenAIWSReplayOutputItem(eventType string, message []byte, add func(gjson.Result) bool) { + body := openAIWSPayloadStringView(message) switch strings.TrimSpace(eventType) { case "response.output_item.done": - item := gjson.GetBytes(message, "item") - c.addAllItem(item) - c.addItem(item) + add(gjson.Get(body, "item")) case "response.completed", "response.done": - output := gjson.GetBytes(message, "response.output") - if !output.IsArray() { - return - } - for _, item := range output.Array() { - c.addAllItem(item) - c.addItem(item) + output := gjson.Get(body, "response.output") + if output.IsArray() { + output.ForEach(func(_, item gjson.Result) bool { + return add(item) + }) } } } -// Items/AllItems 返回浅拷贝头数组;正文由 collector 独立分配且此后不可变, -// 调用方按 replay 所有权不变式共享持有。 +// Items and AllItems return independent slice headers with immutable item bytes. func (c *openAIWSToolCallReplayCollector) Items() []json.RawMessage { return slices.Clone(c.items) } func (c *openAIWSToolCallReplayCollector) AllItems() []json.RawMessage { - return slices.Clone(c.allItems) + return slices.Clone(c.all.items) } -func (c *openAIWSToolCallReplayCollector) addAllItem(item gjson.Result) { - if !item.Exists() || item.Type != gjson.JSON { +// openAIWSReplayOutput collects completed output items once, even when both +// output_item.done and the terminal response carry the same item. +type openAIWSReplayOutput struct { + items []json.RawMessage + seen map[string]struct{} + overflow bool + reserve func(int) bool +} + +func (c *openAIWSReplayOutput) addItem(item gjson.Result) { + if c.overflow || !item.Exists() || item.Type != gjson.JSON { return } raw := strings.TrimSpace(item.Raw) @@ -308,14 +333,21 @@ func (c *openAIWSToolCallReplayCollector) addAllItem(item gjson.Result) { if key == "" { key = raw } - if c.allSeen == nil { - c.allSeen = make(map[string]struct{}) - } - if _, ok := c.allSeen[key]; ok { + if _, ok := c.seen[key]; ok { return } - c.allSeen[key] = struct{}{} - c.allItems = append(c.allItems, json.RawMessage(raw)) + if c.reserve != nil && !c.reserve(len(raw)+responsesWSBridgeHistoryItemOverhead+len(key)) { + c.overflow = true + c.items = nil + c.seen = nil + return + } + if c.seen == nil { + c.seen = make(map[string]struct{}) + } + // Event buffers can be reused by streaming writers. Own the item and key. + c.seen[strings.Clone(key)] = struct{}{} + c.items = append(c.items, json.RawMessage(raw)) } func (c *openAIWSToolCallReplayCollector) addItem(item gjson.Result) { @@ -336,13 +368,17 @@ func (c *openAIWSToolCallReplayCollector) addItem(item gjson.Result) { if key == "" { key = raw } - if c.seen == nil { - c.seen = make(map[string]struct{}) - } if _, ok := c.seen[key]; ok { return } - c.seen[key] = struct{}{} + if c.reserve != nil && !c.reserve(len(raw)+responsesWSBridgeHistoryItemOverhead+len(key)) { + c.overflow = true + return + } + if c.seen == nil { + c.seen = make(map[string]struct{}) + } + c.seen[strings.Clone(key)] = struct{}{} c.items = append(c.items, json.RawMessage(raw)) } @@ -429,6 +465,7 @@ func (s *OpenAIGatewayService) proxyOpenAIWSHTTPBridgeTurn( imageInputSize string, grokCacheIdentity string, turn int, + replayCollector *openAIWSToolCallReplayCollector, writeClientMessage func([]byte) error, ) (*OpenAIForwardResult, error) { if s == nil { @@ -659,7 +696,9 @@ func (s *OpenAIGatewayService) proxyOpenAIWSHTTPBridgeTurn( eventCount := 0 tokenEventCount := 0 terminalEventCount := 0 - replayCollector := &openAIWSToolCallReplayCollector{} + if replayCollector == nil { + replayCollector = &openAIWSToolCallReplayCollector{} + } firstEventType := "" lastEventType := "" upstreamTerminalEvent := "" diff --git a/backend/internal/service/openai_ws_http_bridge_history.go b/backend/internal/service/openai_ws_http_bridge_history.go new file mode 100644 index 0000000000..23b791254e --- /dev/null +++ b/backend/internal/service/openai_ws_http_bridge_history.go @@ -0,0 +1,149 @@ +package service + +import ( + "bytes" + "encoding/json" + "errors" + "sync/atomic" + + coderws "github.com/coder/websocket" + "github.com/tidwall/gjson" +) + +const ( + ResponsesWSBridgeHistoryLimit = 64 << 20 + responsesWSBridgeProcessHistoryLimit = 512 << 20 + // Allow for a RawMessage slice entry, collection capacity and dedup bookkeeping. + responsesWSBridgeHistoryItemOverhead = 64 +) + +var ErrResponsesWSBridgeHistoryLimit = errors.New("responses websocket bridge replay history unavailable") + +func NewResponsesWSBridgeHistoryCloseError() error { + return NewOpenAIWSClientCloseError(coderws.StatusTryAgainLater, + "bridge replay history unavailable; reconnect and send full input", ErrResponsesWSBridgeHistoryLimit) +} + +type responsesWSBridgeProcessHistory struct { + bytes atomic.Int64 + overflows atomic.Uint64 +} + +var sharedResponsesWSBridgeHistory responsesWSBridgeProcessHistory + +// ResponsesWSBridgeHistory accounts for replay history on one client connection. +// Callers on a connection must serialize access. Reservations on other +// connections may run concurrently. +type ResponsesWSBridgeHistory struct { + bytes int +} + +// TryReserve accounts for additional retained replay bytes before copying them. +func (h *ResponsesWSBridgeHistory) TryReserve(size int) bool { + if size > ResponsesWSBridgeHistoryLimit-h.bytes { + return false + } + for { + current := sharedResponsesWSBridgeHistory.bytes.Load() + if int64(size) > responsesWSBridgeProcessHistoryLimit-current { + return false + } + if sharedResponsesWSBridgeHistory.bytes.CompareAndSwap(current, current+int64(size)) { + h.bytes += size + return true + } + } +} + +// Release returns bytes previously reserved by the caller. +func (h *ResponsesWSBridgeHistory) Release(size int) { + h.bytes -= size + sharedResponsesWSBridgeHistory.bytes.Add(-int64(size)) +} + +func (h *ResponsesWSBridgeHistory) LogSize(path string) { + logOpenAIWSModeDebug("bridge_history_bytes path=%s connection_bytes=%d process_bytes=%d", + path, h.bytes, sharedResponsesWSBridgeHistory.bytes.Load()) +} + +// LogReservationFailure records an unsuccessful reservation after any eviction attempts. +func (h *ResponsesWSBridgeHistory) LogReservationFailure(path string, size int) { + reason := "process" + if size > ResponsesWSBridgeHistoryLimit-h.bytes { + reason = "connection" + } + h.LogLimit(path, reason) +} + +func (h *ResponsesWSBridgeHistory) LogLimit(path, reason string) { + total := sharedResponsesWSBridgeHistory.overflows.Add(1) + logOpenAIWSModeWarn("bridge_history_limit path=%s reason=%s connection_bytes=%d process_bytes=%d overflows_total=%d", + path, reason, h.bytes, sharedResponsesWSBridgeHistory.bytes.Load(), total) +} + +// ResponsesWSBridgeReplayInputFits cheaply bounds the size and number of items +// before allocating a replay slice. The normalized items are measured again +// after parsing, since string inputs can grow during conversion. +func ResponsesWSBridgeReplayInputFits(payload []byte, limit int) bool { + input := gjson.Get(openAIWSPayloadStringView(payload), "input") + if !input.IsArray() { + return !input.Exists() || len(input.Raw)+responsesWSBridgeHistoryItemOverhead <= limit + } + remaining := limit - len(input.Raw) + input.ForEach(func(_, _ gjson.Result) bool { + remaining -= responsesWSBridgeHistoryItemOverhead + return remaining >= 0 + }) + return remaining >= 0 +} + +func ResponsesWSBridgeReplayItemsBytes(items []json.RawMessage) int { + size := len(items) * responsesWSBridgeHistoryItemOverhead + for _, item := range items { + size += len(item) + } + return size +} + +// CloneResponsesWSBridgeReplayItems gives replay items their own backing bytes +// so retaining an item cannot keep an entire client frame alive. +func CloneResponsesWSBridgeReplayItems(items []json.RawMessage) []json.RawMessage { + if len(items) == 0 { + return nil + } + out := make([]json.RawMessage, len(items)) + for i, item := range items { + out[i] = bytes.Clone(item) + } + return out +} + +const openAIWSLegacyBridgeHistoryPath = "openai_grok" + +type openAIWSLegacyBridgeHistory struct { + budget *ResponsesWSBridgeHistory + held int +} + +func (h *openAIWSLegacyBridgeHistory) reserve(size int) bool { + if !h.budget.TryReserve(size) { + h.budget.LogReservationFailure(openAIWSLegacyBridgeHistoryPath, size) + return false + } + h.held += size + return true +} + +func (h *openAIWSLegacyBridgeHistory) resize(size int) bool { + if size > h.held { + return h.reserve(size - h.held) + } + h.budget.Release(h.held - size) + h.held = size + return true +} + +func (h *openAIWSLegacyBridgeHistory) close() { + h.resize(0) + h.budget.LogSize(openAIWSLegacyBridgeHistoryPath) +} diff --git a/backend/internal/service/openai_ws_http_bridge_history_test.go b/backend/internal/service/openai_ws_http_bridge_history_test.go new file mode 100644 index 0000000000..5019751ff9 --- /dev/null +++ b/backend/internal/service/openai_ws_http_bridge_history_test.go @@ -0,0 +1,164 @@ +//go:build unit + +package service + +import ( + "context" + "errors" + "fmt" + "io" + "net/http" + "net/http/httptest" + "strings" + "sync" + "testing" + "time" + + "github.com/Wei-Shaw/sub2api/internal/config" + "github.com/Wei-Shaw/sub2api/internal/pkg/xai" + coderws "github.com/coder/websocket" + "github.com/gin-gonic/gin" + "github.com/stretchr/testify/require" + "github.com/tidwall/gjson" +) + +func TestResponsesWSBridgeHistoryConcurrentProcessBudget(t *testing.T) { + const connections = 12 + reserved := make(chan *ResponsesWSBridgeHistory, connections) + var workers sync.WaitGroup + for range connections { + workers.Go(func() { + history := &ResponsesWSBridgeHistory{} + if history.TryReserve(ResponsesWSBridgeHistoryLimit) { + reserved <- history + } + }) + } + workers.Wait() + close(reserved) + require.Len(t, reserved, responsesWSBridgeProcessHistoryLimit/ResponsesWSBridgeHistoryLimit) + for history := range reserved { + history.Release(ResponsesWSBridgeHistoryLimit) + } + require.Zero(t, sharedResponsesWSBridgeHistory.bytes.Load()) + + probe := &ResponsesWSBridgeHistory{} + require.False(t, probe.TryReserve(ResponsesWSBridgeHistoryLimit+1)) + require.True(t, probe.TryReserve(ResponsesWSBridgeHistoryLimit)) + probe.Release(ResponsesWSBridgeHistoryLimit) +} + +func TestOpenAIWSHTTPBridgeHistoryOverLimitReconnectsWithFullInput(t *testing.T) { + for _, scope := range []string{"connection", "process"} { + t.Run(scope, func(t *testing.T) { + const free = 300 + firstConnectionHistory := &ResponsesWSBridgeHistory{} + switch scope { + case "connection": + require.True(t, firstConnectionHistory.TryReserve(ResponsesWSBridgeHistoryLimit-free)) + t.Cleanup(func() { firstConnectionHistory.Release(ResponsesWSBridgeHistoryLimit - free) }) + case "process": + for i := 0; i < responsesWSBridgeProcessHistoryLimit/ResponsesWSBridgeHistoryLimit; i++ { + history := &ResponsesWSBridgeHistory{} + size := ResponsesWSBridgeHistoryLimit + if i == 0 { + size -= free + } + require.True(t, history.TryReserve(size)) + t.Cleanup(func() { history.Release(size) }) + } + } + processBytes := sharedResponsesWSBridgeHistory.bytes.Load() + overflows := sharedResponsesWSBridgeHistory.overflows.Load() + + response := func(id, output string) *http.Response { + sse := fmt.Sprintf("data: {\"type\":\"response.completed\",\"response\":{\"id\":%q,\"output\":%s}}\n\n", id, output) + return &http.Response{ + StatusCode: http.StatusOK, + Header: http.Header{"Content-Type": {"text/event-stream"}}, + Body: io.NopCloser(strings.NewReader(sse)), + } + } + // A plain assistant message belongs only to the account-failover + // sequence. Its size alone must invalidate the replay snapshot. + output := fmt.Sprintf(`[{"type":"message","id":"assistant","role":"assistant","content":[{"type":"output_text","text":%q}]}]`, + strings.Repeat("x", free)) + upstream := &httpUpstreamRecorder{responses: []*http.Response{ + response("resp_first", output), + response("resp_retried", "[]"), + }} + svc := &OpenAIGatewayService{cfg: &config.Config{}, httpUpstream: upstream} + account := &Account{ + ID: 71, Platform: PlatformGrok, Type: AccountTypeOAuth, + Credentials: map[string]any{"base_url": xai.DefaultCLIBaseURL}, + } + + done := make(chan error, 2) + wsServer := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + conn, err := coderws.Accept(w, r, nil) + if err != nil { + done <- err + return + } + defer func() { _ = conn.CloseNow() }() + _, firstMessage, err := conn.Read(r.Context()) + if err != nil { + done <- err + return + } + ginCtx, _ := gin.CreateTestContext(httptest.NewRecorder()) + ginCtx.Request = r + hooks := &OpenAIWSIngressHooks{BridgeHistory: firstConnectionHistory} + if r.URL.Path == "/retry" { + hooks.BridgeHistory = nil + } + err = svc.ProxyResponsesWebSocketFromClient(r.Context(), ginCtx, conn, account, "access-token", firstMessage, hooks) + var closeErr *OpenAIWSClientCloseError + if errors.As(err, &closeErr) { + _ = conn.Close(closeErr.StatusCode(), closeErr.Reason()) + } + done <- err + })) + defer wsServer.Close() + + ctx, cancel := context.WithTimeout(t.Context(), 5*time.Second) + defer cancel() + dial := func(path string) *coderws.Conn { + conn, _, err := coderws.Dial(ctx, "ws"+strings.TrimPrefix(wsServer.URL, "http")+path, nil) + require.NoError(t, err) + t.Cleanup(func() { _ = conn.CloseNow() }) + return conn + } + send := func(conn *coderws.Conn, frame string) { + require.NoError(t, conn.Write(ctx, coderws.MessageText, []byte(frame))) + } + readCompleted := func(conn *coderws.Conn, id string) { + _, frame, err := conn.Read(ctx) + require.NoError(t, err) + require.Equal(t, "response.completed", gjson.GetBytes(frame, "type").String()) + require.Equal(t, id, gjson.GetBytes(frame, "response.id").String()) + } + + first := dial("/") + send(first, `{"type":"response.create","model":"grok","input":"first"}`) + readCompleted(first, "resp_first") + send(first, `{"type":"response.create","model":"grok","previous_response_id":"resp_first","input":"second"}`) + _, _, err := first.Read(ctx) + require.Equal(t, coderws.StatusTryAgainLater, coderws.CloseStatus(err)) + require.ErrorIs(t, <-done, ErrResponsesWSBridgeHistoryLimit) + require.Equal(t, processBytes, sharedResponsesWSBridgeHistory.bytes.Load()) + require.Equal(t, overflows+1, sharedResponsesWSBridgeHistory.overflows.Load()) + require.Len(t, upstream.requests, 1) + + retry := dial("/retry") + send(retry, `{"type":"response.create","model":"grok","input":[{"type":"message","role":"user","content":"first"},{"type":"message","role":"user","content":"second"}]}`) + readCompleted(retry, "resp_retried") + require.NoError(t, retry.Close(coderws.StatusNormalClosure, "")) + require.NoError(t, <-done) + require.Len(t, upstream.requests, 2) + require.Len(t, gjson.GetBytes(upstream.bodies[1], "input").Array(), 2) + require.False(t, gjson.GetBytes(upstream.bodies[1], "previous_response_id").Exists()) + require.Equal(t, processBytes, sharedResponsesWSBridgeHistory.bytes.Load()) + }) + } +} diff --git a/backend/internal/service/openai_ws_http_bridge_resume_test.go b/backend/internal/service/openai_ws_http_bridge_resume_test.go index 1468892bbe..b18ac294e4 100644 --- a/backend/internal/service/openai_ws_http_bridge_resume_test.go +++ b/backend/internal/service/openai_ws_http_bridge_resume_test.go @@ -50,6 +50,7 @@ func TestProxyOpenAIWSHTTPBridgeTurnLaterTurn429FailsOverBeforeClientWrite(t *te result, err := svc.proxyOpenAIWSHTTPBridgeTurn( context.Background(), c, account, "access-token", payload, len(payload), "gpt-5.6-sol", "", "", "", "", 281, + nil, func([]byte) error { writes++ return nil @@ -85,6 +86,7 @@ func TestProxyOpenAIWSHTTPBridgeTurnLaterTurnDoesNotFailOverAfterDownstreamOutpu result, err := svc.proxyOpenAIWSHTTPBridgeTurn( context.Background(), c, account, "sk-test", payload, len(payload), "gpt-5", "", "", "", "", 281, + nil, func(message []byte) error { writes = append(writes, append([]byte(nil), message...)) return nil diff --git a/backend/internal/service/openai_ws_http_bridge_test.go b/backend/internal/service/openai_ws_http_bridge_test.go index dfa42702e5..4515b8c58f 100644 --- a/backend/internal/service/openai_ws_http_bridge_test.go +++ b/backend/internal/service/openai_ws_http_bridge_test.go @@ -90,6 +90,7 @@ func TestProxyOpenAIWSHTTPBridgeTurn_KeepsOutboundAndObservedServiceTiersSeparat result, err := svc.proxyOpenAIWSHTTPBridgeTurn( context.Background(), c, account, "test-token", payload, len(payload), "gpt-5.5", "", "", "", "", 1, + nil, func([]byte) error { return nil }, ) @@ -128,6 +129,7 @@ func TestProxyOpenAIWSHTTPBridgeTurn_NormalizesFastWithoutLosingObservedDefault( result, err := svc.proxyOpenAIWSHTTPBridgeTurn( context.Background(), c, account, "test-token", payload, len(payload), "gpt-5.5", "", "", "", "", 1, + nil, func([]byte) error { return nil }, ) @@ -177,6 +179,7 @@ func TestProxyOpenAIWSHTTPBridgeTurnAPIKeyAdaptsClientTools(t *testing.T) { result, err := svc.proxyOpenAIWSHTTPBridgeTurn( context.Background(), c, account, "test-token", payload, len(payload), "gpt-5", "", "", "", "", 2, + nil, func(message []byte) error { events = append(events, append([]byte(nil), message...)) return nil @@ -247,6 +250,7 @@ func TestProxyOpenAIWSHTTPBridgeTurnAPIKeyRestoresClientToolsInResponseDone(t *t result, err := svc.proxyOpenAIWSHTTPBridgeTurn( context.Background(), c, account, "test-token", payload, len(payload), "gpt-5", "", "", "", "", 1, + nil, func(message []byte) error { events = append(events, append([]byte(nil), message...)) return nil @@ -311,6 +315,7 @@ func TestProxyOpenAIWSHTTPBridgeTurnGrokPromotesDiscoveryAndRestoresNamespaceSSE result, err := svc.proxyOpenAIWSHTTPBridgeTurn( context.Background(), c, account, "access-token", payload, len(payload), "grok-4.5", "", "", "", "", 1, + nil, func(message []byte) error { events = append(events, append([]byte(nil), message...)) return nil @@ -360,7 +365,7 @@ func TestProxyOpenAIWSHTTPBridgeTurnGrokInheritsToolSearchAndPromotesFollowupDis first := []byte(`{"type":"response.create","model":"grok-4.5","stream":true,"tools":[{"type":"tool_search"}],"input":"discover tools"}`) _, err := svc.proxyOpenAIWSHTTPBridgeTurn( context.Background(), c, account, "access-token", first, len(first), - "grok-4.5", "", "", "", "grok-ws-cache", 1, func([]byte) error { return nil }, + "grok-4.5", "", "", "", "grok-ws-cache", 1, nil, func([]byte) error { return nil }, ) require.NoError(t, err) @@ -374,6 +379,7 @@ func TestProxyOpenAIWSHTTPBridgeTurnGrokInheritsToolSearchAndPromotesFollowupDis _, err = svc.proxyOpenAIWSHTTPBridgeTurn( context.Background(), c, account, "access-token", second, len(second), "grok-4.5", "", "", "", "grok-ws-cache", 2, + nil, func(message []byte) error { events = append(events, append([]byte(nil), message...)) return nil @@ -794,6 +800,7 @@ func TestProxyOpenAIWSHTTPBridgeTurnTransportErrorFailoverSafety(t *testing.T) { result, err := svc.proxyOpenAIWSHTTPBridgeTurn( context.Background(), c, account, "sk-test", payload, len(payload), "gpt-5", "", "", "", "", tt.turn, + nil, func(message []byte) error { writes = append(writes, append([]byte(nil), message...)) return nil @@ -852,6 +859,7 @@ func TestProxyOpenAIWSHTTPBridgeTurnHTTPStatusFailoverSafety(t *testing.T) { result, err := svc.proxyOpenAIWSHTTPBridgeTurn( context.Background(), c, account, "sk-test", payload, len(payload), "gpt-5", "", "", "", "", tt.turn, + nil, func(message []byte) error { writes = append(writes, append([]byte(nil), message...)) return nil @@ -902,6 +910,7 @@ func TestProxyOpenAIWSHTTPBridgeTurnRetriesRejectedFieldBeforeClientOutput(t *te result, err := svc.proxyOpenAIWSHTTPBridgeTurn( context.Background(), c, account, "sk-test", payload, len(payload), "gpt-5", "", "", "", "", 1, + nil, func(message []byte) error { writes = append(writes, append([]byte(nil), message...)) return nil @@ -941,6 +950,7 @@ func TestProxyOpenAIWSHTTPBridgeTurnSSEErrorFailoverSafety(t *testing.T) { result, err := svc.proxyOpenAIWSHTTPBridgeTurn( context.Background(), c, account, "sk-test", payload, len(payload), "gpt-5", "", "", "", "", turn, + nil, func(message []byte) error { writes = append(writes, append([]byte(nil), message...)) return nil @@ -999,6 +1009,7 @@ func TestProxyOpenAIWSHTTPBridgeTurnRewritesCapacityShedCodeForClient(t *testing _, err := svc.proxyOpenAIWSHTTPBridgeTurn( context.Background(), c, account, "sk-test", payload, len(payload), "gpt-5", "", "", "", "", tt.turn, + nil, func(message []byte) error { writes = append(writes, append([]byte(nil), message...)) return nil @@ -1038,7 +1049,7 @@ func TestProxyOpenAIWSHTTPBridgeTurnBareErrorUsesAuthoritativeFailed(t *testing. payload := []byte(`{"type":"response.create","model":"gpt-5","input":"hi"}`) var writes [][]byte - result, err := svc.proxyOpenAIWSHTTPBridgeTurn(context.Background(), c, account, "sk-test", payload, len(payload), "gpt-5", "", "", "", "", 2, func(message []byte) error { + result, err := svc.proxyOpenAIWSHTTPBridgeTurn(context.Background(), c, account, "sk-test", payload, len(payload), "gpt-5", "", "", "", "", 2, nil, func(message []byte) error { writes = append(writes, append([]byte(nil), message...)) return nil }) @@ -1110,7 +1121,7 @@ func TestProxyOpenAIWSHTTPBridgeTurnMarksCyberPolicyForFailureShapes(t *testing. result, err := svc.proxyOpenAIWSHTTPBridgeTurn( context.Background(), c, account, "sk-test", payload, len(payload), - "gpt-5", "", "", "", "", 1, func([]byte) error { return nil }, + "gpt-5", "", "", "", "", 1, nil, func([]byte) error { return nil }, ) require.Equal(t, tt.wantResult, result != nil) @@ -1139,7 +1150,7 @@ func TestProxyOpenAIWSHTTPBridgeTurnBareErrorEOFSynthesizesFailed(t *testing.T) payload := []byte(`{"type":"response.create","model":"gpt-5","input":"hi"}`) var writes [][]byte - result, err := svc.proxyOpenAIWSHTTPBridgeTurn(context.Background(), c, account, "sk-test", payload, len(payload), "gpt-5", "", "", "", "", 2, func(message []byte) error { + result, err := svc.proxyOpenAIWSHTTPBridgeTurn(context.Background(), c, account, "sk-test", payload, len(payload), "gpt-5", "", "", "", "", 2, nil, func(message []byte) error { writes = append(writes, append([]byte(nil), message...)) return nil }) @@ -1172,7 +1183,7 @@ func TestProxyOpenAIWSHTTPBridgeTurnBareErrorFollowedByCompletedUsesCompleted(t payload := []byte(`{"type":"response.create","model":"gpt-5","input":"hi"}`) var writes [][]byte - result, err := svc.proxyOpenAIWSHTTPBridgeTurn(context.Background(), c, account, "sk-test", payload, len(payload), "gpt-5", "", "", "", "", 2, func(message []byte) error { + result, err := svc.proxyOpenAIWSHTTPBridgeTurn(context.Background(), c, account, "sk-test", payload, len(payload), "gpt-5", "", "", "", "", 2, nil, func(message []byte) error { writes = append(writes, append([]byte(nil), message...)) return nil }) @@ -1238,6 +1249,7 @@ func TestProxyOpenAIWSHTTPBridgeTurnStagesMetadataAndRelaysKeepaliveBeforeCapaci result, err := svc.proxyOpenAIWSHTTPBridgeTurn( context.Background(), c, account, "sk-test", payload, len(payload), "gpt-5", "", "", "", "", 1, + nil, func(message []byte) error { writes = append(writes, append([]byte(nil), message...)) if gjson.GetBytes(message, "type").String() == "keepalive" { @@ -1289,6 +1301,7 @@ func TestProxyOpenAIWSHTTPBridgeTurnDoesNotReplayCapacityAfterSemanticOutput(t * result, err := svc.proxyOpenAIWSHTTPBridgeTurn( context.Background(), c, account, "sk-test", payload, len(payload), "gpt-5", "", "", "", "", 1, + nil, func(message []byte) error { writes = append(writes, append([]byte(nil), message...)) return nil @@ -1345,6 +1358,7 @@ func TestProxyOpenAIWSHTTPBridgeTurnKeepaliveWriteFailure(t *testing.T) { result, err := svc.proxyOpenAIWSHTTPBridgeTurn( context.Background(), c, account, "sk-test", payload, len(payload), "gpt-5", "", "", "", "", 1, + nil, func(message []byte) error { writes = append(writes, append([]byte(nil), message...)) return tc.writeErr @@ -1413,6 +1427,7 @@ func TestProxyOpenAIWSHTTPBridgeTurnDisconnectedBeforeOutputDoesNotFailOver(t *t result, err := svc.proxyOpenAIWSHTTPBridgeTurn( context.Background(), c, account, "sk-test", payload, len(payload), "gpt-5", "", "", "", "", 1, + nil, func(message []byte) error { writes = append(writes, append([]byte(nil), message...)) if len(writes) == 1 { @@ -1480,6 +1495,7 @@ func TestProxyOpenAIWSHTTPBridgeTurnRequiresTerminalEvent(t *testing.T) { result, err := svc.proxyOpenAIWSHTTPBridgeTurn( context.Background(), c, account, "sk-test", payload, len(payload), "gpt-5", "", "", "", "", 1, + nil, func(message []byte) error { writes = append(writes, append([]byte(nil), message...)) return nil @@ -1579,6 +1595,7 @@ func TestOpenAIWSHTTPBridgeRelaysSSEFramesAsWebSocketMessages(t *testing.T) { "", "", 1, + nil, writeClient, ) resultCh <- bridgeResult{result: result, err: bridgeErr} @@ -1663,6 +1680,7 @@ func TestProxyOpenAIWSHTTPBridgeTurnForGrokDefaultsEmptyModelTo45(t *testing.T) result, err := svc.proxyOpenAIWSHTTPBridgeTurn( context.Background(), c, account, "access-token", payload, len(payload), "", "", "", "", "", 1, + nil, func(message []byte) error { events = append(events, append([]byte(nil), message...)) return nil @@ -1723,6 +1741,7 @@ func TestProxyOpenAIWSHTTPBridgeTurnPromotesCodexAdditionalToolsForMixedCache(t result, err := svc.proxyOpenAIWSHTTPBridgeTurn( context.Background(), c, account, "access-token", payload, len(payload), "grok", "", "", "", "isolated-ws-cache-id", 1, + nil, func(message []byte) error { events = append(events, append([]byte(nil), message...)) return nil @@ -2386,6 +2405,7 @@ func TestProxyOpenAIWSHTTPBridgeTurn_StagesCodexFingerprint(t *testing.T) { _, err := svc.proxyOpenAIWSHTTPBridgeTurn( context.Background(), c, account, "test-token", payload, len(payload), "gpt-5.5", "", "", "", "", 1, + nil, func([]byte) error { return nil }, ) require.NoError(t, err) From 8aa5c2a4ba3627072f4b866d4dcabfa2d1588f2e Mon Sep 17 00:00:00 2001 From: shaw Date: Wed, 2 Dec 2026 11:42:27 +0800 Subject: [PATCH 06/11] =?UTF-8?q?fix:=20omit=20Retry-After=20hint=20when?= =?UTF-8?q?=20any=20supporting=20account=20is=20not=20in=20persisted=20coo?= =?UTF-8?q?ldown=EF=BC=88audit=20follow-up=20for=20#9197=EF=BC=89?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../service/gateway_model_availability.go | 9 +++ .../gateway_model_availability_test.go | 65 +++++++++++++++++++ .../openai_gateway_model_availability.go | 9 +++ 3 files changed, 83 insertions(+) diff --git a/backend/internal/service/gateway_model_availability.go b/backend/internal/service/gateway_model_availability.go index fbe727c886..71c36d6dc4 100644 --- a/backend/internal/service/gateway_model_availability.go +++ b/backend/internal/service/gateway_model_availability.go @@ -109,6 +109,10 @@ func (s *GatewayService) DiagnoseModelAvailabilityForPlatform( diag := ModelAvailabilityDiagnosis{} var earliestRecovery time.Duration + // A supporting account with no persisted cooldown is waiting on a runtime + // filter (quota, RPM, window cost, ...) whose recovery time is unknown, so + // the pool-level hint must be omitted rather than inflated by a cooling peer. + hasUncooledCandidate := false for i := range accounts { if useMixed && accounts[i].Platform == PlatformAntigravity && !accounts[i].IsMixedSchedulingEnabled() { continue @@ -120,9 +124,14 @@ func (s *GatewayService) DiagnoseModelAvailabilityForPlatform( if earliestRecovery == 0 || remaining < earliestRecovery { earliestRecovery = remaining } + } else { + hasUncooledCandidate = true } } } + if hasUncooledCandidate { + earliestRecovery = 0 + } diag.RetryAfterSeconds = ceilRetryAfterSeconds(earliestRecovery, DownstreamRetryAfterMaxSeconds(s.cfg)) return diag } diff --git a/backend/internal/service/gateway_model_availability_test.go b/backend/internal/service/gateway_model_availability_test.go index ed32f620e8..bf5ba12fde 100644 --- a/backend/internal/service/gateway_model_availability_test.go +++ b/backend/internal/service/gateway_model_availability_test.go @@ -249,3 +249,68 @@ func TestDiagnoseModelAvailabilityForPlatform_WrongPlatformFiltersOut(t *testing require.False(t, diag.HasAccountsInPool, "OpenAI route must not see Anthropic accounts in pool") require.False(t, diag.HasModelSupport) } + +func retryAfterTestAccount(id int64, platform string, groupID int64, cooldown time.Duration) Account { + acc := Account{ + ID: id, + Platform: platform, + Status: StatusActive, + Schedulable: true, + AccountGroups: []AccountGroup{{GroupID: groupID}}, + Credentials: map[string]any{ + "model_mapping": map[string]any{"claude-opus-4-8": "claude-opus-4-8"}, + }, + } + if cooldown > 0 { + until := time.Now().Add(cooldown) + acc.RateLimitResetAt = &until + } + return acc +} + +func TestDiagnoseModelAvailability_RetryAfterHint(t *testing.T) { + groupID := int64(44) + tests := []struct { + name string + cooldowns []time.Duration + want func(t *testing.T, seconds int) + }{ + { + name: "mixed pool with runtime-filtered account omits hint", + cooldowns: []time.Duration{0, 2 * time.Hour}, + want: func(t *testing.T, s int) { require.Equal(t, 0, s) }, + }, + { + name: "all cooling picks earliest", + cooldowns: []time.Duration{90 * time.Second, 2 * time.Hour}, + want: func(t *testing.T, s int) { require.InDelta(t, 90, s, 2) }, + }, + { + name: "all cooling is capped at the default maximum", + cooldowns: []time.Duration{2 * time.Hour, 3 * time.Hour}, + want: func(t *testing.T, s int) { require.Equal(t, DownstreamRetryAfterMaxSeconds(nil), s) }, + }, + } + for _, tt := range tests { + t.Run("anthropic/"+tt.name, func(t *testing.T) { + repo := &mockAccountRepoForPlatform{accountsByID: map[int64]*Account{}} + for i, c := range tt.cooldowns { + repo.accounts = append(repo.accounts, retryAfterTestAccount(int64(i+1), PlatformAnthropic, groupID, c)) + } + svc := &GatewayService{accountRepo: repo, cfg: testConfig(), schedulerSnapshot: &SchedulerSnapshotService{}} + diag := svc.DiagnoseModelAvailabilityForPlatform(context.Background(), &groupID, "claude-opus-4-8", PlatformAnthropic) + require.True(t, diag.HasModelSupport) + tt.want(t, diag.RetryAfterSeconds) + }) + t.Run("openai/"+tt.name, func(t *testing.T) { + repo := &mockAccountRepoForPlatform{accountsByID: map[int64]*Account{}} + for i, c := range tt.cooldowns { + repo.accounts = append(repo.accounts, retryAfterTestAccount(int64(i+1), PlatformOpenAI, groupID, c)) + } + svc := &OpenAIGatewayService{accountRepo: repo, cfg: testConfig(), schedulerSnapshot: &SchedulerSnapshotService{}} + diag := svc.DiagnoseModelAvailabilityForPlatform(context.Background(), &groupID, "claude-opus-4-8", PlatformOpenAI) + require.True(t, diag.HasModelSupport) + tt.want(t, diag.RetryAfterSeconds) + }) + } +} diff --git a/backend/internal/service/openai_gateway_model_availability.go b/backend/internal/service/openai_gateway_model_availability.go index b253ef1764..eec311d4af 100644 --- a/backend/internal/service/openai_gateway_model_availability.go +++ b/backend/internal/service/openai_gateway_model_availability.go @@ -56,6 +56,10 @@ func (s *OpenAIGatewayService) DiagnoseModelAvailabilityForPlatform( diag := ModelAvailabilityDiagnosis{} var earliestRecovery time.Duration + // A supporting account with no persisted cooldown is waiting on a runtime + // filter (quota, RPM, window cost, ...) whose recovery time is unknown, so + // the pool-level hint must be omitted rather than inflated by a cooling peer. + hasUncooledCandidate := false for i := range accounts { diag.HasAccountsInPool = true if isRetiredOpenAISubscriptionModel(&accounts[i], resolveOpenAIAccountUpstreamModelForRequest(&accounts[i], requestedModel, false)) { @@ -71,9 +75,14 @@ func (s *OpenAIGatewayService) DiagnoseModelAvailabilityForPlatform( if earliestRecovery == 0 || remaining < earliestRecovery { earliestRecovery = remaining } + } else { + hasUncooledCandidate = true } } } + if hasUncooledCandidate { + earliestRecovery = 0 + } diag.RetryAfterSeconds = ceilRetryAfterSeconds(earliestRecovery, DownstreamRetryAfterMaxSeconds(s.cfg)) return diag } From 385e07ca8568890aa5d27caa8558de62a8b8c59d Mon Sep 17 00:00:00 2001 From: shaw Date: Wed, 2 Dec 2026 11:44:07 +0800 Subject: [PATCH 07/11] =?UTF-8?q?fix:=20shorten=20Codex=20models=20ETag=20?= =?UTF-8?q?mapping=20TTL=20and=20clear=20it=20for=20upstream-less=20manife?= =?UTF-8?q?sts=EF=BC=88audit=20follow-up=20for=20#9199=EF=BC=89?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../service/openai_codex_models_etag.go | 33 ++++++++++++- .../service/openai_codex_models_etag_test.go | 49 +++++++++++++++++++ .../openai_codex_models_etag_ws_test.go | 19 +++++++ 3 files changed, 99 insertions(+), 2 deletions(-) diff --git a/backend/internal/service/openai_codex_models_etag.go b/backend/internal/service/openai_codex_models_etag.go index 550bdc2fb5..a068099398 100644 --- a/backend/internal/service/openai_codex_models_etag.go +++ b/backend/internal/service/openai_codex_models_etag.go @@ -29,7 +29,13 @@ const ( codexModelsETagHeader = "x-models-etag" codexModelsETagRegistryMaxEntries = 4096 - codexModelsETagRegistryTTL = 24 * time.Hour + // The Codex client caches the catalog for 300s and only renews that cache + // when the ETag is unchanged. The served manifest also depends on group + // configuration and schedulable accounts, none of which change the upstream + // ETag, so a recorded mapping can go stale. Ten minutes keeps the per-turn + // full download away (at most one refresh per window) while bounding how + // long a stale mapping can hide a changed catalog. + codexModelsETagRegistryTTL = 10 * time.Minute ) type codexModelsETagKey struct { @@ -92,6 +98,20 @@ func (r *codexModelsETagRegistry) record(groupID int64, upstreamETags []string, r.evictLocked(now) } +// clearGroup drops every mapping of a group. +func (r *codexModelsETagRegistry) clearGroup(groupID int64) { + if r == nil || groupID <= 0 { + return + } + r.mu.Lock() + defer r.mu.Unlock() + for key := range r.entries { + if key.groupID == groupID { + delete(r.entries, key) + } + } +} + func (r *codexModelsETagRegistry) lookup(groupID int64, upstream string, now time.Time) (string, bool) { upstream = normalizeCodexModelsETag(upstream) if r == nil || groupID <= 0 || upstream == "" { @@ -154,11 +174,20 @@ func (r *OpenAIModelsResponse) upstreamCatalogETags() []string { // was served with for every upstream catalog ETag it was derived from. The // mapping lets codex.response.metadata events carry an ETag the client // recognizes. Verbatim manifests are recorded too, so their ETag is kept. +// A manifest without any upstream ETag (for example one built from group +// configuration alone) invalidates the group's earlier mappings: they describe +// a catalog the group no longer serves, so later metadata events lose the +// header instead of reporting a stale ETag. func (s *OpenAIGatewayService) RecordCodexModelsManifestETag(groupID int64, manifest *OpenAIModelsResponse) { if manifest == nil { return } - codexModelsETags.record(groupID, manifest.upstreamCatalogETags(), manifest.ETag, time.Now()) + upstreamETags := manifest.upstreamCatalogETags() + if len(upstreamETags) == 0 { + codexModelsETags.clearGroup(groupID) + return + } + codexModelsETags.record(groupID, upstreamETags, manifest.ETag, time.Now()) } // rewriteCodexResponseMetadataModelsETag translates the x-models-etag header of diff --git a/backend/internal/service/openai_codex_models_etag_test.go b/backend/internal/service/openai_codex_models_etag_test.go index 1a918a2125..24d507647f 100644 --- a/backend/internal/service/openai_codex_models_etag_test.go +++ b/backend/internal/service/openai_codex_models_etag_test.go @@ -158,3 +158,52 @@ func TestRecordCodexModelsManifestETagUsesEveryUpstreamSource(t *testing.T) { local := &OpenAIModelsResponse{ETag: `W/"local-only"`} require.Empty(t, local.upstreamCatalogETags()) } + +func TestCodexModelsETagRegistryTTLIsShort(t *testing.T) { + t.Parallel() + + require.Equal(t, 10*time.Minute, codexModelsETagRegistryTTL) + + now := time.Unix(1_800_000_000, 0) + registry := newCodexModelsETagRegistry(16, codexModelsETagRegistryTTL) + registry.record(7, []string{`"u"`}, `"served"`, now) + _, ok := registry.lookup(7, `"u"`, now.Add(9*time.Minute)) + require.True(t, ok) + _, ok = registry.lookup(7, `"u"`, now.Add(11*time.Minute)) + require.False(t, ok, "mappings past the TTL must not be used") +} + +func TestCodexModelsETagRegistryClearGroup(t *testing.T) { + t.Parallel() + + now := time.Unix(1_800_000_000, 0) + registry := newCodexModelsETagRegistry(16, time.Hour) + registry.record(7, []string{`"a"`, `"b"`}, `"served-7"`, now) + registry.record(8, []string{`"a"`}, `"served-8"`, now) + registry.clearGroup(7) + registry.clearGroup(0) + (*codexModelsETagRegistry)(nil).clearGroup(7) + + _, ok := registry.lookup(7, `"a"`, now) + require.False(t, ok) + _, ok = registry.lookup(7, `"b"`, now) + require.False(t, ok) + served, ok := registry.lookup(8, `"a"`, now) + require.True(t, ok) + require.Equal(t, `"served-8"`, served) +} + +func TestRecordCodexModelsManifestETagWithoutUpstreamClearsGroup(t *testing.T) { + t.Parallel() + + const groupID int64 = 77_002 + svc := &OpenAIGatewayService{} + svc.RecordCodexModelsManifestETag(groupID, &OpenAIModelsResponse{ETag: `W/"scheduled"`, upstreamETag: `W/"up"`}) + _, ok := codexModelsETags.lookup(groupID, `W/"up"`, time.Now()) + require.True(t, ok) + + // Group switched to the configuration branch: no upstream ETag. + svc.RecordCodexModelsManifestETag(groupID, &OpenAIModelsResponse{ETag: `W/"configured"`}) + _, ok = codexModelsETags.lookup(groupID, `W/"up"`, time.Now()) + require.False(t, ok, "stale mapping must be dropped") +} diff --git a/backend/internal/service/openai_codex_models_etag_ws_test.go b/backend/internal/service/openai_codex_models_etag_ws_test.go index c1eaecaec9..c2d560ea11 100644 --- a/backend/internal/service/openai_codex_models_etag_ws_test.go +++ b/backend/internal/service/openai_codex_models_etag_ws_test.go @@ -177,3 +177,22 @@ func TestCodexResponseMetadataUnknownModelsETagIsRemovedOverWebSocket(t *testing }) } } + +func TestCodexResponseMetadataETagNotRewrittenAfterConfiguredManifestOverWebSocket(t *testing.T) { + const groupID int64 = 96_031 + svc := &OpenAIGatewayService{} + svc.RecordCodexModelsManifestETag(groupID, &OpenAIModelsResponse{ + ETag: `W/"scheduled-manifest"`, + upstreamETag: `W/"upstream-catalog"`, + }) + // The group is now served from its configuration: no upstream ETag. + svc.RecordCodexModelsManifestETag(groupID, &OpenAIModelsResponse{ETag: `W/"configured-manifest"`}) + + events := runCodexMetadataWSTurn(t, false, groupID, [][]byte{ + []byte(`{"type":"codex.response.metadata","headers":{"x-models-etag":"W/\"upstream-catalog\"","x-codex-other":"kept"}}`), + []byte(`{"type":"response.completed","response":{"id":"resp_metadata_configured","model":"gpt-5.1","usage":{"input_tokens":1,"output_tokens":1}}}`), + }) + metadata := codexMetadataEvent(t, events) + require.False(t, gjson.GetBytes(metadata, "headers.x-models-etag").Exists()) + require.Equal(t, "kept", gjson.GetBytes(metadata, "headers.x-codex-other").String()) +} From 0dba88681bd983a64913e2452545743194d28f34 Mon Sep 17 00:00:00 2001 From: shaw Date: Wed, 2 Dec 2026 11:45:21 +0800 Subject: [PATCH 08/11] =?UTF-8?q?fix:=20hide=20create-account=20scheduling?= =?UTF-8?q?=20threshold=20unless=20submit=20writes=20it=20and=20reset=20it?= =?UTF-8?q?=20on=20close=EF=BC=88audit=20follow-up=20for=20#9135=EF=BC=89?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../components/account/CreateAccountModal.vue | 20 +++++++- .../__tests__/CreateAccountModal.spec.ts | 47 +++++++++++++++++++ 2 files changed, 65 insertions(+), 2 deletions(-) diff --git a/frontend/src/components/account/CreateAccountModal.vue b/frontend/src/components/account/CreateAccountModal.vue index 8478f2056c..f5ba3d6df8 100644 --- a/frontend/src/components/account/CreateAccountModal.vue +++ b/frontend/src/components/account/CreateAccountModal.vue @@ -4519,8 +4519,22 @@ const extraMultiProtocolPlatforms = computed(() => const ACCOUNT_SCHEDULING_THRESHOLD_CREDENTIAL_KEY = 'account_scheduling_threshold' const createSchedulingThresholdOverrideEnabled = ref(false) const createSchedulingThresholdOverrideValue = ref(100) -const supportsCreateSchedulingThresholdOverride = computed(() => - (SCHEDULING_THRESHOLD_PLATFORMS as readonly string[]).includes(form.platform) +// handleSubmit 中走到通用 apikey 创建分支的条件:其余分支(OAuth 流程、Bedrock、 +// Antigravity upstream、service_account)都会先行返回,不会写入阈值。 +const submitsViaGenericApiKeyPath = computed( + () => + !isOAuthFlow.value && + !(form.platform === 'anthropic' && accountCategory.value === 'bedrock') && + !(form.platform === 'antigravity' && antigravityAccountType.value === 'upstream') && + !( + (form.platform === 'gemini' || form.platform === 'anthropic') && + accountCategory.value === 'service_account' + ) +) +const supportsCreateSchedulingThresholdOverride = computed( + () => + (SCHEDULING_THRESHOLD_PLATFORMS as readonly string[]).includes(form.platform) && + submitsViaGenericApiKeyPath.value ) const genericAccountModes = computed(() => providerAccountModes(form.platform)) // 按模型分流的供应商(OpenCode 等):adaptive 账号携带 protocol_rules。 @@ -5748,6 +5762,8 @@ const resetForm = () => { upstreamRequestIdHeader.value = '' upstreamBillingAutoProbeEnabled.value = true upstreamGroupSyncEnabled.value = false + createSchedulingThresholdOverrideEnabled.value = false + createSchedulingThresholdOverrideValue.value = 100 editQuotaLimit.value = null editQuotaDailyLimit.value = null editQuotaWeeklyLimit.value = null diff --git a/frontend/src/components/account/__tests__/CreateAccountModal.spec.ts b/frontend/src/components/account/__tests__/CreateAccountModal.spec.ts index 0e30886822..9360bf518d 100644 --- a/frontend/src/components/account/__tests__/CreateAccountModal.spec.ts +++ b/frontend/src/components/account/__tests__/CreateAccountModal.spec.ts @@ -530,6 +530,53 @@ describe('CreateAccountModal OpenAI long-context billing', () => { expect(probeUpstreamBillingMock).not.toHaveBeenCalled() }) + describe('account scheduling threshold override', () => { + const toggleSelector = '[data-testid="create-account-scheduling-threshold"]' + const enabledSelector = '[data-testid="create-account-scheduling-threshold-enabled"]' + const valueSelector = '[data-testid="create-account-scheduling-threshold-value"]' + + it('is hidden for OAuth-based creation, which never writes the threshold', async () => { + const wrapper = mountModal() + await selectButtonByText(wrapper, 'OpenAI') + expect(wrapper.find(toggleSelector).exists()).toBe(false) + + await selectButtonByText(wrapper, 'API Key') + expect(wrapper.find(toggleSelector).exists()).toBe(true) + }) + + it('writes the threshold into credentials for API key accounts', async () => { + const wrapper = mountModal() + await selectButtonByText(wrapper, 'OpenAI') + await selectButtonByText(wrapper, 'API Key') + await wrapper.get(enabledSelector).setValue(true) + await wrapper.get(valueSelector).setValue(80) + await wrapper.get('form#create-account-form input[type="text"]').setValue('threshold account') + await wrapper.get('form#create-account-form input[type="password"]').setValue('test-api-key') + await wrapper.get('form#create-account-form').trigger('submit.prevent') + await flushPromises() + + expect(createAccountMock).toHaveBeenCalledTimes(1) + expect(createAccountMock.mock.calls[0]?.[0]?.credentials?.account_scheduling_threshold).toBe(80) + }) + + it('does not carry the previous value over to the next created account', async () => { + const wrapper = mountModal() + await selectButtonByText(wrapper, 'OpenAI') + await selectButtonByText(wrapper, 'API Key') + await wrapper.get(enabledSelector).setValue(true) + await wrapper.get(valueSelector).setValue(80) + + await wrapper.setProps({ show: false }) + await wrapper.setProps({ show: true }) + await selectButtonByText(wrapper, 'OpenAI') + await selectButtonByText(wrapper, 'API Key') + + expect((wrapper.get(enabledSelector).element as HTMLInputElement).checked).toBe(false) + await wrapper.get(enabledSelector).setValue(true) + expect((wrapper.get(valueSelector).element as HTMLInputElement).value).toBe('100') + }) + }) + it('submits OpenCode Zen default protocol rules with adaptive endpoints', async () => { const wrapper = mountModal() await selectButtonByText(wrapper, 'OpenCode') From 9e63d8b986d58e0d451c243b4c5a5e43572053cc Mon Sep 17 00:00:00 2001 From: shaw Date: Wed, 2 Dec 2026 11:48:59 +0800 Subject: [PATCH 09/11] =?UTF-8?q?fix:=20=E9=9D=9E=E7=BB=AD=E6=8E=A5?= =?UTF-8?q?=E6=9C=AA=E7=BC=93=E5=AD=98=E8=BD=AE=E4=BF=9D=E7=95=99=20failov?= =?UTF-8?q?er=20=E8=BE=93=E5=85=A5=E5=B9=B6=E5=8E=BB=E9=87=8D=E5=85=B1?= =?UTF-8?q?=E4=BA=AB=E5=8E=86=E5=8F=B2=E5=AD=97=E8=8A=82=EF=BC=88audit=20f?= =?UTF-8?q?ollow-up=20for=20#9203=EF=BC=89?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../service/openai_ws_forwarder_ingress.go | 20 ++- .../service/openai_ws_http_bridge_history.go | 25 +++ .../openai_ws_http_bridge_history_test.go | 168 ++++++++++++++++++ 3 files changed, 209 insertions(+), 4 deletions(-) diff --git a/backend/internal/service/openai_ws_forwarder_ingress.go b/backend/internal/service/openai_ws_forwarder_ingress.go index 267cb40b48..b9e5c36055 100644 --- a/backend/internal/service/openai_ws_forwarder_ingress.go +++ b/backend/internal/service/openai_ws_forwarder_ingress.go @@ -647,12 +647,15 @@ func (s *OpenAIGatewayService) ProxyResponsesWebSocketFromClient( } var turnReplayInput, turnAccountFailoverInput []json.RawMessage var turnReplayInputExists, turnAccountFailoverInputExists bool + var turnItems []json.RawMessage + var turnItemsExists, turnItemsParsed bool cacheTurn := ResponsesWSBridgeReplayInputFits(currentBridgePayload.payloadRaw, ResponsesWSBridgeHistoryLimit) if cacheTurn { items, exists, extractErr := openAIWSExtractNormalizedInputSequence(currentBridgePayload.payloadRaw) if extractErr != nil { return fmt.Errorf("build websocket http bridge replay input: %w", extractErr) } + turnItems, turnItemsExists, turnItemsParsed = items, exists, true cacheTurn = history.reserve(ResponsesWSBridgeReplayItemsBytes(items)) if cacheTurn { items = CloneResponsesWSBridgeReplayItems(items) @@ -662,7 +665,7 @@ func (s *OpenAIGatewayService) ProxyResponsesWebSocketFromClient( turnAccountFailoverInput, turnAccountFailoverInputExists = buildOpenAIWSReplayInputSequenceFromItems( bridgeAccountFailoverInput, bridgeAccountFailoverInputExists, items, exists, needsBridgeReplay, ) - turnBytes := ResponsesWSBridgeReplayItemsBytes(turnReplayInput) + ResponsesWSBridgeReplayItemsBytes(turnAccountFailoverInput) + turnBytes := ResponsesWSBridgeReplayUnionBytes(turnReplayInput, turnAccountFailoverInput) cacheTurn = history.resize(turnBytes) } } else { @@ -672,9 +675,18 @@ func (s *OpenAIGatewayService) ProxyResponsesWebSocketFromClient( if needsBridgeReplay { return NewResponsesWSBridgeHistoryCloseError() } - turnReplayInput, turnAccountFailoverInput = nil, nil - turnReplayInputExists, turnAccountFailoverInputExists = false, false + turnReplayInput, turnReplayInputExists = nil, false history.resize(0) + // 本轮不进入历史,但独立请求仍须能跨账号重试:failover 输入仅在本轮 + // 生命周期内引用(回合结束即随 historyLost 丢弃),不占用历史预算。 + if !turnItemsParsed { + items, exists, extractErr := openAIWSExtractNormalizedInputSequence(currentBridgePayload.payloadRaw) + if extractErr != nil { + return fmt.Errorf("build websocket http bridge failover input: %w", extractErr) + } + turnItems, turnItemsExists = items, exists + } + turnAccountFailoverInput, turnAccountFailoverInputExists = turnItems, turnItemsExists } if needsBridgeReplay && turnReplayInputExists { updatedPayload, setInputErr := setOpenAIWSPayloadInputSequence( @@ -785,7 +797,7 @@ func (s *OpenAIGatewayService) ProxyResponsesWebSocketFromClient( ) bridgeAccountFailoverInputExists = true } - history.resize(ResponsesWSBridgeReplayItemsBytes(bridgeReplayInput) + ResponsesWSBridgeReplayItemsBytes(bridgeAccountFailoverInput)) + history.resize(ResponsesWSBridgeReplayUnionBytes(bridgeReplayInput, bridgeAccountFailoverInput)) } history.budget.LogSize(openAIWSLegacyBridgeHistoryPath) if bridgeTurnState := strings.TrimSpace(result.ResponseHeaders.Get(openAIWSTurnStateHeader)); bridgeTurnState != "" { diff --git a/backend/internal/service/openai_ws_http_bridge_history.go b/backend/internal/service/openai_ws_http_bridge_history.go index 23b791254e..7aceca5371 100644 --- a/backend/internal/service/openai_ws_http_bridge_history.go +++ b/backend/internal/service/openai_ws_http_bridge_history.go @@ -105,6 +105,31 @@ func ResponsesWSBridgeReplayItemsBytes(items []json.RawMessage) int { return size } +// ResponsesWSBridgeReplayUnionBytes measures two replay sequences that may share +// item bodies. Identical sequences count once; otherwise each sequence pays for +// its own slice entries but a body referenced by both is counted once. +func ResponsesWSBridgeReplayUnionBytes(a, b []json.RawMessage) int { + if len(a) == len(b) && (len(a) == 0 || &a[0] == &b[0]) { + return ResponsesWSBridgeReplayItemsBytes(a) + } + seen := make(map[*byte]struct{}, len(a)) + for _, item := range a { + if len(item) > 0 { + seen[&item[0]] = struct{}{} + } + } + size := ResponsesWSBridgeReplayItemsBytes(a) + len(b)*responsesWSBridgeHistoryItemOverhead + for _, item := range b { + if len(item) == 0 { + continue + } + if _, shared := seen[&item[0]]; !shared { + size += len(item) + } + } + return size +} + // CloneResponsesWSBridgeReplayItems gives replay items their own backing bytes // so retaining an item cannot keep an entire client frame alive. func CloneResponsesWSBridgeReplayItems(items []json.RawMessage) []json.RawMessage { diff --git a/backend/internal/service/openai_ws_http_bridge_history_test.go b/backend/internal/service/openai_ws_http_bridge_history_test.go index 5019751ff9..0376a8d710 100644 --- a/backend/internal/service/openai_ws_http_bridge_history_test.go +++ b/backend/internal/service/openai_ws_http_bridge_history_test.go @@ -4,6 +4,7 @@ package service import ( "context" + "encoding/json" "errors" "fmt" "io" @@ -162,3 +163,170 @@ func TestOpenAIWSHTTPBridgeHistoryOverLimitReconnectsWithFullInput(t *testing.T) }) } } + +func bridgeHistoryTestResponse(status int, body string) *http.Response { + contentType := "text/event-stream" + if status != http.StatusOK { + contentType = "application/json" + } + return &http.Response{ + StatusCode: status, + Header: http.Header{"Content-Type": {contentType}}, + Body: io.NopCloser(strings.NewReader(body)), + } +} + +func bridgeHistoryTestCompleted(id string) string { + return fmt.Sprintf("data: {\"type\":\"response.completed\",\"response\":{\"id\":%q,\"output\":[]}}\n\n", id) +} + +func TestResponsesWSBridgeReplayUnionBytes(t *testing.T) { + shared := []json.RawMessage{json.RawMessage(`{"a":1}`), json.RawMessage(`{"b":2}`)} + require.Equal(t, ResponsesWSBridgeReplayItemsBytes(shared), ResponsesWSBridgeReplayUnionBytes(shared, shared)) + require.Zero(t, ResponsesWSBridgeReplayUnionBytes(nil, nil)) + + extended := append(append([]json.RawMessage(nil), shared...), json.RawMessage(`{"c":3}`)) + want := ResponsesWSBridgeReplayItemsBytes(extended) + len(shared)*responsesWSBridgeHistoryItemOverhead + require.Equal(t, want, ResponsesWSBridgeReplayUnionBytes(extended, shared)) + + distinct := []json.RawMessage{json.RawMessage(`{"a":1}`)} + require.Equal(t, ResponsesWSBridgeReplayItemsBytes(shared)+ResponsesWSBridgeReplayItemsBytes(distinct), + ResponsesWSBridgeReplayUnionBytes(shared, distinct)) +} + +// An independent turn that is not retained in history must still be able to +// fail over to another account with the current turn's input. +func TestOpenAIWSHTTPBridgeUncachedIndependentTurnKeepsFailoverRetryPayload(t *testing.T) { + const free = 1000 + connHistory := &ResponsesWSBridgeHistory{} + require.True(t, connHistory.TryReserve(ResponsesWSBridgeHistoryLimit-free)) + t.Cleanup(func() { connHistory.Release(ResponsesWSBridgeHistoryLimit - free) }) + processBytes := sharedResponsesWSBridgeHistory.bytes.Load() + + upstream := &httpUpstreamRecorder{responses: []*http.Response{ + bridgeHistoryTestResponse(http.StatusOK, bridgeHistoryTestCompleted("resp_first")), + bridgeHistoryTestResponse(http.StatusTooManyRequests, `{"error":{"message":"rate limited"}}`), + }} + svc := &OpenAIGatewayService{cfg: &config.Config{}, httpUpstream: upstream} + account := &Account{ + ID: 72, Platform: PlatformGrok, Type: AccountTypeOAuth, + Credentials: map[string]any{"base_url": xai.DefaultCLIBaseURL}, + } + + done := make(chan error, 1) + wsServer := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + conn, err := coderws.Accept(w, r, nil) + if err != nil { + done <- err + return + } + defer func() { _ = conn.CloseNow() }() + _, firstMessage, err := conn.Read(r.Context()) + if err != nil { + done <- err + return + } + ginCtx, _ := gin.CreateTestContext(httptest.NewRecorder()) + ginCtx.Request = r + hooks := &OpenAIWSIngressHooks{BridgeHistory: connHistory} + done <- svc.ProxyResponsesWebSocketFromClient(r.Context(), ginCtx, conn, account, "access-token", firstMessage, hooks) + })) + defer wsServer.Close() + + ctx, cancel := context.WithTimeout(t.Context(), 5*time.Second) + defer cancel() + client, _, err := coderws.Dial(ctx, "ws"+strings.TrimPrefix(wsServer.URL, "http"), nil) + require.NoError(t, err) + t.Cleanup(func() { _ = client.CloseNow() }) + + require.NoError(t, client.Write(ctx, coderws.MessageText, []byte(`{"type":"response.create","model":"grok","input":"first"}`))) + _, frame, err := client.Read(ctx) + require.NoError(t, err) + require.Equal(t, "resp_first", gjson.GetBytes(frame, "response.id").String()) + + // Larger than the remaining connection budget: this turn is not cached. + big := strings.Repeat("y", 4*free) + require.NoError(t, client.Write(ctx, coderws.MessageText, + []byte(fmt.Sprintf(`{"type":"response.create","model":"grok","input":[{"type":"message","role":"user","content":%q}]}`, big)))) + + var runErr error + select { + case runErr = <-done: + case <-ctx.Done(): + t.Fatal("timed out waiting for bridge to return") + } + var failoverErr *UpstreamFailoverError + require.ErrorAs(t, runErr, &failoverErr) + retryPayload, ok := OpenAIWSCurrentTurnRetryPayload(runErr) + require.True(t, ok) + require.NotEmpty(t, retryPayload, "uncached independent turn must remain retryable on another account") + require.Equal(t, big, gjson.GetBytes(retryPayload, "input.0.content").String()) + require.False(t, gjson.GetBytes(retryPayload, "previous_response_id").Exists()) + require.Equal(t, processBytes, sharedResponsesWSBridgeHistory.bytes.Load()) +} + +// Replay and account-failover sequences share item bodies, so a single frame +// between limit/2 and limit must still be cacheable for a follow-up turn. +func TestOpenAIWSHTTPBridgeSharedItemsCountedOnceForLargeFrame(t *testing.T) { + processBytes := sharedResponsesWSBridgeHistory.bytes.Load() + upstream := &httpUpstreamRecorder{responses: []*http.Response{ + bridgeHistoryTestResponse(http.StatusOK, bridgeHistoryTestCompleted("resp_first")), + bridgeHistoryTestResponse(http.StatusOK, bridgeHistoryTestCompleted("resp_second")), + }} + svc := &OpenAIGatewayService{cfg: &config.Config{}, httpUpstream: upstream} + account := &Account{ + ID: 73, Platform: PlatformGrok, Type: AccountTypeOAuth, + Credentials: map[string]any{"base_url": xai.DefaultCLIBaseURL}, + } + + // Between limit/2 and limit, so counting the shared items twice would overflow. + bigSize := ResponsesWSBridgeHistoryLimit * 5 / 8 + big := strings.Repeat("z", bigSize) + + done := make(chan error, 1) + wsServer := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + conn, err := coderws.Accept(w, r, nil) + if err != nil { + done <- err + return + } + defer func() { _ = conn.CloseNow() }() + conn.SetReadLimit(int64(bigSize) + 4096) + _, firstMessage, err := conn.Read(r.Context()) + if err != nil { + done <- err + return + } + ginCtx, _ := gin.CreateTestContext(httptest.NewRecorder()) + ginCtx.Request = r + done <- svc.ProxyResponsesWebSocketFromClient(r.Context(), ginCtx, conn, account, "access-token", firstMessage, nil) + })) + defer wsServer.Close() + + ctx, cancel := context.WithTimeout(t.Context(), 30*time.Second) + defer cancel() + client, _, err := coderws.Dial(ctx, "ws"+strings.TrimPrefix(wsServer.URL, "http"), nil) + require.NoError(t, err) + t.Cleanup(func() { _ = client.CloseNow() }) + client.SetReadLimit(1 << 20) + + read := func(id string) { + _, frame, readErr := client.Read(ctx) + require.NoError(t, readErr) + require.Equal(t, id, gjson.GetBytes(frame, "response.id").String()) + } + require.NoError(t, client.Write(ctx, coderws.MessageText, + []byte(fmt.Sprintf(`{"type":"response.create","model":"grok","input":[{"type":"message","role":"user","content":%q}]}`, big)))) + read("resp_first") + require.Greater(t, sharedResponsesWSBridgeHistory.bytes.Load()-processBytes, int64(bigSize)) + require.Less(t, sharedResponsesWSBridgeHistory.bytes.Load()-processBytes, int64(ResponsesWSBridgeHistoryLimit)) + + require.NoError(t, client.Write(ctx, coderws.MessageText, + []byte(`{"type":"response.create","model":"grok","previous_response_id":"resp_first","input":"next"}`))) + read("resp_second") + require.Len(t, upstream.requests, 2) + + require.NoError(t, client.Close(coderws.StatusNormalClosure, "")) + require.NoError(t, <-done) + require.Equal(t, processBytes, sharedResponsesWSBridgeHistory.bytes.Load()) +} From 71436d44cc67104522b90a5e079a74e16167321b Mon Sep 17 00:00:00 2001 From: shaw Date: Wed, 2 Dec 2026 11:50:32 +0800 Subject: [PATCH 10/11] =?UTF-8?q?fix:=20keep=20existing=20400=20classifica?= =?UTF-8?q?tion=20before=20alpha=20search=20API-key=20failover=EF=BC=88aud?= =?UTF-8?q?it=20follow-up=20for=20#9149=EF=BC=89?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../internal/service/openai_alpha_search.go | 33 ++++--- .../service/openai_alpha_search_test.go | 85 ++++++++++++++++++- 2 files changed, 107 insertions(+), 11 deletions(-) diff --git a/backend/internal/service/openai_alpha_search.go b/backend/internal/service/openai_alpha_search.go index 1b1b3e7834..aa55cc2a2e 100644 --- a/backend/internal/service/openai_alpha_search.go +++ b/backend/internal/service/openai_alpha_search.go @@ -91,16 +91,6 @@ 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) || @@ -126,6 +116,20 @@ func (s *OpenAIGatewayService) ForwardAlphaSearch(ctx context.Context, c *gin.Co } } + // API key 中转可能只拒绝独立搜索端点。上面的既有分类(访问状态、transient + // 等)保持原有副作用;其余会被直接透传的 400,除 cyber_policy 与上下文 + // 窗口超限这类请求级错误外,直接换号,不重试同一账号,也不把这次 400 + // 计入账号健康;耗尽时仍透传最后一次上游响应。 + if account.Type == AccountTypeAPIKey && resp.StatusCode == http.StatusBadRequest && + !isOpenAIAlphaSearchRequestScoped400(sanitizeUpstreamErrorMessage(strings.TrimSpace(extractUpstreamErrorMessage(respBody))), respBody) { + return nil, &UpstreamFailoverError{ + StatusCode: resp.StatusCode, + ResponseBody: respBody, + ResponseHeaders: resp.Header, + Reason: OpenAIAlphaSearchRejectedReason, + } + } + if !account.IsShadow() { s.UpdateCodexUsageSnapshotFromHeaders(ctx, account.ID, resp.Header) } @@ -557,6 +561,15 @@ func isOpenAIAlphaSearchEndpointUnsupported(account *Account, statusCode int) bo return statusCode == http.StatusNotFound || statusCode == http.StatusMethodNotAllowed } +// isOpenAIAlphaSearchRequestScoped400 reports 400s that blame the request rather +// than the account/endpoint, which main passes through without rotating. +func isOpenAIAlphaSearchRequestScoped400(upstreamMessage string, responseBody []byte) bool { + if hit, _, _ := detectOpenAICyberPolicy(responseBody); hit { + return true + } + return isOpenAIContextWindowError(upstreamMessage, responseBody) +} + func shouldApplyOpenAIAlphaSearchAccountErrorSideEffects(statusCode int, upstreamMessage string, responseBody []byte) bool { switch statusCode { case http.StatusUnauthorized, http.StatusNotFound, http.StatusMethodNotAllowed: diff --git a/backend/internal/service/openai_alpha_search_test.go b/backend/internal/service/openai_alpha_search_test.go index 64199e617b..ffc6bb1104 100644 --- a/backend/internal/service/openai_alpha_search_test.go +++ b/backend/internal/service/openai_alpha_search_test.go @@ -252,7 +252,7 @@ func TestForwardAlphaSearchAPIKeyMapsModelAndFailsOverOnBadRequest(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":"organization has been disabled"}}` + upstreamBody := `{"error":{"type":"invalid_request_error","message":"search command is not supported by this relay"}}` upstream := &httpUpstreamRecorder{resp: &http.Response{ StatusCode: http.StatusBadRequest, Header: http.Header{"Content-Type": []string{"application/json"}}, @@ -759,3 +759,86 @@ func TestIsOpenAIAlphaSearchEndpointUnsupported(t *testing.T) { require.False(t, isOpenAIAlphaSearchEndpointUnsupported(oauth, http.StatusNotFound)) require.False(t, isOpenAIAlphaSearchEndpointUnsupported(nil, http.StatusNotFound)) } + +func newAlphaSearchAPIKeyBadRequestFixture(t *testing.T, upstreamBody string) (*OpenAIGatewayService, *alphaSearchAccountStateRepo, *Account, *gin.Context, *httptest.ResponseRecorder, []byte) { + t.Helper() + gin.SetMode(gin.TestMode) + body := []byte(`{"id":"search-session","model":"gpt-5.6-sol","commands":{"search_query":[{"q":"news"}]}}`) + recorder := httptest.NewRecorder() + c, _ := gin.CreateTestContext(recorder) + c.Request = httptest.NewRequest(http.MethodPost, "/alpha/search", bytes.NewReader(body)) + c.Request.Header.Set("Content-Type", "application/json") + upstream := &httpUpstreamRecorder{resp: &http.Response{ + StatusCode: http.StatusBadRequest, + Header: http.Header{"Content-Type": []string{"application/json"}}, + Body: io.NopCloser(strings.NewReader(upstreamBody)), + }} + repo := &alphaSearchAccountStateRepo{} + cfg := &config.Config{} + svc := &OpenAIGatewayService{ + cfg: cfg, httpUpstream: upstream, accountRepo: repo, + rateLimitService: NewRateLimitService(repo, nil, cfg, nil, nil), + } + account := &Account{ + ID: 7, + Platform: PlatformOpenAI, + Type: AccountTypeAPIKey, + Credentials: map[string]any{ + "api_key": "sk-test", + "base_url": "https://compat.example/v4", + }, + } + return svc, repo, account, c, recorder, body +} + +func TestForwardAlphaSearchAPIKeyBadRequestAccessStateKeepsMainSideEffects(t *testing.T) { + upstreamBody := `{"error":{"code":"organization_disabled","message":"Organization has been disabled"}}` + svc, repo, account, c, _, body := newAlphaSearchAPIKeyBadRequestFixture(t, upstreamBody) + + result, err := svc.ForwardAlphaSearch(context.Background(), c, account, body) + + var failoverErr *UpstreamFailoverError + require.ErrorAs(t, err, &failoverErr) + require.Nil(t, result) + require.NotEqual(t, OpenAIAlphaSearchRejectedReason, failoverErr.Reason, "access-state 400 must stay on the existing classification") + require.Equal(t, 1, repo.setErrorCalls, "access-state 400 must still mark the account as in main") + require.False(t, c.Writer.Written()) +} + +func TestForwardAlphaSearchAPIKeyBadRequestRequestScopedPassesThrough(t *testing.T) { + tests := []struct { + name string + body string + }{ + {"cyber_policy", `{"error":{"code":"cyber_policy","message":"blocked by cyber policy"}}`}, + {"context window exceeded", `{"error":{"code":"context_length_exceeded","message":"Your input exceeds the context window of this model"}}`}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + svc, repo, account, c, recorder, body := newAlphaSearchAPIKeyBadRequestFixture(t, tt.body) + + result, err := svc.ForwardAlphaSearch(context.Background(), c, account, body) + + require.NoError(t, err, "request-scoped 400 must not rotate accounts") + require.Nil(t, result) + require.Equal(t, http.StatusBadRequest, recorder.Code) + require.JSONEq(t, tt.body, recorder.Body.String()) + require.Zero(t, repo.setErrorCalls) + }) + } +} + +func TestForwardAlphaSearchAPIKeyBadRequestUnrecognizedFailsOverWithoutAccountState(t *testing.T) { + upstreamBody := `{"error":{"code":"unsupported_endpoint","message":"alpha search is not available"}}` + svc, repo, account, c, _, body := newAlphaSearchAPIKeyBadRequestFixture(t, upstreamBody) + + result, err := svc.ForwardAlphaSearch(context.Background(), c, account, body) + + var failoverErr *UpstreamFailoverError + require.ErrorAs(t, err, &failoverErr) + require.Nil(t, result) + require.Equal(t, OpenAIAlphaSearchRejectedReason, failoverErr.Reason) + require.Equal(t, upstreamBody, string(failoverErr.ResponseBody)) + require.Zero(t, repo.setErrorCalls) + require.False(t, c.Writer.Written()) +} From 293428484457b93727a6d3a0eb00a0156979973b Mon Sep 17 00:00:00 2001 From: shaw Date: Wed, 2 Dec 2026 12:04:31 +0800 Subject: [PATCH 11/11] =?UTF-8?q?fix:=20drop=20bridge=20history=20when=20e?= =?UTF-8?q?nd-of-turn=20resize=20does=20not=20fit=EF=BC=88audit=20follow-u?= =?UTF-8?q?p=20for=20#9203=EF=BC=89?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Retaining a turn can need more budget than the turn held because the replay and failover sequences get separate header arrays. When that growth does not fit, drop the history instead of keeping it under-accounted. Count a shared body only when both pointer and length match, and skip the common prefix by index so the lookup set covers only the diverging tail. --- .../service/openai_ws_forwarder_ingress.go | 9 +- .../service/openai_ws_http_bridge_history.go | 28 ++++-- .../openai_ws_http_bridge_history_test.go | 96 +++++++++++++++++++ 3 files changed, 126 insertions(+), 7 deletions(-) diff --git a/backend/internal/service/openai_ws_forwarder_ingress.go b/backend/internal/service/openai_ws_forwarder_ingress.go index b9e5c36055..fc2d5e188c 100644 --- a/backend/internal/service/openai_ws_forwarder_ingress.go +++ b/backend/internal/service/openai_ws_forwarder_ingress.go @@ -797,7 +797,14 @@ func (s *OpenAIGatewayService) ProxyResponsesWebSocketFromClient( ) bridgeAccountFailoverInputExists = true } - history.resize(ResponsesWSBridgeReplayUnionBytes(bridgeReplayInput, bridgeAccountFailoverInput)) + if !history.resize(ResponsesWSBridgeReplayUnionBytes(bridgeReplayInput, bridgeAccountFailoverInput)) { + // 保存的历史超出可用预算时整体丢弃,保证持有预算始终覆盖已保留的历史; + // 后续续接回合将按 historyLost 以 1013 要求客户端重发完整输入。 + historyLost = true + bridgeReplayInput, bridgeAccountFailoverInput = nil, nil + bridgeReplayInputExists, bridgeAccountFailoverInputExists = false, false + history.resize(0) + } } history.budget.LogSize(openAIWSLegacyBridgeHistoryPath) if bridgeTurnState := strings.TrimSpace(result.ResponseHeaders.Get(openAIWSTurnStateHeader)); bridgeTurnState != "" { diff --git a/backend/internal/service/openai_ws_http_bridge_history.go b/backend/internal/service/openai_ws_http_bridge_history.go index 7aceca5371..259ed74556 100644 --- a/backend/internal/service/openai_ws_http_bridge_history.go +++ b/backend/internal/service/openai_ws_http_bridge_history.go @@ -112,24 +112,40 @@ func ResponsesWSBridgeReplayUnionBytes(a, b []json.RawMessage) int { if len(a) == len(b) && (len(a) == 0 || &a[0] == &b[0]) { return ResponsesWSBridgeReplayItemsBytes(a) } - seen := make(map[*byte]struct{}, len(a)) - for _, item := range a { + size := ResponsesWSBridgeReplayItemsBytes(a) + len(b)*responsesWSBridgeHistoryItemOverhead + // The sequences usually share a leading run of bodies; walk it by index so + // the lookup set only covers the diverging tail. A body shared outside the + // tails is counted twice, which over-estimates and stays within budget. + prefix := 0 + for prefix < len(a) && prefix < len(b) && sameResponsesWSBridgeReplayBody(a[prefix], b[prefix]) { + prefix++ + } + seen := make(map[*byte]int, len(a)-prefix) + for _, item := range a[prefix:] { if len(item) > 0 { - seen[&item[0]] = struct{}{} + seen[&item[0]] = len(item) } } - size := ResponsesWSBridgeReplayItemsBytes(a) + len(b)*responsesWSBridgeHistoryItemOverhead - for _, item := range b { + for _, item := range b[prefix:] { if len(item) == 0 { continue } - if _, shared := seen[&item[0]]; !shared { + if seenLen, shared := seen[&item[0]]; !shared || seenLen != len(item) { size += len(item) } } return size } +// sameResponsesWSBridgeReplayBody reports whether two items are the same +// retained body, not merely equal bytes. +func sameResponsesWSBridgeReplayBody(a, b json.RawMessage) bool { + if len(a) != len(b) { + return false + } + return len(a) == 0 || &a[0] == &b[0] +} + // CloneResponsesWSBridgeReplayItems gives replay items their own backing bytes // so retaining an item cannot keep an entire client frame alive. func CloneResponsesWSBridgeReplayItems(items []json.RawMessage) []json.RawMessage { diff --git a/backend/internal/service/openai_ws_http_bridge_history_test.go b/backend/internal/service/openai_ws_http_bridge_history_test.go index 0376a8d710..2ed62b0a0a 100644 --- a/backend/internal/service/openai_ws_http_bridge_history_test.go +++ b/backend/internal/service/openai_ws_http_bridge_history_test.go @@ -330,3 +330,99 @@ func TestOpenAIWSHTTPBridgeSharedItemsCountedOnceForLargeFrame(t *testing.T) { require.NoError(t, <-done) require.Equal(t, processBytes, sharedResponsesWSBridgeHistory.bytes.Load()) } + +func TestResponsesWSBridgeReplayUnionBytesPrefixAndAliases(t *testing.T) { + head := []json.RawMessage{json.RawMessage(`{"a":1}`), json.RawMessage(`{"b":2}`)} + replay := append(append([]json.RawMessage(nil), head...), json.RawMessage(`{"r":1}`)) + failover := append(append([]json.RawMessage(nil), head...), json.RawMessage(`{"f":1}`)) + want := ResponsesWSBridgeReplayItemsBytes(replay) + len(failover)*responsesWSBridgeHistoryItemOverhead + len(`{"f":1}`) + require.Equal(t, want, ResponsesWSBridgeReplayUnionBytes(replay, failover)) + + // A shorter view of the same backing bytes is a different body and must not + // be treated as already counted. + body := json.RawMessage(`{"long":"value"}`) + view := body[:7] + require.Equal(t, + ResponsesWSBridgeReplayItemsBytes([]json.RawMessage{body})+ResponsesWSBridgeReplayItemsBytes([]json.RawMessage{view}), + ResponsesWSBridgeReplayUnionBytes([]json.RawMessage{body}, []json.RawMessage{view})) +} + +// Retaining a turn can need more budget than the turn held (each sequence gets +// its own header array). When that growth does not fit, the history must be +// dropped instead of being kept under-accounted. +func TestOpenAIWSHTTPBridgeEndOfTurnResizeFailureDropsHistory(t *testing.T) { + const n = 200 + itemRaw := `{"type":"message","role":"user","content":"x"}` + items := make([]string, n) + for i := range items { + items[i] = itemRaw + } + outItem := `{"type":"message","id":"m1","role":"assistant","content":[]}` + itemsBytes := n * (len(itemRaw) + responsesWSBridgeHistoryItemOverhead) + collector := len(outItem) + responsesWSBridgeHistoryItemOverhead + len("m1") + free := itemsBytes + collector + 100 + + conn := &ResponsesWSBridgeHistory{} + pre := ResponsesWSBridgeHistoryLimit - free + require.True(t, conn.TryReserve(pre)) + t.Cleanup(func() { conn.Release(pre) }) + processBytes := sharedResponsesWSBridgeHistory.bytes.Load() + + heldAtTurn2 := -1 + hooks := &OpenAIWSIngressHooks{BridgeHistory: conn, BeforeTurn: func(turn int) error { + if turn == 2 { + heldAtTurn2 = conn.bytes - pre + } + return nil + }} + upstream := &httpUpstreamRecorder{responses: []*http.Response{ + bridgeHistoryTestResponse(http.StatusOK, fmt.Sprintf( + "data: {\"type\":\"response.completed\",\"response\":{\"id\":\"resp_first\",\"output\":[%s]}}\n\n", outItem)), + bridgeHistoryTestResponse(http.StatusOK, bridgeHistoryTestCompleted("resp_second")), + }} + svc := &OpenAIGatewayService{cfg: &config.Config{}, httpUpstream: upstream} + account := &Account{ + ID: 74, Platform: PlatformGrok, Type: AccountTypeOAuth, + Credentials: map[string]any{"base_url": xai.DefaultCLIBaseURL}, + } + done := make(chan error, 1) + wsServer := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + wsConn, err := coderws.Accept(w, r, nil) + if err != nil { + done <- err + return + } + defer func() { _ = wsConn.CloseNow() }() + _, firstMessage, err := wsConn.Read(r.Context()) + if err != nil { + done <- err + return + } + ginCtx, _ := gin.CreateTestContext(httptest.NewRecorder()) + ginCtx.Request = r + done <- svc.ProxyResponsesWebSocketFromClient(r.Context(), ginCtx, wsConn, account, "access-token", firstMessage, hooks) + })) + defer wsServer.Close() + + ctx, cancel := context.WithTimeout(t.Context(), 10*time.Second) + defer cancel() + client, _, err := coderws.Dial(ctx, "ws"+strings.TrimPrefix(wsServer.URL, "http"), nil) + require.NoError(t, err) + t.Cleanup(func() { _ = client.CloseNow() }) + + require.NoError(t, client.Write(ctx, coderws.MessageText, + []byte(`{"type":"response.create","model":"grok","input":[`+strings.Join(items, ",")+`]}`))) + _, frame, err := client.Read(ctx) + require.NoError(t, err) + require.Equal(t, "resp_first", gjson.GetBytes(frame, "response.id").String()) + + require.NoError(t, client.Write(ctx, coderws.MessageText, + []byte(`{"type":"response.create","model":"grok","previous_response_id":"resp_first","input":"next"}`))) + runErr := <-done + require.Zero(t, heldAtTurn2, "history that does not fit must be released, not kept under-accounted") + var closeErr *OpenAIWSClientCloseError + require.True(t, errors.As(runErr, &closeErr)) + require.Equal(t, coderws.StatusTryAgainLater, closeErr.StatusCode()) + require.Len(t, upstream.requests, 1) + require.Equal(t, processBytes, sharedResponsesWSBridgeHistory.bytes.Load()) +}