From 5f12044f59d6cc317f9bf64861fc023c02620434 Mon Sep 17 00:00:00 2001 From: Anankke Date: Mon, 16 Nov 2026 01:29:16 -0800 Subject: [PATCH 01/23] fix(accounts): refetch Claude and Gemini usage cells when auto-refresh updates a row With auto-refresh on, the accounts page replaces a row only when OpenAI or Grok usage inputs change, and AccountUsageCell watches only the OpenAI usage key, so Claude OAuth, setup-token and Gemini bars stay at what they loaded until the refresh button is clicked. Add usage refresh keys for Claude (session window columns, passive samples in extra, last_used_at) and Gemini (updated_at, last_used_at), replace a row when either changes, and have the cell watch one key across the three platforms. A change asks the batch loader for a forced refetch, or outside batch mode drops the cached entry and reloads, passive for Claude. Both backend paths read local data only, so a refetch per changed row sends no upstream request. --- .../components/account/AccountUsageCell.vue | 18 +- .../AccountUsageCell.usageRefresh.spec.ts | 174 ++++++++++++++++++ .../__tests__/accountUsageRefresh.spec.ts | 80 +++++++- frontend/src/utils/accountUsageRefresh.ts | 37 ++++ frontend/src/views/admin/AccountsView.vue | 3 + .../admin/__tests__/AccountsView.lite.spec.ts | 56 +++++- 6 files changed, 361 insertions(+), 7 deletions(-) create mode 100644 frontend/src/components/account/__tests__/AccountUsageCell.usageRefresh.spec.ts diff --git a/frontend/src/components/account/AccountUsageCell.vue b/frontend/src/components/account/AccountUsageCell.vue index 8ccc433706..e243f4b060 100644 --- a/frontend/src/components/account/AccountUsageCell.vue +++ b/frontend/src/components/account/AccountUsageCell.vue @@ -751,7 +751,11 @@ import { ref, computed, onMounted, onBeforeUnmount, onUnmounted, watch } from 'v import { useI18n } from 'vue-i18n' import { adminAPI } from '@/api/admin' import type { Account, AccountUsageInfo, GeminiCredentials, WindowStats } from '@/types' -import { buildOpenAIUsageRefreshKey } from '@/utils/accountUsageRefresh' +import { + buildAnthropicUsageRefreshKey, + buildGeminiUsageRefreshKey, + buildOpenAIUsageRefreshKey +} from '@/utils/accountUsageRefresh' import { enqueueUsageRequest } from '@/utils/usageLoadQueue' import { formatCompactNumber } from '@/utils/format' import { isOfficialGeminiBaseUrl } from '@/utils/geminiExplicitCache' @@ -917,7 +921,12 @@ const openAISevenDayEstimatedTotalCost = computed(() => { return Number.isFinite(estimate) && estimate > 0 ? estimate : null }) -const openAIUsageRefreshKey = computed(() => buildOpenAIUsageRefreshKey(props.account)) +// Each builder returns '' for other platforms, so at most one contributes. +const usageRefreshKey = computed(() => ( + buildOpenAIUsageRefreshKey(props.account) || + buildAnthropicUsageRefreshKey(props.account) || + buildGeminiUsageRefreshKey(props.account) +)) const shouldAutoLoadUsageOnMount = computed(() => { return shouldFetchUsage.value @@ -1797,9 +1806,8 @@ watch( { flush: 'post' } ) -watch(openAIUsageRefreshKey, (nextKey, prevKey) => { +watch(usageRefreshKey, (nextKey, prevKey) => { if (!prevKey || nextKey === prevKey) return - if (props.account.platform !== 'openai' || props.account.type !== 'oauth') return if (isBatchManaged.value) { requestParentBatchUsage({ force: true }) @@ -1807,7 +1815,7 @@ watch(openAIUsageRefreshKey, (nextKey, prevKey) => { } _usageCache.delete(props.account.id) - requestAutoLoad() + requestAutoLoad(isAnthropicOAuthOrSetupToken.value ? 'passive' : undefined) }) watch( diff --git a/frontend/src/components/account/__tests__/AccountUsageCell.usageRefresh.spec.ts b/frontend/src/components/account/__tests__/AccountUsageCell.usageRefresh.spec.ts new file mode 100644 index 0000000000..34dae1ae81 --- /dev/null +++ b/frontend/src/components/account/__tests__/AccountUsageCell.usageRefresh.spec.ts @@ -0,0 +1,174 @@ +import { beforeEach, describe, expect, it, vi } from 'vitest' +import { flushPromises, mount } from '@vue/test-utils' +import AccountUsageCell from '../AccountUsageCell.vue' +import type { Account } from '@/types' + +const { getUsage } = vi.hoisted(() => ({ + getUsage: vi.fn() +})) + +vi.mock('@/api/admin', () => ({ + adminAPI: { + accounts: { + getUsage + } + } +})) + +vi.mock('vue-i18n', async () => { + const actual = await vi.importActual('vue-i18n') + return { + ...actual, + useI18n: () => ({ + t: (key: string) => key + }) + } +}) + +function makeAccount(overrides: Partial): Account { + return { + id: 1, + name: 'account', + platform: 'anthropic', + type: 'oauth', + proxy_id: null, + concurrency: 1, + priority: 1, + status: 'active', + error_message: null, + last_used_at: null, + expires_at: null, + auto_pause_on_expired: true, + created_at: '2026-10-25T00:00:00Z', + updated_at: '2026-10-25T00:00:00Z', + schedulable: true, + rate_limited_at: null, + rate_limit_reset_at: null, + overload_until: null, + temp_unschedulable_until: null, + temp_unschedulable_reason: null, + session_window_start: null, + session_window_end: null, + session_window_status: null, + ...overrides, + } +} + +const passiveUsage = (fiveHour: number, sevenDay: number) => ({ + source: 'passive', + five_hour: { utilization: fiveHour, resets_at: null, remaining_seconds: 0 }, + seven_day: { utilization: sevenDay, resets_at: null, remaining_seconds: 0 } +}) + +const stubs = { + UsageProgressBar: { + props: ['label', 'utilization'], + template: '
{{ label }}|{{ utilization }}
' + }, + ClaudeResetCreditsCell: { template: '
' }, + AccountQuotaInfo: true +} + +const sampledClaudeAccount = (id: number, sampledAt: string, fiveHour: number) => makeAccount({ + id, + extra: { + passive_usage_sampled_at: sampledAt, + session_window_utilization: fiveHour, + passive_usage_7d_utilization: 0.2 + } +}) + +describe('AccountUsageCell usage refresh on row updates', () => { + beforeEach(() => { + getUsage.mockReset() + Object.defineProperty(window, 'matchMedia', { + writable: true, + value: vi.fn().mockImplementation(() => ({ + matches: true, + media: '(min-width: 768px)', + onchange: null, + addListener: vi.fn(), + removeListener: vi.fn(), + addEventListener: vi.fn(), + removeEventListener: vi.fn(), + dispatchEvent: vi.fn(), + })) + }) + }) + + it('refetches passive usage past its cache when the Claude row carries a new sample', async () => { + getUsage + .mockResolvedValueOnce(passiveUsage(10, 20)) + .mockResolvedValueOnce(passiveUsage(55, 20)) + + const wrapper = mount(AccountUsageCell, { + props: { account: sampledClaudeAccount(4101, '2026-10-25T10:00:00Z', 0.1) }, + global: { stubs } + }) + await flushPromises() + expect(getUsage).toHaveBeenCalledTimes(1) + expect(getUsage).toHaveBeenLastCalledWith(4101, 'passive', false) + expect(wrapper.text()).toContain('5h|10') + + // A replaced row whose usage inputs are unchanged keeps the cached usage. + await wrapper.setProps({ + account: { ...sampledClaudeAccount(4101, '2026-10-25T10:00:00Z', 0.1), current_concurrency: 3 } + }) + await flushPromises() + expect(getUsage).toHaveBeenCalledTimes(1) + + await wrapper.setProps({ account: sampledClaudeAccount(4101, '2026-10-25T10:01:00Z', 0.55) }) + await flushPromises() + expect(getUsage).toHaveBeenCalledTimes(2) + expect(getUsage).toHaveBeenLastCalledWith(4101, 'passive', false) + expect(wrapper.text()).toContain('5h|55') + }) + + it('asks the batch loader to bypass its cache when a batch-managed Claude row carries a new sample', async () => { + const requestBatchedUsage = vi.fn() + const wrapper = mount(AccountUsageCell, { + props: { + account: sampledClaudeAccount(4102, '2026-10-25T10:00:00Z', 0.1), + requestBatchedUsage + }, + global: { stubs } + }) + await flushPromises() + expect(requestBatchedUsage).toHaveBeenCalledTimes(1) + + await wrapper.setProps({ + account: { ...sampledClaudeAccount(4102, '2026-10-25T10:00:00Z', 0.1), current_concurrency: 3 } + }) + await flushPromises() + expect(requestBatchedUsage).toHaveBeenCalledTimes(1) + + await wrapper.setProps({ account: sampledClaudeAccount(4102, '2026-10-25T10:01:00Z', 0.55) }) + await flushPromises() + expect(requestBatchedUsage).toHaveBeenCalledTimes(2) + expect(requestBatchedUsage).toHaveBeenLastCalledWith(expect.objectContaining({ id: 4102 }), { force: true }) + expect(getUsage).not.toHaveBeenCalled() + }) + + it('refetches Gemini usage when the row reports new use', async () => { + getUsage.mockResolvedValue({}) + const account = makeAccount({ + id: 4103, + platform: 'gemini', + type: 'oauth', + last_used_at: '2026-10-25T10:00:00Z', + credentials: { oauth_type: 'google_one' } + }) + const wrapper = mount(AccountUsageCell, { + props: { account }, + global: { stubs } + }) + await flushPromises() + expect(getUsage).toHaveBeenCalledTimes(1) + expect(getUsage).toHaveBeenLastCalledWith(4103) + + await wrapper.setProps({ account: { ...account, last_used_at: '2026-10-25T10:01:00Z' } }) + await flushPromises() + expect(getUsage).toHaveBeenCalledTimes(2) + expect(getUsage).toHaveBeenLastCalledWith(4103) + }) +}) diff --git a/frontend/src/utils/__tests__/accountUsageRefresh.spec.ts b/frontend/src/utils/__tests__/accountUsageRefresh.spec.ts index f9559697e1..d54606b88d 100644 --- a/frontend/src/utils/__tests__/accountUsageRefresh.spec.ts +++ b/frontend/src/utils/__tests__/accountUsageRefresh.spec.ts @@ -1,5 +1,10 @@ import { describe, expect, it } from 'vitest' -import { buildGrokUsageRefreshKey, buildOpenAIUsageRefreshKey } from '../accountUsageRefresh' +import { + buildAnthropicUsageRefreshKey, + buildGeminiUsageRefreshKey, + buildGrokUsageRefreshKey, + buildOpenAIUsageRefreshKey +} from '../accountUsageRefresh' describe('buildOpenAIUsageRefreshKey', () => { it('会在 codex 快照变化时生成不同 key', () => { @@ -159,3 +164,76 @@ describe('buildGrokUsageRefreshKey', () => { } as any)).toBe('') }) }) + +describe('buildAnthropicUsageRefreshKey', () => { + const base = { + id: 7, + platform: 'anthropic', + type: 'oauth', + updated_at: '2026-10-25T10:00:00Z', + last_used_at: '2026-10-25T09:59:00Z', + rate_limit_reset_at: null, + session_window_start: '2026-10-25T08:00:00Z', + session_window_end: '2026-10-25T13:00:00Z', + session_window_status: 'allowed', + extra: { + passive_usage_sampled_at: '2026-10-25T09:59:00Z', + session_window_utilization: 0.1, + passive_usage_7d_utilization: 0.2, + passive_usage_7d_reset: 1761900000, + passive_usage_7d_oi_utilization: 0.3, + passive_usage_7d_oi_reset: 1761900000 + } + } as any + + it('changes when any input of the passive /usage response changes', () => { + const variants = [ + { last_used_at: '2026-10-25T10:01:00Z' }, + { session_window_start: '2026-10-25T13:00:00Z' }, + { session_window_end: '2026-10-25T18:00:00Z' }, + { session_window_status: 'rejected' }, + { extra: { ...base.extra, passive_usage_sampled_at: '2026-10-25T10:01:00Z' } }, + { extra: { ...base.extra, session_window_utilization: 0.5 } }, + { extra: { ...base.extra, passive_usage_7d_utilization: 0.6 } }, + { extra: { ...base.extra, passive_usage_7d_reset: 1762500000 } }, + { extra: { ...base.extra, passive_usage_7d_oi_utilization: 0.7 } }, + { extra: { ...base.extra, passive_usage_7d_oi_reset: 1762500000 } } + ] + for (const variant of variants) { + expect(buildAnthropicUsageRefreshKey({ ...base, ...variant })).not.toBe(buildAnthropicUsageRefreshKey(base)) + } + }) + + it('covers setup-token accounts', () => { + const setupToken = { ...base, type: 'setup-token' } + expect(buildAnthropicUsageRefreshKey(setupToken)).not.toBe('') + expect(buildAnthropicUsageRefreshKey({ + ...setupToken, + extra: { ...base.extra, session_window_utilization: 0.9 } + })).not.toBe(buildAnthropicUsageRefreshKey(setupToken)) + }) + + it('returns an empty key for other Anthropic types and other platforms', () => { + expect(buildAnthropicUsageRefreshKey({ ...base, type: 'apikey' })).toBe('') + expect(buildAnthropicUsageRefreshKey({ ...base, platform: 'openai' })).toBe('') + }) +}) + +describe('buildGeminiUsageRefreshKey', () => { + const base = { + id: 8, + platform: 'gemini', + type: 'oauth', + updated_at: '2026-10-25T10:00:00Z', + last_used_at: '2026-10-25T09:59:00Z' + } as any + + it('changes when the account is used or updated', () => { + expect(buildGeminiUsageRefreshKey({ ...base, last_used_at: '2026-10-25T10:01:00Z' })).not.toBe(buildGeminiUsageRefreshKey(base)) + expect(buildGeminiUsageRefreshKey({ ...base, updated_at: '2026-10-25T10:01:00Z' })).not.toBe(buildGeminiUsageRefreshKey(base)) + }) + + it('returns an empty key for non-Gemini accounts', () => { + expect(buildGeminiUsageRefreshKey({ ...base, platform: 'anthropic' })).toBe('') + }) +}) diff --git a/frontend/src/utils/accountUsageRefresh.ts b/frontend/src/utils/accountUsageRefresh.ts index 121dae253a..ff89d8edde 100644 --- a/frontend/src/utils/accountUsageRefresh.ts +++ b/frontend/src/utils/accountUsageRefresh.ts @@ -52,6 +52,43 @@ export const buildOpenAIUsageRefreshKey = (account: Pick): string => { + if (account.platform !== 'anthropic' || (account.type !== 'oauth' && account.type !== 'setup-token')) { + return '' + } + + const extra = account.extra ?? {} + return [ + account.id, + account.last_used_at, + account.session_window_start, + account.session_window_end, + account.session_window_status, + extra.passive_usage_sampled_at, + extra.session_window_utilization, + extra.passive_usage_7d_utilization, + extra.passive_usage_7d_reset, + extra.passive_usage_7d_oi_utilization, + extra.passive_usage_7d_oi_reset + ].map(normalizeUsageRefreshValue).join('|') +} + +// Gemini /usage counts usage logs against a tier derived from the account, so +// new use (last_used_at) or an account edit (updated_at) changes it. +export const buildGeminiUsageRefreshKey = (account: Pick): string => { + if (account.platform !== 'gemini') { + return '' + } + + return [ + account.id, + account.updated_at, + account.last_used_at + ].map(normalizeUsageRefreshValue).join('|') +} + export const buildGrokUsageRefreshKey = (account: Pick): string => { if (account.platform !== 'grok') { return '' diff --git a/frontend/src/views/admin/AccountsView.vue b/frontend/src/views/admin/AccountsView.vue index 7384e4858b..8cc2a32688 100644 --- a/frontend/src/views/admin/AccountsView.vue +++ b/frontend/src/views/admin/AccountsView.vue @@ -539,6 +539,7 @@ import { sanitizeUrl } from '@/utils/url' import { getFloatingPanelPosition } from '@/utils/floatingPanel' import { formatMultiplier } from '@/utils/formatters' import type { Account, AccountListItem, AccountPlatform, AccountSchedulerGroupScore, AccountType, AccountUsageInfo, Proxy as AccountProxy, AdminGroup, WindowStats, ClaudeModel, UpstreamBillingProbeSnapshot } from '@/types' +import { buildAnthropicUsageRefreshKey, buildGeminiUsageRefreshKey } from '@/utils/accountUsageRefresh' const { t } = useI18n() const appStore = useAppStore() @@ -1436,6 +1437,8 @@ const shouldReplaceAutoRefreshRow = (current: Account, next: Account) => { current.overload_until !== next.overload_until || current.temp_unschedulable_until !== next.temp_unschedulable_until || buildOpenAIUsageRefreshKey(current) !== buildOpenAIUsageRefreshKey(next) || + buildAnthropicUsageRefreshKey(current) !== buildAnthropicUsageRefreshKey(next) || + buildGeminiUsageRefreshKey(current) !== buildGeminiUsageRefreshKey(next) || buildGrokUsageRefreshKey(current) !== buildGrokUsageRefreshKey(next) ) } diff --git a/frontend/src/views/admin/__tests__/AccountsView.lite.spec.ts b/frontend/src/views/admin/__tests__/AccountsView.lite.spec.ts index 9d8d7266e5..fb44a917d9 100644 --- a/frontend/src/views/admin/__tests__/AccountsView.lite.spec.ts +++ b/frontend/src/views/admin/__tests__/AccountsView.lite.spec.ts @@ -67,6 +67,7 @@ const DataTableStub = defineComponent({
@@ -78,6 +79,11 @@ const AccountGroupsCellStub = defineComponent({ template: '{{ groups.map(group => group.name).join(",") }}' }) +const AccountUsageCellStub = defineComponent({ + props: { account: { type: Object, required: true } }, + template: '{{ account.extra?.session_window_utilization }}|{{ account.last_used_at }}' +}) + const EditAccountModalStub = defineComponent({ props: { show: Boolean, account: { type: Object, default: null } }, template: '
{{ show ? account?.name : "" }}
' @@ -124,7 +130,7 @@ function mountView(stubActionMenu = true) { AccountStatusIndicator: true, AccountTodayStatsCell: true, AccountGroupsCell: AccountGroupsCellStub, - AccountUsageCell: true, + AccountUsageCell: AccountUsageCellStub, UpstreamBillingRateCell: true, HelpTooltip: true, Icon: true, @@ -266,6 +272,54 @@ describe('admin AccountsView lite account list', () => { wrapper.unmount() }) + it.each([ + { + name: 'a Claude passive usage sample', + row: { + ...listRow, + platform: 'anthropic', + updated_at: '2026-10-25T10:00:00Z', + last_used_at: '2026-10-25T10:00:00Z', + extra: { passive_usage_sampled_at: '2026-10-25T10:00:00Z', session_window_utilization: 0.1 } + }, + change: { extra: { passive_usage_sampled_at: '2026-10-25T10:01:00Z', session_window_utilization: 0.55 } }, + before: '0.1|2026-10-25T10:00:00Z', + after: '0.55|2026-10-25T10:00:00Z' + }, + { + name: 'new Gemini use', + row: { + ...listRow, + platform: 'gemini', + updated_at: '2026-10-25T10:00:00Z', + last_used_at: '2026-10-25T10:00:00Z' + }, + change: { last_used_at: '2026-10-25T10:01:00Z' }, + before: '|2026-10-25T10:00:00Z', + after: '|2026-10-25T10:01:00Z' + } + ])('replaces a row on automatic refresh when only $name changed', async ({ row, change, before, after }) => { + vi.useFakeTimers() + vi.spyOn(document, 'hidden', 'get').mockReturnValue(false) + localStorage.setItem('account-auto-refresh', JSON.stringify({ enabled: true, interval_seconds: 5 })) + listAccounts.mockResolvedValue({ items: [row], total: 1, page: 1, page_size: 20, pages: 1 }) + listWithEtag.mockResolvedValueOnce({ + notModified: false, + etag: 'next-etag', + data: { items: [{ ...row, ...change }], total: 1, page: 1, page_size: 20, pages: 1 } + }) + const wrapper = mountView() + await flushPromises() + expect(wrapper.get('[data-test="usage-row"]').text()).toBe(before) + + await vi.advanceTimersByTimeAsync(6000) + await flushPromises() + + expect(listWithEtag).toHaveBeenCalled() + expect(wrapper.get('[data-test="usage-row"]').text()).toBe(after) + wrapper.unmount() + }) + it('loads the full account by id before opening edit, test, and stats actions', async () => { const wrapper = mountView() await flushPromises() From 88b1924bd9711a458c5e78deb45c0178725e0810 Mon Sep 17 00:00:00 2001 From: wucm667 Date: Fri, 20 Nov 2026 21:39:18 +0800 Subject: [PATCH 02/23] fix(openai): normalize standalone terminal context --- .../internal/handler/openai_page_context.go | 4 +- .../handler/openai_page_context_test.go | 87 ++++++++++++++++++- 2 files changed, 88 insertions(+), 3 deletions(-) diff --git a/backend/internal/handler/openai_page_context.go b/backend/internal/handler/openai_page_context.go index 4c13187178..4ce0dba35a 100644 --- a/backend/internal/handler/openai_page_context.go +++ b/backend/internal/handler/openai_page_context.go @@ -16,7 +16,7 @@ var codexSelectedPageName = regexp.MustCompile(`^codex_apps_selected_page_part_( func normalizeCodexUntrustedContext(body []byte) ([]byte, bool) { if !mayContainCodexCallOutputCandidate(body, "codex_apps_open_page", "codex_apps_selected_page_part_", - "browser_info", "goal_objective", "untrusted_context", "untrusted_content", "ide_context", "proposed_plan", + "browser_info", "terminal_info", "goal_objective", "untrusted_context", "untrusted_content", "ide_context", "proposed_plan", ) || !hasUniqueJSONMembers(body) { return body, false } @@ -89,7 +89,7 @@ func normalizeCodexUntrustedContext(body []byte) ([]byte, bool) { func validCodexUntrustedContext(name, output string) bool { switch name { - case "browser_info", "goal_objective", "untrusted_context", "ide_context": + case "browser_info", "terminal_info", "goal_objective", "untrusted_context", "ide_context": return strings.TrimSpace(output) != "" case "untrusted_content": // Codex's fallback for an unnamed context source can carry any text, including an empty value. diff --git a/backend/internal/handler/openai_page_context_test.go b/backend/internal/handler/openai_page_context_test.go index 615ce687c2..fb59bac2a0 100644 --- a/backend/internal/handler/openai_page_context_test.go +++ b/backend/internal/handler/openai_page_context_test.go @@ -54,7 +54,92 @@ func TestNormalizeCodexPageContextFirstMessage(t *testing.T) { require.Equal(t, got, again) } -var codexTextContextNamesForTest = []string{"browser_info", "goal_objective", "untrusted_context", "untrusted_content", "ide_context", "proposed_plan"} +var codexTextContextNamesForTest = []string{"browser_info", "terminal_info", "goal_objective", "untrusted_context", "untrusted_content", "ide_context", "proposed_plan"} + +func TestNormalizeCodexTerminalInfoIssue8991(t *testing.T) { + body := []byte(`{"model":"deepseek-flash","input":[{"type":"function_call_output","namespace":"agent","name":"terminal_info","output":"retest context"}]}`) + h := &OpenAIGatewayHandler{} + w := httptest.NewRecorder() + c, _ := gin.CreateTestContext(w) + require.False(t, h.validateFunctionCallOutputRequest(c, body, zap.NewNop())) + require.Equal(t, 400, w.Code) + require.Contains(t, w.Body.String(), "function_call_output requires call_id") + + got, changed := normalizeCodexUntrustedContext(body) + require.True(t, changed) + require.JSONEq(t, `{"model":"deepseek-flash","input":[{"type":"message","role":"user","content":[{"type":"input_text","text":"retest context"}]}]}`, string(got)) + w = httptest.NewRecorder() + c, _ = gin.CreateTestContext(w) + require.True(t, h.validateFunctionCallOutputRequest(c, got, zap.NewNop())) + require.False(t, c.Writer.Written()) +} + +func TestNormalizeCodexTerminalInfoBoundaries(t *testing.T) { + for _, testCase := range []struct { + name string + key string + value any + }{ + {"call id with surrounding whitespace", "call_id", " call_real "}, + {"boolean call id", "call_id", false}, + {"array call id", "call_id", []any{}}, + {"object call id", "call_id", map[string]any{}}, + {"namespace whitespace", "namespace", " agent "}, + {"namespace case", "namespace", "Agent"}, + {"boolean output", "output", false}, + {"numeric output", "output", 42}, + {"object output", "output", map[string]any{"text": "context"}}, + {"name prefix", "name", "terminal_info_extra"}, + {"name case", "name", "Terminal_info"}, + {"unknown context", "name", "arbitrary_context"}, + {"other type", "type", "custom_tool_call_output"}, + } { + t.Run(testCase.name, func(t *testing.T) { + item := pageContextItem("terminal_info", "retest context") + item[testCase.key] = testCase.value + body := pageContextRequest(t, item) + got, changed := normalizeCodexUntrustedContext(body) + require.False(t, changed) + require.Equal(t, body, got) + }) + } + for _, body := range []string{ + `{"input":[{"type":"function_call_output","namespace":"other","namespace":"agent","name":"terminal_info","output":"context"}]}`, + `{"input":[{"type":"function_call_output","namespace":"agent","name":"read_file","name":"terminal_info","output":"context"}]}`, + `{"input":[],"input":[{"type":"function_call_output","namespace":"agent","name":"terminal_info","output":"context"}]}`, + `{"input":[{"type":"function_call_output","namespace":"agent","name":"terminal_info","output":"context"}]} trailing`, + } { + got, changed := normalizeCodexUntrustedContext([]byte(body)) + require.False(t, changed) + require.Equal(t, body, string(got)) + } +} + +func TestNormalizeCodexTerminalInfoEscapedName(t *testing.T) { + body := []byte(`{"input":[{"type":"function_call_output","namespace":"agent","name":"terminal_\u0069nfo","output":" context\n\t"}]}`) + got, changed := normalizeCodexUntrustedContext(body) + require.True(t, changed) + require.Equal(t, " context\n\t", gjson.GetBytes(got, "input.0.content.0.text").String()) +} + +func TestNormalizeCodexTerminalInfoPreservesUnrelatedResults(t *testing.T) { + body := pageContextRequest(t, + pageContextItem("terminal_info", "retest context"), + map[string]any{"type": "function_call_output", "namespace": "agent", "name": "terminal_info", "call_id": "call_real", "output": "real result"}, + pageContextItem("read_file", "unrelated result")) + got, changed := normalizeCodexUntrustedContext(body) + require.True(t, changed) + require.Equal(t, "message", gjson.GetBytes(got, "input.0.type").String()) + for _, path := range []string{"input.1", "input.2"} { + require.JSONEq(t, gjson.GetBytes(body, path).Raw, gjson.GetBytes(got, path).Raw) + } + h := &OpenAIGatewayHandler{} + w := httptest.NewRecorder() + c, _ := gin.CreateTestContext(w) + require.False(t, h.validateFunctionCallOutputRequest(c, got, zap.NewNop())) + require.Equal(t, 400, w.Code) + require.Contains(t, w.Body.String(), "function_call_output requires call_id") +} func TestNormalizeCodexAdditionalUntrustedContext(t *testing.T) { for _, name := range codexTextContextNamesForTest { From bb110fda5307a6cefa2718b72627a3623ed23546 Mon Sep 17 00:00:00 2001 From: r266-tech Date: Fri, 20 Nov 2026 22:38:07 +0800 Subject: [PATCH 03/23] fix(ops): show requester in request error details --- .../ops/components/OpsErrorDetailModal.vue | 21 ++++++++----- .../__tests__/OpsErrorDetailModal.spec.ts | 30 +++++++++++++++++++ 2 files changed, 43 insertions(+), 8 deletions(-) diff --git a/frontend/src/views/admin/ops/components/OpsErrorDetailModal.vue b/frontend/src/views/admin/ops/components/OpsErrorDetailModal.vue index 8b0dc388f8..e90c517547 100644 --- a/frontend/src/views/admin/ops/components/OpsErrorDetailModal.vue +++ b/frontend/src/views/admin/ops/components/OpsErrorDetailModal.vue @@ -28,17 +28,22 @@ -
+
- {{ isUpstreamError(detail) ? t('admin.ops.errorDetail.account') : t('admin.ops.errorDetail.user') }} + {{ t('admin.ops.errorDetail.user') }}
- - + {{ detail.user_email || (detail.user_id != null ? String(detail.user_id) : '—') }} +
+
+ +
+
{{ t('admin.ops.errorDetail.account') }}
+
+ {{ detail.account_name || (detail.account_id != null ? String(detail.account_id) : '—') }}
diff --git a/frontend/src/views/admin/ops/components/__tests__/OpsErrorDetailModal.spec.ts b/frontend/src/views/admin/ops/components/__tests__/OpsErrorDetailModal.spec.ts index 188c150e07..922cba91fa 100644 --- a/frontend/src/views/admin/ops/components/__tests__/OpsErrorDetailModal.spec.ts +++ b/frontend/src/views/admin/ops/components/__tests__/OpsErrorDetailModal.spec.ts @@ -76,4 +76,34 @@ describe('OpsErrorDetailModal', () => { expect(wrapper.findAll('pre')).toHaveLength(2) expect(wrapper.text()).not.toContain('admin.ops.errorDetail.payloads.upstream_detail') }) + + it('shows the requester alongside the account for a provider 400 in request details', async () => { + mocks.getRequestErrorDetail.mockResolvedValue({ + id: 2, + created_at: '2026-11-20T00:00:00Z', + phase: 'upstream', + type: 'upstream_error', + error_owner: 'provider', + status_code: 400, + upstream_status_code: 400, + platform: 'openai', + account_name: 'test-provider-account', + user_id: 42, + user_email: 'requester@example.test' + }) + + const wrapper = shallowMount(OpsErrorDetailModal, { + props: { show: true, errorId: 2, errorType: 'request' }, + global: { + stubs: { + BaseDialog: { template: '
' }, + Icon: true + } + } + }) + await flushPromises() + + expect(wrapper.text()).toContain('test-provider-account') + expect(wrapper.text()).toContain('requester@example.test') + }) }) From cc2a2616d84d2d685818a37e784a381474f2e5dc Mon Sep 17 00:00:00 2001 From: Anankke Date: Fri, 20 Nov 2026 15:04:42 -0800 Subject: [PATCH 04/23] fix(accounts): refetch Gemini usage when the account's quota tier changes The usage refresh key has no Gemini quota input. When a Gemini account's tier changes, as when the token refresher re-detects the Google One tier, auto refresh replaces the row but the key is unchanged: the tier badge shows the new tier, the quota bars keep the old limits until the account is used, Refresh is clicked or the page is reloaded. An API key account moved from a third-party base URL to the official one gets no bars for the same reason. The Gemini key now carries credentials.oauth_type, project_id, tier_id and base_url, the credentials geminiQuotaTierKeyForAccount depends on. Gemini usage is read from local usage logs, so the refetch sends nothing upstream, and a token refresh that leaves these four fields alone keeps the key. --- .../components/account/AccountUsageCell.vue | 1 - .../__tests__/AccountUsageCell.spec.ts | 57 +++++- .../AccountUsageCell.usageRefresh.spec.ts | 174 ------------------ .../__tests__/accountUsageRefresh.spec.ts | 97 ++-------- frontend/src/utils/accountUsageRefresh.ts | 73 ++++---- .../admin/__tests__/AccountsView.lite.spec.ts | 57 +----- 6 files changed, 101 insertions(+), 358 deletions(-) delete mode 100644 frontend/src/components/account/__tests__/AccountUsageCell.usageRefresh.spec.ts diff --git a/frontend/src/components/account/AccountUsageCell.vue b/frontend/src/components/account/AccountUsageCell.vue index 2a16ab98ce..8a5a8bd0fe 100644 --- a/frontend/src/components/account/AccountUsageCell.vue +++ b/frontend/src/components/account/AccountUsageCell.vue @@ -947,7 +947,6 @@ const openAISevenDayEstimatedTotalCost = computed(() => estimateWindowTotalCost(usageInfo.value?.seven_day) ) -// Covers OpenAI, Claude and Gemini; '' for other platforms. const usageRefreshKey = computed(() => buildAccountUsageRefreshKey(props.account)) const shouldAutoLoadUsageOnMount = computed(() => { diff --git a/frontend/src/components/account/__tests__/AccountUsageCell.spec.ts b/frontend/src/components/account/__tests__/AccountUsageCell.spec.ts index b7b0ced41b..7181f63c91 100644 --- a/frontend/src/components/account/__tests__/AccountUsageCell.spec.ts +++ b/frontend/src/components/account/__tests__/AccountUsageCell.spec.ts @@ -130,7 +130,62 @@ describe('AccountUsageCell', () => { expect(wrapper.text()).toContain('54') await wrapper.setProps({ account: { ...next, updated_at: 'unrelated', current_concurrency: 3 } }) await flushPromises() - expect(getUsage).toHaveBeenCalledTimes(platform === 'gemini' ? 3 : 2) + expect(getUsage).toHaveBeenCalledTimes(2) + wrapper.unmount() + }) + + it('refetches Gemini usage when the account quota tier changes', async () => { + const account = makeAccount({ id: 98210, platform: 'gemini', type: 'oauth', credentials: { oauth_type: 'google_one', tier_id: 'google_ai_pro' } }) + getUsage.mockResolvedValue({ gemini_shared_daily: { utilization: 31 } }) + const wrapper = mount(AccountUsageCell, { props: { account } }) + await flushPromises() + expect(getUsage).toHaveBeenCalledTimes(1) + expect(getUsage).toHaveBeenLastCalledWith(account.id) + await wrapper.setProps({ account: { ...account, credentials: { ...account.credentials, tier_id: 'google_ai_ultra' } } }) + await flushPromises() + expect(getUsage).toHaveBeenCalledTimes(2) + expect(getUsage).toHaveBeenLastCalledWith(account.id) + wrapper.unmount() + }) + + it.each([false, true])('sends one usage request when a relay Gemini base_url becomes the official one (batch %s)', async (batch) => { + const requestBatchedUsage = vi.fn() + const relayAccount = (baseUrl: string) => makeAccount({ + id: 98220, + platform: 'gemini', + type: 'apikey', + credentials: { base_url: baseUrl, tier_id: 'aistudio_free' } + }) + const wrapper = mount(AccountUsageCell, { + props: { account: relayAccount('https://relay.example'), ...(batch ? { requestBatchedUsage } : {}) } + }) + const calls = () => (batch ? requestBatchedUsage.mock.calls.length : getUsage.mock.calls.length) + await flushPromises() + const before = calls() + await wrapper.setProps({ account: relayAccount('https://generativelanguage.googleapis.com') }) + await flushPromises() + expect(calls() - before).toBe(1) + if (!batch) expect(getUsage).toHaveBeenLastCalledWith(98220) + wrapper.unmount() + }) + + it.each([false, true])('sends no usage request when one relay Gemini base_url becomes another (batch %s)', async (batch) => { + const requestBatchedUsage = vi.fn() + const relayAccount = (baseUrl: string) => makeAccount({ + id: 98230, + platform: 'gemini', + type: 'apikey', + credentials: { base_url: baseUrl, tier_id: 'aistudio_free' } + }) + const wrapper = mount(AccountUsageCell, { + props: { account: relayAccount('https://relay.example'), ...(batch ? { requestBatchedUsage } : {}) } + }) + const calls = () => (batch ? requestBatchedUsage.mock.calls.length : getUsage.mock.calls.length) + await flushPromises() + const before = calls() + await wrapper.setProps({ account: relayAccount('https://relay2.example') }) + await flushPromises() + expect(calls()).toBe(before) wrapper.unmount() }) diff --git a/frontend/src/components/account/__tests__/AccountUsageCell.usageRefresh.spec.ts b/frontend/src/components/account/__tests__/AccountUsageCell.usageRefresh.spec.ts deleted file mode 100644 index 33f2fcd953..0000000000 --- a/frontend/src/components/account/__tests__/AccountUsageCell.usageRefresh.spec.ts +++ /dev/null @@ -1,174 +0,0 @@ -import { beforeEach, describe, expect, it, vi } from 'vitest' -import { flushPromises, mount } from '@vue/test-utils' -import AccountUsageCell from '../AccountUsageCell.vue' -import type { Account } from '@/types' - -const { getUsage } = vi.hoisted(() => ({ - getUsage: vi.fn() -})) - -vi.mock('@/api/admin', () => ({ - adminAPI: { - accounts: { - getUsage - } - } -})) - -vi.mock('vue-i18n', async () => { - const actual = await vi.importActual('vue-i18n') - return { - ...actual, - useI18n: () => ({ - t: (key: string) => key - }) - } -}) - -function makeAccount(overrides: Partial): Account { - return { - id: 1, - name: 'account', - platform: 'anthropic', - type: 'oauth', - proxy_id: null, - concurrency: 1, - priority: 1, - status: 'active', - error_message: null, - last_used_at: null, - expires_at: null, - auto_pause_on_expired: true, - created_at: '2026-10-25T00:00:00Z', - updated_at: '2026-10-25T00:00:00Z', - schedulable: true, - rate_limited_at: null, - rate_limit_reset_at: null, - overload_until: null, - temp_unschedulable_until: null, - temp_unschedulable_reason: null, - session_window_start: null, - session_window_end: null, - session_window_status: null, - ...overrides, - } -} - -const passiveUsage = (fiveHour: number, sevenDay: number) => ({ - source: 'passive', - five_hour: { utilization: fiveHour, resets_at: null, remaining_seconds: 0 }, - seven_day: { utilization: sevenDay, resets_at: null, remaining_seconds: 0 } -}) - -const stubs = { - UsageProgressBar: { - props: ['label', 'utilization'], - template: '
{{ label }}|{{ utilization }}
' - }, - ClaudeResetCreditsCell: { template: '
' }, - AccountQuotaInfo: true -} - -const sampledClaudeAccount = (id: number, sampledAt: string, fiveHour: number) => makeAccount({ - id, - extra: { - passive_usage_sampled_at: sampledAt, - session_window_utilization: fiveHour, - passive_usage_7d_utilization: 0.2 - } -}) - -describe('AccountUsageCell usage refresh on row updates', () => { - beforeEach(() => { - getUsage.mockReset() - Object.defineProperty(window, 'matchMedia', { - writable: true, - value: vi.fn().mockImplementation(() => ({ - matches: true, - media: '(min-width: 768px)', - onchange: null, - addListener: vi.fn(), - removeListener: vi.fn(), - addEventListener: vi.fn(), - removeEventListener: vi.fn(), - dispatchEvent: vi.fn(), - })) - }) - }) - - it('refetches passive usage past its cache when the Claude row carries a new sample', async () => { - getUsage - .mockResolvedValueOnce(passiveUsage(10, 20)) - .mockResolvedValueOnce(passiveUsage(55, 20)) - - const wrapper = mount(AccountUsageCell, { - props: { account: sampledClaudeAccount(4101, '2026-10-25T10:00:00Z', 0.1) }, - global: { stubs } - }) - await flushPromises() - expect(getUsage).toHaveBeenCalledTimes(1) - expect(getUsage).toHaveBeenLastCalledWith(4101, 'passive', false) - expect(wrapper.text()).toContain('5h|10') - - // A replaced row whose usage inputs are unchanged keeps the cached usage. - await wrapper.setProps({ - account: { ...sampledClaudeAccount(4101, '2026-10-25T10:00:00Z', 0.1), current_concurrency: 3 } - }) - await flushPromises() - expect(getUsage).toHaveBeenCalledTimes(1) - - await wrapper.setProps({ account: sampledClaudeAccount(4101, '2026-10-25T10:01:00Z', 0.55) }) - await flushPromises() - expect(getUsage).toHaveBeenCalledTimes(2) - expect(getUsage).toHaveBeenLastCalledWith(4101, 'passive', false) - expect(wrapper.text()).toContain('5h|55') - }) - - it('asks the batch loader to bypass its cache when a batch-managed Claude row carries a new sample', async () => { - const requestBatchedUsage = vi.fn() - const wrapper = mount(AccountUsageCell, { - props: { - account: sampledClaudeAccount(4102, '2026-10-25T10:00:00Z', 0.1), - requestBatchedUsage - }, - global: { stubs } - }) - await flushPromises() - expect(requestBatchedUsage).toHaveBeenCalledTimes(1) - - await wrapper.setProps({ - account: { ...sampledClaudeAccount(4102, '2026-10-25T10:00:00Z', 0.1), current_concurrency: 3 } - }) - await flushPromises() - expect(requestBatchedUsage).toHaveBeenCalledTimes(1) - - await wrapper.setProps({ account: sampledClaudeAccount(4102, '2026-10-25T10:01:00Z', 0.55) }) - await flushPromises() - expect(requestBatchedUsage).toHaveBeenCalledTimes(2) - expect(requestBatchedUsage).toHaveBeenLastCalledWith(expect.objectContaining({ id: 4102 }), undefined) - expect(getUsage).not.toHaveBeenCalled() - }) - - it('refetches Gemini usage when the row reports new use', async () => { - getUsage.mockResolvedValue({}) - const account = makeAccount({ - id: 4103, - platform: 'gemini', - type: 'oauth', - last_used_at: '2026-10-25T10:00:00Z', - credentials: { oauth_type: 'google_one' } - }) - const wrapper = mount(AccountUsageCell, { - props: { account }, - global: { stubs } - }) - await flushPromises() - expect(getUsage).toHaveBeenCalledTimes(1) - expect(getUsage).toHaveBeenLastCalledWith(4103) - - await wrapper.setProps({ account: { ...account, last_used_at: '2026-10-25T10:01:00Z' } }) - await flushPromises() - expect(getUsage).toHaveBeenCalledTimes(2) - expect(getUsage).toHaveBeenLastCalledWith(4103) - }) -}) diff --git a/frontend/src/utils/__tests__/accountUsageRefresh.spec.ts b/frontend/src/utils/__tests__/accountUsageRefresh.spec.ts index 4c9fcc0885..1bba33e58e 100644 --- a/frontend/src/utils/__tests__/accountUsageRefresh.spec.ts +++ b/frontend/src/utils/__tests__/accountUsageRefresh.spec.ts @@ -1,11 +1,5 @@ import { describe, expect, it } from 'vitest' -import { - buildAccountUsageRefreshKey, - buildAnthropicUsageRefreshKey, - buildGeminiUsageRefreshKey, - buildGrokUsageRefreshKey, - buildOpenAIUsageRefreshKey -} from '../accountUsageRefresh' +import { buildAccountUsageRefreshKey, buildGrokUsageRefreshKey, buildOpenAIUsageRefreshKey } from '../accountUsageRefresh' describe('buildAccountUsageRefreshKey', () => { it.each(['oauth', 'setup-token'])('tracks every Claude %s passive snapshot input', (type) => { @@ -20,15 +14,19 @@ describe('buildAccountUsageRefreshKey', () => { it.each(['anthropic', 'gemini'])('ignores unrelated %s changes and extra key ordering', (platform) => { const base = { id: 1, platform, type: 'oauth', extra: { session_window_utilization: 0, other: 1 } } as any - expect(buildAccountUsageRefreshKey({ ...base, current_concurrency: 5, extra: { other: 2, session_window_utilization: 0 } } as any)).toBe(buildAccountUsageRefreshKey(base)) + expect(buildAccountUsageRefreshKey({ ...base, updated_at: 'new', current_concurrency: 5, extra: { other: 2, session_window_utilization: 0 } } as any)).toBe(buildAccountUsageRefreshKey(base)) expect(buildAccountUsageRefreshKey({ ...base, last_used_at: 'new' })).not.toBe(buildAccountUsageRefreshKey(base)) }) - it('tracks an account edit for Gemini but not for Claude', () => { - const claude = { id: 1, platform: 'anthropic', type: 'oauth', extra: {} } as any - expect(buildAccountUsageRefreshKey({ ...claude, updated_at: 'new' })).toBe(buildAccountUsageRefreshKey(claude)) - const gemini = { id: 1, platform: 'gemini', type: 'oauth', extra: {} } as any - expect(buildAccountUsageRefreshKey({ ...gemini, updated_at: 'new' })).not.toBe(buildAccountUsageRefreshKey(gemini)) + it('tracks the Gemini quota tier and ignores other credential keys', () => { + const base = { id: 1, platform: 'gemini', type: 'oauth', credentials: { oauth_type: 'google_one', tier_id: 'google_ai_pro' } } as any + expect(buildAccountUsageRefreshKey({ ...base, credentials: { ...base.credentials, tier_id: 'google_ai_ultra' } })).not.toBe(buildAccountUsageRefreshKey(base)) + expect(buildAccountUsageRefreshKey({ ...base, credentials: { ...base.credentials, oauth_type: 'ai_studio' } })).not.toBe(buildAccountUsageRefreshKey(base)) + const legacy = { id: 1, platform: 'gemini', type: 'oauth', credentials: {} } as any + expect(buildAccountUsageRefreshKey({ ...legacy, credentials: { project_id: 'p-1' } })).not.toBe(buildAccountUsageRefreshKey(legacy)) + expect(buildAccountUsageRefreshKey({ ...base, credentials: { ...base.credentials, client_id: 'other', expires_at: '999' } })).toBe(buildAccountUsageRefreshKey(base)) + const apiKey = { id: 1, platform: 'gemini', type: 'apikey', credentials: { base_url: 'https://relay.example' } } as any + expect(buildAccountUsageRefreshKey({ ...apiKey, credentials: { ...apiKey.credentials, base_url: 'https://generativelanguage.googleapis.com' } })).not.toBe(buildAccountUsageRefreshKey(apiKey)) }) it('retains OpenAI keys and excludes unsupported platforms/types', () => { @@ -197,76 +195,3 @@ describe('buildGrokUsageRefreshKey', () => { } as any)).toBe('') }) }) - -describe('buildAnthropicUsageRefreshKey', () => { - const base = { - id: 7, - platform: 'anthropic', - type: 'oauth', - updated_at: '2026-10-25T10:00:00Z', - last_used_at: '2026-10-25T09:59:00Z', - rate_limit_reset_at: null, - session_window_start: '2026-10-25T08:00:00Z', - session_window_end: '2026-10-25T13:00:00Z', - session_window_status: 'allowed', - extra: { - passive_usage_sampled_at: '2026-10-25T09:59:00Z', - session_window_utilization: 0.1, - passive_usage_7d_utilization: 0.2, - passive_usage_7d_reset: 1761900000, - passive_usage_7d_oi_utilization: 0.3, - passive_usage_7d_oi_reset: 1761900000 - } - } as any - - it('changes when any input of the passive /usage response changes', () => { - const variants = [ - { last_used_at: '2026-10-25T10:01:00Z' }, - { session_window_start: '2026-10-25T13:00:00Z' }, - { session_window_end: '2026-10-25T18:00:00Z' }, - { session_window_status: 'rejected' }, - { extra: { ...base.extra, passive_usage_sampled_at: '2026-10-25T10:01:00Z' } }, - { extra: { ...base.extra, session_window_utilization: 0.5 } }, - { extra: { ...base.extra, passive_usage_7d_utilization: 0.6 } }, - { extra: { ...base.extra, passive_usage_7d_reset: 1762500000 } }, - { extra: { ...base.extra, passive_usage_7d_oi_utilization: 0.7 } }, - { extra: { ...base.extra, passive_usage_7d_oi_reset: 1762500000 } } - ] - for (const variant of variants) { - expect(buildAnthropicUsageRefreshKey({ ...base, ...variant })).not.toBe(buildAnthropicUsageRefreshKey(base)) - } - }) - - it('covers setup-token accounts', () => { - const setupToken = { ...base, type: 'setup-token' } - expect(buildAnthropicUsageRefreshKey(setupToken)).not.toBe('') - expect(buildAnthropicUsageRefreshKey({ - ...setupToken, - extra: { ...base.extra, session_window_utilization: 0.9 } - })).not.toBe(buildAnthropicUsageRefreshKey(setupToken)) - }) - - it('returns an empty key for other Anthropic types and other platforms', () => { - expect(buildAnthropicUsageRefreshKey({ ...base, type: 'apikey' })).toBe('') - expect(buildAnthropicUsageRefreshKey({ ...base, platform: 'openai' })).toBe('') - }) -}) - -describe('buildGeminiUsageRefreshKey', () => { - const base = { - id: 8, - platform: 'gemini', - type: 'oauth', - updated_at: '2026-10-25T10:00:00Z', - last_used_at: '2026-10-25T09:59:00Z' - } as any - - it('changes when the account is used or updated', () => { - expect(buildGeminiUsageRefreshKey({ ...base, last_used_at: '2026-10-25T10:01:00Z' })).not.toBe(buildGeminiUsageRefreshKey(base)) - expect(buildGeminiUsageRefreshKey({ ...base, updated_at: '2026-10-25T10:01:00Z' })).not.toBe(buildGeminiUsageRefreshKey(base)) - }) - - it('returns an empty key for non-Gemini accounts', () => { - expect(buildGeminiUsageRefreshKey({ ...base, platform: 'anthropic' })).toBe('') - }) -}) diff --git a/frontend/src/utils/accountUsageRefresh.ts b/frontend/src/utils/accountUsageRefresh.ts index ea5642fd6b..be01b6b415 100644 --- a/frontend/src/utils/accountUsageRefresh.ts +++ b/frontend/src/utils/accountUsageRefresh.ts @@ -52,43 +52,6 @@ export const buildOpenAIUsageRefreshKey = (account: Pick): string => { - if (account.platform !== 'anthropic' || (account.type !== 'oauth' && account.type !== 'setup-token')) { - return '' - } - - const extra = account.extra ?? {} - return [ - account.id, - account.last_used_at, - account.session_window_start, - account.session_window_end, - account.session_window_status, - extra.passive_usage_sampled_at, - extra.session_window_utilization, - extra.passive_usage_7d_utilization, - extra.passive_usage_7d_reset, - extra.passive_usage_7d_oi_utilization, - extra.passive_usage_7d_oi_reset - ].map(normalizeUsageRefreshValue).join('|') -} - -// Gemini /usage counts usage logs against a tier derived from the account, so -// new use (last_used_at) or an account edit (updated_at) changes it. -export const buildGeminiUsageRefreshKey = (account: Pick): string => { - if (account.platform !== 'gemini') { - return '' - } - - return [ - account.id, - account.updated_at, - account.last_used_at - ].map(normalizeUsageRefreshValue).join('|') -} - export const buildGrokUsageRefreshKey = (account: Pick): string => { if (account.platform !== 'grok') { return '' @@ -107,9 +70,37 @@ export const buildGrokUsageRefreshKey = (account: Pick): string => { +export const buildAccountUsageRefreshKey = (account: Pick): string => { if (account.platform === 'openai') return buildOpenAIUsageRefreshKey(account) - if (account.platform === 'anthropic') return buildAnthropicUsageRefreshKey(account) - if (account.platform === 'gemini') return buildGeminiUsageRefreshKey(account) - return '' + + const isClaude = account.platform === 'anthropic' && (account.type === 'oauth' || account.type === 'setup-token') + if (!isClaude && account.platform !== 'gemini') return '' + + const credentials = account.credentials ?? {} + const extra = account.extra ?? {} + return serializeSnapshotRefreshValue([ + account.id, + account.platform, + account.type, + account.last_used_at ?? null, + account.session_window_start ?? null, + account.session_window_end ?? null, + ...(isClaude ? [ + account.session_window_status ?? null, + extra.session_window_utilization ?? null, + extra.passive_usage_sampled_at ?? null, + extra.passive_usage_7d_utilization ?? null, + extra.passive_usage_7d_reset ?? null, + extra.passive_usage_7d_oi_utilization ?? null, + extra.passive_usage_7d_oi_reset ?? null + ] : [ + // Gemini quota comes from the canonical tier of (oauth_type, tier_id); a + // legacy project_id alone makes the backend treat the account as code_assist. + // An API key on a third-party base_url has no tier, the official one does. + credentials.oauth_type ?? null, + credentials.project_id ?? null, + credentials.tier_id ?? null, + credentials.base_url ?? null + ]) + ]) } diff --git a/frontend/src/views/admin/__tests__/AccountsView.lite.spec.ts b/frontend/src/views/admin/__tests__/AccountsView.lite.spec.ts index a7c8ee6aae..64115c43f5 100644 --- a/frontend/src/views/admin/__tests__/AccountsView.lite.spec.ts +++ b/frontend/src/views/admin/__tests__/AccountsView.lite.spec.ts @@ -82,11 +82,6 @@ const AccountGroupsCellStub = defineComponent({ template: '{{ groups.map(group => group.name).join(",") }}' }) -const AccountUsageCellStub = defineComponent({ - props: { account: { type: Object, required: true } }, - template: '{{ account.extra?.session_window_utilization }}|{{ account.last_used_at }}' -}) - const EditAccountModalStub = defineComponent({ props: { show: Boolean, account: { type: Object, default: null } }, template: '
{{ show ? account?.name : "" }}
' @@ -133,7 +128,7 @@ function mountView(stubActionMenu = true, realUsageCell = false) { AccountStatusIndicator: true, AccountTodayStatsCell: true, AccountGroupsCell: AccountGroupsCellStub, - AccountUsageCell: realUsageCell ? false : AccountUsageCellStub, + AccountUsageCell: !realUsageCell, UpstreamBillingRateCell: true, HelpTooltip: true, Icon: true, @@ -221,7 +216,7 @@ describe('admin AccountsView lite account list', () => { listWithEtag.mockResolvedValue({ notModified: false, etag: 'unrelated', data: { items: [{ ...next, updated_at: 'new', current_concurrency: 2, extra: { ...next.extra, unrelated: true } }], total: 1, pages: 1 } }) await vi.advanceTimersByTimeAsync(6000) await flushPromises() - expect(getBatchUsage).toHaveBeenCalledTimes(platform === 'gemini' ? 3 : 2) + expect(getBatchUsage).toHaveBeenCalledTimes(2) wrapper.unmount() }) @@ -315,54 +310,6 @@ describe('admin AccountsView lite account list', () => { wrapper.unmount() }) - it.each([ - { - name: 'a Claude passive usage sample', - row: { - ...listRow, - platform: 'anthropic', - updated_at: '2026-10-25T10:00:00Z', - last_used_at: '2026-10-25T10:00:00Z', - extra: { passive_usage_sampled_at: '2026-10-25T10:00:00Z', session_window_utilization: 0.1 } - }, - change: { extra: { passive_usage_sampled_at: '2026-10-25T10:01:00Z', session_window_utilization: 0.55 } }, - before: '0.1|2026-10-25T10:00:00Z', - after: '0.55|2026-10-25T10:00:00Z' - }, - { - name: 'new Gemini use', - row: { - ...listRow, - platform: 'gemini', - updated_at: '2026-10-25T10:00:00Z', - last_used_at: '2026-10-25T10:00:00Z' - }, - change: { last_used_at: '2026-10-25T10:01:00Z' }, - before: '|2026-10-25T10:00:00Z', - after: '|2026-10-25T10:01:00Z' - } - ])('replaces a row on automatic refresh when only $name changed', async ({ row, change, before, after }) => { - vi.useFakeTimers() - vi.spyOn(document, 'hidden', 'get').mockReturnValue(false) - localStorage.setItem('account-auto-refresh', JSON.stringify({ enabled: true, interval_seconds: 5 })) - listAccounts.mockResolvedValue({ items: [row], total: 1, page: 1, page_size: 20, pages: 1 }) - listWithEtag.mockResolvedValueOnce({ - notModified: false, - etag: 'next-etag', - data: { items: [{ ...row, ...change }], total: 1, page: 1, page_size: 20, pages: 1 } - }) - const wrapper = mountView() - await flushPromises() - expect(wrapper.get('[data-test="usage-row"]').text()).toBe(before) - - await vi.advanceTimersByTimeAsync(6000) - await flushPromises() - - expect(listWithEtag).toHaveBeenCalled() - expect(wrapper.get('[data-test="usage-row"]').text()).toBe(after) - wrapper.unmount() - }) - it('loads the full account by id before opening edit, test, and stats actions', async () => { const wrapper = mountView() await flushPromises() From c3219a14ed48c5a8cf2c53f3a346686f77110721 Mon Sep 17 00:00:00 2001 From: Anankke Date: Fri, 20 Nov 2026 19:35:31 -0800 Subject: [PATCH 05/23] fix(gateway): do not overwrite a sticky rebind after a long forward GatewayHandler.Messages writes the sticky binding back after a successful forward. The write was a plain SET, so a long request put its account back over a binding another request made while it was forwarding. The write now runs a Lua compare in the Redis cache. It sets the key when the key is missing or holds an account this request was admitted on under profit control and failed over from, refreshes the TTL when the key already holds the served account, and leaves any other value alone. The compare sits behind GatewayStickySessionCompareCache, an optional capability; a cache without it keeps the plain write. --- backend/internal/handler/gateway_handler.go | 20 +- .../handler/gateway_sticky_writeback_test.go | 284 +++++++++++++++--- backend/internal/repository/gateway_cache.go | 48 +++ .../gateway_cache_integration_test.go | 78 +++++ .../gateway_cache_sticky_cas_test.go | 68 +++++ backend/internal/service/gateway_service.go | 29 ++ 6 files changed, 482 insertions(+), 45 deletions(-) create mode 100644 backend/internal/repository/gateway_cache_sticky_cas_test.go diff --git a/backend/internal/handler/gateway_handler.go b/backend/internal/handler/gateway_handler.go index 300db262d5..075632d1be 100644 --- a/backend/internal/handler/gateway_handler.go +++ b/backend/internal/handler/gateway_handler.go @@ -651,6 +651,9 @@ func (h *GatewayHandler) Messages(c *gin.Context) { // 受限的账号被失败请求的 session hash 卡满整个空闲窗口,后续新会话全部被拒。 // 成功请求保持既有空闲超时语义(会话按最后活动时间过期)。 sessionSlotAccounts := make(map[int64]*service.Account) + // 本请求在利润门下实际尝试转发的账号。终值写回只覆盖其中除最终服务账号以外的 ID; + // fs.FailedAccountIDs 会被退避重试重置,不能用作这个集合。 + var attemptedAccountIDs []int64 upstreamServedSession := false defer func() { if upstreamServedSession { @@ -919,6 +922,11 @@ func (h *GatewayHandler) Messages(c *gin.Context) { // 选号按客户端模型,转发按渠道映射后的模型:模型级账号状态按选号模型记录。 requestCtx = service.WithGatewaySchedulingModel(requestCtx, reqModel) } + // 只记利润门准入的账号:准入时本请求自己写过绑定,failover 后可能留在键里; + // 不开门时每次转发前选号都已把键写成当前账号,键里的失败账号只能是别的请求写的 + if selection.ProfitGateActive() { + attemptedAccountIDs = append(attemptedAccountIDs, account.ID) + } // 记录 Forward 前已写入字节数,Forward 后若增加则说明 SSE 内容已发,禁止 failover writerSizeBeforeForward := c.Writer.Size() if account.Platform == service.PlatformAntigravity && account.Type != service.AccountTypeAPIKey { @@ -1130,13 +1138,21 @@ func (h *GatewayHandler) Messages(c *gin.Context) { // - 选中账号与粘性账号一致:刷新 TTL // - 粘性账号因负载/RPM 被跳过、选中了其他账号:不覆盖原绑定, // 下次请求粘性账号恢复后仍可命中 + // 写入只覆盖缺失的键与本请求在利润门下 failover 掉的账号(准入时本请求自己写过它), + // 转发期间别的请求改绑的值不动。 + failedOverAccountIDs := make([]int64, 0, len(attemptedAccountIDs)) + for _, attemptedAccountID := range attemptedAccountIDs { + if attemptedAccountID != account.ID { + failedOverAccountIDs = append(failedOverAccountIDs, attemptedAccountID) + } + } if sessionKey != "" && (sessionBoundAccountID == 0 || sessionBoundAccountID == account.ID) { // Forward has completed; finish the bounded write even if the client disconnects. bindCtx, cancelBind := context.WithTimeout(context.WithoutCancel(c.Request.Context()), 5*time.Second) - bindErr := h.gatewayService.BindStickySession(bindCtx, currentAPIKey.GroupID, sessionKey, account.ID) + bindErr := h.gatewayService.BindStickySessionUnlessRebound(bindCtx, currentAPIKey.GroupID, sessionKey, account.ID, failedOverAccountIDs) cancelBind() if bindErr != nil { - reqLog.Warn("gateway.bind_sticky_session_failed", zap.Int64("account_id", account.ID), zap.Error(bindErr)) + reqLog.Warn("gateway.bind_sticky_session_failed", zap.Int64("account_id", account.ID), zap.Int("failed_over_account_count", len(failedOverAccountIDs)), zap.Error(bindErr)) } } diff --git a/backend/internal/handler/gateway_sticky_writeback_test.go b/backend/internal/handler/gateway_sticky_writeback_test.go index 2045f2792f..db70a22fab 100644 --- a/backend/internal/handler/gateway_sticky_writeback_test.go +++ b/backend/internal/handler/gateway_sticky_writeback_test.go @@ -4,14 +4,17 @@ package handler import ( "context" + "fmt" "io" "net/http" "net/http/httptest" + "slices" "strings" "testing" "time" "github.com/Wei-Shaw/sub2api/internal/config" + "github.com/Wei-Shaw/sub2api/internal/pkg/tlsfingerprint" middleware "github.com/Wei-Shaw/sub2api/internal/server/middleware" "github.com/Wei-Shaw/sub2api/internal/service" "github.com/gin-gonic/gin" @@ -21,33 +24,49 @@ import ( type stickyWritebackContextKey struct{} type stickyWritebackCall struct { - err error - groupID int64 - account int64 - session string - ttl time.Duration - value any - deadline time.Time + err error + groupID int64 + account int64 + session string + ttl time.Duration + value any + deadline time.Time + replaceable []int64 } type stickyWritebackCache struct { service.GatewayCache accountID int64 - finished bool - calls []stickyWritebackCall + // readErr is returned by the first lookup only, then cleared: the binding + // lookup at request start fails while later reads see the key again. + readErr error + finished bool + calls []stickyWritebackCall + lookups []int64 } func (s *stickyWritebackCache) GetSessionAccountID(context.Context, int64, string) (int64, error) { + s.lookups = append(s.lookups, s.accountID) + if s.readErr != nil { + err := s.readErr + s.readErr = nil + return 0, err + } return s.accountID, nil } +func (s *stickyWritebackCache) record(ctx context.Context, groupID int64, session string, account int64, ttl time.Duration, replaceable []int64) { + deadline, _ := ctx.Deadline() + s.calls = append(s.calls, stickyWritebackCall{ + err: ctx.Err(), groupID: groupID, account: account, session: session, ttl: ttl, + value: ctx.Value(stickyWritebackContextKey{}), deadline: deadline, + replaceable: append([]int64(nil), replaceable...), + }) +} + func (s *stickyWritebackCache) SetSessionAccountID(ctx context.Context, groupID int64, session string, account int64, ttl time.Duration) error { if s.finished { - deadline, _ := ctx.Deadline() - s.calls = append(s.calls, stickyWritebackCall{ - err: ctx.Err(), groupID: groupID, account: account, session: session, ttl: ttl, - value: ctx.Value(stickyWritebackContextKey{}), deadline: deadline, - }) + s.record(ctx, groupID, session, account, ttl, nil) } if err := ctx.Err(); err != nil { return err @@ -56,6 +75,30 @@ func (s *stickyWritebackCache) SetSessionAccountID(ctx context.Context, groupID return nil } +// CompareAndBindSessionAccountID mirrors the Redis compare-and-bind script: a +// key already holding the account only gets its TTL refreshed, a missing key or +// one holding an account this request failed over from is overwritten, anything +// else was rebound by another request and is left alone. +func (s *stickyWritebackCache) CompareAndBindSessionAccountID(ctx context.Context, groupID int64, session string, account int64, replaceable []int64, ttl time.Duration) (bool, error) { + if err := ctx.Err(); err != nil { + return false, err + } + if s.accountID == account { + if s.finished { + s.record(ctx, groupID, session, account, ttl, replaceable) + } + return true, nil + } + if s.accountID == 0 || slices.Contains(replaceable, s.accountID) { + if s.finished { + s.record(ctx, groupID, session, account, ttl, replaceable) + } + s.accountID = account + return true, nil + } + return false, nil +} + func (s *stickyWritebackCache) RefreshSessionTTL(context.Context, int64, string, time.Duration) error { return nil } @@ -75,6 +118,23 @@ func (b *stickyWritebackBody) Close() error { return nil } +// stickyWritebackUpstream answers per account with a freshly built response, so +// a failover row can fail on the first account and serve on the second. +type stickyWritebackUpstream struct { + service.HTTPUpstream + responses map[int64]func() *http.Response + seen []int64 +} + +func (u *stickyWritebackUpstream) DoWithTLS(_ *http.Request, _ string, accountID int64, _ int, _ *tlsfingerprint.Profile) (*http.Response, error) { + u.seen = append(u.seen, accountID) + build, ok := u.responses[accountID] + if !ok { + return nil, fmt.Errorf("no upstream response for account %d", accountID) + } + return build(), nil +} + func TestGatewayMessagesStickyWritebackAfterForward(t *testing.T) { gin.SetMode(gin.TestMode) for _, stream := range []bool{false, true} { @@ -83,11 +143,29 @@ func TestGatewayMessagesStickyWritebackAfterForward(t *testing.T) { name = "streaming" } for _, tt := range []struct { - name string - bound int64 - cancel bool - fail bool - wantWrites int + name string + bound int64 + cancel bool + fail bool + // failover makes account 9401 fail with a 500 and account 9499 serve, + // mirroring a request that switches accounts mid-flight. + failover bool + // profitGate installs the group profit gate, which makes the request + // write the admitted account eagerly and skip a different binding. + profitGate bool + // readErr fails the binding lookup at request start. + readErr bool + during func(*stickyWritebackCache) + // rebindOnServe runs during on the serving forward instead of the + // failing one. + rebindOnServe bool + wantSeen []int64 + // wantWrites counts the terminal writes; reads and admission-time + // writes made before the forward are not counted. + wantWrites int + wantFinal int64 + checkFinal bool + wantSecondLookup int64 }{ {name: "new binding", wantWrites: 1}, {name: "new binding after disconnect", cancel: true, wantWrites: 1}, @@ -95,18 +173,89 @@ func TestGatewayMessagesStickyWritebackAfterForward(t *testing.T) { {name: "refresh after disconnect", bound: 9401, cancel: true, wantWrites: 1}, {name: "different binding", bound: 9499, cancel: true}, {name: "forward failed", cancel: true, fail: true}, + { + name: "rebound during forward", bound: 9401, checkFinal: true, wantFinal: 9499, wantSecondLookup: 9499, + during: func(c *stickyWritebackCache) { c.accountID = 9499 }, + }, + { + name: "bound by another request during forward", checkFinal: true, wantFinal: 9499, wantSecondLookup: 9499, + during: func(c *stickyWritebackCache) { c.accountID = 9499 }, + }, + { + name: "deleted during forward", bound: 9401, wantWrites: 1, checkFinal: true, wantFinal: 9401, + during: func(c *stickyWritebackCache) { c.accountID = 0 }, + }, + { + name: "rebound away and back during forward", bound: 9401, wantWrites: 1, checkFinal: true, wantFinal: 9401, + during: func(c *stickyWritebackCache) { c.accountID = 9499; c.accountID = 9401 }, + }, + { + // K1: the key starts missing, the request writes the admitted + // account A, A fails over to B. The key must end on B instead of + // keeping the account that just failed. + name: "profit gate missing binding failover", failover: true, profitGate: true, + wantSeen: []int64{9401, 9499}, wantWrites: 1, checkFinal: true, wantFinal: 9499, wantSecondLookup: 9499, + }, + { + name: "profit gate failed start lookup failover", failover: true, profitGate: true, readErr: true, + wantSeen: []int64{9401, 9499}, wantWrites: 1, checkFinal: true, wantFinal: 9499, wantSecondLookup: 9499, + }, + { + name: "profit gate bound to the failed account", bound: 9401, failover: true, profitGate: true, + wantSeen: []int64{9401, 9499}, wantWrites: 0, checkFinal: true, wantFinal: 9401, wantSecondLookup: 9401, + }, + { + // Another request rebinds to a third account while the failover + // already serves B: the third account was never tried here, so the + // terminal write leaves it alone and writes nothing. + name: "profit gate rebound by another request during failover", failover: true, profitGate: true, rebindOnServe: true, + wantSeen: []int64{9401, 9499}, checkFinal: true, wantFinal: 9455, + during: func(c *stickyWritebackCache) { c.accountID = 9455 }, + }, + { + // Without a profit gate the scheduler binds before every forward, + // so a failed account found in the key was bound by another request + // and is kept. + name: "rebound to the failed account during failover", failover: true, rebindOnServe: true, + wantSeen: []int64{9401, 9499}, checkFinal: true, wantFinal: 9401, + during: func(c *stickyWritebackCache) { c.accountID = 9401 }, + }, } { t.Run(name+"/"+tt.name, func(t *testing.T) { groupID := int64(9400) - group := &service.Group{ID: groupID, Hydrated: true, Platform: service.PlatformAnthropic, Status: service.StatusActive, RateMultiplier: 1} - account := &service.Account{ - ID: 9401, Platform: service.PlatformAnthropic, Type: service.AccountTypeAPIKey, - Status: service.StatusActive, Schedulable: true, Concurrency: 1, - Credentials: map[string]any{"api_key": "test-key"}, - Extra: map[string]any{"anthropic_passthrough": true}, - AccountGroups: []service.AccountGroup{{AccountID: 9401, GroupID: groupID}}, + group := &service.Group{ + ID: groupID, Hydrated: true, Platform: service.PlatformAnthropic, Status: service.StatusActive, + RateMultiplier: 1, SubscriptionType: service.SubscriptionTypeStandard, + ProfitControlEnabled: tt.profitGate, ProfitMinMargin: 0.5, + } + newAccount := func(id int64, priority int, schedulable bool) *service.Account { + rate := 0.1 + return &service.Account{ + ID: id, Platform: service.PlatformAnthropic, Type: service.AccountTypeAPIKey, + Status: service.StatusActive, Schedulable: schedulable, Concurrency: 1, Priority: priority, + RateMultiplier: &rate, + Credentials: map[string]any{"api_key": "test-key"}, + Extra: map[string]any{"anthropic_passthrough": true}, + AccountGroups: []service.AccountGroup{{AccountID: id, GroupID: groupID}}, + } + } + account := newAccount(9401, 0, true) + other := newAccount(9499, 1, tt.failover) + // third is only bound by the other request; it only has to resolve + // as a known account. + third := newAccount(9455, 2, true) + servedID := account.ID + if tt.failover { + servedID = other.ID + } + wantCalls := 1 + if tt.failover { + wantCalls = 2 } cache := &stickyWritebackCache{accountID: tt.bound} + if tt.readErr { + cache.readErr = fmt.Errorf("sticky cache read failed") + } ctx := context.WithValue(context.Background(), stickyWritebackContextKey{}, "request-scoped value") ctx, cancel := context.WithTimeout(ctx, 4*time.Second) t.Cleanup(cancel) @@ -121,23 +270,50 @@ func TestGatewayMessagesStickyWritebackAfterForward(t *testing.T) { status = http.StatusBadRequest responseBody = `{"type":"error","error":{"type":"invalid_request_error","message":"invalid input"}}` } - upstream := &compatStreamUsageUpstream{response: &http.Response{ - StatusCode: status, - Header: http.Header{"Content-Type": []string{contentType}}, - Body: &stickyWritebackBody{Reader: strings.NewReader(responseBody), finish: func() { - // Forward closes its upstream body on return. Cancel precisely - // after that work, before the handler's terminal sticky write. - cache.finished = true - if tt.cancel { - cancel() + duringRan := false + runDuring := func() { + if duringRan || tt.during == nil { + return + } + duringRan = true + tt.during(cache) + } + finish := func() { + // Forward closes its upstream body on return. Bound the concurrent + // rebind and cancel precisely after that work, before the handler's + // terminal sticky write. + cache.finished = true + runDuring() + if tt.cancel { + cancel() + } + } + respond := func(status int, contentType, body string, bodyFinish func()) func() *http.Response { + return func() *http.Response { + return &http.Response{ + StatusCode: status, + Header: http.Header{"Content-Type": []string{contentType}}, + Body: &stickyWritebackBody{Reader: strings.NewReader(body), finish: bodyFinish}, } - }}, - }} + } + } + responses := map[int64]func() *http.Response{} + if tt.failover { + // By default the failing attempt's body closes before the next + // account is selected, so a rebind there sits inside the + // failover; rebindOnServe moves it into the serving forward. + failingFinish := runDuring + if tt.rebindOnServe { + failingFinish = func() {} + } + responses[account.ID] = respond(http.StatusInternalServerError, "application/json", `{"type":"error","error":{"type":"api_error","message":"upstream boom"}}`, failingFinish) + responses[other.ID] = respond(status, contentType, responseBody, finish) + } else { + responses[account.ID] = respond(status, contentType, responseBody, finish) + } + upstream := &stickyWritebackUpstream{responses: responses} cfg := &config.Config{RunMode: config.RunModeSimple} - other := *account - other.ID = 9499 - other.Schedulable = false - snapshot := service.NewSchedulerSnapshotService(&fakeSchedulerCache{accounts: []*service.Account{account, &other}}, nil, nil, nil, nil) + snapshot := service.NewSchedulerSnapshotService(&fakeSchedulerCache{accounts: []*service.Account{account, other, third}}, nil, nil, nil, nil) gw := service.NewGatewayService( nil, &fakeGroupRepo{group: group}, nil, nil, nil, nil, nil, cache, cfg, snapshot, nil, service.NewBillingService(cfg, nil), nil, nil, nil, upstream, @@ -163,7 +339,12 @@ func TestGatewayMessagesStickyWritebackAfterForward(t *testing.T) { h.Messages(c) - require.Equal(t, 1, upstream.calls) + require.Equal(t, wantCalls, len(upstream.seen)) + if tt.wantSeen != nil { + require.Equal(t, tt.wantSeen, upstream.seen) + } else { + require.Equal(t, servedID, upstream.seen[len(upstream.seen)-1]) + } require.True(t, cache.finished) require.Equal(t, status, rec.Code) if tt.cancel { @@ -173,13 +354,30 @@ func TestGatewayMessagesStickyWritebackAfterForward(t *testing.T) { for _, call := range cache.calls { require.NoError(t, call.err, "a completed upstream request must retain its terminal sticky write") require.Equal(t, groupID, call.groupID) - require.Equal(t, account.ID, call.account) + require.Equal(t, servedID, call.account) require.NotEmpty(t, call.session) require.Positive(t, call.ttl) require.Equal(t, "request-scoped value", call.value) require.False(t, call.deadline.IsZero(), "the detached cache write must have a deadline") require.WithinDuration(t, time.Now(), call.deadline, 5*time.Second) } + if tt.checkFinal { + require.Equal(t, tt.wantFinal, cache.accountID, "the terminal write must only cover values this request may have written") + } + if tt.wantSecondLookup != 0 { + nextLookup := len(cache.lookups) + rec2 := httptest.NewRecorder() + c2, _ := gin.CreateTestContext(rec2) + c2.Request = httptest.NewRequest(http.MethodPost, "/v1/messages", strings.NewReader(requestBody)).WithContext(context.WithValue(context.Background(), stickyWritebackContextKey{}, "request-scoped value")) + c2.Request.Header.Set("Content-Type", "application/json") + c2.Set(string(middleware.ContextKeyAPIKey), key) + c2.Set(string(middleware.ContextKeyUser), middleware.AuthSubject{UserID: 9403}) + + h.Messages(c2) + + require.Equal(t, status, rec2.Code) + require.Equal(t, tt.wantSecondLookup, cache.lookups[nextLookup], "a later request must observe the terminal binding") + } }) } } diff --git a/backend/internal/repository/gateway_cache.go b/backend/internal/repository/gateway_cache.go index 4e5faf6ca2..42652e41a3 100644 --- a/backend/internal/repository/gateway_cache.go +++ b/backend/internal/repository/gateway_cache.go @@ -70,6 +70,53 @@ func (c *gatewayCache) DeleteSessionAccountID(ctx context.Context, groupID int64 return c.rdb.Del(ctx, key).Err() } +// compareAndBindStickySessionScript writes the served account unless another +// request rebound the key during the forward. ARGV[1] is the account, ARGV[2] +// the TTL in milliseconds and ARGV[3..] the accounts this request failed over +// from, which it may have written itself. A key already holding the account only +// gets its TTL refreshed; a missing key and one holding a replaceable account +// are written; any other value is left alone and 0 is returned. +var compareAndBindStickySessionScript = redis.NewScript(` +local current = redis.call('GET', KEYS[1]) +if current == ARGV[1] then + redis.call('PEXPIRE', KEYS[1], ARGV[2]) + return 1 +end +if current == false then + redis.call('SET', KEYS[1], ARGV[1], 'PX', ARGV[2]) + return 1 +end +for i = 3, #ARGV do + if current == ARGV[i] then + redis.call('SET', KEYS[1], ARGV[1], 'PX', ARGV[2]) + return 1 + end +end +return 0 +`) + +func (c *gatewayCache) CompareAndBindSessionAccountID(ctx context.Context, groupID int64, sessionHash string, accountID int64, replaceableAccountIDs []int64, ttl time.Duration) (bool, error) { + if c == nil || c.rdb == nil { + return false, errors.New("gateway cache unavailable") + } + if strings.TrimSpace(sessionHash) == "" || ttl <= 0 { + return false, errors.New("invalid sticky session bind") + } + // The bound values are stored as decimal strings (see SetSessionAccountID). + args := make([]any, 0, 2+len(replaceableAccountIDs)) + args = append(args, strconv.FormatInt(accountID, 10), ttl.Milliseconds()) + for _, replaceableAccountID := range replaceableAccountIDs { + args = append(args, strconv.FormatInt(replaceableAccountID, 10)) + } + n, err := compareAndBindStickySessionScript.Run( + ctx, + c.rdb, + []string{buildSessionKey(groupID, sessionHash)}, + args..., + ).Int() + return n == 1, err +} + var claimOpenAIResponsesSessionWindowScript = redis.NewScript(` local previous = redis.call('GET', KEYS[1]) redis.call('SET', KEYS[1], ARGV[1], 'PX', ARGV[2]) @@ -160,6 +207,7 @@ func (c *gatewayCache) CompareAndDeleteOpenAIResponsesSessionWindow(ctx context. } var _ service.OpenAIWSSessionPreemptionCache = (*gatewayCache)(nil) +var _ service.GatewayStickySessionCompareCache = (*gatewayCache)(nil) const ( grokVideoPendingBillingPrefix = "grok_video_pending:" diff --git a/backend/internal/repository/gateway_cache_integration_test.go b/backend/internal/repository/gateway_cache_integration_test.go index 1cd4217758..775bdea5fc 100644 --- a/backend/internal/repository/gateway_cache_integration_test.go +++ b/backend/internal/repository/gateway_cache_integration_test.go @@ -90,6 +90,84 @@ func (s *GatewayCacheSuite) TestDeleteSessionAccountID() { require.True(s.T(), errors.Is(err, service.ErrStickySessionNotFound), "expected ErrStickySessionNotFound after delete") } +func (s *GatewayCacheSuite) TestCompareAndBindSessionAccountID_BindsWhenHoldingReplaceable() { + sessionID := "cas-replaceable" + groupID := int64(1) + replaceable := int64(9499) + accountID := int64(9500) + + require.NoError(s.T(), s.cache.SetSessionAccountID(s.ctx, groupID, sessionID, replaceable, time.Minute), "SetSessionAccountID") + bound, err := s.cache.(service.GatewayStickySessionCompareCache).CompareAndBindSessionAccountID(s.ctx, groupID, sessionID, accountID, []int64{9400, replaceable}, time.Minute) + + require.NoError(s.T(), err) + require.True(s.T(), bound, "a key holding a replaceable account must be rewritten") + sid, err := s.cache.GetSessionAccountID(s.ctx, groupID, sessionID) + require.NoError(s.T(), err) + require.Equal(s.T(), accountID, sid) +} + +func (s *GatewayCacheSuite) TestCompareAndBindSessionAccountID_RefreshesBoundAccount() { + sessionID := "cas-refresh" + groupID := int64(1) + accountID := int64(9501) + + require.NoError(s.T(), s.cache.SetSessionAccountID(s.ctx, groupID, sessionID, accountID, time.Minute), "SetSessionAccountID") + bound, err := s.cache.(service.GatewayStickySessionCompareCache).CompareAndBindSessionAccountID(s.ctx, groupID, sessionID, accountID, nil, 5*time.Minute) + + require.NoError(s.T(), err) + require.True(s.T(), bound) + sid, err := s.cache.GetSessionAccountID(s.ctx, groupID, sessionID) + require.NoError(s.T(), err) + require.Equal(s.T(), accountID, sid) + ttl, err := s.rdb.TTL(s.ctx, buildSessionKey(groupID, sessionID)).Result() + require.NoError(s.T(), err) + s.AssertTTLWithin(ttl, 1*time.Second, 5*time.Minute) +} + +func (s *GatewayCacheSuite) TestCompareAndBindSessionAccountID_LeavesThirdAccount() { + sessionID := "cas-third" + groupID := int64(1) + third := int64(9499) + + require.NoError(s.T(), s.cache.SetSessionAccountID(s.ctx, groupID, sessionID, third, time.Minute), "SetSessionAccountID") + bound, err := s.cache.(service.GatewayStickySessionCompareCache).CompareAndBindSessionAccountID(s.ctx, groupID, sessionID, 9401, []int64{9400, 9402}, time.Minute) + + require.NoError(s.T(), err) + require.False(s.T(), bound, "a key holding a third account must be left alone") + sid, err := s.cache.GetSessionAccountID(s.ctx, groupID, sessionID) + require.NoError(s.T(), err) + require.Equal(s.T(), third, sid) +} + +func (s *GatewayCacheSuite) TestCompareAndBindSessionAccountID_LeavesThirdAccountWithoutReplaceables() { + sessionID := "cas-third-nil" + groupID := int64(1) + third := int64(9498) + + require.NoError(s.T(), s.cache.SetSessionAccountID(s.ctx, groupID, sessionID, third, time.Minute), "SetSessionAccountID") + bound, err := s.cache.(service.GatewayStickySessionCompareCache).CompareAndBindSessionAccountID(s.ctx, groupID, sessionID, 9401, nil, time.Minute) + + require.NoError(s.T(), err) + require.False(s.T(), bound, "a key holding any other account must be left alone") + sid, err := s.cache.GetSessionAccountID(s.ctx, groupID, sessionID) + require.NoError(s.T(), err) + require.Equal(s.T(), third, sid) +} + +func (s *GatewayCacheSuite) TestCompareAndBindSessionAccountID_BindsMissingKey() { + sessionID := "cas-missing" + groupID := int64(1) + accountID := int64(9402) + + bound, err := s.cache.(service.GatewayStickySessionCompareCache).CompareAndBindSessionAccountID(s.ctx, groupID, sessionID, accountID, []int64{9401}, time.Minute) + + require.NoError(s.T(), err) + require.True(s.T(), bound, "a missing key must be written even when replaceables were passed") + sid, err := s.cache.GetSessionAccountID(s.ctx, groupID, sessionID) + require.NoError(s.T(), err) + require.Equal(s.T(), accountID, sid) +} + func (s *GatewayCacheSuite) TestGetSessionAccountID_CorruptedValue() { sessionID := "corrupted" groupID := int64(1) diff --git a/backend/internal/repository/gateway_cache_sticky_cas_test.go b/backend/internal/repository/gateway_cache_sticky_cas_test.go new file mode 100644 index 0000000000..1acc20ca9f --- /dev/null +++ b/backend/internal/repository/gateway_cache_sticky_cas_test.go @@ -0,0 +1,68 @@ +package repository + +import ( + "context" + "testing" + "time" + + "github.com/Wei-Shaw/sub2api/internal/service" + "github.com/alicebob/miniredis/v2" + "github.com/redis/go-redis/v9" + "github.com/stretchr/testify/require" +) + +func TestGatewayCacheCompareAndBindSessionAccountID(t *testing.T) { + const ( + groupID = int64(7) + session = "cas-session" + account = int64(9401) + other = int64(9499) + neither = int64(8123) + bindTTL = 10 * time.Minute + initialTTL = 2 * time.Minute + ) + for _, tt := range []struct { + name string + current int64 // 0 = 键不存在 + replaceable []int64 + write bool + // refresh keeps the value and only renews the TTL. + refresh bool + wantValue int64 + }{ + {name: "missing key is written", write: true, wantValue: account}, + {name: "account itself only refreshes", current: account, refresh: true, wantValue: account}, + {name: "replaceable account is replaced", current: other, replaceable: []int64{neither, other}, write: true, wantValue: account}, + {name: "third account is left alone", current: other, replaceable: []int64{neither}, wantValue: other}, + {name: "third account without replaceables is left alone", current: other, wantValue: other}, + } { + t.Run(tt.name, func(t *testing.T) { + mr := miniredis.RunT(t) + client := redis.NewClient(&redis.Options{Addr: mr.Addr()}) + t.Cleanup(func() { _ = client.Close() }) + cache := NewGatewayCache(client) + comparable, ok := cache.(service.GatewayStickySessionCompareCache) + require.True(t, ok, "the Redis cache must expose the compare capability") + ctx := context.Background() + if tt.current != 0 { + require.NoError(t, cache.SetSessionAccountID(ctx, groupID, session, tt.current, initialTTL)) + } + + bound, err := comparable.CompareAndBindSessionAccountID(ctx, groupID, session, account, tt.replaceable, bindTTL) + require.NoError(t, err) + require.Equal(t, tt.write || tt.refresh, bound, "the write must be decided on the current value alone") + + got, err := cache.GetSessionAccountID(ctx, groupID, session) + require.NoError(t, err) + require.Equal(t, tt.wantValue, got) + ttl := mr.TTL(buildSessionKey(groupID, session)) + if tt.write || tt.refresh { + require.Greater(t, ttl, bindTTL-time.Minute, "a write must carry the new TTL") + require.LessOrEqual(t, ttl, bindTTL) + return + } + require.Greater(t, ttl, initialTTL-time.Minute, "a left-alone key keeps its TTL") + require.LessOrEqual(t, ttl, initialTTL) + }) + } +} diff --git a/backend/internal/service/gateway_service.go b/backend/internal/service/gateway_service.go index 7ed33d1470..c877007b91 100644 --- a/backend/internal/service/gateway_service.go +++ b/backend/internal/service/gateway_service.go @@ -564,6 +564,18 @@ type GatewayCache interface { GetReasoningContent(ctx context.Context, itemID string) (string, error) } +// GatewayStickySessionCompareCache is an optional GatewayCache capability. The +// production Redis cache compares and writes atomically; cache stubs do not +// need to implement it for ordinary gateway tests. +type GatewayStickySessionCompareCache interface { + // CompareAndBindSessionAccountID writes accountID and returns true when the + // key is missing, already holds accountID (only the TTL is refreshed) or + // holds one of replaceableAccountIDs, i.e. a value this request may have + // written itself. A key holding any other account was rebound by another + // request: it is left alone and false is returned. + CompareAndBindSessionAccountID(ctx context.Context, groupID int64, sessionHash string, accountID int64, replaceableAccountIDs []int64, ttl time.Duration) (bool, error) +} + // derefGroupID safely dereferences *int64 to int64, returning 0 if nil func derefGroupID(groupID *int64) int64 { if groupID == nil { @@ -1048,6 +1060,23 @@ func (s *GatewayService) BindStickySession(ctx context.Context, groupID *int64, return s.cache.SetSessionAccountID(ctx, derefGroupID(groupID), sessionHash, accountID, stickySessionTTL) } +// BindStickySessionUnlessRebound writes the terminal session -> account binding +// unless another request rebound the key while this one was forwarding. The +// write only covers values this request may have written itself: a missing key, +// accountID (only the TTL is refreshed) and the accounts it failed over from. +// Any other value belongs to another request and survives. Caches without the +// compare capability fall back to the unconditional write. +func (s *GatewayService) BindStickySessionUnlessRebound(ctx context.Context, groupID *int64, sessionHash string, accountID int64, replaceableAccountIDs []int64) error { + if sessionHash == "" || accountID <= 0 || s.cache == nil { + return nil + } + if cache, ok := s.cache.(GatewayStickySessionCompareCache); ok { + _, err := cache.CompareAndBindSessionAccountID(ctx, derefGroupID(groupID), sessionHash, accountID, replaceableAccountIDs, stickySessionTTL) + return err + } + return s.BindStickySession(ctx, groupID, sessionHash, accountID) +} + // bindGatewayStickySessionDuringSelection preserves the normal eager sticky // behavior unless a profit gate is installed. Profit-controlled requests bind // only after the terminal post-slot check, otherwise a rejected candidate could From 30fe563b1fc97fb73891abdc81f8403b8b339ebe Mon Sep 17 00:00:00 2001 From: Anankke Date: Fri, 20 Nov 2026 23:07:51 -0800 Subject: [PATCH 06/23] fix(gateway): restore tool names split across stream deltas On streams the response side renames tool names back on each SSE event by itself, so a rewritten name split across two text_delta or input_json_delta events matches in neither and reaches the client unrestored. Keep, per content block, the tail of a text or partial_json payload that could be the start of a rewritten name and join it to the block's next text or JSON delta before renaming back. Held bytes go out as one more delta before content_block_stop, or before the closing event when the stream ends another way. Other delta types such as citations_delta pass through and leave the tail held. The native stream applies this to the events it writes, the Chat Completions and Responses bridges to the upstream event before conversion. --- .../gateway_forward_as_chat_completions.go | 32 +- .../service/gateway_forward_as_responses.go | 36 +- .../service/gateway_tool_rewrite_stream.go | 263 +++++ .../gateway_tool_rewrite_stream_test.go | 988 ++++++++++++++++++ .../service/gateway_upstream_response.go | 124 ++- 5 files changed, 1403 insertions(+), 40 deletions(-) create mode 100644 backend/internal/service/gateway_tool_rewrite_stream.go create mode 100644 backend/internal/service/gateway_tool_rewrite_stream_test.go diff --git a/backend/internal/service/gateway_forward_as_chat_completions.go b/backend/internal/service/gateway_forward_as_chat_completions.go index fb5f932a7e..c304d45690 100644 --- a/backend/internal/service/gateway_forward_as_chat_completions.go +++ b/backend/internal/service/gateway_forward_as_chat_completions.go @@ -423,6 +423,7 @@ func (s *GatewayService) handleCCStreamingFromAnthropic( anthState.Model = originalModel ccState := apicompat.NewResponsesEventToChatState() ccState.Model = originalModel + toolNameRestorer := newToolNameStreamRestorer(toolNameRewriteFromContext(c)) var usage ClaudeUsage var firstTokenMs *int @@ -535,23 +536,36 @@ func (s *GatewayService) handleCCStreamingFromAnthropic( continue } - var event apicompat.AnthropicStreamEvent - if err := json.Unmarshal([]byte(payload), &event); err != nil { - continue + var restored [2][]byte + n := 1 + if toolNameRestorer == nil { + restored[0] = streamEventBytes(payload) + } else { + n = toolNameRestorer.restoreInto(streamEventBytes(payload), &restored) } + for _, payload := range restored[:n] { + var event apicompat.AnthropicStreamEvent + if err := json.Unmarshal(payload, &event); err != nil { + continue + } - // Forward received usage regardless of the client stream_options. - // The intermediate Responses converter synthesizes usage even when absent. - ccState.IncludeUsage = ccState.IncludeUsage || anthropicChatStreamHasUsage(&event, payload) + // Forward received usage regardless of the client stream_options. + // The intermediate Responses converter synthesizes usage even when absent. + ccState.IncludeUsage = ccState.IncludeUsage || anthropicChatStreamHasUsage(&event, string(payload)) - observer.ObserveAnthropic([]byte(payload)) - stream.observe(&event, payload) + observer.ObserveAnthropic(payload) + stream.observe(&event, string(payload)) + if stream.upstreamErrType != "" { + break + } + processAnthropicEvent(&event) + } if stream.upstreamErrType != "" { break } - processAnthropicEvent(&event) } + flushToolNameCarry(c, c.Writer.Size() != writerSizeBeforeStream, toolNameRestorer, processAnthropicEvent) if failure := stream.failure(); failure != nil { return finishAnthropicCompatStreamFailure(c, writerSizeBeforeStream, failure, resultWithUsage(), func() { writeAnthropicCompatCCStreamFailure(c, failure) diff --git a/backend/internal/service/gateway_forward_as_responses.go b/backend/internal/service/gateway_forward_as_responses.go index faa1bd7e0c..8effc0aecd 100644 --- a/backend/internal/service/gateway_forward_as_responses.go +++ b/backend/internal/service/gateway_forward_as_responses.go @@ -634,6 +634,7 @@ func (s *GatewayService) handleResponsesStreamingResponse( state.Model = originalModel state.PreserveThinkingSignatures = isClaude55SignedThinkingModel(mappedModel) clientToolRestorer := apicompat.NewResponsesClientToolStreamRestorer(clientToolMapping) + toolNameRestorer := newToolNameStreamRestorer(toolNameRewriteFromContext(c)) var usage ClaudeUsage var firstTokenMs *int firstChunk := true @@ -763,24 +764,37 @@ func (s *GatewayService) handleResponsesStreamingResponse( continue } - var event apicompat.AnthropicStreamEvent - if err := json.Unmarshal([]byte(payload), &event); err != nil { - logger.L().Warn("forward_as_responses stream: failed to parse event", - zap.Error(err), - zap.String("request_id", requestID), - zap.String("event_type", eventType), - ) - continue + var restored [2][]byte + n := 1 + if toolNameRestorer == nil { + restored[0] = streamEventBytes(payload) + } else { + n = toolNameRestorer.restoreInto(streamEventBytes(payload), &restored) } + for _, payload := range restored[:n] { + var event apicompat.AnthropicStreamEvent + if err := json.Unmarshal(payload, &event); err != nil { + logger.L().Warn("forward_as_responses stream: failed to parse event", + zap.Error(err), + zap.String("request_id", requestID), + zap.String("event_type", eventType), + ) + continue + } - observer.ObserveAnthropic([]byte(payload)) - stream.observe(&event, payload) + observer.ObserveAnthropic(payload) + stream.observe(&event, string(payload)) + if stream.upstreamErrType != "" { + break + } + processEvent(&event) + } if stream.upstreamErrType != "" { break } - processEvent(&event) } + flushToolNameCarry(c, c.Writer.Size() != writerSizeBeforeStream, toolNameRestorer, processEvent) return finalizeStream() } diff --git a/backend/internal/service/gateway_tool_rewrite_stream.go b/backend/internal/service/gateway_tool_rewrite_stream.go new file mode 100644 index 0000000000..132432ec69 --- /dev/null +++ b/backend/internal/service/gateway_tool_rewrite_stream.go @@ -0,0 +1,263 @@ +package service + +import ( + "bytes" + "encoding/json" + "maps" + "slices" + "strconv" + "unicode/utf8" + "unsafe" + + "github.com/Wei-Shaw/sub2api/internal/pkg/apicompat" + "github.com/gin-gonic/gin" + "github.com/tidwall/gjson" +) + +type toolNameStreamRestorer struct { + rw *ToolNameRewrite + maxFakeLen int + carry map[int]toolNameStreamCarry + // pending 是本请求可能原样出现在流里的全部假名(动态 ReverseOrdered 的假名侧加静态 + // 映射的假名侧),构造时一次转成只读视图;heldSuffixLen 逐 delta 只遍历它。 + pending [][]byte + // pendingFirst 标记 pending 中出现过的首字节,用来跳过不可能匹配的起点。 + pendingFirst [256]bool +} + +// 承载文本的 delta 类型 → 载荷字段名。 +var toolNameStreamDeltaFields = map[string]string{ + "text_delta": "text", + "input_json_delta": "partial_json", +} + +// 事件 type 值的廉价预筛:不含这两个子串的事件不进 gjson。 +var ( + sseContentBlockDeltaBytes = []byte("content_block_delta") + sseContentBlockStopBytes = []byte("content_block_stop") +) + +type toolNameStreamCarry struct { + deltaType, field, text string +} + +func newToolNameStreamRestorer(rw *ToolNameRewrite) *toolNameStreamRestorer { + if rw == nil || len(rw.ReverseOrdered) == 0 { + return nil + } + // 静态假前缀不经映射也会被还原,同样要能留尾巴。 + r := &toolNameStreamRestorer{rw: rw, carry: map[int]toolNameStreamCarry{}, pending: make([][]byte, 0, len(rw.ReverseOrdered)+len(staticToolNameRewrites))} + for _, pair := range rw.ReverseOrdered { + r.maxFakeLen = max(r.maxFakeLen, r.addPending(pair[0])) + } + for _, fake := range staticToolNameRewrites { + r.maxFakeLen = max(r.maxFakeLen, r.addPending(fake)) + } + return r +} + +// addPending 把 fake 存进 pending 并登记首字节,返回其字节长度。 +// 假名在请求期内不可变(静态表是进程级常量),存只读视图即可,不复制。 +func (r *toolNameStreamRestorer) addPending(fake string) int { + b := unsafe.Slice(unsafe.StringData(fake), len(fake)) + r.pending = append(r.pending, b) + if len(b) > 0 { + r.pendingFirst[b[0]] = true + } + return len(b) +} + +// restoreInto 处理一个流事件 JSON,把要发出的事件写进 out 并返回条数:0 表示整段 +// 扣住;1 表示 out[0] 是原事件或它的改写;2 仅出现在 content_block_stop 上, +// out[0] 是 stop 前补发的 carry 事件、out[1] 是 stop 本身。 +// 不改动事件时 out[0] 就是 data 本身,不复制也不分配;改写的分支才新建字节。 +// 调用方在 r 为 nil 时跳过本方法,走与无还原器时相同的代码。 +func (r *toolNameStreamRestorer) restoreInto(data []byte, out *[2][]byte) int { + if !bytes.Contains(data, sseContentBlockDeltaBytes) && !bytes.Contains(data, sseContentBlockStopBytes) { + out[0] = data + return 1 + } + view := openAIWSPayloadStringView(data) + eventType := gjson.Get(view, "type").String() + idxRes := gjson.Get(view, "index") + if !idxRes.Exists() || (eventType != "content_block_delta" && eventType != "content_block_stop") { + out[0] = data + return 1 + } + idx := int(idxRes.Int()) + carry := r.carry[idx] + if eventType == "content_block_stop" { + if carry.text == "" { + out[0] = data + return 1 + } + delete(r.carry, idx) + out[0] = r.carryEvent(idx, carry) + out[1] = data + return 2 + } + delta := gjson.Get(view, "delta") + deltaType := delta.Get("type").String() + field, known := toolNameStreamDeltaFields[deltaType] + var payload gjson.Result + if known { + payload = delta.Get(field) + } + if !known || payload.Type != gjson.String { + // 不是承载文本的 delta(citations_delta、未知类型、载荷不是字符串):原样放行, + // 不动该 index 的 carry。若在这里补发,被切名字的后半段就再也拼不回来;carry + // 留到下一个同 index 文本 delta 或 content_block_stop / 结束路径再出。 + out[0] = data + return 1 + } + payloadText := payload.String() + var raw []byte + if carry.text == "" { + raw = unsafe.Slice(unsafe.StringData(payloadText), len(payloadText)) + } else { + raw = make([]byte, len(carry.text)+len(payloadText)) + copy(raw, carry.text) + copy(raw[len(carry.text):], payloadText) + } + keep := r.heldSuffixLen(raw) + if carry.text != "" || keep > 0 { + delete(r.carry, idx) + } + if keep > 0 { + r.carry[idx] = toolNameStreamCarry{deltaType: deltaType, field: field, text: string(raw[len(raw)-keep:])} + } + if keep == len(raw) { + return 0 // 整个载荷都是假名开头,等后续事件或结束路径补发 + } + emit := restoreToolNamesInBytes(raw[:len(raw)-keep], r.rw) + if carry.text == "" && bytes.Equal(emit, raw) { + out[0] = data + return 1 + } + out[0] = setStreamDeltaField(data, payload, emit) + return 1 +} + +// setStreamDeltaField 用 emit 替换事件里 delta 载荷的值,一次分配。 +// gjson 的嵌套 Result.Get 会把父结果的 Index 加到子结果上,payload.Index 因此相对原文 +// data,payload.Raw 含两侧引号。 +func setStreamDeltaField(data []byte, payload gjson.Result, emit []byte) []byte { + next := make([]byte, 0, len(data)+len(emit)+2) + next = append(next, data[:payload.Index]...) + next = appendJSONText(next, string(emit)) + return append(next, data[payload.Index+len(payload.Raw):]...) +} + +// streamEventBytes 返回 s 的只读视图,不复制。事件 JSON 只被读取(restoreInto、 +// gjson、json.Unmarshal),调用方不得写入;拼接时 append 因 cap 用尽会自己复制。 +func streamEventBytes(s string) []byte { + return unsafe.Slice(unsafe.StringData(s), len(s)) +} + +// jsonHexDigits 是 appendJSONText 写 \u00XX 用的十六进制字符表。 +const jsonHexDigits = "0123456789abcdef" + +// appendJSONText 把 s 作为 JSON 字符串追加到 dst,只转义 JSON 要求的字节: +// 双引号、反斜杠与 U+0000–U+001F 的控制字符。其余字节原样输出,< > & 与非 ASCII +// (按 UTF-8 原样)因此不会被改写成 \u003c / \u0026 / \u00e9,解出的值与输入 +// 逐字节相等。无需转义时只补两侧引号,不再额外分配。 +func appendJSONText(dst []byte, s string) []byte { + if !needsJSONEscape(s) { + dst = append(dst, '"') + dst = append(dst, s...) + return append(dst, '"') + } + dst = append(dst, '"') + from := 0 + for i := 0; i < len(s); i++ { + var short byte + switch c := s[i]; { + case c == '"' || c == '\\': + short = c + case c == '\n': + short = 'n' + case c == '\r': + short = 'r' + case c == '\t': + short = 't' + case c >= ' ': + continue + default: // 其余控制字节写成 \u00XX + dst = append(dst, s[from:i]...) + dst = append(dst, '\\', 'u', '0', '0', jsonHexDigits[c>>4], jsonHexDigits[c&0x0f]) + from = i + 1 + continue + } + dst = append(dst, s[from:i]...) + dst = append(dst, '\\', short) + from = i + 1 + } + dst = append(dst, s[from:]...) + return append(dst, '"') +} + +// needsJSONEscape 报告 s 中是否有 appendJSONText 必须转义的字节。 +func needsJSONEscape(s string) bool { + for i := 0; i < len(s); i++ { + if c := s[i]; c < ' ' || c == '"' || c == '\\' { + return true + } + } + return false +} + +// flush 按 index 升序补发全部残留 carry,返回合成的 content_block_delta 事件。 +// 调用方负责 r 非 nil。 +func (r *toolNameStreamRestorer) flush() [][]byte { + var out [][]byte + for _, i := range slices.Sorted(maps.Keys(r.carry)) { + carry := r.carry[i] + out = append(out, r.carryEvent(i, toolNameStreamCarry{carry.deltaType, carry.field, string(restoreToolNamesInBytes([]byte(carry.text), r.rw))})) + } + clear(r.carry) + return out +} + +// heldSuffixLen 返回 s 末尾要扣住的最长 l(1 ≤ l ≤ maxFakeLen-1):后 l 字节是某个假名 +// 的真前缀、该假名比 l 长,且 s[len-l] 是 rune 起点。候选与首字节表在构造时备好, +// 这里不对 map 做 range,不做 string↔[]byte 转换,不分配。 +func (r *toolNameStreamRestorer) heldSuffixLen(s []byte) int { + for l := min(r.maxFakeLen-1, len(s)); l >= 1; l-- { + start := len(s) - l + if !r.pendingFirst[s[start]] || !utf8.RuneStart(s[start]) { + continue + } + for _, fake := range r.pending { + if len(fake) > l && bytes.HasPrefix(fake, s[start:]) { + return l + } + } + } + return 0 +} + +func (r *toolNameStreamRestorer) carryEvent(idx int, carry toolNameStreamCarry) []byte { + b := make([]byte, 0, 96+len(carry.text)) + b = append(b, `{"type":"content_block_delta","index":`...) + b = strconv.AppendInt(b, int64(idx), 10) + b = append(b, `,"delta":{"type":"`...) + b = append(b, carry.deltaType...) + b = append(b, `","`...) + b = append(b, carry.field...) + b = append(b, `":`...) + b = appendJSONText(b, carry.text) + return append(b, '}', '}') +} + +func flushToolNameCarry(c *gin.Context, wrote bool, r *toolNameStreamRestorer, handle func(*apicompat.AnthropicStreamEvent)) { + if !wrote || r == nil { + return + } + for _, data := range r.flush() { + var event apicompat.AnthropicStreamEvent + if err := json.Unmarshal(data, &event); err != nil { + continue + } + handle(&event) + } +} diff --git a/backend/internal/service/gateway_tool_rewrite_stream_test.go b/backend/internal/service/gateway_tool_rewrite_stream_test.go new file mode 100644 index 0000000000..4d276a733c --- /dev/null +++ b/backend/internal/service/gateway_tool_rewrite_stream_test.go @@ -0,0 +1,988 @@ +package service + +import ( + "context" + "encoding/json" + "errors" + "fmt" + "io" + "net/http" + "net/http/httptest" + "strings" + "testing" + "time" + "unicode/utf8" + + "github.com/Wei-Shaw/sub2api/internal/config" + "github.com/Wei-Shaw/sub2api/internal/pkg/apicompat" + "github.com/gin-gonic/gin" + "github.com/stretchr/testify/require" + "github.com/tidwall/gjson" + "github.com/tidwall/sjson" +) + +// toolNameSplitToolsBody 让 buildDynamicToolMap 把 read 映射成 analyze_rea01: +// 6 个工具触发动态映射,工具名与顺序固定 buildDynamicToolMap 的种子。 +const toolNameSplitToolsBody = `{"tools":[{"name":"alpha53","input_schema":{}},{"name":"read","input_schema":{}},{"name":"write_file","input_schema":{}},{"name":"bash","input_schema":{}},{"name":"edit","input_schema":{}},{"name":"grep","input_schema":{}}]}` + +const toolNameSplitFake = "analyze_rea01" + +func newToolNameSplitGatewayService() *GatewayService { + return &GatewayService{ + cfg: &config.Config{Gateway: config.GatewayConfig{MaxLineSize: defaultMaxLineSize}}, + rateLimitService: &RateLimitService{}, + } +} + +// newToolNameSplitContext 返回带请求侧工具名映射(read → analyze_rea01)的测试上下文。 +func newToolNameSplitContext(t *testing.T) (*gin.Context, *httptest.ResponseRecorder, *ToolNameRewrite) { + t.Helper() + gin.SetMode(gin.TestMode) + rec := httptest.NewRecorder() + c, _ := gin.CreateTestContext(rec) + c.Request = httptest.NewRequest(http.MethodPost, "/v1/messages", nil) + rw := buildToolNameRewriteFromBody([]byte(toolNameSplitToolsBody)) + require.NotNil(t, rw) + require.Equal(t, toolNameSplitFake, rw.Forward["read"]) + c.Set(toolNameRewriteKey, rw) + return c, rec, rw +} + +// tnSSEEvent 把一个 data JSON 包成 SSE 事件块,事件名取 type 字段。 +func tnSSEEvent(dataJSON string) string { + return "event: " + gjson.Get(dataJSON, "type").String() + "\ndata: " + dataJSON + "\n\n" +} + +// tnSSEDelta 构造 content_block_delta 的 data JSON。 +func tnSSEDelta(t *testing.T, idx int, deltaType, field, payload string) string { + t.Helper() + b, err := json.Marshal(map[string]any{ + "type": "content_block_delta", + "index": idx, + "delta": map[string]any{"type": deltaType, field: payload}, + }) + require.NoError(t, err) + return string(b) +} + +// tnClientJoined 解析客户端收到的 SSE 体,把 path 命中的字符串按出现顺序拼接。 +func tnClientJoined(body, path string) string { + var b strings.Builder + for _, block := range strings.Split(body, "\n\n") { + for _, line := range strings.Split(block, "\n") { + rest, ok := strings.CutPrefix(strings.TrimSpace(line), "data:") + if !ok { + continue + } + data := strings.TrimSpace(rest) + if !gjson.Valid(data) { + continue + } + if v := gjson.Get(data, path); v.Type == gjson.String { + _, _ = b.WriteString(v.String()) + } + } + } + return b.String() +} + +func TestHandleStreamingResponse_RestoresToolNameSplitAcrossTextDeltas(t *testing.T) { + svc := newToolNameSplitGatewayService() + c, rec, _ := newToolNameSplitContext(t) + + pr, pw := io.Pipe() + resp := &http.Response{StatusCode: http.StatusOK, Header: http.Header{}, Body: pr} + go func() { + defer func() { _ = pw.Close() }() + _, _ = io.WriteString(pw, tnSSEEvent(`{"type":"message_start","message":{"id":"msg_1","type":"message","role":"assistant","content":[],"model":"claude-sonnet-4.5","usage":{"input_tokens":1}}}`)) + _, _ = io.WriteString(pw, tnSSEEvent(`{"type":"content_block_start","index":0,"content_block":{"type":"text","text":""}}`)) + _, _ = io.WriteString(pw, tnSSEEvent(tnSSEDelta(t, 0, "text_delta", "text", "use analyze_r"))) + _, _ = io.WriteString(pw, tnSSEEvent(tnSSEDelta(t, 0, "text_delta", "text", "ea01 now"))) + _, _ = io.WriteString(pw, tnSSEEvent(`{"type":"content_block_stop","index":0}`)) + _, _ = io.WriteString(pw, tnSSEEvent(`{"type":"message_stop"}`)) + }() + + _, err := svc.handleStreamingResponse(context.Background(), resp, c, &Account{ID: 1}, time.Now(), "model", "model", false) + _ = pr.Close() + require.NoError(t, err) + + require.Equal(t, "use read now", tnClientJoined(rec.Body.String(), "delta.text")) + require.NotContains(t, rec.Body.String(), "analyze_") +} + +func TestHandleStreamingResponse_RestoresToolNameSplitAcrossInputJSONDeltas(t *testing.T) { + svc := newToolNameSplitGatewayService() + c, rec, _ := newToolNameSplitContext(t) + + pr, pw := io.Pipe() + resp := &http.Response{StatusCode: http.StatusOK, Header: http.Header{}, Body: pr} + go func() { + defer func() { _ = pw.Close() }() + _, _ = io.WriteString(pw, tnSSEEvent(`{"type":"message_start","message":{"id":"msg_2","type":"message","role":"assistant","content":[],"model":"claude-sonnet-4.5","usage":{"input_tokens":1}}}`)) + _, _ = io.WriteString(pw, tnSSEEvent(`{"type":"content_block_start","index":1,"content_block":{"type":"tool_use","id":"tu_1","name":"analyze_rea01","input":{}}}`)) + _, _ = io.WriteString(pw, tnSSEEvent(tnSSEDelta(t, 1, "input_json_delta", "partial_json", `{"file_path":"analyze_r`))) + _, _ = io.WriteString(pw, tnSSEEvent(tnSSEDelta(t, 1, "input_json_delta", "partial_json", `ea01"}`))) + _, _ = io.WriteString(pw, tnSSEEvent(`{"type":"content_block_stop","index":1}`)) + _, _ = io.WriteString(pw, tnSSEEvent(`{"type":"message_stop"}`)) + }() + + _, err := svc.handleStreamingResponse(context.Background(), resp, c, &Account{ID: 1}, time.Now(), "model", "model", false) + _ = pr.Close() + require.NoError(t, err) + + require.Equal(t, `{"file_path":"read"}`, tnClientJoined(rec.Body.String(), "delta.partial_json")) + require.NotContains(t, rec.Body.String(), "analyze_") +} + +func TestHandleCCStreamingFromAnthropic_RestoresToolNameSplitAcrossTextDeltas(t *testing.T) { + c, rec, _ := newToolNameSplitContext(t) + stream := strings.Join([]string{ + tnSSEEvent(`{"type":"message_start","message":{"id":"msg_3","type":"message","role":"assistant","content":[],"model":"claude-sonnet-4.5","usage":{"input_tokens":1}}}`), + tnSSEEvent(`{"type":"content_block_start","index":0,"content_block":{"type":"text","text":""}}`), + tnSSEEvent(tnSSEDelta(t, 0, "text_delta", "text", "use analyze_r")), + tnSSEEvent(tnSSEDelta(t, 0, "text_delta", "text", "ea01 now")), + tnSSEEvent(`{"type":"content_block_stop","index":0}`), + tnSSEEvent(`{"type":"message_stop"}`), + }, "") + resp := &http.Response{Header: http.Header{}, Body: io.NopCloser(strings.NewReader(stream))} + + svc := &GatewayService{} + _, err := svc.handleCCStreamingFromAnthropic(resp, c, "model", "model", nil, time.Now()) + require.NoError(t, err) + + require.Equal(t, "use read now", tnClientJoined(rec.Body.String(), "choices.0.delta.content")) + require.NotContains(t, rec.Body.String(), "analyze_") +} + +func TestHandleResponsesStreamingResponse_RestoresToolNameSplitAcrossTextDeltas(t *testing.T) { + c, rec, _ := newToolNameSplitContext(t) + stream := strings.Join([]string{ + tnSSEEvent(`{"type":"message_start","message":{"id":"msg_4","type":"message","role":"assistant","content":[],"model":"claude-sonnet-4.5","usage":{"input_tokens":1}}}`), + tnSSEEvent(`{"type":"content_block_start","index":0,"content_block":{"type":"text","text":""}}`), + tnSSEEvent(tnSSEDelta(t, 0, "text_delta", "text", "use analyze_r")), + tnSSEEvent(tnSSEDelta(t, 0, "text_delta", "text", "ea01 now")), + tnSSEEvent(`{"type":"content_block_stop","index":0}`), + tnSSEEvent(`{"type":"message_stop"}`), + }, "") + resp := &http.Response{Header: http.Header{}, Body: io.NopCloser(strings.NewReader(stream))} + + svc := &GatewayService{} + _, err := svc.handleResponsesStreamingResponse(resp, c, "claude-sonnet-4.5", "claude-sonnet-4.5", nil, time.Now(), apicompat.ResponsesClientToolMapping{}) + require.NoError(t, err) + + require.Equal(t, "use read now", tnClientJoined(rec.Body.String(), "delta")) + require.NotContains(t, rec.Body.String(), "analyze_") +} + +// --- 还原器单测 --- + +const toolNameStaticToolsBody = `{"tools":[{"name":"sessions_x","input_schema":{}},{"name":"sessions_xy","input_schema":{}},{"name":"session_x","input_schema":{}},{"name":"session_xy","input_schema":{}}]}` + +func tnDynamicRewrite(t *testing.T) *ToolNameRewrite { + t.Helper() + rw := buildToolNameRewriteFromBody([]byte(toolNameSplitToolsBody)) + require.NotNil(t, rw) + require.Equal(t, toolNameSplitFake, rw.Forward["read"]) + return rw +} + +func tnStaticRewrite(t *testing.T) *ToolNameRewrite { + t.Helper() + rw := buildToolNameRewriteFromBody([]byte(toolNameStaticToolsBody)) + require.NotNil(t, rw) + require.Equal(t, "cc_sess_xy", rw.Forward["sessions_xy"]) + require.Equal(t, "cc_sess_x", rw.Forward["sessions_x"]) + return rw +} + +// tnPayloadOf 取出 delta 的字符串载荷;text 与 partial_json 都认。 +func tnPayloadOf(data []byte) string { + for _, field := range []string{"text", "partial_json"} { + if v := gjson.GetBytes(data, "delta."+field); v.Type == gjson.String { + return v.String() + } + } + return "" +} + +// tnRestore 按生产调用点的语义调用还原器:nil 还原器与 nil data 都在这里挡住。 +func tnRestore(r *toolNameStreamRestorer, data []byte) [][]byte { + if r == nil { + if data == nil { + return nil + } + return [][]byte{data} + } + if data == nil { + return r.flush() + } + var out [2][]byte + return out[:r.restoreInto(data, &out)] +} + +// tnRun 把上游事件喂给还原器,按顺序返回发出的全部事件 JSON。 +func tnRun(r *toolNameStreamRestorer, upstream []string) []string { + var out []string + for _, data := range upstream { + for _, ev := range tnRestore(r, []byte(data)) { + out = append(out, string(ev)) + } + } + return out +} + +// tnCheckInvariant 断言客户端按 index 拼接的载荷,在每个 stop 到达时与全部原始载荷 +// 一次性还原的结果一致;返回拼接结果供调用方继续断言。 +func tnCheckInvariant(t *testing.T, r *toolNameStreamRestorer, rw *ToolNameRewrite, upstream []string, want map[int]string) map[int]string { + t.Helper() + got := map[int]string{} + for _, data := range upstream { + for _, ev := range tnRestore(r, []byte(data)) { + idx := int(gjson.GetBytes(ev, "index").Int()) + switch gjson.GetBytes(ev, "type").String() { + case "content_block_delta": + payload := tnPayloadOf(ev) + if payload == "" && tnIsTextDelta(ev) { + require.NotEmpty(t, payload, "empty delta must not be emitted: %s", ev) + } + if !tnIsTextDelta(ev) { + // 非文本 delta 原样放行,不参与拼接。 + break + } + require.True(t, utf8.ValidString(payload), "payload must stay valid UTF-8: %q", payload) + got[idx] += payload + case "content_block_stop": + require.Equal(t, want[idx], got[idx], "payload for index %d when its stop arrives", idx) + } + } + } + for _, ev := range tnRestore(r, nil) { + got[int(gjson.GetBytes(ev, "index").Int())] += tnPayloadOf(ev) + } + require.Empty(t, r.carry) + for idx, w := range want { + require.Equal(t, w, got[idx], "payload for index %d after flush", idx) + } + return got +} + +// tnIsTextDelta 指示事件是否为承载文本载荷的 delta(text_delta / input_json_delta)。 +func tnIsTextDelta(ev []byte) bool { + switch gjson.GetBytes(ev, "delta.type").String() { + case "text_delta", "input_json_delta": + return true + } + return false +} + +// tnWant 返回按 index 拼接原始载荷后一次性还原的结果,作为不变式的判据。 +func tnWant(rw *ToolNameRewrite, raw map[int]string) map[int]string { + want := map[int]string{} + for idx, s := range raw { + want[idx] = string(restoreToolNamesInBytes([]byte(s), rw)) + } + return want +} + +// tnDeltas 把 full 按 cuts 切开,包成同 index、同类型的 content_block_delta。 +func tnDeltas(t *testing.T, idx int, deltaType, field, full string, cuts []int) []string { + t.Helper() + var out []string + prev := 0 + for _, cut := range append(cuts, len(full)) { + out = append(out, string(tnDeltaJSON(t, idx, deltaType, field, full[prev:cut]))) + prev = cut + } + return out +} + +func tnDeltaJSON(t *testing.T, idx int, deltaType, field, payload string) []byte { + t.Helper() + b, err := json.Marshal(map[string]any{ + "type": "content_block_delta", "index": idx, + "delta": map[string]any{"type": deltaType, field: payload}, + }) + require.NoError(t, err) + return b +} + +func tnStopJSON(idx int) string { + return fmt.Sprintf(`{"type":"content_block_stop","index":%d}`, idx) +} + +func tnCutPositions(n int) []int { + var out []int + for cut := 1; cut < n; cut++ { + out = append(out, cut) + } + return out +} + +type tnDeltaKind struct{ deltaType, field string } + +var tnKinds = []tnDeltaKind{{"text_delta", "text"}, {"input_json_delta", "partial_json"}} + +// 切分点落在假名每个字节位置:动态假名与静态假名、text 与 partial_json。 +func TestToolNameStreamRestorer_SplitAtEveryFakeByte(t *testing.T) { + for _, tc := range []struct { + name string + rw *ToolNameRewrite + fake string + real string + }{ + {"dynamic", tnDynamicRewrite(t), toolNameSplitFake, "read"}, + {"static-prefix-of-fake", tnStaticRewrite(t), "cc_sess_xy", "sessions_xy"}, + } { + t.Run(tc.name, func(t *testing.T) { + full := "use " + tc.fake + " now" + at := strings.Index(full, tc.fake) + for _, cut := range tnCutPositions(len(full)) { + if cut <= at || cut >= at+len(tc.fake) { + continue + } + for _, kind := range tnKinds { + up := tnDeltas(t, 0, kind.deltaType, kind.field, full, []int{cut}) + up = append(up, tnStopJSON(0)) + r := newToolNameStreamRestorer(tc.rw) + got := tnCheckInvariant(t, r, tc.rw, up, tnWant(tc.rw, map[int]string{0: full})) + require.Equal(t, "use "+tc.real+" now", got[0]) + require.NotContains(t, got[0], "cc_ss") + } + } + }) + } +} + +func tnEvenCuts(n, parts, offset int) []int { + step := max(1, (n-2)/(parts-1)) + var cuts []int + for c := 1 + offset; c < n && len(cuts) < parts-1; c += step { + cuts = append(cuts, c) + } + for len(cuts) < parts-1 { + cuts = append(cuts, cuts[len(cuts)-1]+1) + } + return cuts +} + +// 一个假名跨 2 到 5 个 delta。 +func TestToolNameStreamRestorer_SplitAcrossManyDeltas(t *testing.T) { + rw := tnDynamicRewrite(t) + full := "a " + toolNameSplitFake + " b" + want := tnWant(rw, map[int]string{0: full}) + for _, kind := range tnKinds { + for parts := 2; parts <= 5; parts++ { + for offset := 0; offset < 4; offset++ { + cuts := tnEvenCuts(len(full), parts, offset) + up := append(tnDeltas(t, 0, kind.deltaType, kind.field, full, cuts), tnStopJSON(0)) + r := newToolNameStreamRestorer(rw) + got := tnCheckInvariant(t, r, rw, up, want) + require.Equal(t, want[0], got[0]) + require.NotContains(t, got[0], "analyze_") + } + } + } +} + +// 一个 delta 里多个假名。 +func TestToolNameStreamRestorer_MultipleFakesInOneDelta(t *testing.T) { + rw := tnDynamicRewrite(t) + full := rw.Forward["read"] + " + " + rw.Forward["write_file"] + " x" + want := tnWant(rw, map[int]string{0: full}) + for _, cut := range tnCutPositions(len(full)) { + up := append(tnDeltas(t, 0, "text_delta", "text", full, []int{cut}), tnStopJSON(0)) + r := newToolNameStreamRestorer(rw) + got := tnCheckInvariant(t, r, rw, up, want) + require.Equal(t, want[0], got[0]) + } +} + +// 两个 index 交错,各自留各自的 carry。 +func TestToolNameStreamRestorer_InterleavedIndexes(t *testing.T) { + rw := tnDynamicRewrite(t) + text := "zero " + rw.Forward["read"] + " end" + args := `{"path":"` + rw.Forward["write_file"] + `"}` + up := []string{ + string(tnDeltaJSON(t, 0, "text_delta", "text", text[:9])), + string(tnDeltaJSON(t, 1, "input_json_delta", "partial_json", args[:12])), + string(tnDeltaJSON(t, 0, "text_delta", "text", text[9:])), + tnStopJSON(0), + string(tnDeltaJSON(t, 1, "input_json_delta", "partial_json", args[12:])), + tnStopJSON(1), + } + r := newToolNameStreamRestorer(rw) + got := tnCheckInvariant(t, r, rw, up, tnWant(rw, map[int]string{0: text, 1: args})) + require.Equal(t, "zero read end", got[0]) + require.Equal(t, `{"path":"write_file"}`, got[1]) + for _, ev := range tnRun(r, nil) { + _ = ev + } +} + +// 假名前缀后面接别的文字,不成名。 +func TestToolNameStreamRestorer_PrefixFollowedByOtherText(t *testing.T) { + rw := tnDynamicRewrite(t) + for k := 1; k < len(toolNameSplitFake); k++ { + full := "see " + toolNameSplitFake[:k] + "zzz more" + up := append(tnDeltas(t, 0, "text_delta", "text", full, []int{4 + k}), tnStopJSON(0)) + r := newToolNameStreamRestorer(rw) + got := tnCheckInvariant(t, r, rw, up, tnWant(rw, map[int]string{0: full})) + require.Equal(t, full, got[0]) + } +} + +// 假名前后是多字节 UTF-8,切点遍历整段。 +func TestToolNameStreamRestorer_MultibyteAroundFake(t *testing.T) { + rw := tnDynamicRewrite(t) + full := "中文" + toolNameSplitFake + "中文" + want := tnWant(rw, map[int]string{0: full}) + for _, cut := range tnRuneCuts(full) { + up := append(tnDeltas(t, 0, "text_delta", "text", full, []int{cut}), tnStopJSON(0)) + r := newToolNameStreamRestorer(rw) + got := tnCheckInvariant(t, r, rw, up, want) + require.Equal(t, want[0], got[0]) + } +} + +// tnRuneCuts 返回 s 的每个 rune 起始位置(不含 0)。 +func tnRuneCuts(s string) []int { + var out []int + for i := range s { + if i > 0 { + out = append(out, i) + } + } + return out +} + +// 块尾的假名真前缀整段扣住,只在 content_block_stop 之前以同 index、同类型补发; +// 补发的是扣下的原字节(handler 会再走一次还原,这里断言还原器本身的行为)。 +func TestToolNameStreamRestorer_CarryFlushedBeforeStop(t *testing.T) { + rw := tnStaticRewrite(t) + for k := 1; k < len("cc_sess_x"); k++ { + held := "cc_sess_x"[:k] + prefix := "tail " + held + up := []string{string(tnDeltaJSON(t, 3, "input_json_delta", "partial_json", prefix)), tnStopJSON(3)} + got := tnCheckInvariant(t, newToolNameStreamRestorer(rw), rw, up, map[int]string{3: prefix}) + require.Equal(t, prefix, got[3]) + + emitted := tnRun(newToolNameStreamRestorer(rw), up) + require.Len(t, emitted, 3, "扣住的尾巴不能跟着第一段走") + require.Equal(t, "tail ", tnPayloadOf([]byte(emitted[0]))) + flushed := emitted[1] + require.Equal(t, held, tnPayloadOf([]byte(flushed))) + require.Equal(t, tnStopJSON(3), emitted[2], "carry must be flushed before the stop") + require.Equal(t, "content_block_delta", gjson.Get(flushed, "type").String()) + require.Equal(t, "input_json_delta", gjson.Get(flushed, "delta.type").String()) + require.Equal(t, int64(3), gjson.Get(flushed, "index").Int()) + } +} + +// flush 按 index 升序补发所有残留 carry。 +func TestToolNameStreamRestorer_FlushAscending(t *testing.T) { + rw := tnDynamicRewrite(t) + prefix := toolNameSplitFake[:4] + r := newToolNameStreamRestorer(rw) + for _, idx := range []int{2, 0, 1} { + tnRestore(r, tnDeltaJSON(t, idx, "text_delta", "text", "x "+prefix)) + } + out := tnRestore(r, nil) + require.Len(t, out, 3) + for i, ev := range out { + require.Equal(t, int64(i), gjson.GetBytes(ev, "index").Int()) + } + require.Empty(t, tnRestore(r, nil)) +} + +// 无映射:构造为 nil,tnRestore 逐字节原样返回。 +func TestToolNameStreamRestorer_NoMapping(t *testing.T) { + require.Nil(t, newToolNameStreamRestorer(nil)) + require.Nil(t, newToolNameStreamRestorer(toolNameRewriteFromContext(toolRewriteCtxStub{}))) + single := &ToolNameRewrite{ReverseOrdered: [][2]string{{"a", "b"}}} + require.NotNil(t, newToolNameStreamRestorer(single), "静态假前缀不经映射也会被还原,还原器照样要建") + + var nilRestorer *toolNameStreamRestorer + events := []string{ + string(tnDeltaJSON(t, 0, "text_delta", "text", "use analyze_r")), + string(tnDeltaJSON(t, 0, "text_delta", "text", "ea01 now")), + tnStopJSON(0), + } + for _, ev := range events { + out := tnRestore(nilRestorer, []byte(ev)) + require.Len(t, out, 1) + require.Equal(t, ev, string(out[0])) + } + require.Empty(t, tnRestore(nilRestorer, nil)) +} + +// 已经还原过的文本再走一遍还原器不变(第二次还原幂等)。 +func TestToolNameStreamRestorer_SecondPassIsIdempotent(t *testing.T) { + rw := tnDynamicRewrite(t) + text := "use " + rw.Forward["read"] + " and " + rw.Forward["write_file"] + " done" + once := string(restoreToolNamesInBytes([]byte(text), rw)) + twice := string(restoreToolNamesInBytes([]byte(once), rw)) + require.Equal(t, once, twice) + require.NotContains(t, once, "analyze_") + + want := map[int]string{0: once} + for _, cut := range tnCutPositions(len(once)) { + up := append(tnDeltas(t, 0, "text_delta", "text", once, []int{cut}), tnStopJSON(0)) + got := tnCheckInvariant(t, newToolNameStreamRestorer(rw), rw, up, want) + require.Equal(t, once, got[0]) + } +} + +// thinking_delta 与 signature_delta 等事件原样返回,不经 carry。 +func TestToolNameStreamRestorer_NonDeltaEventsUntouched(t *testing.T) { + rw := tnDynamicRewrite(t) + r := newToolNameStreamRestorer(rw) + events := []string{ + `{"type":"message_start","message":{"id":"m1"}}`, + `{"type":"content_block_start","index":0,"content_block":{"type":"thinking","thinking":""}}`, + string(tnDeltaJSON(t, 0, "thinking_delta", "thinking", "ends with "+toolNameSplitFake[:6])), + `{"type":"content_block_delta","index":0,"delta":{"type":"signature_delta","signature":"sig=="}}`, + `{"type":"ping"}`, + `{"type":"message_delta","delta":{"stop_reason":"end_turn"},"usage":{"output_tokens":3}}`, + `{"type":"message_stop"}`, + } + for _, ev := range events { + out := tnRestore(r, []byte(ev)) + require.Len(t, out, 1, ev) + require.Equal(t, ev, string(out[0])) + } + require.Empty(t, r.carry) + out := tnRestore(r, []byte(tnStopJSON(0))) + require.Len(t, out, 1, "no synthetic delta without carry") + require.Equal(t, tnStopJSON(0), string(out[0])) +} + +// 改载荷只动 delta 的载荷字段,事件其余字节不变。 +func TestToolNameStreamRestorer_OnlyPayloadFieldChanges(t *testing.T) { + rw := tnDynamicRewrite(t) + original := "use " + rw.Forward["read"] + b, err := json.Marshal(map[string]any{ + "type": "content_block_delta", "index": 7, "extra": map[string]any{"a": 1}, + "delta": map[string]any{"type": "text_delta", "text": original}, + }) + require.NoError(t, err) + out := tnRestore(newToolNameStreamRestorer(rw), b) + require.Len(t, out, 1) + require.Equal(t, int64(7), gjson.GetBytes(out[0], "index").Int()) + require.Equal(t, int64(1), gjson.GetBytes(out[0], "extra.a").Int()) + require.Equal(t, "use read", gjson.GetBytes(out[0], "delta.text").String()) + back, err := sjson.SetBytes(out[0], "delta.text", original) + require.NoError(t, err) + require.Equal(t, string(b), string(back)) +} + +// 改写后的载荷重新序列化时只转义 JSON 要求的字节:< > & 与非 ASCII 原样保留, +// 解出的值仍与期望文本相等,事件也仍是合法 JSON。 +func TestToolNameStreamRestorer_KeepsHTMLAndUTF8Unescaped(t *testing.T) { + rw := tnDynamicRewrite(t) + full := `ac&d"e\f` + "\n" + "g é " + toolNameSplitFake + " end" + want := `ac&d"e\f` + "\n" + "g é read end" + at := strings.Index(full, toolNameSplitFake) + up := append(tnDeltas(t, 0, "text_delta", "text", full, []int{at + 5}), tnStopJSON(0)) + + emitted := tnEmitted(rw, up) + require.Len(t, emitted, 3) // rewritten delta, second delta, stop + first := emitted[0] + require.True(t, json.Valid([]byte(first)), "rewritten event must stay valid JSON: %s", first) + require.Contains(t, first, `c&d`) + require.Contains(t, first, "é") + require.Contains(t, first, `\"e\\f`) + require.NotContains(t, first, `\u003c`) + require.NotContains(t, first, `\u0026`) + require.NotContains(t, first, `\u00e9`) + require.Equal(t, `ac&d"e\f`+"\n"+"g é ", gjson.Get(first, "delta.text").String()) + require.Equal(t, want, tnPayloadOf([]byte(first))+tnPayloadOf([]byte(emitted[1]))) +} + +func tnStaticContext(t *testing.T) (*gin.Context, *httptest.ResponseRecorder) { + t.Helper() + gin.SetMode(gin.TestMode) + rec := httptest.NewRecorder() + c, _ := gin.CreateTestContext(rec) + c.Request = httptest.NewRequest(http.MethodPost, "/v1/messages", nil) + c.Set(toolNameRewriteKey, tnStaticRewrite(t)) + return c, rec +} + +type tnErrReader struct { + data []byte + err error +} + +func (r *tnErrReader) Read(p []byte) (int, error) { + if len(r.data) > 0 { + n := copy(p, r.data) + r.data = r.data[n:] + return n, nil + } + return 0, r.err +} + +func (r *tnErrReader) Close() error { return nil } + +// tnHeldStream 造一段以扣住的假名开头结尾的上游流:块尾 cc_sess 是假名 cc_sess_x、cc_sess_xy +// 的真前缀,这几个字节只能靠结束路径补发(真名 sessions_x 不是任何假名的前缀,扣不住)。 +func tnHeldStream(t *testing.T) string { + t.Helper() + return tnSSEEvent(`{"type":"message_start","message":{"id":"msg_h","type":"message","role":"assistant","content":[],"model":"claude-sonnet-4.5","usage":{"input_tokens":1}}}`) + + tnSSEEvent(`{"type":"content_block_start","index":0,"content_block":{"type":"text","text":""}}`) + + tnSSEEvent(tnSSEDelta(t, 0, "text_delta", "text", "use cc_sess")) +} + +const tnErrorEvent = "event: error\ndata: {\"type\":\"error\",\"error\":{\"type\":\"overloaded_error\",\"message\":\"boom\"}}\n\n" + +// 结束路径:上游 EOF 无 stop、error 事件、读错误,都要先把 carry 补发给客户端。 +func TestHandleStreamingResponse_FlushesCarryOnEndPaths(t *testing.T) { + for _, tc := range []struct { + name string + frame string // 结束帧的标记;EOF 没有帧 + body func(t *testing.T) io.ReadCloser + }{ + {name: "eof-without-stop", body: func(t *testing.T) io.ReadCloser { return io.NopCloser(strings.NewReader(tnHeldStream(t))) }}, + {name: "error-event", body: func(t *testing.T) io.ReadCloser { // 上游 error 事件不回帧,只返回错误 + return io.NopCloser(strings.NewReader(tnHeldStream(t) + tnErrorEvent)) + }}, + {name: "read-error", frame: "event: error", body: func(t *testing.T) io.ReadCloser { + return &tnErrReader{data: []byte(tnHeldStream(t)), err: errors.New("connection reset by peer")} + }}, + } { + t.Run(tc.name, func(t *testing.T) { + svc := newToolNameSplitGatewayService() + c, rec := tnStaticContext(t) + resp := &http.Response{StatusCode: http.StatusOK, Header: http.Header{}, Body: tc.body(t)} + _, err := svc.handleStreamingResponse(context.Background(), resp, c, &Account{ID: 1}, time.Now(), "model", "model", false) + require.Error(t, err) + body := rec.Body.String() + require.Equal(t, "use cc_sess", tnClientJoined(body, "delta.text")) + if tc.frame != "" { + require.Contains(t, body, tc.frame) + require.Less(t, strings.Index(body, "cc_sess"), strings.Index(body, tc.frame), "carry 必须先于结束帧补发") + } + }) + } +} + +func TestHandleCCStreamingFromAnthropic_FlushesCarryOnEndPaths(t *testing.T) { + for _, tc := range []struct { + name string + frame string + body func(t *testing.T) io.ReadCloser + }{ + {name: "eof-without-stop", body: func(t *testing.T) io.ReadCloser { return io.NopCloser(strings.NewReader(tnHeldStream(t))) }}, + {name: "error-event", frame: `{"error":{`, body: func(t *testing.T) io.ReadCloser { + return io.NopCloser(strings.NewReader(tnHeldStream(t) + tnErrorEvent)) + }}, + {name: "read-error", frame: `{"error":{`, body: func(t *testing.T) io.ReadCloser { + return &tnErrReader{data: []byte(tnHeldStream(t)), err: errors.New("connection reset by peer")} + }}, + } { + t.Run(tc.name, func(t *testing.T) { + c, rec := tnStaticContext(t) + resp := &http.Response{Header: http.Header{}, Body: tc.body(t)} + _, err := (&GatewayService{}).handleCCStreamingFromAnthropic(resp, c, "model", "model", nil, time.Now()) + require.Error(t, err) + body := rec.Body.String() + require.Equal(t, "use cc_sess", tnClientJoined(body, "choices.0.delta.content")) + if tc.frame != "" { + require.Contains(t, body, tc.frame) + require.Less(t, strings.Index(body, "cc_sess"), strings.Index(body, tc.frame), "carry 必须先于结束帧补发") + } + }) + } +} + +func TestHandleResponsesStreamingResponse_FlushesCarryOnEndPaths(t *testing.T) { + for _, tc := range []struct { + name string + frame string + body func(t *testing.T) io.ReadCloser + }{ + {name: "eof-without-stop", body: func(t *testing.T) io.ReadCloser { return io.NopCloser(strings.NewReader(tnHeldStream(t))) }}, + {name: "error-event", frame: "response.failed", body: func(t *testing.T) io.ReadCloser { + return io.NopCloser(strings.NewReader(tnHeldStream(t) + tnErrorEvent)) + }}, + {name: "read-error", frame: "response.failed", body: func(t *testing.T) io.ReadCloser { + return &tnErrReader{data: []byte(tnHeldStream(t)), err: errors.New("connection reset by peer")} + }}, + } { + t.Run(tc.name, func(t *testing.T) { + c, rec := tnStaticContext(t) + resp := &http.Response{Header: http.Header{}, Body: tc.body(t)} + _, err := (&GatewayService{}).handleResponsesStreamingResponse(resp, c, "claude-sonnet-4.5", "claude-sonnet-4.5", nil, time.Now(), apicompat.ResponsesClientToolMapping{}) + require.Error(t, err) + body := rec.Body.String() + require.Equal(t, "use cc_sess", tnClientJoined(body, "delta")) + if tc.frame != "" { + require.Contains(t, body, tc.frame) + require.Less(t, strings.Index(body, "cc_sess"), strings.Index(body, tc.frame), "carry 必须先于结束帧补发") + } + }) + } +} + +// 无映射时逐字节不改:假名原样送到客户端,静态前缀还原照旧。 +func TestHandleStreamingResponse_NoMappingKeepsBytes(t *testing.T) { + svc := newToolNameSplitGatewayService() + gin.SetMode(gin.TestMode) + rec := httptest.NewRecorder() + c, _ := gin.CreateTestContext(rec) + c.Request = httptest.NewRequest(http.MethodPost, "/v1/messages", nil) + + stream := tnSSEEvent(`{"type":"message_start","message":{"id":"msg_n","type":"message","role":"assistant","content":[],"model":"claude-sonnet-4.5","usage":{"input_tokens":1}}}`) + + tnSSEEvent(`{"type":"content_block_start","index":0,"content_block":{"type":"text","text":""}}`) + + tnSSEEvent(tnSSEDelta(t, 0, "text_delta", "text", "use analyze_r")) + + tnSSEEvent(tnSSEDelta(t, 0, "text_delta", "text", "ea01 now")) + + tnSSEEvent(`{"type":"content_block_stop","index":0}`) + + tnSSEEvent(`{"type":"message_stop"}`) + resp := &http.Response{StatusCode: http.StatusOK, Header: http.Header{}, Body: io.NopCloser(strings.NewReader(stream))} + _, err := svc.handleStreamingResponse(context.Background(), resp, c, &Account{ID: 1}, time.Now(), "model", "model", false) + require.NoError(t, err) + require.Equal(t, "use analyze_rea01 now", tnClientJoined(rec.Body.String(), "delta.text")) +} + +// 块尾停在不构成任何完整假名的裸假前缀上也要整段扣住,stop 前原样补发,不丢不移。 +func TestToolNameStreamRestorer_BareStaticPrefixSplit(t *testing.T) { + rw := tnStaticRewrite(t) + for _, held := range []string{"cc_sess_", "cc_ses_"} { + prefix := "a " + held + up := []string{string(tnDeltaJSON(t, 0, "text_delta", "text", prefix)), tnStopJSON(0)} + got := tnCheckInvariant(t, newToolNameStreamRestorer(rw), rw, up, map[int]string{0: prefix}) + require.Equal(t, prefix, got[0], "裸前缀不成名,补发的就是原字节") + + emitted := tnRun(newToolNameStreamRestorer(rw), up) + require.Len(t, emitted, 3) + require.Equal(t, "a ", tnPayloadOf([]byte(emitted[0]))) + require.Equal(t, held, tnPayloadOf([]byte(emitted[1]))) + require.Equal(t, tnStopJSON(0), emitted[2]) + } +} + +// 只有动态映射时,静态假前缀照样被 restoreToolNamesInBytes 整体还原,被切开时也要扣住。 +func TestToolNameStreamRestorer_StaticFakeSplitWithDynamicMapping(t *testing.T) { + rw := tnDynamicRewrite(t) + for real, fake := range staticToolNameRewrites { + full := "a " + fake + "x b" + at := strings.Index(full, fake) + for cut := at + 1; cut < at+len(fake); cut++ { + up := append(tnDeltas(t, 0, "text_delta", "text", full, []int{cut}), tnStopJSON(0)) + got := tnCheckInvariant(t, newToolNameStreamRestorer(rw), rw, up, tnWant(rw, map[int]string{0: full})) + require.Equal(t, "a "+real+"x b", got[0]) + } + } +} + +// 同块出现非文本 delta(citations_delta 与不认识的类型)时,非文本事件原样放行, +// 留下的尾巴保留到同块下一个文本 delta 或 stop。 +const ( + tnCitationsEvent = `{"type":"content_block_delta","index":0,"delta":{"type":"citations_delta","citation":{"type":"web_search_result_location","cited_text":"x","url":"https://example.com","title":"t","encrypted_index":"e"}}}` + tnUnknownDeltaEvent = `{"type":"content_block_delta","index":0,"delta":{"type":"foo_delta","foo":"bar"}}` +) + +// tnEmitted 用新的还原器跑一遍,返回按顺序发出的全部事件 JSON。 +func tnEmitted(rw *ToolNameRewrite, upstream []string) []string { + return tnRun(newToolNameStreamRestorer(rw), upstream) +} + +// tnNonTextEvents 返回发出事件里的非文本 delta 原字节,保持相对顺序。 +func tnNonTextEvents(emitted []string) []string { + var out []string + for _, ev := range emitted { + if gjson.Get(ev, "type").String() == "content_block_delta" && !tnIsTextDelta([]byte(ev)) { + out = append(out, ev) + } + } + return out +} + +// 非文本 delta 不打断扣留:事件原样放行,carry 留到下一个同 index 文本 delta 或 stop, +// 被切名字的后半段因此仍能还原。 +func TestToolNameStreamRestorer_NonTextDeltaKeepsCarry(t *testing.T) { + rw := tnDynamicRewrite(t) + full := "see the a" // 块尾 "a" 是动态假名 analyze_ 的前缀,必须留在 carry 里 + for _, tc := range []struct { + name string + event string + }{ + {name: "citations", event: tnCitationsEvent}, + {name: "unknown-type", event: tnUnknownDeltaEvent}, + } { + t.Run(tc.name, func(t *testing.T) { + up := []string{ + string(tnDeltaJSON(t, 0, "text_delta", "text", "s")), + tc.event, + string(tnDeltaJSON(t, 0, "text_delta", "text", "ee the a")), + tnStopJSON(0), + } + got := tnCheckInvariant(t, newToolNameStreamRestorer(rw), rw, up, tnWant(rw, map[int]string{0: full})) + require.Equal(t, full, got[0]) + require.NotContains(t, got[0], "analyze_") + + emitted := tnEmitted(rw, up) + require.Equal(t, []string{tc.event}, tnNonTextEvents(emitted), "non-text delta must pass through unchanged") + require.Equal(t, tnStopJSON(0), emitted[len(emitted)-1]) + }) + } +} + +// 非文本 delta 排在留下 carry 的 text_delta 之前:原样到达,不打扰之后的 carry 与拼接。 +func TestToolNameStreamRestorer_NonTextDeltaBeforeHeldDelta(t *testing.T) { + rw := tnDynamicRewrite(t) + full := "see the a" + up := []string{ + tnCitationsEvent, + string(tnDeltaJSON(t, 0, "text_delta", "text", "s")), + string(tnDeltaJSON(t, 0, "text_delta", "text", "ee the a")), + tnStopJSON(0), + } + got := tnCheckInvariant(t, newToolNameStreamRestorer(rw), rw, up, tnWant(rw, map[int]string{0: full})) + require.Equal(t, full, got[0]) + + emitted := tnEmitted(rw, up) + require.Equal(t, []string{tnCitationsEvent}, tnNonTextEvents(emitted)) + require.Equal(t, tnStopJSON(0), emitted[len(emitted)-1]) +} + +// 假名前半段先到、非文本 delta 插在中间、后半段随后到:citations_delta 原样经过, +// 名字仍按同一 index 拼回并还原。若在非文本 delta 处就把 carry 补发掉,后半段再也拼不回来。 +func TestToolNameStreamRestorer_TextDeltaSplitByCitationsStitches(t *testing.T) { + rw := tnDynamicRewrite(t) + for _, tc := range []struct { + name string + deltaType, field string + head, tail, want string + }{ + {"text", "text_delta", "text", "use analyze_r", "ea01 now", "use read now"}, + {"input_json", "input_json_delta", "partial_json", `{"file_path":"analyze_r`, `ea01"}`, `{"file_path":"read"}`}, + } { + t.Run(tc.name, func(t *testing.T) { + up := []string{ + string(tnDeltaJSON(t, 0, tc.deltaType, tc.field, tc.head)), + tnCitationsEvent, + string(tnDeltaJSON(t, 0, tc.deltaType, tc.field, tc.tail)), + tnStopJSON(0), + } + got := tnCheckInvariant(t, newToolNameStreamRestorer(rw), rw, up, tnWant(rw, map[int]string{0: tc.head + tc.tail})) + require.Equal(t, tc.want, got[0]) + require.NotContains(t, got[0], "analyze_") + + emitted := tnEmitted(rw, up) + require.Equal(t, []string{tnCitationsEvent}, tnNonTextEvents(emitted), "citations_delta must pass through unchanged") + require.Equal(t, tnStopJSON(0), emitted[len(emitted)-1]) + }) + } +} + +// 不切分时块尾恰好停在假名开头,随后到达 citations_delta:尾巴留到 stop 前,不能丢。 + +func TestToolNameStreamRestorer_WholeDeltaThenCitationsKeepsTail(t *testing.T) { + rw := tnDynamicRewrite(t) + full := "see the a" + up := []string{ + string(tnDeltaJSON(t, 0, "text_delta", "text", full)), + tnCitationsEvent, + tnStopJSON(0), + } + got := tnCheckInvariant(t, newToolNameStreamRestorer(rw), rw, up, tnWant(rw, map[int]string{0: full})) + require.Equal(t, full, got[0]) + + emitted := tnEmitted(rw, up) + require.Equal(t, []string{tnCitationsEvent}, tnNonTextEvents(emitted)) + require.Equal(t, "a", tnPayloadOf([]byte(emitted[len(emitted)-2])), "held tail must arrive just before the stop") + require.Equal(t, tnStopJSON(0), emitted[len(emitted)-1]) +} + +// tnCheckEventLinesMatchData 断言每个带 data 的 SSE 块,event 行与 data 的 type 字段一致。 +func tnCheckEventLinesMatchData(t *testing.T, body string) { + t.Helper() + for _, block := range strings.Split(body, "\n\n") { + event, data := "", "" + for _, line := range strings.Split(block, "\n") { + if rest, ok := strings.CutPrefix(line, "event:"); ok { + event = strings.TrimSpace(rest) + } + if rest, ok := strings.CutPrefix(line, "data:"); ok { + data = strings.TrimSpace(rest) + } + } + if data == "" || !gjson.Valid(data) { + continue + } + require.Equal(t, gjson.Get(data, "type").String(), event, "event line must match the data type in block %q", block) + } +} + +// 块尾扣下的字节在 content_block_stop 前补发:补发的事件必须是 content_block_delta 的 +// event 行,不能沿用 stop 块的 event 行。 +func TestHandleStreamingResponse_CarryFlushUsesDeltaEventLine(t *testing.T) { + svc := newToolNameSplitGatewayService() + c, rec := tnStaticContext(t) + stream := strings.Join([]string{ + tnSSEEvent(`{"type":"message_start","message":{"id":"msg_e","type":"message","role":"assistant","content":[],"model":"claude-sonnet-4.5","usage":{"input_tokens":1}}}`), + tnSSEEvent(`{"type":"content_block_start","index":0,"content_block":{"type":"text","text":""}}`), + tnSSEEvent(tnSSEDelta(t, 0, "text_delta", "text", "use cc_sess_x")), + tnSSEEvent(`{"type":"content_block_stop","index":0}`), + tnSSEEvent(`{"type":"message_stop"}`), + }, "") + resp := &http.Response{StatusCode: http.StatusOK, Header: http.Header{}, Body: io.NopCloser(strings.NewReader(stream))} + + _, err := svc.handleStreamingResponse(context.Background(), resp, c, &Account{ID: 1}, time.Now(), "model", "model", false) + require.NoError(t, err) + + tnCheckEventLinesMatchData(t, rec.Body.String()) + require.Equal(t, "use sessions_x", tnClientJoined(rec.Body.String(), "delta.text")) + require.Equal(t, 2, strings.Count(rec.Body.String(), "event: content_block_delta")) +} + +// carry 与 stop 之间夹一个 citations_delta 时同样如此:citations 原样先到,carry 在 stop 前补发。 +func TestHandleStreamingResponse_CarryFlushAfterCitationsUsesDeltaEventLine(t *testing.T) { + svc := newToolNameSplitGatewayService() + c, rec := tnStaticContext(t) + stream := strings.Join([]string{ + tnSSEEvent(`{"type":"message_start","message":{"id":"msg_c","type":"message","role":"assistant","content":[],"model":"claude-sonnet-4.5","usage":{"input_tokens":1}}}`), + tnSSEEvent(`{"type":"content_block_start","index":0,"content_block":{"type":"text","text":""}}`), + tnSSEEvent(tnSSEDelta(t, 0, "text_delta", "text", "use cc_sess_x")), + tnSSEEvent(tnCitationsEvent), + tnSSEEvent(`{"type":"content_block_stop","index":0}`), + tnSSEEvent(`{"type":"message_stop"}`), + }, "") + resp := &http.Response{StatusCode: http.StatusOK, Header: http.Header{}, Body: io.NopCloser(strings.NewReader(stream))} + + _, err := svc.handleStreamingResponse(context.Background(), resp, c, &Account{ID: 1}, time.Now(), "model", "model", false) + require.NoError(t, err) + + tnCheckEventLinesMatchData(t, rec.Body.String()) + require.Equal(t, "use sessions_x", tnClientJoined(rec.Body.String(), "delta.text")) + require.Equal(t, 3, strings.Count(rec.Body.String(), "event: content_block_delta")) + require.Equal(t, 1, strings.Count(rec.Body.String(), "citations_delta")) + require.Contains(t, rec.Body.String(), tnCitationsEvent) +} + +// 原生入口:text_delta 停在假名中间,citations_delta 插进来,再由后续 text_delta 补完。 +// 客户端按 index 拼出的文本还原为真名,citations_delta 原样到达。 +func TestHandleStreamingResponse_CitationsBetweenTextDeltasStitches(t *testing.T) { + svc := newToolNameSplitGatewayService() + c, rec, _ := newToolNameSplitContext(t) + stream := strings.Join([]string{ + tnSSEEvent(`{"type":"message_start","message":{"id":"msg_s","type":"message","role":"assistant","content":[],"model":"claude-sonnet-4.5","usage":{"input_tokens":1}}}`), + tnSSEEvent(`{"type":"content_block_start","index":0,"content_block":{"type":"text","text":""}}`), + tnSSEEvent(tnSSEDelta(t, 0, "text_delta", "text", "use analyze_r")), + tnSSEEvent(tnCitationsEvent), + tnSSEEvent(tnSSEDelta(t, 0, "text_delta", "text", "ea01 now")), + tnSSEEvent(`{"type":"content_block_stop","index":0}`), + tnSSEEvent(`{"type":"message_stop"}`), + }, "") + resp := &http.Response{StatusCode: http.StatusOK, Header: http.Header{}, Body: io.NopCloser(strings.NewReader(stream))} + + _, err := svc.handleStreamingResponse(context.Background(), resp, c, &Account{ID: 1}, time.Now(), "model", "model", false) + require.NoError(t, err) + + tnCheckEventLinesMatchData(t, rec.Body.String()) + require.Equal(t, "use read now", tnClientJoined(rec.Body.String(), "delta.text")) + require.NotContains(t, rec.Body.String(), "analyze_") + require.Equal(t, 1, strings.Count(rec.Body.String(), "citations_delta")) + require.Contains(t, rec.Body.String(), tnCitationsEvent) +} diff --git a/backend/internal/service/gateway_upstream_response.go b/backend/internal/service/gateway_upstream_response.go index ae1d2f2dca..49e4bc49da 100644 --- a/backend/internal/service/gateway_upstream_response.go +++ b/backend/internal/service/gateway_upstream_response.go @@ -902,6 +902,7 @@ func (s *GatewayService) handleStreamingResponse(ctx context.Context, resp *http needModelReplace := originalModel != mappedModel clientModel := compositeClientModel(ctx, "") clientDisconnected := false // 客户端断开标志,断开后继续读取上游以获取完整usage + toolNameRestorer := newToolNameStreamRestorer(toolNameRewriteFromContext(c)) sawTerminalEvent := false useNoopDeltaKeepalive := c != nil && c.Request != nil && shouldUseClaudeCodeNoopDeltaKeepalive(c.GetHeader("User-Agent")) noopDeltaKeepaliveBlockIndex := -1 @@ -1098,6 +1099,60 @@ func (s *GatewayService) handleStreamingResponse(ctx context.Context, resp *http return []string{block}, string(newData), usagePatch, nil } + flushCarry := func() { + if clientDisconnected || !c.Writer.Written() || toolNameRestorer == nil { + return + } + for _, rest := range toolNameRestorer.flush() { + block := "event: content_block_delta\ndata: " + string(rest) + "\n\n" + _, _ = io.WriteString(w, reverseToolNamesIfPresentString(c, block)) + } + flusher.Flush() + } + + markDisconnected := func() { + clientDisconnected = true + logger.LegacyPrintf("service.gateway", "Client disconnected during streaming, continuing to drain upstream for billing") + // 不 break:客户端断开后仍需继续合并本事件及后续事件的 usage, + // 否则会漏计当前事件携带的 usage 导致少计费。后续写入由 + // clientDisconnected 守卫跳过。 + } + + writeRestoredBlock := func(block string) { + if clientDisconnected { + return + } + if _, werr := io.WriteString(w, reverseToolNamesIfPresentString(c, block)); werr != nil { + markDisconnected() + return + } + flusher.Flush() + lastDataAt = time.Now() + resetKeepaliveTimer() + } + + // writeRestoredParts 分三段写出被改写的块,不重建整块字符串。 + writeRestoredParts := func(prefix string, ev []byte) { + if clientDisconnected { + return + } + if _, werr := io.WriteString(w, prefix); werr != nil { + markDisconnected() + return + } + if _, werr := w.Write(reverseToolNamesIfPresent(c, ev)); werr != nil { + markDisconnected() + return + } + if _, werr := io.WriteString(w, "\n\n"); werr != nil { + markDisconnected() + return + } + flusher.Flush() + lastDataAt = time.Now() + resetKeepaliveTimer() + } + for { select { case ev, ok := <-events: @@ -1106,6 +1161,7 @@ func (s *GatewayService) handleStreamingResponse(ctx context.Context, resp *http } if !ok { // 上游完成,返回结果 + flushCarry() if !sawTerminalEvent { return &streamingResult{usage: usage, firstTokenMs: firstTokenMs, clientDisconnect: clientDisconnected}, fmt.Errorf("stream usage incomplete: missing terminal event") } @@ -1113,6 +1169,7 @@ func (s *GatewayService) handleStreamingResponse(ctx context.Context, resp *http } if ev.err != nil { if sawTerminalEvent { + flushCarry() return &streamingResult{usage: usage, firstTokenMs: firstTokenMs, clientDisconnect: clientDisconnected}, nil } // 检测 context 取消(客户端断开会导致 context 取消,进而影响上游读取) @@ -1126,6 +1183,7 @@ func (s *GatewayService) handleStreamingResponse(ctx context.Context, resp *http // 客户端未断开,正常的错误处理 if errors.Is(ev.err, bufio.ErrTooLong) { logger.LegacyPrintf("service.gateway", "SSE line too long: account=%d max_size=%d error=%v", account.ID, maxLineSize, ev.err) + flushCarry() sendErrorEvent("response_too_large", fmt.Sprintf("upstream SSE line exceeded %d bytes", maxLineSize)) return &streamingResult{usage: usage, firstTokenMs: firstTokenMs}, ev.err } @@ -1151,6 +1209,7 @@ func (s *GatewayService) handleStreamingResponse(ctx context.Context, resp *http RetryableOnSameAccount: true, } } + flushCarry() sendErrorEvent("stream_read_error", disconnectMsg) return &streamingResult{usage: usage, firstTokenMs: firstTokenMs}, fmt.Errorf("stream read error: %w", ev.err) } @@ -1169,31 +1228,55 @@ func (s *GatewayService) handleStreamingResponse(ctx context.Context, resp *http if clientDisconnected { return &streamingResult{usage: usage, firstTokenMs: firstTokenMs, clientDisconnect: true}, nil } + flushCarry() return nil, err } - for _, block := range outputBlocks { - if !clientDisconnected { - restored := reverseToolNamesIfPresentString(c, block) - if _, werr := io.WriteString(w, restored); werr != nil { - clientDisconnected = true - logger.LegacyPrintf("service.gateway", "Client disconnected during streaming, continuing to drain upstream for billing") - // 不 break:客户端断开后仍需继续合并本事件及后续事件的 usage, - // 否则会漏计当前事件携带的 usage 导致少计费。后续写入由 - // clientDisconnected 守卫跳过。 - } else { - flusher.Flush() - lastDataAt = time.Now() - resetKeepaliveTimer() - } + // usage 与首 token 时间按原事件算一次,还原器可能把这一事件拆成多个块或整段扣住。 + if data != "" { + if firstTokenMs == nil && data != "[DONE]" { + ms := int(time.Since(startTime).Milliseconds()) + firstTokenMs = &ms } - if data != "" { - if firstTokenMs == nil && data != "[DONE]" { - ms := int(time.Since(startTime).Milliseconds()) - firstTokenMs = &ms + if usagePatch != nil { + mergeSSEUsagePatch(usage, usagePatch) + } + } + + if toolNameRestorer == nil { + for _, block := range outputBlocks { + writeRestoredBlock(block) + } + } else { + for _, block := range outputBlocks { + dataAt := strings.Index(block, "data:") + if dataAt < 0 { + writeRestoredBlock(block) + continue } - if usagePatch != nil { - mergeSSEUsagePatch(usage, usagePatch) + start := dataAt + len("data:") + if start < len(block) && block[start] == ' ' { + start++ + } + end := len(block) - len("\n\n") + if end < start { + end = len(block) + } + payload := streamEventBytes(block[start:end]) + var restored [2][]byte + n := toolNameRestorer.restoreInto(payload, &restored) + for i, ev := range restored[:n] { + if i == n-1 && bytes.Equal(ev, payload) { + writeRestoredBlock(block) + continue + } + prefix := block[:start] + if i == 0 && n == 2 { + // out[0] 是按约定补发的 carry,永远是 content_block_delta; + // 原事件(stop 或别的 delta)的 event 行不能套在它上面。 + prefix = "event: content_block_delta\ndata: " + } + writeRestoredParts(prefix, ev) } } } @@ -1215,6 +1298,7 @@ func (s *GatewayService) handleStreamingResponse(ctx context.Context, resp *http if s.rateLimitService != nil { s.rateLimitService.HandleStreamTimeout(ctx, account, originalModel) } + flushCarry() sendErrorEvent("stream_timeout", fmt.Sprintf("upstream stream idle for %s", streamInterval)) return &streamingResult{usage: usage, firstTokenMs: firstTokenMs}, fmt.Errorf("stream data interval timeout") From 33ce4ae91484946c1db425349c970a627d8534d2 Mon Sep 17 00:00:00 2001 From: r266-tech Date: Mon, 23 Nov 2026 14:05:47 +0800 Subject: [PATCH 07/23] fix(openai): recover sooner after transport reachability failures --- .../gateway_upstream_transport_error.go | 5 +- .../gemini_upstream_transport_error.go | 2 +- .../openai_upstream_transport_error.go | 90 ++++++++----------- ...ai_upstream_transport_error_handle_test.go | 42 +++++++-- .../openai_upstream_transport_error_test.go | 60 ++++++------- deploy/.env.example | 2 +- deploy/config.example.yaml | 2 +- 7 files changed, 105 insertions(+), 98 deletions(-) diff --git a/backend/internal/service/gateway_upstream_transport_error.go b/backend/internal/service/gateway_upstream_transport_error.go index a9f459fed9..861555d713 100644 --- a/backend/internal/service/gateway_upstream_transport_error.go +++ b/backend/internal/service/gateway_upstream_transport_error.go @@ -12,8 +12,7 @@ import ( ) // gatewayTransportErrorTempUnschedDuration is how long an account is temporarily -// unscheduled after a durable transport failure (matches the OpenAI-side -// openAITransportErrorTempUnschedDuration). +// unscheduled after a durable transport failure on the Anthropic, Bedrock, or Gemini path. const gatewayTransportErrorTempUnschedDuration = 10 * time.Minute // gatewayTransportFailoverBody is the Anthropic-format error body attached to @@ -63,7 +62,7 @@ func (s *GatewayService) handleUpstreamTransportError(ctx context.Context, c *gi // Transport attempt left local validation; count Ollama Cloud activity. scheduleOllamaCloudUsageActivity(s.deferredService, account) - if classifyUpstreamTransportError(err).Persistent { + if classifyUpstreamTransportError(err) != upstreamTransportTransient { s.tempUnscheduleTransportError(ctx, account, safeErr) } diff --git a/backend/internal/service/gemini_upstream_transport_error.go b/backend/internal/service/gemini_upstream_transport_error.go index 27eaec57fb..09a445c591 100644 --- a/backend/internal/service/gemini_upstream_transport_error.go +++ b/backend/internal/service/gemini_upstream_transport_error.go @@ -45,7 +45,7 @@ func (s *GeminiMessagesCompatService) handleUpstreamTransportError(ctx context.C return err } - if classifyUpstreamTransportError(err).Persistent { + if classifyUpstreamTransportError(err) != upstreamTransportTransient { tempUnscheduleAccountForTransportError(ctx, s.accountRepo, account, safeErr) } diff --git a/backend/internal/service/openai_upstream_transport_error.go b/backend/internal/service/openai_upstream_transport_error.go index 7c847b84db..fcb142e2fd 100644 --- a/backend/internal/service/openai_upstream_transport_error.go +++ b/backend/internal/service/openai_upstream_transport_error.go @@ -14,9 +14,10 @@ import ( "go.uber.org/zap" ) -// openAITransportErrorTempUnschedDuration is how long an account is temporarily -// unscheduled after a durable transport failure (matches tokenRefreshTempUnschedDuration). -const openAITransportErrorTempUnschedDuration = 10 * time.Minute +const ( + openAITransportReachabilityCooldown = 30 * time.Second + openAITransportProxyAuthCooldown = 10 * time.Minute +) // openAITransportFailoverBody is the OpenAI-format error body attached to the // failover error for a transport-level failure. Kept identical to the legacy @@ -27,68 +28,51 @@ var openAITransportFailoverBody = []byte(`{"error":{"type":"upstream_error","mes // upstreamTransportErrorClass describes how to react to a transport-level upstream // failure — i.e. the HTTP round-trip never completed (proxy / DNS / TCP / TLS // error, no HTTP status code received). -type upstreamTransportErrorClass struct { - // Persistent marks failures where retrying the same proxy/account is - // pointless: expired or rejected proxy credentials, a dead proxy endpoint, - // or DNS/routing failure. Such accounts should be temporarily unscheduled - // (and alerted on) instead of being repeatedly scheduled into hard failures. - Persistent bool -} +type upstreamTransportErrorClass uint8 -// persistentUpstreamTransportErrorMarkers are substrings (matched case-insensitively -// against the raw transport error) that indicate a durable proxy/network fault. -// Matched signals are intentionally specific failure *reasons*, not the operation -// (e.g. we match "connection refused", not "proxyconnect") so that a transient -// failure of the same operation (a proxy timeout) is NOT misclassified as durable. -var persistentUpstreamTransportErrorMarkers = []string{ - "authentication failed", // SOCKS5 RFC1929 / proxy credentials rejected (expired account) - "proxy authentication required", // HTTP proxy 407 - "connection refused", // proxy/upstream endpoint down +const ( + upstreamTransportTransient upstreamTransportErrorClass = iota + upstreamTransportReachability + upstreamTransportProxyAuth +) + +// Match specific reachability errors so a proxy timeout keeps its transient classification. +var upstreamReachabilityErrorMarkers = []string{ + "connection refused", "no route to host", "network is unreachable", - "no such host", // DNS resolution failure (bad/expired proxy hostname) + "no such host", } -// classifyUpstreamTransportError decides whether a transport-level upstream error -// is durable (Persistent — evict the account + alert) or a transient blip -// (fail over to a healthy account but keep this one schedulable). -// -// Motivating incident: a SOCKS5 proxy whose subscription lapsed returned -// `username/password authentication failed`; the account was nonetheless -// rescheduled on every request, hard-failing users with 502s. -// -// Classification strategy (mirrors sanitizeStreamError in gateway_service.go): -// 1. Typed-error checks first (syscall constants, *net.DNSError) — portable and -// unambiguous. -// 2. String-marker fallback for errors that have no typed form (e.g. the plain -// string returned by golang.org/x/net/proxy for SOCKS5 credential rejection). -// The network-layer string markers ("connection refused", "no route to host", -// "network is unreachable", "no such host") are kept as a cross-platform safety -// net even though the typed checks should cover them on modern Go+Linux. +// classifyUpstreamTransportError distinguishes reachability failures that can +// recover when the network returns from rejected proxy credentials that require +// operator intervention. Prefer typed errors and fall back to transport messages. func classifyUpstreamTransportError(err error) upstreamTransportErrorClass { if err == nil { - return upstreamTransportErrorClass{} + return upstreamTransportTransient } - // — Typed checks (preferred) —————————————————————————————————————————————— if errors.Is(err, syscall.ECONNREFUSED) || errors.Is(err, syscall.EHOSTUNREACH) || errors.Is(err, syscall.ENETUNREACH) { - return upstreamTransportErrorClass{Persistent: true} + return upstreamTransportReachability } var dnsErr *net.DNSError if errors.As(err, &dnsErr) && dnsErr.IsNotFound { - return upstreamTransportErrorClass{Persistent: true} + return upstreamTransportReachability } - // — String-marker fallback ———————————————————————————————————————————————— + // SOCKS5 and HTTP CONNECT report rejected credentials as plain errors. msg := strings.ToLower(err.Error()) - for _, marker := range persistentUpstreamTransportErrorMarkers { + if strings.Contains(msg, "authentication failed") || strings.Contains(msg, "proxy authentication required") { + return upstreamTransportProxyAuth + } + for _, marker := range upstreamReachabilityErrorMarkers { if strings.Contains(msg, marker) { - return upstreamTransportErrorClass{Persistent: true} + return upstreamTransportReachability } } - return upstreamTransportErrorClass{} + return upstreamTransportTransient } // isClientCanceledTransportError reports whether a transport-level failure was @@ -103,9 +87,8 @@ func isClientCanceledTransportError(ctx context.Context, err error) bool { // (Do/DoWithTLS returned a non-HTTP error: proxy/DNS/TCP/TLS). It: // 1. records the failure in Ops error logs (status 0, kind=request_error), // except when the client disconnected (see isClientCanceledTransportError); -// 2. for durable faults (expired/rejected proxy creds, dead proxy, DNS/routing) -// temporarily unschedules the account (DB + in-memory) and logs a stable -// warn event that alert rules can key on; +// 2. temporarily unschedules the account (DB + in-memory) for reachability +// failures and rejected proxy credentials, with a cooldown for each class; // 3. returns an error that is *UpstreamFailoverError (so the handler fails over // to a healthy account) for all non-canceled errors, or a plain error for // context.Canceled (client gone — no failover, no eviction). @@ -150,8 +133,11 @@ func (s *OpenAIGatewayService) handleOpenAIUpstreamTransportError(ctx context.Co return err } - if classifyUpstreamTransportError(err).Persistent { - s.tempUnscheduleOpenAITransportError(ctx, account, safeErr) + switch classifyUpstreamTransportError(err) { + case upstreamTransportReachability: + s.tempUnscheduleOpenAITransportError(ctx, account, safeErr, openAITransportReachabilityCooldown) + case upstreamTransportProxyAuth: + s.tempUnscheduleOpenAITransportError(ctx, account, safeErr, openAITransportProxyAuthCooldown) } return &UpstreamFailoverError{ @@ -161,7 +147,7 @@ func (s *OpenAIGatewayService) handleOpenAIUpstreamTransportError(ctx context.Co } // tempUnscheduleOpenAITransportError marks an account temporarily unschedulable -// after a durable transport failure, both persistently (DB, survives restart) +// after a transport failure, both persistently (DB, survives restart) // and in-memory (immediate scheduler effect before the DB/account cache propagates). // // Log semantics: @@ -171,14 +157,14 @@ func (s *OpenAIGatewayService) handleOpenAIUpstreamTransportError(ctx context.Co // accountRepo is nil (in-memory only; no persistence). // - "openai.account_temp_unscheduled_transport_failed" — DB write attempted // but returned an error. -func (s *OpenAIGatewayService) tempUnscheduleOpenAITransportError(ctx context.Context, account *Account, safeErr string) { +func (s *OpenAIGatewayService) tempUnscheduleOpenAITransportError(ctx context.Context, account *Account, safeErr string, cooldown time.Duration) { if s == nil || account == nil { return } if s.cfg != nil && s.cfg.Gateway.DisableOpenAITransportErrorCooldown { return } - until := time.Now().Add(openAITransportErrorTempUnschedDuration) + until := time.Now().Add(cooldown) reason := "upstream transport error (proxy/network): " + safeErr // Immediate in-memory block so this process skips the account until the diff --git a/backend/internal/service/openai_upstream_transport_error_handle_test.go b/backend/internal/service/openai_upstream_transport_error_handle_test.go index 27090f8cdd..cb9f84a58f 100644 --- a/backend/internal/service/openai_upstream_transport_error_handle_test.go +++ b/backend/internal/service/openai_upstream_transport_error_handle_test.go @@ -10,7 +10,9 @@ import ( "net/http" "net/http/httptest" "net/url" + "syscall" "testing" + "testing/synctest" "time" "github.com/Wei-Shaw/sub2api/internal/config" @@ -49,7 +51,7 @@ func TestHandleOpenAIUpstreamTransportError_DNSCooldownConfig(t *testing.T) { Err: "no such host", Name: "chatgpt.com", Server: "127.0.0.11:53", IsNotFound: true, }}, } - require.True(t, classifyUpstreamTransportError(transportErr).Persistent) + require.Equal(t, upstreamTransportReachability, classifyUpstreamTransportError(transportErr)) for _, testCase := range []struct { name string cfg *config.Config @@ -104,13 +106,13 @@ func TestHandleOpenAIUpstreamTransportError_DNSCooldownConfig(t *testing.T) { } else { blockUntil, exists := svc.openaiAccountRuntimeBlockUntil.Load(account.ID) require.True(t, exists) - require.WithinRange(t, blockUntil.(time.Time), before.Add(10*time.Minute), after.Add(10*time.Minute)) + require.WithinRange(t, blockUntil.(time.Time), before.Add(30*time.Second), after.Add(30*time.Second)) } if withRepo && !testCase.disabled { require.Len(t, repo.tempUnschedCalls, 1) call := repo.tempUnschedCalls[0] require.Equal(t, account.ID, call.accountID) - require.WithinRange(t, call.until, before.Add(10*time.Minute), after.Add(10*time.Minute)) + require.WithinRange(t, call.until, before.Add(30*time.Second), after.Add(30*time.Second)) require.Contains(t, call.reason, "no such host") } else { require.Empty(t, repo.tempUnschedCalls) @@ -121,13 +123,38 @@ func TestHandleOpenAIUpstreamTransportError_DNSCooldownConfig(t *testing.T) { } } +func TestHandleOpenAIUpstreamTransportError_RefusedProxyAllowsPromptRecovery(t *testing.T) { + synctest.Test(t, func(t *testing.T) { + repo := &openaiTransportAccountRepoStub{} + svc := &OpenAIGatewayService{accountRepo: repo} + account := &Account{ID: 9006, Platform: PlatformOpenAI, Status: StatusActive, Schedulable: true} + c, _ := newOpenAITransportErrTestContext() + transportErr := &url.Error{ + Op: "Post", + URL: "https://upstream.example.test/v1/responses", + Err: &net.OpError{Op: "proxyconnect", Net: "tcp", Err: syscall.ECONNREFUSED}, + } + + var failover *UpstreamFailoverError + require.ErrorAs(t, svc.handleOpenAIUpstreamTransportError(context.Background(), c, account, transportErr, false), &failover) + require.Len(t, repo.tempUnschedCalls, 1) + account.TempUnschedulableUntil = &repo.tempUnschedCalls[0].until + require.False(t, account.IsSchedulable()) + require.True(t, svc.isOpenAIAccountRuntimeBlocked(account)) + + time.Sleep(31 * time.Second) + require.True(t, account.IsSchedulable(), "a recovered proxy should become eligible after the reachability cooldown") + require.False(t, svc.isOpenAIAccountRuntimeBlocked(account)) + }) +} + func TestTempUnscheduleOpenAITransportError_DisabledPreservesExistingState(t *testing.T) { for _, paused := range []bool{false, true} { t.Run(fmt.Sprintf("paused=%t", paused), func(t *testing.T) { repo := &openaiTransportAccountRepoStub{} svc := &OpenAIGatewayService{accountRepo: repo, cfg: &config.Config{}} account := &Account{ID: 8541, Platform: PlatformOpenAI, Status: StatusActive, Schedulable: !paused} - svc.tempUnscheduleOpenAITransportError(context.Background(), account, "previous failure") + svc.tempUnscheduleOpenAITransportError(context.Background(), account, "previous failure", openAITransportProxyAuthCooldown) require.Len(t, repo.tempUnschedCalls, 1) previousCall := repo.tempUnschedCalls[0] persistedUntil := previousCall.until @@ -139,7 +166,7 @@ func TestTempUnscheduleOpenAITransportError_DisabledPreservesExistingState(t *te previousGeneration, _ := svc.openaiAccountRuntimeBlockGeneration.Load(account.ID) svc.cfg.Gateway.DisableOpenAITransportErrorCooldown = true - svc.tempUnscheduleOpenAITransportError(context.Background(), account, "new failure") + svc.tempUnscheduleOpenAITransportError(context.Background(), account, "new failure", openAITransportReachabilityCooldown) require.Equal(t, []tempUnschedCall{previousCall}, repo.tempUnschedCalls) require.Equal(t, previousAccount, *account) @@ -205,8 +232,7 @@ func TestHandleOpenAIUpstreamTransportError_PersistentEvictsAndFailsOver(t *test require.Len(t, repo.tempUnschedCalls, 1) require.Equal(t, int64(4627), repo.tempUnschedCalls[0].accountID) require.Contains(t, repo.tempUnschedCalls[0].reason, "authentication failed") - require.True(t, repo.tempUnschedCalls[0].until.After(before.Add(openAITransportErrorTempUnschedDuration-time.Second))) - require.True(t, repo.tempUnschedCalls[0].until.Before(after.Add(openAITransportErrorTempUnschedDuration+time.Second))) + require.WithinRange(t, repo.tempUnschedCalls[0].until, before.Add(10*time.Minute), after.Add(10*time.Minute)) // Immediate in-memory effect so subsequent requests skip it before DB/cache catches up. require.True(t, svc.isOpenAIAccountRuntimeBlocked(account)) @@ -293,7 +319,7 @@ func TestTempUnscheduleOpenAITransportError_NilAccountRepo_InMemoryBlockOnly(t * svc := &OpenAIGatewayService{accountRepo: nil} account := &Account{ID: 55, Name: "no-db", Platform: PlatformOpenAI} - svc.tempUnscheduleOpenAITransportError(context.Background(), account, "proxy refused") + svc.tempUnscheduleOpenAITransportError(context.Background(), account, "proxy refused", openAITransportReachabilityCooldown) // In-memory block must still happen. require.True(t, svc.isOpenAIAccountRuntimeBlocked(account), diff --git a/backend/internal/service/openai_upstream_transport_error_test.go b/backend/internal/service/openai_upstream_transport_error_test.go index 881b71177d..f951218903 100644 --- a/backend/internal/service/openai_upstream_transport_error_test.go +++ b/backend/internal/service/openai_upstream_transport_error_test.go @@ -11,33 +11,29 @@ import ( "testing" ) -// TestClassifyUpstreamTransportError pins which transport-level upstream failures -// are "persistent" (retrying the same proxy/account is pointless — evict + alert) -// versus "transient" (a blip — fail over to a healthy account but do not evict). -// -// The motivating incident: a SOCKS5 proxy whose credentials expired returned -// `username/password authentication failed`, yet the account kept being scheduled. +// TestClassifyUpstreamTransportError covers proxy authentication and network +// reachability failures in both typed errors and transport error messages. func TestClassifyUpstreamTransportError(t *testing.T) { cases := []struct { - name string - err error - persistent bool + name string + err error + want upstreamTransportErrorClass }{ - // Durable — config/credential/routing problems. Retrying same proxy won't help. - {"socks5 proxy credential rejected", errors.New(`Post "https://chatgpt.com/backend-api/codex/responses": socks connect tcp 85.255.176.68:12324->chatgpt.com:443: username/password authentication failed`), true}, - {"proxy connection refused", errors.New(`proxyconnect tcp: dial tcp 1.2.3.4:1080: connect: connection refused`), true}, - {"no route to host", errors.New(`dial tcp 1.2.3.4:443: connect: no route to host`), true}, - {"dns resolution failure", errors.New(`dial tcp: lookup proxy.example.com: no such host`), true}, - {"network unreachable", errors.New(`dial tcp 1.2.3.4:443: connect: network is unreachable`), true}, + {"socks5 proxy credential rejected", errors.New(`socks connect: username/password authentication failed`), upstreamTransportProxyAuth}, + {"HTTP CONNECT proxy credential rejected", errors.New(`Proxy Authentication Required`), upstreamTransportProxyAuth}, + {"proxy connection refused", errors.New(`proxyconnect tcp: dial tcp 1.2.3.4:1080: connect: connection refused`), upstreamTransportReachability}, + {"no route to host", errors.New(`dial tcp 1.2.3.4:443: connect: no route to host`), upstreamTransportReachability}, + {"dns resolution failure", errors.New(`dial tcp: lookup proxy.example.com: no such host`), upstreamTransportReachability}, + {"network unreachable", errors.New(`dial tcp 1.2.3.4:443: connect: network is unreachable`), upstreamTransportReachability}, // Transient — a temporary blip. Fail over, but do NOT evict the account. - {"client timeout", errors.New(`Post "https://chatgpt.com/...": context deadline exceeded (Client.Timeout exceeded while awaiting headers)`), false}, - {"i/o timeout", errors.New(`dial tcp 1.2.3.4:443: i/o timeout`), false}, - {"connection reset by peer", errors.New(`read tcp 10.0.0.1:5->2.2.2.2:443: read: connection reset by peer`), false}, - {"unexpected eof", errors.New(`unexpected EOF`), false}, - {"broken pipe", errors.New(`write tcp 10.0.0.1:5->2.2.2.2:443: write: broken pipe`), false}, + {"client timeout", errors.New(`Post "https://chatgpt.com/...": context deadline exceeded (Client.Timeout exceeded while awaiting headers)`), upstreamTransportTransient}, + {"i/o timeout", errors.New(`dial tcp 1.2.3.4:443: i/o timeout`), upstreamTransportTransient}, + {"connection reset by peer", errors.New(`read tcp 10.0.0.1:5->2.2.2.2:443: read: connection reset by peer`), upstreamTransportTransient}, + {"unexpected eof", errors.New(`unexpected EOF`), upstreamTransportTransient}, + {"broken pipe", errors.New(`write tcp 10.0.0.1:5->2.2.2.2:443: write: broken pipe`), upstreamTransportTransient}, - {"nil error", nil, false}, + {"nil error", nil, upstreamTransportTransient}, // ── Typed-error cases ────────────────────────────────────────────── // ECONNREFUSED wrapped in the canonical net.OpError shape Go produces. @@ -48,37 +44,37 @@ func TestClassifyUpstreamTransportError(t *testing.T) { Net: "tcp", Err: &os.SyscallError{Syscall: "connect", Err: syscall.ECONNREFUSED}, }, - true, + upstreamTransportReachability, }, // Bare syscall error (errors.Is traverses the chain). - {"ECONNREFUSED bare", syscall.ECONNREFUSED, true}, - {"EHOSTUNREACH bare", syscall.EHOSTUNREACH, true}, - {"ENETUNREACH bare", syscall.ENETUNREACH, true}, + {"ECONNREFUSED bare", syscall.ECONNREFUSED, upstreamTransportReachability}, + {"EHOSTUNREACH bare", syscall.EHOSTUNREACH, upstreamTransportReachability}, + {"ENETUNREACH bare", syscall.ENETUNREACH, upstreamTransportReachability}, // *net.DNSError with IsNotFound — permanent DNS lookup failure. { "DNS not found (IsNotFound=true)", &net.DNSError{Err: "no such host", Name: "proxy.example.com", IsNotFound: true}, - true, + upstreamTransportReachability, }, // *net.DNSError with IsNotFound=false — transient DNS timeout (not persistent). { "DNS timeout (IsNotFound=false)", &net.DNSError{Err: "i/o timeout", Name: "proxy.example.com", IsTimeout: true}, - false, + upstreamTransportTransient, }, // context.Canceled — client gone; NOT classified as persistent. - {"context.Canceled", context.Canceled, false}, + {"context.Canceled", context.Canceled, upstreamTransportTransient}, // context.DeadlineExceeded — slow upstream; NOT persistent. - {"context.DeadlineExceeded", context.DeadlineExceeded, false}, + {"context.DeadlineExceeded", context.DeadlineExceeded, upstreamTransportTransient}, } for _, tc := range cases { t.Run(tc.name, func(t *testing.T) { - got := classifyUpstreamTransportError(tc.err).Persistent - if got != tc.persistent { - t.Fatalf("classifyUpstreamTransportError(%q).Persistent = %v, want %v", errString(tc.err), got, tc.persistent) + got := classifyUpstreamTransportError(tc.err) + if got != tc.want { + t.Fatalf("classifyUpstreamTransportError(%q) = %v, want %v", errString(tc.err), got, tc.want) } }) } diff --git a/deploy/.env.example b/deploy/.env.example index d9d1beb337..f16e3483d0 100644 --- a/deploy/.env.example +++ b/deploy/.env.example @@ -307,7 +307,7 @@ GATEWAY_OPENAI_COMPACT_MODEL=gpt-5.5 SUB2API_IMAGES_MAIN_MODEL=gpt-5.6-luna # OpenAI/Codex 等待上游响应头超时(秒);0 表示不使用本地响应头超时截断。 GATEWAY_OPENAI_RESPONSE_HEADER_TIMEOUT=0 -# Disable only the fixed 10-minute account cooldown for persistent OpenAI DNS/proxy/network failures. +# Disable OpenAI gateway transport cooldowns (30 seconds for network reachability, 10 minutes for rejected proxy credentials). # YAML: gateway.disable_openai_transport_error_cooldown; false preserves the default protection. # Ops/errors and bounded failover remain; other cooldowns, existing state and admin pauses are unchanged. # Later requests retry broken shared egress; this is not a DNS/proxy repair or a model speed guarantee. diff --git a/deploy/config.example.yaml b/deploy/config.example.yaml index 257dbc751f..113bd35deb 100644 --- a/deploy/config.example.yaml +++ b/deploy/config.example.yaml @@ -239,7 +239,7 @@ gateway: # OpenAI/Codex upstream response header timeout (seconds, 0=disabled) # OpenAI/Codex 等待上游响应头超时时间(秒,0=禁用本地响应头超时) openai_response_header_timeout: 0 - # Opt out of the fixed 10-minute account cooldown for persistent OpenAI transport failures (DNS/proxy/network). + # Opt out of OpenAI gateway transport cooldowns (30 seconds for network reachability, 10 minutes for rejected proxy credentials). # Env: GATEWAY_DISABLE_OPENAI_TRANSPORT_ERROR_COOLDOWN=true; default false retains protection. # Errors/Ops and bounded request failover remain; HTTP 401/403/429, quota/model limits, # stream timeouts and token-refresh cooldowns are unchanged. Existing cooldowns and admin pauses are not cleared. From f3a0a652451d4ce395e98f5ad3cd7732ef80a29b Mon Sep 17 00:00:00 2001 From: alfadb Date: Mon, 23 Nov 2026 20:19:23 +0800 Subject: [PATCH 08/23] =?UTF-8?q?fix(ratelimit):=20=E6=99=BA=E8=B0=B1?= =?UTF-8?q?=E5=B9=B3=E5=8F=B0=E8=BF=87=E8=BD=BD=20429=20=E6=94=B9=E7=94=A8?= =?UTF-8?q?=E7=A7=92=E7=BA=A7=E5=86=B7=E5=8D=B4?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 线上实测报文 {"error":{"code":"1305","message":"该模型当前访问量过大,请您稍后再试"}} 表示平台服务过载,与账号额度无关。该文案既不命中 cnFrequencyLimitMarkers 的频率型特征,也不含额度类词,于是被当成额度耗尽,冷却到配额快照最早的窗口重置点(5h 或周窗,实测 16 分钟到数小时,需人工恢复)。 将「访问量过大」加入频率型 429 文案白名单,并补充注释说明 1305 的实测文案;命中后交给通用 429 兜底使用秒级冷却。90% 用量守卫(cnProviderQuotaSnapshotNearExhausted)保持不变:快照任一窗口用量达到 90% 或快照缺失时仍按窗口冷却。新增 1305 回归测试覆盖该报文。 --- .../ratelimit_cn_frequency_429_test.go | 20 +++++++++++++++++++ .../service/ratelimit_cn_providers.go | 3 +++ 2 files changed, 23 insertions(+) diff --git a/backend/internal/service/ratelimit_cn_frequency_429_test.go b/backend/internal/service/ratelimit_cn_frequency_429_test.go index 2343a0152c..39858fdcee 100644 --- a/backend/internal/service/ratelimit_cn_frequency_429_test.go +++ b/backend/internal/service/ratelimit_cn_frequency_429_test.go @@ -15,6 +15,9 @@ import ( // 智谱 GLM Coding Plan 实测 429 文案:额度充裕时的「限频」。 const zhipuFrequencyLimitedBody = `{"error":{"code":"1302","message":"您的账户已达到速率限制,请您控制请求频率"}}` +// 智谱错误码 1305 实测 429 文案:平台服务过载,与账号额度无关。 +const zhipuOverloadLimitedBody = `{"error":{"code":"1305","message":"该模型当前访问量过大,请您稍后再试"}}` + // newZhipuCodingPlanAccount 构造一个智谱 Coding Plan 账号,Extra 带 5h/weekly // 用量与重置快照(与 CNProviderQuotaService 写入的键一致)。 func newZhipuCodingPlanAccount(h5Used, weeklyUsed float64, resetIn time.Duration) *Account { @@ -61,6 +64,23 @@ func TestHandleUpstreamError_ZhipuFrequency429UsesShortCooldown(t *testing.T) { "frequency 429 must cool down seconds, not to the 5h window reset") } +// 智谱平台过载(1305「该模型当前访问量过大,请您稍后再试」)与账号额度无关, +// 也应走秒级 429 兜底,而不是冷却到 5h 窗口结束。 +func TestHandleUpstreamError_ZhipuOverload1305UsesShortCooldown(t *testing.T) { + repo := &rateLimitAccountRepoStub{} + service := NewRateLimitService(repo, nil, &config.Config{}, nil, nil) + account := newZhipuCodingPlanAccount(12, 4, 4*time.Hour) + + runZhipu429(service, account, zhipuOverloadLimitedBody) + + require.Equal(t, 0, repo.setErrorCalls, "a platform overload 429 must never SetError") + require.Equal(t, 1, repo.rateLimitedCalls) + require.Equal(t, account.ID, repo.lastRateLimitedID) + require.WithinDuration(t, time.Now().Add(defaultRateLimit429CooldownSeconds*time.Second), + repo.lastRateLimitedAt, 30*time.Second, + "platform overload 429 must cool down seconds, not to the 5h window reset") +} + // 快照显示窗口已耗尽时,即使文案是限频,也仍然冷却到窗口重置点(护栏)。 func TestHandleUpstreamError_ZhipuFrequency429WithExhaustedSnapshotKeepsWindowCooldown(t *testing.T) { repo := &rateLimitAccountRepoStub{} diff --git a/backend/internal/service/ratelimit_cn_providers.go b/backend/internal/service/ratelimit_cn_providers.go index 9fa194de69..2ad7d7723b 100644 --- a/backend/internal/service/ratelimit_cn_providers.go +++ b/backend/internal/service/ratelimit_cn_providers.go @@ -126,6 +126,8 @@ const cnFrequencyLimitQuotaGuardPercent = 90 // cnFrequencyLimitMarkers 是「请求频率/速率限制」类 429 的文案特征(小写比较)。 // 智谱实测文案:「您的账户已达到速率限制,请您控制请求频率」。 +// 智谱平台过载(错误码 1305)的实测文案「该模型当前访问量过大,请您稍后再试」 +// 与账号额度无关,同样按秒级冷却处理。 var cnFrequencyLimitMarkers = []string{ "速率限制", "请求频率", @@ -136,6 +138,7 @@ var cnFrequencyLimitMarkers = []string{ "rate limit exceeded", "rate_limit_exceeded", "ratelimit exceeded", + "访问量过大", } // cnQuotaExhaustionMarkers 是额度耗尽类文案;命中任一即认为 429 与额度有关, From 52b5d71d607327edff2a9d46566c9519182615e0 Mon Sep 17 00:00:00 2001 From: LagrangeQ <43517024+LagrangeQ@users.noreply.github.com> Date: Tue, 24 Nov 2026 14:57:23 +0800 Subject: [PATCH 09/23] fix(gemini): preserve stream usage after empty metadata Ignore usageMetadata without counters so a trailing placeholder cannot overwrite measured input, output, or cached tokens. Preserve explicit zero counters and add regression coverage for the Gemini native, Chat Completions, Messages, and stream collection paths. --- .../service/gemini_messages_compat_service.go | 30 ++++--- .../gemini_messages_compat_service_test.go | 78 ++++++++++++++++--- 2 files changed, 88 insertions(+), 20 deletions(-) diff --git a/backend/internal/service/gemini_messages_compat_service.go b/backend/internal/service/gemini_messages_compat_service.go index 04add43379..f5754e41f0 100644 --- a/backend/internal/service/gemini_messages_compat_service.go +++ b/backend/internal/service/gemini_messages_compat_service.go @@ -3101,35 +3101,43 @@ func isValidBase64(data string) bool { func extractGeminiUsage(data []byte) *ClaudeUsage { usage := gjson.GetBytes(data, "usageMetadata") - if !usage.Exists() { + if !usage.IsObject() { return nil } - prompt := int(usage.Get("promptTokenCount").Int()) - cand := int(usage.Get("candidatesTokenCount").Int()) - cached := int(usage.Get("cachedContentTokenCount").Int()) - thoughts := int(usage.Get("thoughtsTokenCount").Int()) + prompt := usage.Get("promptTokenCount") + cand := usage.Get("candidatesTokenCount") + cached := usage.Get("cachedContentTokenCount") + thoughts := usage.Get("thoughtsTokenCount") // 从 candidatesTokensDetails 提取 IMAGE 模态 token 数 - imageTokens := 0 + var imageTokens gjson.Result candidateDetails := usage.Get("candidatesTokensDetails") if candidateDetails.Exists() { candidateDetails.ForEach(func(_, detail gjson.Result) bool { if detail.Get("modality").String() == "IMAGE" { - imageTokens = int(detail.Get("tokenCount").Int()) + imageTokens = detail.Get("tokenCount") return false } return true }) } + // A frame without usage counters must not replace usage already seen in the stream. + // Explicit zeroes are valid counters. + if prompt.Type == gjson.Null && cand.Type == gjson.Null && cached.Type == gjson.Null && + thoughts.Type == gjson.Null && imageTokens.Type == gjson.Null { + return nil + } + // 注意:Gemini 的 promptTokenCount 包含 cachedContentTokenCount, // 但 Claude 的 input_tokens 不包含 cache_read_input_tokens,需要减去。 // prompt 被拦截时上游可能只报 cachedContentTokenCount,差值下限为 0。 + cacheReadTokens := int(cached.Int()) return &ClaudeUsage{ - InputTokens: max(prompt-cached, 0), - OutputTokens: cand + thoughts, - CacheReadInputTokens: cached, - ImageOutputTokens: imageTokens, + InputTokens: max(int(prompt.Int())-cacheReadTokens, 0), + OutputTokens: int(cand.Int() + thoughts.Int()), + CacheReadInputTokens: cacheReadTokens, + ImageOutputTokens: int(imageTokens.Int()), } } diff --git a/backend/internal/service/gemini_messages_compat_service_test.go b/backend/internal/service/gemini_messages_compat_service_test.go index 8380ea7608..4f970cbcf5 100644 --- a/backend/internal/service/gemini_messages_compat_service_test.go +++ b/backend/internal/service/gemini_messages_compat_service_test.go @@ -1193,16 +1193,24 @@ func TestExtractGeminiUsage(t *testing.T) { wantNil: true, }, { - // gjson 对 null 返回 Exists()=true,因此函数不会返回 nil, - // 而是返回全零的 ClaudeUsage。 - name: "null usageMetadata — gjson Exists 为 true", + name: "null usageMetadata", input: `{"usageMetadata":null}`, - wantNil: false, - wantUsage: &ClaudeUsage{ - InputTokens: 0, - OutputTokens: 0, - CacheReadInputTokens: 0, - }, + wantNil: true, + }, + { + name: "空 usageMetadata", + input: `{"usageMetadata":{}}`, + wantNil: true, + }, + { + name: "只有 null 字段和辅助元数据", + input: `{"usageMetadata":{"promptTokenCount":null,"trafficType":"ON_DEMAND","candidatesTokensDetails":[]}}`, + wantNil: true, + }, + { + name: "只有图片 Token 明细", + input: `{"usageMetadata":{"candidatesTokensDetails":[{"modality":"IMAGE","tokenCount":12}]}}`, + wantUsage: &ClaudeUsage{ImageOutputTokens: 12}, }, { name: "零值字段", @@ -1237,6 +1245,7 @@ func TestExtractGeminiUsage(t *testing.T) { if got.CacheReadInputTokens != tt.wantUsage.CacheReadInputTokens { t.Errorf("CacheReadInputTokens: 期望 %d,实际 %d", tt.wantUsage.CacheReadInputTokens, got.CacheReadInputTokens) } + require.Equal(t, tt.wantUsage.ImageOutputTokens, got.ImageOutputTokens) // Gemini usageMetadata 只有 cachedContentTokenCount(缓存命中),没有缓存写入 // 的 token 类别:cache_creation_input_tokens 恒为 0,计费侧不会产生缓存创建分项。 if got.CacheCreationInputTokens != 0 { @@ -1246,6 +1255,57 @@ func TestExtractGeminiUsage(t *testing.T) { } } +func TestGeminiStreamsRetainUsageAfterEmptyMetadata(t *testing.T) { + gin.SetMode(gin.TestMode) + + const model = "gemini-2.5-flash" + const measured = `data: {"candidates":[{"content":{"parts":[{"text":"ok"}]},"finishReason":"STOP"}],"usageMetadata":{"promptTokenCount":13,"cachedContentTokenCount":3,"candidatesTokenCount":4,"thoughtsTokenCount":1}}` + "\n\n" + want := ClaudeUsage{InputTokens: 10, OutputTokens: 5, CacheReadInputTokens: 3} + + for _, trailer := range []struct{ name, payload string }{ + {"empty object", `{"usageMetadata":{}}`}, + {"null", `{"usageMetadata":null}`}, + } { + t.Run(trailer.name, func(t *testing.T) { + stream := measured + "data: " + trailer.payload + "\n\ndata: [DONE]\n\n" + newResponse := func() *http.Response { + return &http.Response{StatusCode: http.StatusOK, Body: io.NopCloser(strings.NewReader(stream))} + } + newContext := func(rec *httptest.ResponseRecorder) *gin.Context { + c, _ := gin.CreateTestContext(rec) + c.Request = httptest.NewRequest(http.MethodPost, "/", nil) + return c + } + svc := &GeminiMessagesCompatService{} + + t.Run("Chat Completions", func(t *testing.T) { + rec := httptest.NewRecorder() + result, err := svc.handleChatCompletionsStreamingResponseFromGemini(newContext(rec), newResponse(), time.Now(), model, false, true) + require.NoError(t, err) + require.Equal(t, &want, result.usage) + require.Contains(t, rec.Body.String(), "data: [DONE]") + }) + t.Run("Messages", func(t *testing.T) { + result, err := svc.handleStreamingResponse(newContext(httptest.NewRecorder()), newResponse(), time.Now(), model) + require.NoError(t, err) + require.Equal(t, &want, result.usage) + }) + t.Run("Gemini native", func(t *testing.T) { + rec := httptest.NewRecorder() + result, err := svc.handleNativeStreamingResponse(newContext(rec), newResponse(), time.Now(), false, nil, "") + require.NoError(t, err) + require.Equal(t, &want, result.usage) + require.Equal(t, stream, rec.Body.String()) + }) + t.Run("collected stream", func(t *testing.T) { + _, usage, err := collectGeminiSSE(nil, strings.NewReader(stream), false) + require.NoError(t, err) + require.Equal(t, &want, usage) + }) + }) + } +} + // --------------------------------------------------------------------------- // Task 8.2 — estimateGeminiCountTokens 测试 // --------------------------------------------------------------------------- From 0c7d3ff58c64075aed0cb2f819a4e47d80bca7be Mon Sep 17 00:00:00 2001 From: wucm667 Date: Tue, 24 Nov 2026 18:42:21 +0800 Subject: [PATCH 10/23] fix(accounts): show proxy account counts in account dialogs --- .../__tests__/ProxySelector.testing.spec.ts | 21 +++++++++++++++++-- frontend/src/views/admin/AccountsView.vue | 2 +- .../__tests__/AccountsView.bulkEdit.spec.ts | 2 +- .../admin/__tests__/AccountsView.lite.spec.ts | 19 +++++++++++++++-- .../AccountsView.priorityColumn.spec.ts | 2 +- .../AccountsView.schedulerScore.spec.ts | 2 +- .../AccountsView.selectAllResults.spec.ts | 2 +- .../AccountsView.sparkShadow.spec.ts | 4 ++-- .../AccountsView.usageWindowsHint.spec.ts | 2 +- 9 files changed, 44 insertions(+), 12 deletions(-) diff --git a/frontend/src/components/common/__tests__/ProxySelector.testing.spec.ts b/frontend/src/components/common/__tests__/ProxySelector.testing.spec.ts index f175fa6a92..6807cb6302 100644 --- a/frontend/src/components/common/__tests__/ProxySelector.testing.spec.ts +++ b/frontend/src/components/common/__tests__/ProxySelector.testing.spec.ts @@ -9,10 +9,11 @@ vi.mock('vue-i18n', () => ({ useI18n: () => ({ t: (key: string) => key }) })) enableAutoUnmount(afterEach) beforeEach(() => { vi.clearAllMocks() }) -async function openSelector() { +async function openSelector(accountCounts?: number[]) { const wrapper = mount(ProxySelector, { props: { modelValue: null, proxies: [1, 2].map(id => ({ - id, name: `Proxy ${id}`, host: 'localhost', port: 8080, protocol: 'http' + id, name: `Proxy ${id}`, host: 'localhost', port: 8080, protocol: 'http', + account_count: accountCounts?.[id - 1] } as Proxy)) }, global: { stubs: { Icon: true } } }) @@ -20,6 +21,22 @@ async function openSelector() { return wrapper } +describe('proxy account counts', () => { + it('displays zero and nonzero counts in dropdown options', async () => { + const wrapper = await openSelector([0, 7]) + const options = wrapper.findAll('.select-option').slice(1) + + expect(options[0].get('.bg-gray-100').text()).toBe('0') + expect(options[1].get('.bg-gray-100').text()).toBe('7') + }) + + it('does not display a count when it is unavailable', async () => { + const wrapper = await openSelector() + + expect(wrapper.findAll('.select-option .bg-gray-100')).toHaveLength(0) + }) +}) + describe('proxy connection tests', () => { it('does not restart an individual test when a batch is started', async () => { let finish!: (result: object) => void diff --git a/frontend/src/views/admin/AccountsView.vue b/frontend/src/views/admin/AccountsView.vue index 4ded2775b6..0f46ea3b7d 100644 --- a/frontend/src/views/admin/AccountsView.vue +++ b/frontend/src/views/admin/AccountsView.vue @@ -2622,7 +2622,7 @@ onMounted(async () => { load() loadUpstreamBillingProbeGlobalState() const [proxiesResult, groupsResult] = await Promise.allSettled([ - adminAPI.proxies.getAll(), + adminAPI.proxies.getAllWithCount(), adminAPI.groups.getAll() ]) if (proxiesResult.status === 'fulfilled') { diff --git a/frontend/src/views/admin/__tests__/AccountsView.bulkEdit.spec.ts b/frontend/src/views/admin/__tests__/AccountsView.bulkEdit.spec.ts index 425fa5def7..2a92a7d2ff 100644 --- a/frontend/src/views/admin/__tests__/AccountsView.bulkEdit.spec.ts +++ b/frontend/src/views/admin/__tests__/AccountsView.bulkEdit.spec.ts @@ -45,7 +45,7 @@ vi.mock('@/api/admin', () => ({ toggleSchedulable: vi.fn() }, proxies: { - getAll: getAllProxies + getAllWithCount: getAllProxies }, groups: { getAll: getAllGroups diff --git a/frontend/src/views/admin/__tests__/AccountsView.lite.spec.ts b/frontend/src/views/admin/__tests__/AccountsView.lite.spec.ts index 1eea4bf2c7..977d4c4fc4 100644 --- a/frontend/src/views/admin/__tests__/AccountsView.lite.spec.ts +++ b/frontend/src/views/admin/__tests__/AccountsView.lite.spec.ts @@ -52,7 +52,7 @@ vi.mock('@/api/admin', () => ({ previewUpstreamGroup, update: updateAccount }, - proxies: { getAll: getAllProxies }, + proxies: { getAllWithCount: getAllProxies }, groups: { getAll: getAllGroups } } })) @@ -90,7 +90,7 @@ const AccountGroupsCellStub = defineComponent({ }) const EditAccountModalStub = defineComponent({ - props: { show: Boolean, account: { type: Object, default: null } }, + props: { show: Boolean, account: { type: Object, default: null }, proxies: Array }, template: '
{{ show ? account?.name : "" }}
' }) @@ -188,6 +188,21 @@ describe('admin AccountsView lite account list', () => { vi.restoreAllMocks() }) + it('loads proxies with account counts and passes them to create and edit modals', async () => { + const proxies = [ + { id: 1, name: 'Unused proxy', account_count: 0 }, + { id: 2, name: 'Shared proxy', account_count: 7 } + ] + getAllProxies.mockResolvedValue(proxies) + const wrapper = mountView() + await flushPromises() + + expect(getAllProxies).toHaveBeenCalledTimes(1) + expect(wrapper.findComponent({ name: 'CreateAccountModal' }).props('proxies')).toEqual(proxies) + expect(wrapper.findComponent(EditAccountModalStub).props('proxies')).toEqual(proxies) + wrapper.unmount() + }) + it('syncs the selected row without clearing notes missing from the upstream', async () => { const account = { ...listRow, type: 'apikey', notes: 'local notes' } listAccounts.mockResolvedValue({ items: [account], total: 1, page: 1, page_size: 20, pages: 1 }) diff --git a/frontend/src/views/admin/__tests__/AccountsView.priorityColumn.spec.ts b/frontend/src/views/admin/__tests__/AccountsView.priorityColumn.spec.ts index 42c1071e87..e8f4483e14 100644 --- a/frontend/src/views/admin/__tests__/AccountsView.priorityColumn.spec.ts +++ b/frontend/src/views/admin/__tests__/AccountsView.priorityColumn.spec.ts @@ -19,7 +19,7 @@ vi.mock('@/api/admin', () => ({ batchRefresh: vi.fn(), toggleSchedulable: vi.fn() }, - proxies: { getAll: vi.fn().mockResolvedValue([]) }, + proxies: { getAllWithCount: vi.fn().mockResolvedValue([]) }, groups: { getAll: vi.fn().mockResolvedValue([]) } } })) diff --git a/frontend/src/views/admin/__tests__/AccountsView.schedulerScore.spec.ts b/frontend/src/views/admin/__tests__/AccountsView.schedulerScore.spec.ts index c63087b393..a21dcb0819 100644 --- a/frontend/src/views/admin/__tests__/AccountsView.schedulerScore.spec.ts +++ b/frontend/src/views/admin/__tests__/AccountsView.schedulerScore.spec.ts @@ -30,7 +30,7 @@ vi.mock('@/api/admin', () => ({ toggleSchedulable: vi.fn() }, proxies: { - getAll: getAllProxies + getAllWithCount: getAllProxies }, groups: { getAll: getAllGroups diff --git a/frontend/src/views/admin/__tests__/AccountsView.selectAllResults.spec.ts b/frontend/src/views/admin/__tests__/AccountsView.selectAllResults.spec.ts index c80ddcaaab..2a7e2dd7cf 100644 --- a/frontend/src/views/admin/__tests__/AccountsView.selectAllResults.spec.ts +++ b/frontend/src/views/admin/__tests__/AccountsView.selectAllResults.spec.ts @@ -36,7 +36,7 @@ vi.mock('@/api/admin', () => ({ bulkUpdate: vi.fn() }, proxies: { - getAll: getAllProxies + getAllWithCount: getAllProxies }, groups: { getAll: getAllGroups diff --git a/frontend/src/views/admin/__tests__/AccountsView.sparkShadow.spec.ts b/frontend/src/views/admin/__tests__/AccountsView.sparkShadow.spec.ts index 08191b511b..de509a2547 100644 --- a/frontend/src/views/admin/__tests__/AccountsView.sparkShadow.spec.ts +++ b/frontend/src/views/admin/__tests__/AccountsView.sparkShadow.spec.ts @@ -45,7 +45,7 @@ vi.mock('@/api/admin', () => ({ batchRefresh: vi.fn(), toggleSchedulable: vi.fn() }, - proxies: { getAll: getAllProxies }, + proxies: { getAllWithCount: getAllProxies }, groups: { getAll: getAllGroups } } })) @@ -341,7 +341,7 @@ describe('admin AccountsView — 账号行展示', () => { const tooltip = wrapper.findComponent(HelpTooltip) expect(tooltip.props('content')).toBe('https://relay.example.com') expect(tooltip.props('widthClass')).toBe('w-max max-w-sm break-all') - expect(tooltip.classes()).toEqual(expect.arrayContaining(['self-start'])) + expect(tooltip.classes()).toEqual(expect.arrayContaining(['inline-flex', 'items-center', 'align-middle', '-ml-1'])) expect(wrapper.text()).toContain('oauth-account') expect(wrapper.text()).toContain('invalid-url') diff --git a/frontend/src/views/admin/__tests__/AccountsView.usageWindowsHint.spec.ts b/frontend/src/views/admin/__tests__/AccountsView.usageWindowsHint.spec.ts index 9f25d0dcd3..bd283f84de 100644 --- a/frontend/src/views/admin/__tests__/AccountsView.usageWindowsHint.spec.ts +++ b/frontend/src/views/admin/__tests__/AccountsView.usageWindowsHint.spec.ts @@ -30,7 +30,7 @@ vi.mock('@/api/admin', () => ({ toggleSchedulable: vi.fn() }, proxies: { - getAll: getAllProxies + getAllWithCount: getAllProxies }, groups: { getAll: getAllGroups From 8decae97790c4875b07e940819233878262688a7 Mon Sep 17 00:00:00 2001 From: PMExtra Date: Thu, 12 Nov 2026 12:47:09 +0800 Subject: [PATCH 11/23] feat(accounts): show upstream error counts in today stats and usage trend Count provider-owned, non-business-limited rows in ops_error_logs per account (same definition as the ops dashboard) and expose them as `upstream_errors` on today stats and per-day account usage history. - Today stats column shows today's upstream errors (highlighted when > 0). - Usage statistics modal adds an upstream error trend line plus today and 30-day totals; days with only errors are merged into the history. - Counts are omitted when ops monitoring is disabled so the UI hides them instead of showing a misleading 0. Failover intermediate attempts are attributed only to the last failing account. Co-Authored-By: Claude Opus 5.5 --- backend/cmd/server/wire_gen.go | 2 +- .../pkg/usagestats/usage_log_types.go | 7 +- .../usage_log_repo_integration_test.go | 37 +++++ .../repository/usage_log_repo_stats.go | 75 +++++++++ .../internal/service/account_usage_service.go | 99 +++++++++++- .../account_usage_upstream_errors_test.go | 153 ++++++++++++++++++ backend/internal/service/wire.go | 4 + .../account/AccountTodayStatsCell.vue | 19 +++ .../__tests__/AccountTodayStatsCell.spec.ts | 46 ++++++ .../admin/account/AccountStatsModal.vue | 49 +++++- .../__tests__/AccountStatsModal.spec.ts | 117 ++++++++++++++ .../src/i18n/locales/en/admin/accounts.ts | 2 + .../src/i18n/locales/zh/admin/accounts.ts | 2 + frontend/src/types/index.ts | 4 + 14 files changed, 611 insertions(+), 5 deletions(-) create mode 100644 backend/internal/service/account_usage_upstream_errors_test.go create mode 100644 frontend/src/components/account/__tests__/AccountTodayStatsCell.spec.ts create mode 100644 frontend/src/components/admin/account/__tests__/AccountStatsModal.spec.ts diff --git a/backend/cmd/server/wire_gen.go b/backend/cmd/server/wire_gen.go index 2835089f9c..33650eed3b 100644 --- a/backend/cmd/server/wire_gen.go +++ b/backend/cmd/server/wire_gen.go @@ -208,7 +208,7 @@ func initializeApplication(buildInfo handler.BuildInfo) (*Application, error) { openAIReferralClient := repository.NewOpenAIReferralClient(privacyClientFactory) openAIQuotaService := service.ProvideOpenAIQuotaService(accountRepository, proxyRepository, openAITokenProvider, privacyClientFactory, openAIReferralClient, openAIGatewayService) usageCache := service.NewUsageCache() - accountUsageService := service.ProvideAccountUsageService(accountRepository, usageLogRepository, claudeUsageFetcher, geminiQuotaService, antigravityQuotaFetcher, grokQuotaFetcher, grokQuotaService, openAIQuotaService, usageCache, identityCache, tlsFingerprintProfileService, openAIGatewayService) + accountUsageService := service.ProvideAccountUsageService(accountRepository, usageLogRepository, claudeUsageFetcher, geminiQuotaService, antigravityQuotaFetcher, grokQuotaFetcher, grokQuotaService, openAIQuotaService, usageCache, identityCache, tlsFingerprintProfileService, openAIGatewayService, opsService) pluginRepository := repository.NewPluginRepository(db) pluginHostInfo := providePluginHostInfo(buildInfo) pluginKVStore := repository.NewPluginKVStore(redisClient) diff --git a/backend/internal/pkg/usagestats/usage_log_types.go b/backend/internal/pkg/usagestats/usage_log_types.go index 9b9c4cb668..7141a9d862 100644 --- a/backend/internal/pkg/usagestats/usage_log_types.go +++ b/backend/internal/pkg/usagestats/usage_log_types.go @@ -340,6 +340,8 @@ type AccountUsageHistory struct { Cost float64 `json:"cost"` // 标准计费(total_cost) ActualCost float64 `json:"actual_cost"` // 账号口径费用(total_cost * account_rate_multiplier) UserCost float64 `json:"user_cost"` // 用户口径费用(actual_cost,受分组倍率影响) + // UpstreamErrors 当日上游错误次数;运维监控关闭时为 nil。 + UpstreamErrors *int64 `json:"upstream_errors,omitempty"` } // AccountUsageSummary represents summary statistics for an account @@ -356,7 +358,10 @@ type AccountUsageSummary struct { AvgDailyRequests float64 `json:"avg_daily_requests"` AvgDailyTokens float64 `json:"avg_daily_tokens"` AvgDurationMs float64 `json:"avg_duration_ms"` - Today *struct { + // 上游错误次数;运维监控关闭时为 nil。 + TotalUpstreamErrors *int64 `json:"total_upstream_errors,omitempty"` + TodayUpstreamErrors *int64 `json:"today_upstream_errors,omitempty"` + Today *struct { Date string `json:"date"` Cost float64 `json:"cost"` UserCost float64 `json:"user_cost"` diff --git a/backend/internal/repository/usage_log_repo_integration_test.go b/backend/internal/repository/usage_log_repo_integration_test.go index e0798b2fb7..e60046b425 100644 --- a/backend/internal/repository/usage_log_repo_integration_test.go +++ b/backend/internal/repository/usage_log_repo_integration_test.go @@ -947,6 +947,43 @@ func (s *UsageLogRepoSuite) TestGetAccountTodayStats() { s.Require().InEpsilon(3.0, stats.UserCost, 0.0001) } +func (s *UsageLogRepoSuite) TestAccountUpstreamErrorCounts() { + account := mustCreateAccount(s.T(), s.client, &service.Account{Name: "acc-upstream-errors"}) + other := mustCreateAccount(s.T(), s.client, &service.Account{Name: "acc-upstream-errors-other"}) + + today := timezone.Today().Add(1 * time.Hour) + yesterday := today.Add(-24 * time.Hour) + insert := func(accountID int64, owner string, businessLimited bool, statusCode int, createdAt time.Time) { + _, err := s.tx.ExecContext(s.ctx, ` + INSERT INTO ops_error_logs ( + account_id, error_phase, error_type, severity, status_code, error_owner, is_business_limited, created_at + ) VALUES ($1, 'upstream', 'upstream_error', 'P2', $2, $3, $4, $5)`, + accountID, statusCode, owner, businessLimited, createdAt, + ) + s.Require().NoError(err) + } + insert(account.ID, "provider", false, 502, today) + insert(account.ID, "provider", false, 429, today) + // 故障转移后恢复的请求:最终状态码 < 400,仍计为上游错误。 + insert(account.ID, "provider", false, 200, today) + insert(account.ID, "provider", false, 500, yesterday) + insert(account.ID, "client", false, 400, today) + insert(account.ID, "provider", true, 503, today) + insert(other.ID, "provider", false, 500, today) + + counts, err := s.repo.GetAccountUpstreamErrorCountsBatch(s.ctx, []int64{account.ID, 999999}, timezone.Today()) + s.Require().NoError(err) + s.Require().Equal(int64(3), counts[account.ID]) + s.Require().Contains(counts, int64(999999)) + s.Require().Equal(int64(0), counts[999999]) + s.Require().NotContains(counts, other.ID) + + daily, err := s.repo.GetAccountDailyUpstreamErrorCounts(s.ctx, account.ID, timezone.Today().Add(-24*time.Hour), timezone.Today().Add(24*time.Hour)) + s.Require().NoError(err) + s.Require().Equal(int64(3), daily[today.Format("2006-01-02")]) + s.Require().Equal(int64(1), daily[yesterday.Format("2006-01-02")]) +} + func (s *UsageLogRepoSuite) TestDashboardAggregationConsistency() { now := time.Now().UTC().Truncate(time.Second) // 使用固定的时间偏移确保 hour1 和 hour2 在同一天且都在过去 diff --git a/backend/internal/repository/usage_log_repo_stats.go b/backend/internal/repository/usage_log_repo_stats.go index 5dfb74646f..203cb9170d 100644 --- a/backend/internal/repository/usage_log_repo_stats.go +++ b/backend/internal/repository/usage_log_repo_stats.go @@ -387,6 +387,81 @@ func (r *usageLogRepository) GetAccountWindowStatsBatch(ctx context.Context, acc return result, nil } +// accountUpstreamErrorPredicate 与运维看板的上游错误口径一致(不区分 429/529)。 +// ops_error_logs 每个请求一行,account_id 为最终(或最后失败的)账号,故障转移中间尝试不单独计入。 +const accountUpstreamErrorPredicate = `error_owner = 'provider' AND NOT is_business_limited` + +// GetAccountUpstreamErrorCountsBatch 批量统计多个账号自 startTime 起的上游错误次数。 +// 未命中的账号返回 0。 +func (r *usageLogRepository) GetAccountUpstreamErrorCountsBatch(ctx context.Context, accountIDs []int64, startTime time.Time) (map[int64]int64, error) { + result := make(map[int64]int64, len(accountIDs)) + if len(accountIDs) == 0 { + return result, nil + } + + query := ` + SELECT account_id, COUNT(*) + FROM ops_error_logs + WHERE account_id = ANY($1) AND created_at >= $2 + AND ` + accountUpstreamErrorPredicate + ` + GROUP BY account_id + ` + rows, err := r.sql.QueryContext(ctx, query, pq.Array(accountIDs), startTime) + if err != nil { + return nil, err + } + defer func() { _ = rows.Close() }() + + for rows.Next() { + var accountID, count int64 + if err := rows.Scan(&accountID, &count); err != nil { + return nil, err + } + result[accountID] = count + } + if err := rows.Err(); err != nil { + return nil, err + } + + for _, accountID := range accountIDs { + if _, ok := result[accountID]; !ok { + result[accountID] = 0 + } + } + return result, nil +} + +// GetAccountDailyUpstreamErrorCounts 按日统计账号在 [startTime, endTime) 内的上游错误次数,key 为 YYYY-MM-DD。 +// 日期分组口径与 GetAccountUsageStats 保持一致。 +func (r *usageLogRepository) GetAccountDailyUpstreamErrorCounts(ctx context.Context, accountID int64, startTime, endTime time.Time) (map[string]int64, error) { + query := ` + SELECT TO_CHAR(created_at, 'YYYY-MM-DD') as date, COUNT(*) + FROM ops_error_logs + WHERE account_id = $1 AND created_at >= $2 AND created_at < $3 + AND ` + accountUpstreamErrorPredicate + ` + GROUP BY date + ` + rows, err := r.sql.QueryContext(ctx, query, accountID, startTime, endTime) + if err != nil { + return nil, err + } + defer func() { _ = rows.Close() }() + + result := make(map[string]int64) + for rows.Next() { + var date string + var count int64 + if err := rows.Scan(&date, &count); err != nil { + return nil, err + } + result[date] = count + } + if err := rows.Err(); err != nil { + return nil, err + } + return result, nil +} + // GetGeminiUsageTotalsBatch 批量聚合 Gemini 账号在窗口内的 Pro/Flash 请求与用量。 // 模型分类规则与 service.geminiModelClassFromName 一致:model 包含 flash/lite 视为 flash,其余视为 pro。 func (r *usageLogRepository) GetGeminiUsageTotalsBatch(ctx context.Context, accountIDs []int64, startTime, endTime time.Time) (map[int64]service.GeminiUsageTotals, error) { diff --git a/backend/internal/service/account_usage_service.go b/backend/internal/service/account_usage_service.go index 07272f5bf1..153e1cab4d 100644 --- a/backend/internal/service/account_usage_service.go +++ b/backend/internal/service/account_usage_service.go @@ -9,6 +9,7 @@ import ( "log/slog" "math/rand/v2" "net/http" + "sort" "strings" "sync" "time" @@ -85,6 +86,16 @@ type accountWindowStatsBatchReader interface { GetAccountWindowStatsBatch(ctx context.Context, accountIDs []int64, startTime time.Time) (map[int64]*usagestats.AccountStats, error) } +// accountUpstreamErrorStatsReader 读取 ops_error_logs 中按账号归属的上游错误次数。 +type accountUpstreamErrorStatsReader interface { + GetAccountUpstreamErrorCountsBatch(ctx context.Context, accountIDs []int64, startTime time.Time) (map[int64]int64, error) + GetAccountDailyUpstreamErrorCounts(ctx context.Context, accountID int64, startTime, endTime time.Time) (map[string]int64, error) +} + +type opsMonitoringStatusReader interface { + IsMonitoringEnabled(ctx context.Context) bool +} + // apiUsageCache 缓存从 Anthropic API 获取的使用率数据(utilization, resets_at) // 同时支持缓存错误响应(负缓存),防止 429 等错误导致的重试风暴 type apiUsageCache struct { @@ -150,6 +161,8 @@ type WindowStats struct { Cost float64 `json:"cost"` StandardCost float64 `json:"standard_cost"` UserCost float64 `json:"user_cost"` + // UpstreamErrors 仅今日统计填充;运维监控关闭时为 nil。 + UpstreamErrors *int64 `json:"upstream_errors,omitempty"` } // UsageProgress 使用量进度 @@ -342,6 +355,7 @@ type AccountUsageService struct { tlsFPProfileService *TLSFingerprintProfileService agentIdentityTaskMu sync.Mutex agentIdentityWS agentIdentityWSConnectionInvalidator + opsMonitoring opsMonitoringStatusReader } // NewAccountUsageService 创建AccountUsageService实例 @@ -1535,13 +1549,49 @@ func (s *AccountUsageService) GetTodayStats(ctx context.Context, accountID int64 return nil, fmt.Errorf("get today stats failed: %w", err) } - return &WindowStats{ + result := &WindowStats{ Requests: stats.Requests, Tokens: stats.Tokens, Cost: stats.Cost, StandardCost: stats.StandardCost, UserCost: stats.UserCost, - }, nil + } + s.attachTodayUpstreamErrors(ctx, map[int64]*WindowStats{accountID: result}, []int64{accountID}) + return result, nil +} + +// upstreamErrorStatsReader 返回上游错误统计读取器;运维监控关闭(不再写入错误日志)时返回 nil, +// 调用方据此不下发错误次数,避免前端把“未记录”误显示为 0。 +func (s *AccountUsageService) upstreamErrorStatsReader(ctx context.Context) accountUpstreamErrorStatsReader { + if s.opsMonitoring == nil || !s.opsMonitoring.IsMonitoringEnabled(ctx) { + return nil + } + reader, ok := s.usageLogRepo.(accountUpstreamErrorStatsReader) + if !ok { + return nil + } + return reader +} + +// attachTodayUpstreamErrors 为今日统计补充上游错误次数;查询失败仅记录日志,不影响主统计。 +func (s *AccountUsageService) attachTodayUpstreamErrors(ctx context.Context, result map[int64]*WindowStats, accountIDs []int64) { + reader := s.upstreamErrorStatsReader(ctx) + if reader == nil || len(accountIDs) == 0 { + return + } + counts, err := reader.GetAccountUpstreamErrorCountsBatch(ctx, accountIDs, timezone.Today()) + if err != nil { + slog.Warn("account_today_upstream_errors_query_failed", "accounts", len(accountIDs), "error", err) + return + } + for _, accountID := range accountIDs { + stats := result[accountID] + if stats == nil { + continue + } + count := counts[accountID] + stats.UpstreamErrors = &count + } } // GetTodayStatsBatch 批量获取账号今日统计,优先走批量 SQL,失败时回退单账号查询。 @@ -1581,6 +1631,7 @@ func (s *AccountUsageService) GetTodayStatsBatch(ctx context.Context, accountIDs for _, accountID := range uniqueIDs { result[accountID] = windowStatsFromAccountStats(statsByAccount[accountID]) } + s.attachTodayUpstreamErrors(ctx, result, uniqueIDs) return result, nil } } @@ -1610,6 +1661,7 @@ func (s *AccountUsageService) GetTodayStatsBatch(ctx context.Context, accountIDs result[accountID] = &WindowStats{} } } + s.attachTodayUpstreamErrors(ctx, result, uniqueIDs) return result, nil } @@ -1705,9 +1757,52 @@ func (s *AccountUsageService) GetAccountUsageStats(ctx context.Context, accountI if err != nil { return nil, fmt.Errorf("get account usage stats failed: %w", err) } + if reader := s.upstreamErrorStatsReader(ctx); reader != nil && stats != nil { + counts, err := reader.GetAccountDailyUpstreamErrorCounts(ctx, accountID, startTime, endTime) + if err != nil { + slog.Warn("account_daily_upstream_errors_query_failed", "account_id", accountID, "error", err) + } else { + mergeAccountDailyUpstreamErrors(stats, counts, timezone.Now().Format("2006-01-02")) + } + } return stats, nil } +// mergeAccountDailyUpstreamErrors 将按日上游错误次数并入 history:已有日期直接填充, +// 只有错误没有成功请求的日期补入空用量行,保证趋势图不丢点。 +func mergeAccountDailyUpstreamErrors(stats *usagestats.AccountUsageStatsResponse, counts map[string]int64, todayStr string) { + seen := make(map[string]struct{}, len(stats.History)) + for i := range stats.History { + h := &stats.History[i] + count := counts[h.Date] + h.UpstreamErrors = &count + seen[h.Date] = struct{}{} + } + for date, count := range counts { + if _, ok := seen[date]; ok { + continue + } + t, err := time.Parse("2006-01-02", date) + if err != nil { + continue + } + stats.History = append(stats.History, usagestats.AccountUsageHistory{ + Date: date, + Label: t.Format("01/02"), + UpstreamErrors: &count, + }) + } + sort.Slice(stats.History, func(i, j int) bool { return stats.History[i].Date < stats.History[j].Date }) + + var total int64 + for _, count := range counts { + total += count + } + today := counts[todayStr] + stats.Summary.TotalUpstreamErrors = &total + stats.Summary.TodayUpstreamErrors = &today +} + // fetchOAuthUsageRaw 从 Anthropic API 获取原始响应(不构建 UsageInfo) // 如果账号开启了 TLS 指纹,则使用 TLS 指纹伪装 // 如果有缓存的 Fingerprint,则使用缓存的 User-Agent 等信息 diff --git a/backend/internal/service/account_usage_upstream_errors_test.go b/backend/internal/service/account_usage_upstream_errors_test.go new file mode 100644 index 0000000000..3205e686d6 --- /dev/null +++ b/backend/internal/service/account_usage_upstream_errors_test.go @@ -0,0 +1,153 @@ +package service + +import ( + "context" + "errors" + "testing" + "time" + + "github.com/Wei-Shaw/sub2api/internal/pkg/timezone" + "github.com/Wei-Shaw/sub2api/internal/pkg/usagestats" + "github.com/stretchr/testify/require" +) + +type upstreamErrorUsageLogRepoStub struct { + usageBatchLogRepoStub + windowStats map[int64]*usagestats.AccountStats + usageStats *usagestats.AccountUsageStatsResponse + errorCounts map[int64]int64 + dailyCounts map[string]int64 + errorsErr error + batchCalls int + dailyCalls int + batchStartAt time.Time +} + +func (r *upstreamErrorUsageLogRepoStub) GetAccountWindowStatsBatch(_ context.Context, _ []int64, _ time.Time) (map[int64]*usagestats.AccountStats, error) { + return r.windowStats, nil +} + +func (r *upstreamErrorUsageLogRepoStub) GetAccountTodayStats(context.Context, int64) (*usagestats.AccountStats, error) { + return &usagestats.AccountStats{Requests: 3}, nil +} + +func (r *upstreamErrorUsageLogRepoStub) GetAccountUsageStats(context.Context, int64, time.Time, time.Time) (*usagestats.AccountUsageStatsResponse, error) { + return r.usageStats, nil +} + +func (r *upstreamErrorUsageLogRepoStub) GetAccountUpstreamErrorCountsBatch(_ context.Context, _ []int64, startTime time.Time) (map[int64]int64, error) { + r.batchCalls++ + r.batchStartAt = startTime + return r.errorCounts, r.errorsErr +} + +func (r *upstreamErrorUsageLogRepoStub) GetAccountDailyUpstreamErrorCounts(context.Context, int64, time.Time, time.Time) (map[string]int64, error) { + r.dailyCalls++ + return r.dailyCounts, r.errorsErr +} + +type opsMonitoringStatusStub bool + +func (s opsMonitoringStatusStub) IsMonitoringEnabled(context.Context) bool { return bool(s) } + +func TestGetTodayStatsBatch_AttachesUpstreamErrorsWhenMonitoringEnabled(t *testing.T) { + repo := &upstreamErrorUsageLogRepoStub{ + windowStats: map[int64]*usagestats.AccountStats{1: {Requests: 10}, 2: {Requests: 5}}, + errorCounts: map[int64]int64{1: 4}, + } + svc := &AccountUsageService{usageLogRepo: repo, opsMonitoring: opsMonitoringStatusStub(true)} + + result, err := svc.GetTodayStatsBatch(context.Background(), []int64{1, 2}) + require.NoError(t, err) + require.Equal(t, 1, repo.batchCalls) + require.Equal(t, timezone.Today(), repo.batchStartAt) + require.NotNil(t, result[1].UpstreamErrors) + require.Equal(t, int64(4), *result[1].UpstreamErrors) + require.NotNil(t, result[2].UpstreamErrors) + require.Equal(t, int64(0), *result[2].UpstreamErrors) + require.Equal(t, int64(10), result[1].Requests) +} + +func TestGetTodayStatsBatch_OmitsUpstreamErrorsWhenMonitoringDisabled(t *testing.T) { + for name, monitoring := range map[string]opsMonitoringStatusReader{ + "disabled": opsMonitoringStatusStub(false), + "unwired": nil, + } { + t.Run(name, func(t *testing.T) { + repo := &upstreamErrorUsageLogRepoStub{ + windowStats: map[int64]*usagestats.AccountStats{1: {Requests: 10}}, + errorCounts: map[int64]int64{1: 4}, + } + svc := &AccountUsageService{usageLogRepo: repo, opsMonitoring: monitoring} + + result, err := svc.GetTodayStatsBatch(context.Background(), []int64{1}) + require.NoError(t, err) + require.Zero(t, repo.batchCalls) + require.Nil(t, result[1].UpstreamErrors) + }) + } +} + +func TestGetTodayStats_UpstreamErrorQueryFailureKeepsUsageStats(t *testing.T) { + repo := &upstreamErrorUsageLogRepoStub{errorsErr: errors.New("boom")} + svc := &AccountUsageService{usageLogRepo: repo, opsMonitoring: opsMonitoringStatusStub(true)} + + result, err := svc.GetTodayStats(context.Background(), 1) + require.NoError(t, err) + require.Equal(t, int64(3), result.Requests) + require.Nil(t, result.UpstreamErrors) +} + +func TestGetAccountUsageStats_MergesDailyUpstreamErrors(t *testing.T) { + today := timezone.Now().Format("2006-01-02") + yesterday := timezone.Now().AddDate(0, 0, -1).Format("2006-01-02") + twoDaysAgo := timezone.Now().AddDate(0, 0, -2).Format("2006-01-02") + + repo := &upstreamErrorUsageLogRepoStub{ + usageStats: &usagestats.AccountUsageStatsResponse{ + History: []usagestats.AccountUsageHistory{ + {Date: twoDaysAgo, Requests: 7}, + {Date: today, Requests: 2}, + }, + Summary: usagestats.AccountUsageSummary{ActualDaysUsed: 2}, + }, + // yesterday 只有错误、没有成功请求。 + dailyCounts: map[string]int64{yesterday: 5, today: 1}, + } + svc := &AccountUsageService{usageLogRepo: repo, opsMonitoring: opsMonitoringStatusStub(true)} + + stats, err := svc.GetAccountUsageStats(context.Background(), 1, time.Now().AddDate(0, 0, -3), time.Now()) + require.NoError(t, err) + require.Len(t, stats.History, 3) + + require.Equal(t, twoDaysAgo, stats.History[0].Date) + require.Equal(t, int64(0), *stats.History[0].UpstreamErrors) + require.Equal(t, yesterday, stats.History[1].Date) + require.Equal(t, int64(0), stats.History[1].Requests) + require.Equal(t, int64(5), *stats.History[1].UpstreamErrors) + require.NotEmpty(t, stats.History[1].Label) + require.Equal(t, today, stats.History[2].Date) + require.Equal(t, int64(1), *stats.History[2].UpstreamErrors) + + require.Equal(t, int64(6), *stats.Summary.TotalUpstreamErrors) + require.Equal(t, int64(1), *stats.Summary.TodayUpstreamErrors) + // 补入的纯错误日期不计入活跃天数。 + require.Equal(t, 2, stats.Summary.ActualDaysUsed) +} + +func TestGetAccountUsageStats_OmitsUpstreamErrorsWhenMonitoringDisabled(t *testing.T) { + repo := &upstreamErrorUsageLogRepoStub{ + usageStats: &usagestats.AccountUsageStatsResponse{ + History: []usagestats.AccountUsageHistory{{Date: "2026-01-01", Requests: 1}}, + }, + dailyCounts: map[string]int64{"2026-01-02": 3}, + } + svc := &AccountUsageService{usageLogRepo: repo, opsMonitoring: opsMonitoringStatusStub(false)} + + stats, err := svc.GetAccountUsageStats(context.Background(), 1, time.Now().AddDate(0, 0, -3), time.Now()) + require.NoError(t, err) + require.Zero(t, repo.dailyCalls) + require.Len(t, stats.History, 1) + require.Nil(t, stats.History[0].UpstreamErrors) + require.Nil(t, stats.Summary.TotalUpstreamErrors) +} diff --git a/backend/internal/service/wire.go b/backend/internal/service/wire.go index efa0c2587e..97ca115e4e 100644 --- a/backend/internal/service/wire.go +++ b/backend/internal/service/wire.go @@ -238,6 +238,7 @@ func ProvideAccountUsageService( identityCache IdentityCache, tlsFPProfileService *TLSFingerprintProfileService, openAIGatewayService *OpenAIGatewayService, + opsService *OpsService, ) *AccountUsageService { service := NewAccountUsageService( accountRepo, @@ -253,6 +254,9 @@ func ProvideAccountUsageService( tlsFPProfileService, ) service.agentIdentityWS = openAIGatewayService + if opsService != nil { + service.opsMonitoring = opsService + } return service } diff --git a/frontend/src/components/account/AccountTodayStatsCell.vue b/frontend/src/components/account/AccountTodayStatsCell.vue index a422d1f000..158bc38a1c 100644 --- a/frontend/src/components/account/AccountTodayStatsCell.vue +++ b/frontend/src/components/account/AccountTodayStatsCell.vue @@ -46,6 +46,25 @@ formatCurrency(props.stats.user_cost) }}
+ +
+ {{ t('admin.accounts.stats.upstreamErrors') }}: + {{ formatNumber(props.stats.upstream_errors) }} +
diff --git a/frontend/src/components/account/__tests__/AccountTodayStatsCell.spec.ts b/frontend/src/components/account/__tests__/AccountTodayStatsCell.spec.ts new file mode 100644 index 0000000000..6f0d060e05 --- /dev/null +++ b/frontend/src/components/account/__tests__/AccountTodayStatsCell.spec.ts @@ -0,0 +1,46 @@ +import { mount } from '@vue/test-utils' +import { describe, expect, it, vi } from 'vitest' +import AccountTodayStatsCell from '../AccountTodayStatsCell.vue' +import type { WindowStats } from '@/types' + +vi.mock('vue-i18n', async () => { + const actual = await vi.importActual('vue-i18n') + return { + ...actual, + useI18n: () => ({ + t: (key: string) => key + }) + } +}) + +const baseStats: WindowStats = { + requests: 10, + tokens: 1000, + cost: 1, + standard_cost: 1, + user_cost: 1 +} + +const mountCell = (stats: WindowStats) => mount(AccountTodayStatsCell, { props: { stats } }) + +describe('AccountTodayStatsCell upstream errors', () => { + it('highlights a non-zero upstream error count', () => { + const row = mountCell({ ...baseStats, upstream_errors: 12 }).get('[data-testid="today-upstream-errors"]') + expect(row.text()).toContain('admin.accounts.stats.upstreamErrors') + expect(row.text()).toContain('12') + expect(row.find('.text-red-600').exists()).toBe(true) + }) + + it('shows zero without highlighting', () => { + const row = mountCell({ ...baseStats, upstream_errors: 0 }).get('[data-testid="today-upstream-errors"]') + expect(row.text()).toContain('0') + expect(row.find('.text-red-600').exists()).toBe(false) + }) + + it('hides the row when the backend omits the count', () => { + expect(mountCell(baseStats).find('[data-testid="today-upstream-errors"]').exists()).toBe(false) + expect( + mountCell({ ...baseStats, upstream_errors: null }).find('[data-testid="today-upstream-errors"]').exists() + ).toBe(false) + }) +}) diff --git a/frontend/src/components/admin/account/AccountStatsModal.vue b/frontend/src/components/admin/account/AccountStatsModal.vue index 4dc84d5e93..1c30e8a3fe 100644 --- a/frontend/src/components/admin/account/AccountStatsModal.vue +++ b/frontend/src/components/admin/account/AccountStatsModal.vue @@ -195,6 +195,24 @@ formatTokens(stats.summary.today?.tokens || 0) }} +
+ {{ + t('admin.accounts.stats.upstreamErrors') + }} + {{ formatNumber(stats.summary.today_upstream_errors) }} +
@@ -346,6 +364,18 @@ >{{ stats.summary.actual_days_used }} / {{ stats.summary.days }} +
+ {{ + t('admin.accounts.stats.totalUpstreamErrors') + }} + {{ + formatNumber(stats.summary.total_upstream_errors) + }} +
@@ -510,6 +540,22 @@ const chartColors = computed(() => ({ const trendChartData = computed(() => { if (!stats.value?.history?.length) return null + // 运维监控关闭时后端不下发 upstream_errors,此时不画这条线。 + const hasUpstreamErrors = stats.value.summary.total_upstream_errors != null + const upstreamErrorDatasets = hasUpstreamErrors + ? [ + { + label: t('admin.accounts.stats.upstreamErrors'), + data: stats.value.history.map((h) => h.upstream_errors ?? 0), + borderColor: '#ef4444', + backgroundColor: 'rgba(239, 68, 68, 0.1)', + fill: false, + tension: 0.3, + yAxisID: 'y1' + } + ] + : [] + return { labels: stats.value.history.map((h) => h.label), datasets: [ @@ -540,7 +586,8 @@ const trendChartData = computed(() => { fill: false, tension: 0.3, yAxisID: 'y1' - } + }, + ...upstreamErrorDatasets ] } }) diff --git a/frontend/src/components/admin/account/__tests__/AccountStatsModal.spec.ts b/frontend/src/components/admin/account/__tests__/AccountStatsModal.spec.ts new file mode 100644 index 0000000000..b1cb5041ac --- /dev/null +++ b/frontend/src/components/admin/account/__tests__/AccountStatsModal.spec.ts @@ -0,0 +1,117 @@ +import { flushPromises, mount } from '@vue/test-utils' +import { beforeEach, describe, expect, it, vi } from 'vitest' +import AccountStatsModal from '../AccountStatsModal.vue' +import type { Account, AccountUsageStatsResponse } from '@/types' + +const { getStats } = vi.hoisted(() => ({ + getStats: vi.fn() +})) + +vi.mock('@/api/admin', () => ({ + adminAPI: { + accounts: { + getStats + } + } +})) + +vi.mock('vue-chartjs', () => ({ + Line: { + props: ['data', 'options'], + template: '
{{ JSON.stringify(data) }}
' + } +})) + +vi.mock('vue-i18n', async () => { + const actual = await vi.importActual('vue-i18n') + return { + ...actual, + useI18n: () => ({ + t: (key: string) => key + }) + } +}) + +function makeStats(withUpstreamErrors: boolean): AccountUsageStatsResponse { + const errors = (value: number) => (withUpstreamErrors ? { upstream_errors: value } : {}) + return { + history: [ + { date: '2026-11-10', label: '11/10', requests: 5, tokens: 100, cost: 1, actual_cost: 1, user_cost: 1, ...errors(0) }, + { date: '2026-11-11', label: '11/11', requests: 0, tokens: 0, cost: 0, actual_cost: 0, user_cost: 0, ...errors(4) }, + { date: '2026-11-12', label: '11/12', requests: 3, tokens: 50, cost: 1, actual_cost: 1, user_cost: 1, ...errors(2) } + ], + summary: { + days: 30, + actual_days_used: 2, + total_cost: 2, + total_user_cost: 2, + total_standard_cost: 2, + total_requests: 8, + total_tokens: 150, + avg_daily_cost: 1, + avg_daily_user_cost: 1, + avg_daily_requests: 4, + avg_daily_tokens: 75, + avg_duration_ms: 100, + ...(withUpstreamErrors ? { total_upstream_errors: 6, today_upstream_errors: 2 } : {}), + today: { date: '2026-11-12', cost: 1, user_cost: 1, requests: 3, tokens: 50 }, + highest_cost_day: null, + highest_request_day: null + }, + models: [], + endpoints: [], + upstream_endpoints: [] + } as AccountUsageStatsResponse +} + +const mountModal = async () => { + const wrapper = mount(AccountStatsModal, { + props: { show: false, account: { id: 1, name: 'acc', status: 'active' } as Account }, + global: { + stubs: { + BaseDialog: { template: '
' }, + ModelDistributionChart: true, + EndpointDistributionChart: true, + LoadingSpinner: true, + Icon: true + } + } + }) + await wrapper.setProps({ show: true }) + await flushPromises() + return wrapper +} + +describe('AccountStatsModal upstream errors', () => { + beforeEach(() => { + getStats.mockReset() + }) + + it('adds an upstream error trend line and summary rows when reported', async () => { + getStats.mockResolvedValue(makeStats(true)) + const wrapper = await mountModal() + + const chartData = JSON.parse(wrapper.get('.chart-data').text()) as { + datasets: Array<{ label: string; data: number[]; yAxisID: string }> + } + const errorDataset = chartData.datasets.find((d) => d.label === 'admin.accounts.stats.upstreamErrors') + expect(errorDataset).toBeDefined() + expect(errorDataset!.data).toEqual([0, 4, 2]) + expect(errorDataset!.yAxisID).toBe('y1') + + expect(wrapper.get('[data-testid="today-upstream-errors"]').text()).toContain('2') + expect(wrapper.get('[data-testid="total-upstream-errors"]').text()).toContain('6') + }) + + it('hides upstream errors when the backend omits them', async () => { + getStats.mockResolvedValue(makeStats(false)) + const wrapper = await mountModal() + + const chartData = JSON.parse(wrapper.get('.chart-data').text()) as { + datasets: Array<{ label: string }> + } + expect(chartData.datasets.map((d) => d.label)).not.toContain('admin.accounts.stats.upstreamErrors') + expect(wrapper.find('[data-testid="today-upstream-errors"]').exists()).toBe(false) + expect(wrapper.find('[data-testid="total-upstream-errors"]').exists()).toBe(false) + }) +}) diff --git a/frontend/src/i18n/locales/en/admin/accounts.ts b/frontend/src/i18n/locales/en/admin/accounts.ts index 469e60210e..bfdfec7f55 100644 --- a/frontend/src/i18n/locales/en/admin/accounts.ts +++ b/frontend/src/i18n/locales/en/admin/accounts.ts @@ -1739,6 +1739,8 @@ export default { todayRequests: 'Today Requests', todayTokens: 'Today Tokens', todayCost: 'Today Cost', + upstreamErrors: 'Upstream Errors', + totalUpstreamErrors: '30-Day Upstream Errors', usageTrend: '30-Day Cost & Request Trend', noData: 'No usage data available for this account' }, diff --git a/frontend/src/i18n/locales/zh/admin/accounts.ts b/frontend/src/i18n/locales/zh/admin/accounts.ts index 1af0ea3644..0d35c23776 100644 --- a/frontend/src/i18n/locales/zh/admin/accounts.ts +++ b/frontend/src/i18n/locales/zh/admin/accounts.ts @@ -1837,6 +1837,8 @@ export default { todayRequests: '今日请求', todayTokens: '今日 Token', todayCost: '今日费用', + upstreamErrors: '上游错误', + totalUpstreamErrors: '30天上游错误', usageTrend: '30天费用与请求趋势', noData: '该账号暂无使用数据' } diff --git a/frontend/src/types/index.ts b/frontend/src/types/index.ts index 25ecc4f66b..ecc221a6da 100644 --- a/frontend/src/types/index.ts +++ b/frontend/src/types/index.ts @@ -1434,6 +1434,7 @@ export interface WindowStats { cost: number // Account cost (account multiplier) standard_cost?: number user_cost?: number + upstream_errors?: number | null // Today stats only; absent when ops monitoring is disabled } export interface UsageProgress { @@ -2317,6 +2318,7 @@ export interface AccountUsageHistory { cost: number actual_cost: number // Account cost (account multiplier) user_cost: number // User/API key billed cost (group multiplier) + upstream_errors?: number | null // Absent when ops monitoring is disabled } export interface AccountUsageSummary { @@ -2332,6 +2334,8 @@ export interface AccountUsageSummary { avg_daily_requests: number avg_daily_tokens: number avg_duration_ms: number + total_upstream_errors?: number | null // Absent when ops monitoring is disabled + today_upstream_errors?: number | null today: { date: string cost: number From 876f137d8fbfa1dd873fd31831d18f10241dc3eb Mon Sep 17 00:00:00 2001 From: r266-tech Date: Wed, 25 Nov 2026 01:15:18 +0800 Subject: [PATCH 12/23] feat(antigravity): let upstream choose Gemini stream summaries --- backend/internal/config/config.go | 3 +++ backend/internal/config/config_test.go | 8 ++++++++ .../service/antigravity_gateway_compat.go | 6 +++++- .../antigravity_gateway_compat_test.go | 19 +++++++++++++++++++ deploy/config.example.yaml | 5 +++++ 5 files changed, 40 insertions(+), 1 deletion(-) diff --git a/backend/internal/config/config.go b/backend/internal/config/config.go index 3e264053d3..6dad5c9722 100644 --- a/backend/internal/config/config.go +++ b/backend/internal/config/config.go @@ -1193,6 +1193,8 @@ type GatewayConfig struct { // Gemini 同账号重试次数(429/5xx 等可重试错误在换号前对同一账号的重发次数,不含首次请求) MaxSameAccountRetriesGemini int `mapstructure:"max_same_account_retries_gemini"` + // Let the upstream decide whether to stream thought summaries on Antigravity Gemini compatibility requests. + AntigravityGeminiOmitIncludeThoughts bool `mapstructure:"antigravity_gemini_omit_include_thoughts"` // Antigravity 429 fallback 限流时间(分钟),解析重置时间失败时使用 AntigravityFallbackCooldownMinutes int `mapstructure:"antigravity_fallback_cooldown_minutes"` @@ -2621,6 +2623,7 @@ func setDefaults() { viper.SetDefault("gateway.image_concurrency.overflow_mode", ImageConcurrencyOverflowModeReject) viper.SetDefault("gateway.image_concurrency.wait_timeout_seconds", 30) viper.SetDefault("gateway.image_concurrency.max_waiting_requests", 100) + viper.SetDefault("gateway.antigravity_gemini_omit_include_thoughts", false) viper.SetDefault("gateway.antigravity_fallback_cooldown_minutes", 1) viper.SetDefault("gateway.antigravity_extra_retries", 10) viper.SetDefault("gateway.max_body_size", int64(256*1024*1024)) diff --git a/backend/internal/config/config_test.go b/backend/internal/config/config_test.go index 9c17de959b..0160b4b657 100644 --- a/backend/internal/config/config_test.go +++ b/backend/internal/config/config_test.go @@ -132,6 +132,14 @@ func TestLoadMinOutputTokensFromEnv(t *testing.T) { require.Equal(t, 16, cfg.Gateway.MinOutputTokens) } +func TestLoadAntigravityGeminiOmitIncludeThoughtsFromEnv(t *testing.T) { + resetViperWithJWTSecret(t) + t.Setenv("GATEWAY_ANTIGRAVITY_GEMINI_OMIT_INCLUDE_THOUGHTS", "true") + cfg, err := Load() + require.NoError(t, err) + require.True(t, cfg.Gateway.AntigravityGeminiOmitIncludeThoughts) +} + func TestLoadGeminiSameAccountRetries(t *testing.T) { resetViperWithJWTSecret(t) cfg, err := Load() diff --git a/backend/internal/service/antigravity_gateway_compat.go b/backend/internal/service/antigravity_gateway_compat.go index 639edef8b0..7d6c2c49b7 100644 --- a/backend/internal/service/antigravity_gateway_compat.go +++ b/backend/internal/service/antigravity_gateway_compat.go @@ -322,7 +322,11 @@ func (s *AntigravityGatewayService) buildAntigravityCompatGeminiBody( return nil, err } body = ensureGeminiFunctionCallThoughtSignatures(body) - body = applyGeminiCompatThinkingConfig(body, claudeBody, mappedModel, claudeRequest != nil && claudeRequest.Stream) + includeThoughts := claudeRequest != nil && claudeRequest.Stream + if s.settingService != nil && s.settingService.cfg != nil && s.settingService.cfg.Gateway.AntigravityGeminiOmitIncludeThoughts { + includeThoughts = false + } + body = applyGeminiCompatThinkingConfig(body, claudeBody, mappedModel, includeThoughts) body, err = injectIdentityPatchToGeminiRequest(body) if err != nil { return nil, err diff --git a/backend/internal/service/antigravity_gateway_compat_test.go b/backend/internal/service/antigravity_gateway_compat_test.go index f830286d94..d73abc4eec 100644 --- a/backend/internal/service/antigravity_gateway_compat_test.go +++ b/backend/internal/service/antigravity_gateway_compat_test.go @@ -1416,6 +1416,25 @@ func TestAntigravityCompatGeminiThinkingConfig(t *testing.T) { require.True(t, cfg.Get("includeThoughts").Bool(), "thinkingConfig=%s", cfg.Raw) }) + t.Run("streaming chat can omit includeThoughts and keep the requested effort", func(t *testing.T) { + reply := antigravityCompatSuccessResponse() + reply.Body = io.NopCloser(strings.NewReader(`data: {"response":{"candidates":[{"content":{"parts":[{"thought":true,"text":"summary"},{"text":"answer"}]},"finishReason":"STOP"}]}}` + "\n\n")) + upstream := &queuedHTTPUpstreamStub{responses: []*http.Response{reply}} + svc := newAntigravityCompatService(config.GatewayConfig{AntigravityGeminiOmitIncludeThoughts: true}, upstream) + account := newAntigravityCompatAccount(AccountTypeOAuth) + account.Credentials["model_mapping"] = map[string]any{"gemini-3.5-flash": "gemini-3.5-flash"} + body := []byte(`{"model":"gemini-3.5-flash","reasoning_effort":"medium","stream":true,"messages":[{"role":"user","content":"hello"}]}`) + c, recorder := newAntigravityCompatContext(http.MethodPost, "/v1/chat/completions", body) + _, err := svc.ForwardAsChatCompletions(context.Background(), c, account, body, nil) + require.NoError(t, err) + require.Len(t, upstream.requestBodies, 1) + cfg := gjson.GetBytes(upstream.requestBodies[0], "request.generationConfig.thinkingConfig") + require.False(t, cfg.Get("includeThoughts").Exists()) + require.Equal(t, "medium", cfg.Get("thinkingLevel").String()) + require.Contains(t, recorder.Body.String(), `"reasoning_content":"summary"`) + require.Contains(t, recorder.Body.String(), `"content":"answer"`) + }) + t.Run("non-streaming responses do not force includeThoughts", func(t *testing.T) { upstream := &queuedHTTPUpstreamStub{responses: []*http.Response{antigravityCompatSuccessResponse()}} svc := newAntigravityCompatService(config.GatewayConfig{MaxLineSize: defaultMaxLineSize}, upstream) diff --git a/deploy/config.example.yaml b/deploy/config.example.yaml index 257dbc751f..70d3d3e2d4 100644 --- a/deploy/config.example.yaml +++ b/deploy/config.example.yaml @@ -523,6 +523,11 @@ gateway: # Concurrency slot expiration time (minutes) # 并发槽位过期时间(分钟) concurrency_slot_ttl_minutes: 30 + # On Antigravity Gemini Chat Completions and Responses streams, let the upstream decide + # whether to return thought summaries. Long silent thinking periods may hit the stream timeout. + # 让上游决定是否返回思考摘要。长时间没有数据的思考阶段可能触发流超时。 + # Env: GATEWAY_ANTIGRAVITY_GEMINI_OMIT_INCLUDE_THOUGHTS + antigravity_gemini_omit_include_thoughts: false # Stream data interval timeout (seconds), 0=disable # 流数据间隔超时(秒),0=禁用 stream_data_interval_timeout: 180 From 2b836b7b7c26c8f14ccd26d10c2a8404830bb640 Mon Sep 17 00:00:00 2001 From: wucm667 Date: Wed, 25 Nov 2026 02:44:44 +0800 Subject: [PATCH 13/23] fix(antigravity): handle versionless system identity openers --- .../pkg/antigravity/attribution_test.go | 12 +++++ .../pkg/antigravity/request_transformer.go | 1 + .../antigravity_gateway_compat_test.go | 54 ++++++++++++++++++- 3 files changed, 66 insertions(+), 1 deletion(-) diff --git a/backend/internal/pkg/antigravity/attribution_test.go b/backend/internal/pkg/antigravity/attribution_test.go index 1eee227383..204d7715f9 100644 --- a/backend/internal/pkg/antigravity/attribution_test.go +++ b/backend/internal/pkg/antigravity/attribution_test.go @@ -31,6 +31,18 @@ func TestTransformClaudeToGemini_AttributionSystemText(t *testing.T) { {"Codex GPT 5.6", "You are Codex, a coding agent based on GPT-5.6.\nKeep indentation.", "You are an AI agent.\nKeep indentation."}, {"Codex GPT 6", "You are Codex, based on GPT-6.", "You are an AI agent."}, {"Codex GPT 6 agent", "You are Codex, an agent based on GPT-6. Rest.", "You are an AI agent. Rest."}, + {"Codex versionless", "You are Codex, a coding agent.", "You are an AI agent."}, + {"Codex versionless instructions", "You are Codex, a coding agent. Keep all instructions.\n Preserve indentation.\n", "You are an AI agent. Keep all instructions.\n Preserve indentation.\n"}, + {"Codex versionless whitespace", " \t\r\nYou are Codex, a coding agent.\r\n\tKeep indentation.", "You are an AI agent.\r\n\tKeep indentation."}, + {"Codex versionless case", "you are codex, a coding agent. Rest.", "You are an AI agent. Rest."}, + {"attribution before versionless", attribution + "\r\nYou are Codex, a coding agent. Rest.", "You are an AI agent. Rest."}, + {"quoted versionless", `"You are Codex, a coding agent."`, `"You are Codex, a coding agent."`}, + {"later versionless", "Example:\nYou are Codex, a coding agent.", "Example:\nYou are Codex, a coding agent."}, + {"versionless mention", "Explain You are Codex, a coding agent.", "Explain You are Codex, a coding agent."}, + {"versionless missing period", "You are Codex, a coding agent", "You are Codex, a coding agent"}, + {"versionless longer sentence", "You are Codex, a coding agent helping with tests.", "You are Codex, a coding agent helping with tests."}, + {"versionless longer word", "You are Codex, a coding agentic assistant.", "You are Codex, a coding agentic assistant."}, + {"versionless period boundary", "You are Codex, a coding agent.example", "You are Codex, a coding agent.example"}, {"CLI comma", "You are GPT-5.6 running in the Codex CLI, a terminal-based coding assistant.", "You are an AI agent, a terminal-based coding assistant."}, {"Codex model suffix", "You are Codex, based on GPT-5.6-Codex. Rest.", "You are an AI agent. Rest."}, {"CLI GPT 5.6", "You are GPT-5.6 running in the Codex CLI. Rest.", "You are an AI agent. Rest."}, diff --git a/backend/internal/pkg/antigravity/request_transformer.go b/backend/internal/pkg/antigravity/request_transformer.go index 6a05b10754..17a698eff3 100644 --- a/backend/internal/pkg/antigravity/request_transformer.go +++ b/backend/internal/pkg/antigravity/request_transformer.go @@ -301,6 +301,7 @@ var systemIdentityOpeners = []*regexp.Regexp{ regexp.MustCompile(`(?i)^[ \t\r\n]*You are a Claude agent, built on Anthropic'?s Claude Agent SDK\.?`), regexp.MustCompile(`(?i)^[ \t\r\n]*You are Claude Code, Anthropic'?s official CLI for Claude\.?`), regexp.MustCompile(`(?i)^[ \t\r\n]*You are Codex,? (?:a coding agent |an agent )?based on GPT-[0-9]+(?:\.[0-9]+)*(?:-[a-z0-9]+)*\.?`), + regexp.MustCompile(`(?i)^[ \t\r\n]*You are Codex, a coding agent\.`), regexp.MustCompile(`(?i)^[ \t\r\n]*You are GPT-[0-9]+(?:\.[0-9]+)*(?:-[a-z0-9]+)* running in the Codex CLI\.?`), } diff --git a/backend/internal/service/antigravity_gateway_compat_test.go b/backend/internal/service/antigravity_gateway_compat_test.go index f830286d94..5c4da60d62 100644 --- a/backend/internal/service/antigravity_gateway_compat_test.go +++ b/backend/internal/service/antigravity_gateway_compat_test.go @@ -200,10 +200,62 @@ func TestAntigravityCompatToolSchemaItemsMatchSelectedType(t *testing.T) { } } +func TestConvertAntigravityCompatResponsesToAnthropic_VersionlessCodex(t *testing.T) { + const identity = "You are Codex, a coding agent." + const task = "\n Keep subsequent instructions and GPT-6 model ids." + for _, placement := range []string{"instructions", "system/string", "system/array", "developer/string", "developer/array"} { + for _, text := range []string{identity + task, "Example:\n" + identity, identity + "example", "You are Codex, a coding agent helping with tests."} { + t.Run(placement+"/"+text, func(t *testing.T) { + input := []map[string]any{{"role": "user", "content": identity}} + body := map[string]any{ + "model": "gemini-3.1-pro-high", + "tools": []map[string]any{{ + "type": "function", "name": "example", "description": identity, + "parameters": map[string]any{"type": "object", "properties": map[string]any{"query": map[string]string{"type": "string", "description": identity}}}, + }}, + } + if placement == "instructions" { + body["instructions"] = text + } else { + role, form, _ := strings.Cut(placement, "/") + var content any = text + if form == "array" { + content = []map[string]string{{"type": "input_text", "text": text}} + } + input = append([]map[string]any{{"role": role, "content": content}}, input...) + } + body["input"] = input + encoded, err := json.Marshal(body) + require.NoError(t, err) + var request apicompat.ResponsesRequest + require.NoError(t, json.Unmarshal(encoded, &request)) + got, err := convertAntigravityCompatResponsesToAnthropic(&request) + require.NoError(t, err) + want := text + if text == identity+task { + want = "You are an AI agent." + task + } + var system string + require.NoError(t, json.Unmarshal(got.System, &system)) + require.Equal(t, want, system) + require.Len(t, got.Messages, 1) + require.Equal(t, "user", got.Messages[0].Role) + var userText string + require.NoError(t, json.Unmarshal(got.Messages[0].Content, &userText)) + require.Equal(t, identity, userText) + require.Len(t, got.Tools, 1) + require.Equal(t, "example", got.Tools[0].Name) + require.Equal(t, identity, got.Tools[0].Description) + require.JSONEq(t, gjson.GetBytes(encoded, "tools.0.parameters").Raw, string(got.Tools[0].InputSchema)) + }) + } + } +} + func TestAntigravitySystemIdentityAcrossProtocols(t *testing.T) { gin.SetMode(gin.TestMode) const task = "\nKeep GPT-5.6, gpt-6 and Claude model ids unchanged." - for _, identity := range []string{"You are Codex, based on GPT-5.6.", "You are Codex, an agent based on GPT-6.", "You are GPT-6 running in the Codex CLI.", "You are Claude Code, Anthropic's official CLI for Claude."} { + for _, identity := range []string{"You are Codex, based on GPT-5.6.", "You are Codex, an agent based on GPT-6.", "You are Codex, a coding agent.", "You are GPT-6 running in the Codex CLI.", "You are Claude Code, Anthropic's official CLI for Claude."} { for _, model := range []string{"gemini-3.1-pro-high", "claude-sonnet-4-6"} { for _, protocol := range []string{"responses", "chat", "messages"} { for _, arraySystem := range []bool{false, true} { From fe72ddf1ae7e027958ca0724f48fbcf64e037987 Mon Sep 17 00:00:00 2001 From: bin-bash-dev <205939566+bin-bash-dev@users.noreply.github.com> Date: Wed, 25 Nov 2026 03:56:32 +0800 Subject: [PATCH 14/23] fix(moderation): allocate async moderation queue on demand MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 问题:NewContentModerationService 在构造时就执行 make(chan contentModerationTask, maxContentModerationQueueSize)。 maxContentModerationQueueSize=100000,单个任务 288 字节,因此每个实例一 构造就常驻约 28.8MB,与是否启用异步审核、是否有流量都无关。service 包测 试会创建数百个短生命周期实例,测试进程的提交内存随之涨到 GiB 级;生产上 任何额外构造的实例也要白白付出同样的代价。 根因:队列深度按允许的最大值预分配,而真正的丢弃判据 len(queue) >= cfg.QueueSize 只依赖运行期配置,并不需要预先占满容量。 修法: - 构造函数不再创建队列,只标记 asyncQueueLazy;首次入队时按 min(64, QueueSize) 创建,满且仍低于 QueueSize 时按 2 倍扩容(上限 QueueSize),迁移已排队任务;运行期调大 QueueSize 也能继续扩容。 - 丢弃判据仍是 len >= QueueSize,丢弃计数与告警日志保持不变。 - 未经构造函数创建的零值服务入队仍是 no-op(不计数、不告警)。 - 队列创建/扩容时关闭并替换 asyncWake 广播唤醒 worker,阻塞在旧 channel 上的 worker 会重新读取新队列,不空转、不漏取任务。 - GetStatus 与日志读取队列长度改为加锁读取,不会触发分配。 测试: - content_moderation_queue_contract_test.go 只使用既有接口:构造后不预 留队列;在独立子进程中测量 64 个空闲实例的堆增量(旧实现约 28,803,490 字节/实例,修复后约 451 字节/实例,阈值 64KiB); QueueSize=8 时收 8 丢 12、记录路径同样受限、4096 全收且调大到 8192 后继续接收;零值服务 no-op;真实 worker 并发消费 400 条记录不丢不重。 结构与内存用例在修复前失败,其余语义用例修复前后均通过。 - content_moderation_queue_lazy_test.go 用 synctest 覆盖初始容量与扩容 上限、多生产者/消费者恰好一次投递、扩容期间消费者持续读取、首次创建 与替换队列时的唤醒、取消与空闲超时。 --- .../internal/service/content_moderation.go | 236 +++++++-- .../content_moderation_queue_contract_test.go | 213 ++++++++ .../content_moderation_queue_lazy_test.go | 496 ++++++++++++++++++ 3 files changed, 894 insertions(+), 51 deletions(-) create mode 100644 backend/internal/service/content_moderation_queue_contract_test.go create mode 100644 backend/internal/service/content_moderation_queue_lazy_test.go diff --git a/backend/internal/service/content_moderation.go b/backend/internal/service/content_moderation.go index 95bbfdaf9c..d045a55cd7 100644 --- a/backend/internal/service/content_moderation.go +++ b/backend/internal/service/content_moderation.go @@ -521,7 +521,10 @@ type ContentModerationService struct { emailService *EmailService httpClient *http.Client moderationProxyCache atomic.Pointer[moderationProxyURLCacheEntry] + asyncQueueMu sync.RWMutex asyncQueue chan contentModerationTask + asyncWake chan struct{} + asyncQueueLazy bool workerCount int apiKeyCursor atomic.Uint64 asyncActive atomic.Int64 @@ -605,7 +608,8 @@ func NewContentModerationService( emailService: emailService, httpClient: servertiming.InstrumentClient(nil), workerCount: maxContentModerationWorkerCount, - asyncQueue: make(chan contentModerationTask, maxContentModerationQueueSize), + asyncQueueLazy: true, + asyncWake: make(chan struct{}), keyHealth: make(map[string]*contentModerationKeyHealth), } if settingRepo != nil && repo != nil { @@ -1064,7 +1068,7 @@ func (s *ContentModerationService) Check(ctx context.Context, input ContentModer "group_id", contentModerationLogGroupID(input.GroupID), "endpoint", input.Endpoint, "protocol", input.Protocol, - "queue_len", len(s.asyncQueue)) + "queue_len", len(s.asyncQueueOf())) s.enqueueAsync(input, cfg, content, hashText) return allow, nil } @@ -1187,17 +1191,133 @@ func (s *ContentModerationService) recordPreBlockSyncMetric(latencyMS int, actio } } -func (s *ContentModerationService) enqueueAsync(input ContentModerationCheckInput, cfg *ContentModerationConfig, content ContentModerationInput, hashText string) { - if s == nil || s.asyncQueue == nil { +// contentModerationInitialQueueCapacity is the starting depth of the worker +// queue. The queue grows on demand up to the configured QueueSize, so a service +// that never sees a burst does not reserve the whole configured depth. +const contentModerationInitialQueueCapacity = 64 + +// asyncQueueOf returns the current worker queue without allocating it. Callers +// that only inspect len/cap (status, logging) use this so reading the queue +// never forces the backing array into existence. +func (s *ContentModerationService) asyncQueueOf() chan contentModerationTask { + if s == nil { + return nil + } + s.asyncQueueMu.RLock() + queue := s.asyncQueue + s.asyncQueueMu.RUnlock() + return queue +} + +// queueDropThreshold reports how many pending tasks the configuration allows. +// This is the threshold the enqueue paths have always compared len() against. +func queueDropThreshold(cfg *ContentModerationConfig) int { + threshold := defaultContentModerationQueueSize + if cfg != nil && cfg.QueueSize > 0 { + threshold = cfg.QueueSize + } + if threshold > maxContentModerationQueueSize { + threshold = maxContentModerationQueueSize + } + if threshold < 1 { + threshold = 1 + } + return threshold +} + +// wakeWorkersLocked broadcasts to every waiting worker that the queue object +// changed (grown or replaced). Closing the channel wakes all current waiters; +// a fresh channel is installed for the next round. Callers must hold +// asyncQueueMu for writing. +func (s *ContentModerationService) wakeWorkersLocked() { + if s.asyncWake == nil { + s.asyncWake = make(chan struct{}) return } - queueSize := defaultContentModerationQueueSize - if cfg != nil && cfg.QueueSize > 0 { - queueSize = cfg.QueueSize + close(s.asyncWake) + s.asyncWake = make(chan struct{}) +} + +// growAsyncQueueLocked doubles the channel capacity, capped at the configured +// drop threshold, and moves the pending tasks across. Callers must hold +// asyncQueueMu for writing. +func (s *ContentModerationService) growAsyncQueueLocked(threshold int) { + current := s.asyncQueue + next := cap(current) * 2 + if next < contentModerationInitialQueueCapacity { + next = contentModerationInitialQueueCapacity } - if len(s.asyncQueue) >= queueSize { - slog.Warn("content_moderation.async_queue_full", "user_id", input.UserID, "endpoint", input.Endpoint, "queue_size", queueSize) - s.asyncDropped.Add(1) + if next > threshold { + next = threshold + } + if next <= cap(current) { + return + } + grown := make(chan contentModerationTask, next) + for { + select { + case task := <-current: + grown <- task + default: + s.asyncQueue = grown + s.wakeWorkersLocked() + return + } + } +} + +// queueDisabled reports whether this service can never accept asynchronous +// work. A zero-value ContentModerationService has no queue and no lazy flag, so +// enqueues are ignored exactly as they were before the queue became lazy: no +// warning, no drop counter. +func (s *ContentModerationService) queueDisabled() bool { + if s == nil { + return true + } + s.asyncQueueMu.RLock() + defer s.asyncQueueMu.RUnlock() + return s.asyncQueue == nil && !s.asyncQueueLazy +} + +// enqueueTask appends one task when the queue is below the configured threshold. +// A zero-value ContentModerationService keeps the historical behaviour of +// silently ignoring enqueues (its channel was never initialised); services built +// by NewContentModerationService allocate their channel on first use and grow it +// on demand. +func (s *ContentModerationService) enqueueTask(cfg *ContentModerationConfig, task contentModerationTask) (bool, int) { + if s == nil { + return false, 0 + } + threshold := queueDropThreshold(cfg) + s.asyncQueueMu.Lock() + defer s.asyncQueueMu.Unlock() + if s.asyncQueue == nil { + if !s.asyncQueueLazy { + return false, threshold + } + initial := contentModerationInitialQueueCapacity + if initial > threshold { + initial = threshold + } + s.asyncQueue = make(chan contentModerationTask, initial) + s.wakeWorkersLocked() + } + if len(s.asyncQueue) >= threshold { + return false, threshold + } + if len(s.asyncQueue) >= cap(s.asyncQueue) { + s.growAsyncQueueLocked(threshold) + } + select { + case s.asyncQueue <- task: + return true, threshold + default: + return false, threshold + } +} + +func (s *ContentModerationService) enqueueAsync(input ContentModerationCheckInput, cfg *ContentModerationConfig, content ContentModerationInput, hashText string) { + if s.queueDisabled() { return } task := contentModerationTask{ @@ -1206,33 +1326,20 @@ func (s *ContentModerationService) enqueueAsync(input ContentModerationCheckInpu inputHash: hashText, enqueuedAt: time.Now(), } - select { - case s.asyncQueue <- task: + accepted, queueSize := s.enqueueTask(cfg, task) + if accepted { s.asyncEnqueued.Add(1) - default: - slog.Warn("content_moderation.async_queue_full", "user_id", input.UserID, "endpoint", input.Endpoint) - s.asyncDropped.Add(1) + return } + slog.Warn("content_moderation.async_queue_full", "user_id", input.UserID, "endpoint", input.Endpoint, "queue_size", queueSize) + s.asyncDropped.Add(1) } func (s *ContentModerationService) enqueueRecord(input ContentModerationCheckInput, cfg *ContentModerationConfig, log *ContentModerationLog, inputHash string, recordHash bool, applySideEffects bool) { - if s == nil || s.asyncQueue == nil || log == nil { + if log == nil || s.queueDisabled() { return } - queueSize := defaultContentModerationQueueSize - if cfg != nil && cfg.QueueSize > 0 { - queueSize = cfg.QueueSize - } - if len(s.asyncQueue) >= queueSize { - slog.Warn("content_moderation.record_queue_full", - "user_id", input.UserID, - "endpoint", input.Endpoint, - "action", log.Action, - "queue_size", queueSize) - s.asyncDropped.Add(1) - return - } - task := contentModerationTask{ + accepted, queueSize := s.enqueueTask(cfg, contentModerationTask{ input: input, inputHash: inputHash, log: log, @@ -1240,17 +1347,17 @@ func (s *ContentModerationService) enqueueRecord(input ContentModerationCheckInp recordHash: recordHash, applySideEffects: applySideEffects, enqueuedAt: time.Now(), - } - select { - case s.asyncQueue <- task: + }) + if accepted { s.asyncEnqueued.Add(1) - default: - slog.Warn("content_moderation.record_queue_full", - "user_id", input.UserID, - "endpoint", input.Endpoint, - "action", log.Action) - s.asyncDropped.Add(1) + return } + slog.Warn("content_moderation.record_queue_full", + "user_id", input.UserID, + "endpoint", input.Endpoint, + "action", log.Action, + "queue_size", queueSize) + s.asyncDropped.Add(1) } func (s *ContentModerationService) worker(id int) { @@ -1308,21 +1415,48 @@ func (s *ContentModerationService) worker(id int) { func (s *ContentModerationService) dequeueAsyncTask(ctx context.Context, idleWait time.Duration) (contentModerationTask, bool) { var zero contentModerationTask - if s == nil || s.asyncQueue == nil { + if s == nil { return zero, false } if idleWait <= 0 { idleWait = time.Second } - timer := time.NewTimer(idleWait) - defer timer.Stop() - select { - case task, ok := <-s.asyncQueue: - return task, ok - case <-ctx.Done(): - return zero, false - case <-timer.C: - return zero, false + for { + timer := time.NewTimer(idleWait) + s.asyncQueueMu.RLock() + queue := s.asyncQueue + wake := s.asyncWake + s.asyncQueueMu.RUnlock() + + if queue == nil { + // Nothing was enqueued yet. Wait for the first enqueue instead of + // spinning; the timer keeps shutdown paths bounded. + select { + case <-wake: + timer.Stop() + continue + case <-ctx.Done(): + timer.Stop() + return zero, false + case <-timer.C: + return zero, false + } + } + + select { + case task, ok := <-queue: + timer.Stop() + return task, ok + case <-wake: + // The queue object was created, grown or replaced; re-read it. + timer.Stop() + continue + case <-ctx.Done(): + timer.Stop() + return zero, false + case <-timer.C: + return zero, false + } } } @@ -1427,8 +1561,8 @@ func (s *ContentModerationService) GetStatus(ctx context.Context) (*ContentModer preBlockAvgLatency = s.preBlockLatencyTotalMS.Load() / preBlockChecked } queueLength := 0 - if s.asyncQueue != nil { - queueLength = len(s.asyncQueue) + if queue := s.asyncQueueOf(); queue != nil { + queueLength = len(queue) } queueUsage := 0.0 if cfg.QueueSize > 0 { diff --git a/backend/internal/service/content_moderation_queue_contract_test.go b/backend/internal/service/content_moderation_queue_contract_test.go new file mode 100644 index 0000000000..cbd36e4234 --- /dev/null +++ b/backend/internal/service/content_moderation_queue_contract_test.go @@ -0,0 +1,213 @@ +package service + +import ( + "context" + "fmt" + "os" + "os/exec" + "runtime" + "strings" + "sync" + "testing" + "time" + "unsafe" +) + +// 本文件只使用构造函数、enqueueAsync/enqueueRecord、计数器与真实 worker 等既有接口, +// 用来钉住异步审核队列对外可见的契约:空闲实例不得预留整条队列,QueueSize 仍是 +// 丢弃阈值,零值服务入队仍是 no-op,真实 worker 消费不丢不重。 + +const contentModerationQueueChildProcessEnv = "SUB2API_CONTENT_MODERATION_QUEUE_CHILD" + +// TestContentModerationIdleServiceDoesNotReserveQueue 是确定性的结构断言: +// 构造后、首次入队前不得已分配任务队列。旧实现在构造时就创建 +// maxContentModerationQueueSize 深度的 channel。 +func TestContentModerationIdleServiceDoesNotReserveQueue(t *testing.T) { + svc := NewContentModerationService(nil, nil, nil, nil, nil, nil, nil, nil) + if reserved := cap(svc.asyncQueue); reserved != 0 { + t.Fatalf("new ContentModerationService reserved a %d-slot task queue (%d bytes) before any enqueue, want none", + reserved, reserved*int(unsafe.Sizeof(contentModerationTask{}))) + } +} + +// TestContentModerationIdleServiceMemoryIsBounded 测量空闲实例的常驻堆增量。 +// +// 旧实现每个实例构造时占用 sizeof(contentModerationTask) * maxContentModerationQueueSize +// (约 28.8 MB),与是否启用异步审核无关。HeapAlloc 是进程级计数,而本包其它测试会留下 +// 常驻的审核 worker,因此测量放在只运行本用例的子进程里完成,父进程只传播结果。 +func TestContentModerationIdleServiceMemoryIsBounded(t *testing.T) { + if os.Getenv(contentModerationQueueChildProcessEnv) != "1" { + runContentModerationQueueTestInChildProcess(t, "TestContentModerationIdleServiceMemoryIsBounded") + return + } + + const instances = 64 + // 旧实现约 28.8 MB/实例;64 KiB 给分配器噪声留足余量,同时仍能识别任何预分配。 + const maxIdleBytesPerInstance = 64 * 1024 + + var before, after runtime.MemStats + runtime.GC() + runtime.ReadMemStats(&before) + services := make([]*ContentModerationService, 0, instances) + for range instances { + services = append(services, NewContentModerationService(nil, nil, nil, nil, nil, nil, nil, nil)) + } + runtime.GC() + runtime.ReadMemStats(&after) + runtime.KeepAlive(services) + + perInstance := int64(0) + if after.HeapAlloc > before.HeapAlloc { + perInstance = int64(after.HeapAlloc-before.HeapAlloc) / instances + } + t.Logf("idle ContentModerationService retains %d heap bytes/instance over %d instances", perInstance, instances) + if perInstance > maxIdleBytesPerInstance { + t.Fatalf("idle ContentModerationService retains %d bytes/instance, want <= %d (a preallocated %d-slot queue is %d bytes)", + perInstance, maxIdleBytesPerInstance, maxContentModerationQueueSize, + maxContentModerationQueueSize*int(unsafe.Sizeof(contentModerationTask{}))) + } +} + +// runContentModerationQueueTestInChildProcess 在新的测试进程里只运行 name 指定的用例, +// 子进程失败或超时都会让父用例失败。 +func runContentModerationQueueTestInChildProcess(t *testing.T, name string) { + t.Helper() + executable, err := os.Executable() + if err != nil { + t.Fatalf("locate test binary: %v", err) + } + ctx, cancel := context.WithTimeout(context.Background(), 2*time.Minute) + defer cancel() + cmd := exec.CommandContext(ctx, executable, "-test.run=^"+name+"$", "-test.count=1", "-test.v") + cmd.Env = append(os.Environ(), contentModerationQueueChildProcessEnv+"=1") + output, runErr := cmd.CombinedOutput() + if runErr != nil { + t.Fatalf("isolated %s failed: %v\n%s", name, runErr, output) + } + if !strings.Contains(string(output), "--- PASS: "+name) { + t.Fatalf("isolated child did not run %s\n%s", name, output) + } + t.Logf("isolated child output:\n%s", output) +} + +// TestContentModerationQueueSizeStillBoundsPendingTasks 钉住丢弃语义:待处理任务数达到 +// QueueSize 即丢弃并计数;配置调大后可以继续接收;零值服务(未经构造函数)入队仍被忽略。 +func TestContentModerationQueueSizeStillBoundsPendingTasks(t *testing.T) { + cfg := defaultContentModerationConfig() + cfg.QueueSize = 8 + svc := NewContentModerationService(nil, nil, nil, nil, nil, nil, nil, nil) + for i := range 20 { + svc.enqueueAsync(ContentModerationCheckInput{}, cfg, ContentModerationInput{}, fmt.Sprintf("bounded-%d", i)) + } + if got := svc.asyncEnqueued.Load(); got != 8 { + t.Fatalf("asyncEnqueued = %d for QueueSize=8, want 8", got) + } + if got := svc.asyncDropped.Load(); got != 12 { + t.Fatalf("asyncDropped = %d for QueueSize=8, want 12", got) + } + if got := len(svc.asyncQueue); got != 8 { + t.Fatalf("pending tasks = %d, want 8", got) + } + svc.enqueueRecord(ContentModerationCheckInput{}, cfg, &ContentModerationLog{RequestID: "record-over-limit"}, "", false, false) + if got := svc.asyncDropped.Load(); got != 13 { + t.Fatalf("asyncDropped = %d after a record enqueue on a full queue, want 13", got) + } + + large := defaultContentModerationConfig() + large.QueueSize = 4096 + grown := NewContentModerationService(nil, nil, nil, nil, nil, nil, nil, nil) + for i := range 4096 { + grown.enqueueAsync(ContentModerationCheckInput{}, large, ContentModerationInput{}, fmt.Sprintf("large-%d", i)) + } + if got := grown.asyncEnqueued.Load(); got != 4096 { + t.Fatalf("asyncEnqueued = %d for QueueSize=4096, want 4096", got) + } + if got := grown.asyncDropped.Load(); got != 0 { + t.Fatalf("asyncDropped = %d below QueueSize=4096, want 0", got) + } + + // 运行期调大 QueueSize 后,已到达旧上限的队列必须能继续接收。 + raised := defaultContentModerationConfig() + raised.QueueSize = 8192 + for i := range 4096 { + grown.enqueueAsync(ContentModerationCheckInput{}, raised, ContentModerationInput{}, fmt.Sprintf("raised-%d", i)) + } + grown.enqueueAsync(ContentModerationCheckInput{}, raised, ContentModerationInput{}, "raised-over-limit") + if got := grown.asyncEnqueued.Load(); got != 8192 { + t.Fatalf("asyncEnqueued = %d after raising QueueSize to 8192, want 8192", got) + } + if got := grown.asyncDropped.Load(); got != 1 { + t.Fatalf("asyncDropped = %d after exceeding QueueSize=8192, want 1", got) + } + if got := len(grown.asyncQueue); got != 8192 { + t.Fatalf("pending tasks = %d, want 8192", got) + } + + zero := &ContentModerationService{} + zero.enqueueAsync(ContentModerationCheckInput{}, cfg, ContentModerationInput{}, "zero") + zero.enqueueRecord(ContentModerationCheckInput{}, cfg, &ContentModerationLog{RequestID: "zero"}, "", false, false) + if zero.asyncEnqueued.Load() != 0 || zero.asyncDropped.Load() != 0 || zero.asyncQueue != nil { + t.Fatalf("zero-value service must ignore enqueues: enqueued=%d dropped=%d queue=%v", + zero.asyncEnqueued.Load(), zero.asyncDropped.Load(), zero.asyncQueue != nil) + } +} + +// TestContentModerationWorkerConsumesConcurrentQueue 走构造函数启动的真实 worker: +// 4 个生产者并发写入 400 条记录任务,每条必须恰好落库一次,队列最终清空。 +func TestContentModerationWorkerConsumesConcurrentQueue(t *testing.T) { + cfg := defaultContentModerationConfig() + cfg.Enabled = true + cfg.Mode = ContentModerationModePreBlock + cfg.WorkerCount = 4 + cfg.QueueSize = 4096 + svc, repo := newContentModerationModelFilterTestService(t, cfg) + + const producers = 4 + const perProducer = 100 + const total = producers * perProducer + var group sync.WaitGroup + for p := range producers { + group.Add(1) + go func(producer int) { + defer group.Done() + for i := range perProducer { + svc.enqueueRecord( + ContentModerationCheckInput{}, + cfg, + &ContentModerationLog{ + RequestID: fmt.Sprintf("worker-%d-%d", producer, i), + Mode: ContentModerationModePreBlock, + Action: ContentModerationActionAllow, + }, + "", + false, + false, + ) + } + }(p) + } + group.Wait() + + deadline := time.Now().Add(10 * time.Second) + for svc.asyncProcessed.Load() < total && time.Now().Before(deadline) { + time.Sleep(10 * time.Millisecond) + } + + if got := svc.asyncEnqueued.Load(); got != total { + t.Fatalf("asyncEnqueued = %d, want %d", got, total) + } + if got := svc.asyncProcessed.Load(); got != total { + t.Fatalf("asyncProcessed = %d, want %d", got, total) + } + logs := repo.snapshotLogs() + if len(logs) != total { + t.Fatalf("persisted logs = %d, want %d", len(logs), total) + } + seen := make(map[string]struct{}, len(logs)) + for _, log := range logs { + if _, exists := seen[log.RequestID]; exists { + t.Fatalf("duplicate persisted request id %q", log.RequestID) + } + seen[log.RequestID] = struct{}{} + } +} diff --git a/backend/internal/service/content_moderation_queue_lazy_test.go b/backend/internal/service/content_moderation_queue_lazy_test.go new file mode 100644 index 0000000000..c0598ce280 --- /dev/null +++ b/backend/internal/service/content_moderation_queue_lazy_test.go @@ -0,0 +1,496 @@ +package service + +import ( + "context" + "fmt" + "sync" + "sync/atomic" + "testing" + "testing/synctest" + "time" +) + +// TestContentModerationQueueStartsSmallAndGrowsToQueueSize pins the lazy +// allocation shape: the first enqueue creates min(initial, QueueSize) slots, +// growth doubles the capacity, and capacity never exceeds the configured +// QueueSize drop threshold. +func TestContentModerationQueueStartsSmallAndGrowsToQueueSize(t *testing.T) { + small := defaultContentModerationConfig() + small.QueueSize = 8 + svc := NewContentModerationService(nil, nil, nil, nil, nil, nil, nil, nil) + if svc.asyncQueueOf() != nil { + t.Fatal("new service must start without an allocated queue") + } + svc.enqueueAsync(ContentModerationCheckInput{}, small, ContentModerationInput{}, "small") + if got := cap(svc.asyncQueueOf()); got != 8 { + t.Fatalf("first queue capacity for QueueSize=8 = %d, want 8", got) + } + + cfg := defaultContentModerationConfig() + cfg.QueueSize = 100 + grown := NewContentModerationService(nil, nil, nil, nil, nil, nil, nil, nil) + for i := 0; i < contentModerationInitialQueueCapacity; i++ { + grown.enqueueAsync(ContentModerationCheckInput{}, cfg, ContentModerationInput{}, fmt.Sprintf("fill-%d", i)) + } + if got := cap(grown.asyncQueueOf()); got != contentModerationInitialQueueCapacity { + t.Fatalf("queue capacity before growth = %d, want %d", got, contentModerationInitialQueueCapacity) + } + grown.enqueueAsync(ContentModerationCheckInput{}, cfg, ContentModerationInput{}, "grow") + if got := cap(grown.asyncQueueOf()); got != 100 { + t.Fatalf("queue capacity after growth = %d, want doubling capped at QueueSize=100", got) + } + if got := len(grown.asyncQueueOf()); got != contentModerationInitialQueueCapacity+1 { + t.Fatalf("pending tasks after growth = %d, want %d (growth must keep queued tasks)", got, contentModerationInitialQueueCapacity+1) + } +} + +// newConcurrentQueueTestService returns a constructor-built service with no +// setting repository, so it has the lazy queue but starts no worker goroutines. +// The queue tests drive dequeueAsyncTask directly, which is the exact call the +// worker loop makes. A real worker() cannot be used inside synctest because it +// has no stop handle; TestContentModerationWorkerConsumesConcurrentQueue covers +// the real worker loop separately. +func newConcurrentQueueTestService() *ContentModerationService { + return NewContentModerationService(nil, nil, nil, nil, nil, nil, nil, nil) +} + +// TestContentModerationQueueConcurrentProducersAndConsumersExactlyOnce forces +// the lazy queue through several growth steps while four consumers are already +// parked, then releases them. It proves the properties the old single-producer +// test could not see: every unique task is consumed exactly once, growth does +// not drop or duplicate a task, no task is stranded after the consumers drain, +// and the queue actually grew beyond its initial 64-slot allocation. +func TestContentModerationQueueConcurrentProducersAndConsumersExactlyOnce(t *testing.T) { + synctest.Test(t, func(t *testing.T) { + svc := newConcurrentQueueTestService() + cfg := defaultContentModerationConfig() + cfg.QueueSize = 4096 + + const producerCount = 8 + const perProducer = 200 + const consumerCount = 4 + const total = producerCount * perProducer + + ctx, cancel := context.WithCancel(context.Background()) + defer cancel() + + var mu sync.Mutex + received := make(map[string]int, total) + consumersDone := make(chan struct{}, consumerCount) + release := make(chan struct{}) + + for i := 0; i < consumerCount; i++ { + go func() { + defer func() { consumersDone <- struct{}{} }() + <-release + for { + task, ok := svc.dequeueAsyncTask(ctx, time.Minute) + if !ok { + return + } + mu.Lock() + received[task.inputHash]++ + mu.Unlock() + } + }() + } + synctest.Wait() // every consumer is durably parked on release + + var producers sync.WaitGroup + for p := 0; p < producerCount; p++ { + producers.Add(1) + go func(producer int) { + defer producers.Done() + for i := 0; i < perProducer; i++ { + svc.enqueueAsync(ContentModerationCheckInput{}, cfg, ContentModerationInput{}, fmt.Sprintf("p%d-%d", producer, i)) + } + }(p) + } + producers.Wait() + + if got := svc.asyncEnqueued.Load(); got != total { + t.Fatalf("asyncEnqueued = %d, want %d", got, total) + } + if got := svc.asyncDropped.Load(); got != 0 { + t.Fatalf("asyncDropped = %d, want 0 below the configured threshold", got) + } + if got := cap(svc.asyncQueueOf()); got <= contentModerationInitialQueueCapacity { + t.Fatalf("queue capacity = %d, want growth beyond the initial %d", got, contentModerationInitialQueueCapacity) + } + if got := len(svc.asyncQueueOf()); got != total { + t.Fatalf("queued before consumers released = %d, want %d", got, total) + } + + close(release) + synctest.Wait() + + mu.Lock() + unique := 0 + duplicates := 0 + emptyID := false + for id, count := range received { + if id == "" { + emptyID = true + } + unique++ + if count > 1 { + duplicates += count - 1 + } + } + mu.Unlock() + if emptyID { + t.Fatal("consumer received a task without an input hash") + } + if unique != total { + t.Fatalf("unique task ids consumed = %d, want %d", unique, total) + } + if duplicates != 0 { + t.Fatalf("duplicate deliveries = %d, want 0", duplicates) + } + if got := len(svc.asyncQueueOf()); got != 0 { + t.Fatalf("queue length after consumers drained = %d, want 0 (stranded tasks)", got) + } + + cancel() + for i := 0; i < consumerCount; i++ { + <-consumersDone + } + }) +} + +// TestContentModerationQueueConsumerOverlapsGrowth proves the missing overlap +// property directly, using the same dequeueAsyncTask call the real worker loop +// makes: +// +// 1. A seed phase consumes 20 tasks, proving the consumer entered its loop and +// made progress before any growth. +// 2. The consumer then blocks INSIDE dequeueAsyncTask on the empty 64-slot +// queue. A producer burst of 500 tasks grows the channel 64->128->256->512 +// while that read is in flight; growAsyncQueueLocked replaces the channel +// and wakes the parked read. Capacity growth, the in-flight read, and the +// consumer's +1 progress are all asserted explicitly. +// 3. A sustained phase keeps both loops progressing in the same window: each +// round writes 50 tasks, releases 50 permits, and waits for only 25 reads, +// so permits stay outstanding while the next round is being written. Reads +// taken while the producer has not finished writing are counted, which +// proves reads and writes interleave instead of running in two disjoint +// phases. +// +// A final drain proves every task is consumed exactly once with no stranded +// queue entries. synctest makes every phase deterministic and instant. +func TestContentModerationQueueConsumerOverlapsGrowth(t *testing.T) { + synctest.Test(t, func(t *testing.T) { + svc := newConcurrentQueueTestService() + cfg := defaultContentModerationConfig() + cfg.QueueSize = 4096 + + const seedTasks = 20 + const growthBurst = 500 + const overlapRounds = 6 + const overlapWritePerHalf = 25 + const overlapPermitsPerHalf = 10 + const overlapMinReadsPerHalf = 5 + const overlapTasks = overlapRounds * 2 * overlapWritePerHalf + const total = seedTasks + growthBurst + overlapTasks + + ctx, cancel := context.WithCancel(context.Background()) + defer cancel() + + permits := make(chan struct{}, total+1) + consumedSignal := make(chan struct{}, total+1) + consumerDone := make(chan struct{}) + producerDone := make(chan struct{}) + var producerActive atomic.Bool + var phaseWritten atomic.Int64 + var consumerInDequeue atomic.Int64 + var consumed atomic.Int64 + var overlapReads atomic.Int64 + var midPhaseReads atomic.Int64 + var mu sync.Mutex + received := make(map[string]int, total) + + go func() { + defer close(consumerDone) + for { + select { + case <-ctx.Done(): + return + case _, ok := <-permits: + if !ok { + return + } + } + consumerInDequeue.Add(1) + task, ok := svc.dequeueAsyncTask(ctx, time.Minute) + consumerInDequeue.Add(-1) + if !ok { + return + } + mu.Lock() + received[task.inputHash]++ + mu.Unlock() + if producerActive.Load() { + overlapReads.Add(1) + if phaseWritten.Load() < overlapTasks { + midPhaseReads.Add(1) + } + } + consumed.Add(1) + consumedSignal <- struct{}{} + } + }() + + // Phase 1: progress before growth. + for i := 0; i < seedTasks; i++ { + svc.enqueueAsync(ContentModerationCheckInput{}, cfg, ContentModerationInput{}, fmt.Sprintf("seed-%d", i)) + } + for i := 0; i < seedTasks; i++ { + permits <- struct{}{} + } + for i := 0; i < seedTasks; i++ { + <-consumedSignal + } + if got := consumed.Load(); got != seedTasks { + t.Fatalf("consumer progress before growth = %d, want %d", got, seedTasks) + } + if got := len(svc.asyncQueueOf()); got != 0 { + t.Fatalf("queue length after seed drain = %d, want 0", got) + } + capBefore := cap(svc.asyncQueueOf()) + if capBefore != contentModerationInitialQueueCapacity { + t.Fatalf("initial queue capacity = %d, want %d", capBefore, contentModerationInitialQueueCapacity) + } + consumedBeforeGrowth := consumed.Load() + + // Phase 2: one read is in flight while the producer burst grows the queue. + permits <- struct{}{} + synctest.Wait() // consumer is durably blocked inside dequeueAsyncTask + if got := consumerInDequeue.Load(); got != 1 { + t.Fatalf("consumer in-flight dequeue count = %d before growth burst, want 1", got) + } + for i := 0; i < growthBurst; i++ { + svc.enqueueAsync(ContentModerationCheckInput{}, cfg, ContentModerationInput{}, fmt.Sprintf("grow-%d", i)) + } + synctest.Wait() + capAfterGrowth := cap(svc.asyncQueueOf()) + if capAfterGrowth <= contentModerationInitialQueueCapacity { + t.Fatalf("queue capacity after growth burst = %d, want more than initial %d", capAfterGrowth, contentModerationInitialQueueCapacity) + } + if capAfterGrowth < 512 { + t.Fatalf("queue capacity after %d growth tasks = %d, want at least 512", growthBurst, capAfterGrowth) + } + if got := consumed.Load(); got != consumedBeforeGrowth+1 { + t.Fatalf("consumer progress across queue growth = %d, want %d", got, consumedBeforeGrowth+1) + } + if got := svc.asyncDropped.Load(); got != 0 { + t.Fatalf("asyncDropped during growth = %d, want 0", got) + } + + // Phase 3: sustained interleaving. Every half-round writes 25 tasks and + // then releases 10 permits, waiting for 5 reads before writing the next + // 25. The producer therefore yields mid-round with reads still + // outstanding, so reads land between writes instead of after the whole + // burst. The queue is above 512 in round 0, proving a second observed + // growth while the consumer loops. + producerActive.Store(true) + go func() { + defer close(producerDone) + for round := 0; round < overlapRounds; round++ { + for half := 0; half < 2; half++ { + target := consumed.Load() + overlapMinReadsPerHalf + for i := 0; i < overlapWritePerHalf; i++ { + svc.enqueueAsync(ContentModerationCheckInput{}, cfg, ContentModerationInput{}, + fmt.Sprintf("overlap-%d-%d-%d", round, half, i)) + phaseWritten.Add(1) + } + for i := 0; i < overlapPermitsPerHalf; i++ { + permits <- struct{}{} + } + for consumed.Load() < target { + <-consumedSignal + } + } + } + producerActive.Store(false) + }() + + <-producerDone + capAfterOverlap := cap(svc.asyncQueueOf()) + if capAfterOverlap < 1024 { + t.Fatalf("queue capacity after overlap phase = %d, want at least 1024", capAfterOverlap) + } + if got := overlapReads.Load(); got < int64(overlapRounds*2*overlapMinReadsPerHalf) { + t.Fatalf("consumer reads while producer phase was active = %d, want at least %d", got, overlapRounds*2*overlapMinReadsPerHalf) + } + if got := midPhaseReads.Load(); got < int64(overlapRounds*2*overlapMinReadsPerHalf) { + t.Fatalf("consumer reads before the producer finished writing = %d, want at least %d", got, overlapRounds*2*overlapMinReadsPerHalf) + } + if got := consumed.Load(); got <= consumedBeforeGrowth { + t.Fatalf("consumer progress across growth = %d, want more than %d", got, consumedBeforeGrowth) + } + if got := svc.asyncDropped.Load(); got != 0 { + t.Fatalf("asyncDropped during overlap = %d, want 0", got) + } + + // Drain the remaining backlog; every task is already queued, so the + // consumer never waits on an empty queue during this pass. + remaining := total - int(consumed.Load()) + for i := 0; i < remaining; i++ { + permits <- struct{}{} + } + for consumed.Load() < total { + <-consumedSignal + } + close(permits) + <-consumerDone + + if got := svc.asyncEnqueued.Load(); got != total { + t.Fatalf("asyncEnqueued = %d, want %d", got, total) + } + if got := svc.asyncDropped.Load(); got != 0 { + t.Fatalf("asyncDropped = %d, want 0 below the configured threshold", got) + } + if got := len(svc.asyncQueueOf()); got != 0 { + t.Fatalf("queue length after all consumers stopped = %d, want 0 (stranded tasks)", got) + } + if got := consumed.Load(); got != total { + t.Fatalf("consumer progress = %d, want %d", got, total) + } + + mu.Lock() + unique := 0 + duplicates := 0 + emptyID := false + for id, count := range received { + if id == "" { + emptyID = true + } + unique++ + if count > 1 { + duplicates += count - 1 + } + } + mu.Unlock() + if emptyID { + t.Fatal("consumer received a task without an input hash") + } + if unique != total { + t.Fatalf("unique task ids consumed = %d, want %d", unique, total) + } + if duplicates != 0 { + t.Fatalf("duplicate deliveries = %d, want 0", duplicates) + } + }) +} + +// TestContentModerationDequeueWakesOnFirstLazyQueue pins the first-enqueue wake: +// a consumer parked while the queue is still nil must be released by the +// enqueue that lazily creates the channel, not by its idle timer. +func TestContentModerationDequeueWakesOnFirstLazyQueue(t *testing.T) { + synctest.Test(t, func(t *testing.T) { + svc := newConcurrentQueueTestService() + if svc.asyncQueueOf() != nil { + t.Fatal("new service must start without an allocated queue") + } + ctx, cancel := context.WithCancel(context.Background()) + defer cancel() + + result := make(chan contentModerationTask, 1) + go func() { + task, ok := svc.dequeueAsyncTask(ctx, time.Hour) + if ok { + result <- task + } + close(result) + }() + synctest.Wait() // consumer is durably parked on the nil queue + + cfg := defaultContentModerationConfig() + cfg.QueueSize = 8 + svc.enqueueAsync(ContentModerationCheckInput{}, cfg, ContentModerationInput{}, "first") + synctest.Wait() + + task, ok := <-result + if !ok { + t.Fatal("consumer did not receive the first task") + } + if task.inputHash != "first" { + t.Fatalf("consumer received %q, want the first task", task.inputHash) + } + }) +} + +// TestContentModerationDequeueWakesWhenQueueReplaced pins the old-waiting-queue +// to new-queue hand-off. growAsyncQueueLocked swaps the channel and calls +// wakeWorkersLocked; a consumer already blocked on the old channel must re-read +// the new channel instead of waiting for its one-second idle timer. The swap is +// performed directly under asyncQueueMu because a real grow can only happen +// while the old queue is full, which would let the consumer receive from the old +// channel instead of exercising the blocked hand-off. +func TestContentModerationDequeueWakesWhenQueueReplaced(t *testing.T) { + synctest.Test(t, func(t *testing.T) { + svc := newConcurrentQueueTestService() + cfg := defaultContentModerationConfig() + cfg.QueueSize = 8 + svc.enqueueAsync(ContentModerationCheckInput{}, cfg, ContentModerationInput{}, "seed") + seed, ok := svc.dequeueAsyncTask(context.Background(), time.Second) + if !ok || seed.inputHash != "seed" { + t.Fatalf("seed dequeue = %q, %v", seed.inputHash, ok) + } + if got := len(svc.asyncQueueOf()); got != 0 { + t.Fatalf("queue length before replacement = %d, want 0", got) + } + + ctx, cancel := context.WithCancel(context.Background()) + defer cancel() + result := make(chan contentModerationTask, 1) + go func() { + task, ok := svc.dequeueAsyncTask(ctx, time.Hour) + if ok { + result <- task + } + close(result) + }() + synctest.Wait() // consumer is durably parked on the old empty channel + + svc.asyncQueueMu.Lock() + grown := make(chan contentModerationTask, 128) + grown <- contentModerationTask{inputHash: "replacement"} + svc.asyncQueue = grown + svc.wakeWorkersLocked() + svc.asyncQueueMu.Unlock() + + synctest.Wait() + task, ok := <-result + if !ok { + t.Fatal("consumer did not wake after the queue was replaced") + } + if task.inputHash != "replacement" { + t.Fatalf("consumer received %q, want the replacement task", task.inputHash) + } + }) +} + +// TestContentModerationDequeueHonorsCancellationAndIdleTimeout covers both exit +// paths of dequeueAsyncTask: a cancelled context returns immediately and an +// empty idle queue returns false when the idle timer fires. It must not spin or +// return a zero-value task as if it were real work. +func TestContentModerationDequeueHonorsCancellationAndIdleTimeout(t *testing.T) { + synctest.Test(t, func(t *testing.T) { + svc := newConcurrentQueueTestService() + + cancelled, cancel := context.WithCancel(context.Background()) + cancel() + if _, ok := svc.dequeueAsyncTask(cancelled, time.Second); ok { + t.Fatal("cancelled context must not dequeue a task") + } + + start := time.Now() + if _, ok := svc.dequeueAsyncTask(context.Background(), 10*time.Second); ok { + t.Fatal("idle queue must not dequeue a task") + } + if elapsed := time.Since(start); elapsed != 10*time.Second { + t.Fatalf("idle wait = %s, want 10s", elapsed) + } + }) +} From 1f5ca63440be22303352787c45e08fedf7982f98 Mon Sep 17 00:00:00 2001 From: bin-bash-dev <205939566+bin-bash-dev@users.noreply.github.com> Date: Wed, 25 Nov 2026 03:49:18 +0800 Subject: [PATCH 15/23] fix(openai): account SSE keepalive bytes across failover attempts Problem: on /v1/responses passthrough accounts with gateway.stream_keepalive_interval enabled, a failover-eligible upstream error (e.g. an overloaded `event: error` before any visible output) is only failed over once. If the first attempt has already written a keepalive comment, the next attempt that fails the same way is treated as if semantic output had reached the client: the error is delivered as response.failed and the remaining schedulable accounts are never tried. Root cause: handleStreamingResponsePassthrough starts a new SSE keepalive for every attempt, and startOpenAISSEKeepalive replaces the instance stored on the gin.Context. Keepalive bytes were tracked per instance, so OpenAICompactKeepaliveAdjustedWrittenSize subtracted only the current instance's bytes from c.Writer.Size(); comments written by an earlier attempt stayed in Size() and were counted as real output. openAIStreamClientOutputStarted therefore reported output as started and the passthrough stream stopped proposing failover. StopOpenAICompactSSEKeepaliveCommitted had the same per-instance blind spot and reported "not committed" when only an earlier instance had committed the 200 response. Fix: keep the keepalive byte count in a request-scoped atomic counter stored on the gin.Context and shared by every keepalive instance of the request (retries and nested starts). AdjustedWrittenSize subtracts the cumulative count, and the committed check also reports true once any keepalive of the request has written a comment. Single-keepalive behaviour is unchanged. Tests: a handler-level regression test drives the real Responses handler with three passthrough accounts (the first attempt emits a real keepalive and then fails over, the second fails immediately, the third succeeds); on the previous code only accounts [1 2] are called and the client receives response.failed. Service-level tests cover cumulative accounting across restarts, the committed check after a previous attempt, restarts without beats, and nested keepalives; they drive beats manually instead of relying on timer scheduling. --- ...ses_passthrough_keepalive_failover_test.go | 165 ++++++++++++++++++ .../service/openai_compact_sse_keepalive.go | 62 +++++-- .../openai_compact_sse_keepalive_test.go | 86 +++++++++ 3 files changed, 303 insertions(+), 10 deletions(-) create mode 100644 backend/internal/handler/openai_responses_passthrough_keepalive_failover_test.go diff --git a/backend/internal/handler/openai_responses_passthrough_keepalive_failover_test.go b/backend/internal/handler/openai_responses_passthrough_keepalive_failover_test.go new file mode 100644 index 0000000000..9880898705 --- /dev/null +++ b/backend/internal/handler/openai_responses_passthrough_keepalive_failover_test.go @@ -0,0 +1,165 @@ +//go:build unit + +package handler + +// /v1/responses 透传账号的下游心跳换号回归。 +// +// 透传流式路径(handleStreamingResponsePassthrough)在每次尝试进入流式循环时 +// 都会新建一个 SSE 心跳器。第一次尝试真实写出心跳后遇到可换号的 event: error, +// 第二个账号立即以同样的错误失败,第三个账号成功:前一次尝试写出的心跳字节 +// 不能被当成语义输出,否则第二次尝试会放弃换号,把错误直接写给客户端。 + +import ( + "bytes" + "io" + "net/http" + "net/http/httptest" + "strings" + "sync" + "testing" + "time" + + "github.com/Wei-Shaw/sub2api/internal/config" + middleware2 "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" +) + +const openAIPassthroughKeepaliveSuccessSSE = "event: response.created\n" + + `data: {"type":"response.created","response":{"id":"resp_passthrough_ok","status":"in_progress","output":[]}}` + "\n\n" + + "event: response.completed\n" + + `data: {"type":"response.completed","response":{"id":"resp_passthrough_ok","object":"response","status":"completed","output":[{"type":"message","role":"assistant","content":[{"type":"output_text","text":"ok"}]}],"usage":{"input_tokens":1,"output_tokens":1,"total_tokens":2}}}` + "\n\n" + +const openAIPassthroughKeepaliveOverloadedSSE = "event: error\n" + + `data: {"type":"error","error":{"type":"overloaded_error","message":"Overloaded","status":529}}` + "\n\n" + +type openAIPassthroughKeepaliveUpstream struct { + service.HTTPUpstream + mu sync.Mutex + calls []int64 + responses []*http.Response +} + +func (u *openAIPassthroughKeepaliveUpstream) Do(_ *http.Request, _ string, accountID int64, _ int) (*http.Response, error) { + u.mu.Lock() + defer u.mu.Unlock() + u.calls = append(u.calls, accountID) + if len(u.responses) == 0 { + return nil, io.ErrUnexpectedEOF + } + resp := u.responses[0] + u.responses = u.responses[1:] + return resp, nil +} + +func (u *openAIPassthroughKeepaliveUpstream) callIDs() []int64 { + u.mu.Lock() + defer u.mu.Unlock() + return append([]int64(nil), u.calls...) +} + +// openAIPassthroughKeepaliveWriter 在第一拍心跳写出时通知测试,测试据此 +// 推进上游,不依赖 sleep 时序。 +type openAIPassthroughKeepaliveWriter struct { + gin.ResponseWriter + once sync.Once + notify chan struct{} +} + +func (w *openAIPassthroughKeepaliveWriter) Write(p []byte) (int, error) { + n, err := w.ResponseWriter.Write(p) + if bytes.Contains(p, []byte(": keepalive\n\n")) { + w.once.Do(func() { close(w.notify) }) + } + return n, err +} + +func newOpenAIPassthroughKeepaliveHandler(t *testing.T, upstream service.HTTPUpstream) *OpenAIGatewayHandler { + t.Helper() + newAccount := func(id int64, priority int) service.Account { + return service.Account{ + ID: id, Name: "passthrough-keepalive", Platform: service.PlatformOpenAI, + Type: service.AccountTypeOAuth, Status: service.StatusActive, Schedulable: true, + Concurrency: 1, Priority: priority, + Credentials: map[string]any{"access_token": "test-token"}, + Extra: map[string]any{"openai_passthrough": true}, + } + } + accounts := []service.Account{newAccount(1, 0), newAccount(2, 1), newAccount(3, 2)} + cfg := &config.Config{RunMode: config.RunModeSimple} + cfg.Gateway.StreamKeepaliveInterval = 1 + gatewayService := service.NewOpenAIGatewayService( + openAIImagesFailoverAccountRepo{accounts: accounts}, nil, nil, nil, nil, nil, nil, cfg, + nil, nil, nil, nil, nil, upstream, nil, nil, nil, nil, nil, nil, nil, nil, + ) + billing := service.NewBillingCacheService(nil, nil, nil, nil, nil, nil, cfg, nil) + t.Cleanup(billing.Stop) + h := NewOpenAIGatewayHandler( + gatewayService, + service.NewConcurrencyService(nil), + billing, + service.NewAPIKeyService(nil, nil, nil, nil, nil, nil, cfg), + nil, nil, nil, nil, cfg, + ) + h.maxAccountSwitches = 2 + return h +} + +func newOpenAIPassthroughKeepaliveContext(t *testing.T) (*gin.Context, *httptest.ResponseRecorder, *openAIPassthroughKeepaliveWriter) { + t.Helper() + gin.SetMode(gin.TestMode) + rec := httptest.NewRecorder() + c, _ := gin.CreateTestContext(rec) + body := []byte(`{"model":"gpt-5.1","stream":true,"input":"hello"}`) + c.Request = httptest.NewRequest(http.MethodPost, "/openai/v1/responses", bytes.NewReader(body)) + c.Request.Header.Set("Content-Type", "application/json") + groupID := int64(3135) + c.Set(string(middleware2.ContextKeyAPIKey), &service.APIKey{ + ID: 99, GroupID: &groupID, + Group: &service.Group{ID: groupID, Platform: service.PlatformOpenAI}, + User: &service.User{ID: 100}, + }) + c.Set(string(middleware2.ContextKeyUser), middleware2.AuthSubject{UserID: 100}) + writer := &openAIPassthroughKeepaliveWriter{ResponseWriter: c.Writer, notify: make(chan struct{})} + c.Writer = writer + return c, rec, writer +} + +func TestOpenAIGatewayHandlerResponsesPassthroughKeepaliveFailoverAcrossAttempts(t *testing.T) { + firstBody, firstWriter := io.Pipe() + sseHeader := func() http.Header { return http.Header{"Content-Type": []string{"text/event-stream"}} } + upstream := &openAIPassthroughKeepaliveUpstream{responses: []*http.Response{ + {StatusCode: http.StatusOK, Header: sseHeader(), Body: firstBody}, + {StatusCode: http.StatusOK, Header: sseHeader(), Body: io.NopCloser(strings.NewReader(openAIPassthroughKeepaliveOverloadedSSE))}, + {StatusCode: http.StatusOK, Header: sseHeader(), Body: io.NopCloser(strings.NewReader(openAIPassthroughKeepaliveSuccessSSE))}, + }} + h := newOpenAIPassthroughKeepaliveHandler(t, upstream) + c, rec, writer := newOpenAIPassthroughKeepaliveContext(t) + + done := make(chan struct{}) + go func() { h.Responses(c); close(done) }() + select { + case <-writer.notify: + case <-done: + t.Fatalf("handler 在第一拍心跳前返回: calls=%v body=%q", upstream.callIDs(), rec.Body.String()) + case <-time.After(15 * time.Second): + t.Fatal("等待透传流第一拍心跳超时") + } + _, err := io.WriteString(firstWriter, openAIPassthroughKeepaliveOverloadedSSE) + require.NoError(t, err) + require.NoError(t, firstWriter.Close()) + select { + case <-done: + case <-time.After(15 * time.Second): + t.Fatal("handler 未在后续尝试完成后返回") + } + + body := rec.Body.String() + require.Equal(t, []int64{1, 2, 3}, upstream.callIDs(), "前一次尝试的心跳字节不得阻止第二次尝试换号: body=%q", body) + require.Equal(t, http.StatusOK, rec.Code) + require.Contains(t, body, ": keepalive\n\n", "第一次尝试必须真实写出心跳") + require.Equal(t, 1, strings.Count(body, "event: response.completed"), "成功流只允许一个 completed") + require.NotContains(t, body, "response.failed", "可换号的首输出前错误不得写给客户端") + require.NotContains(t, body, "Overloaded", "可换号的首输出前错误不得写给客户端") +} diff --git a/backend/internal/service/openai_compact_sse_keepalive.go b/backend/internal/service/openai_compact_sse_keepalive.go index c0aba9108b..8e36be89d7 100644 --- a/backend/internal/service/openai_compact_sse_keepalive.go +++ b/backend/internal/service/openai_compact_sse_keepalive.go @@ -6,6 +6,7 @@ import ( "net" "net/http" "sync" + "sync/atomic" "time" "github.com/gin-gonic/gin" @@ -14,6 +15,31 @@ import ( // openAICompactSSEKeepaliveKey 存放 body-signal compact 请求的下游 SSE 心跳器。 const openAICompactSSEKeepaliveKey = "openai_compact_sse_keepalive" +// openAICompactSSEKeepaliveAccountingKey 存放同一请求内所有心跳器共享的累计 +// 注释字节数。/v1/responses 透传路径每次尝试进入流式循环都会新建心跳器并覆盖 +// openAICompactSSEKeepaliveKey,而旧实例写出的注释仍留在底层 writer 的 Size +// 里;若只扣除当前实例的字节,failover 后的下一次尝试会把上一次尝试的心跳 +// 误判为语义输出,从而放弃换号。 +const openAICompactSSEKeepaliveAccountingKey = "openai_compact_sse_keepalive_accounting" + +// openAICompactSSEKeepaliveAccounting 是请求级心跳字节计数,跨心跳器实例共享。 +type openAICompactSSEKeepaliveAccounting struct { + bytes atomic.Int64 +} + +func (a *openAICompactSSEKeepaliveAccounting) add(n int) { + if a != nil && n > 0 { + a.bytes.Add(int64(n)) + } +} + +func (a *openAICompactSSEKeepaliveAccounting) load() int { + if a == nil { + return 0 + } + return int(a.bytes.Load()) +} + // openAICompactSSEKeepalive 在 compact 上游 unary 等待期间向下游写 SSE 注释行 // 心跳。上游 /responses/compact 在模型处理期间不发送任何字节(大上下文可长达 // 数分钟),下游若经过反向代理(Nginx/Cloudflare Tunnel 等),零字节静默会触发 @@ -29,11 +55,12 @@ type openAICompactSSEKeepalive struct { writer gin.ResponseWriter started bool stopped bool - // bytes 是心跳已写出的注释字节数。心跳不构成语义响应,handler 的 - // "Forward 期间是否已写响应"判定(failover 放弃换号的依据)必须扣除 - // 这部分字节,见 OpenAICompactKeepaliveAdjustedWrittenSize。 - bytes int - stop chan struct{} + // accounting 是本请求所有心跳器已写出的注释字节累计(跨重试/嵌套实例 + // 共享)。心跳不构成语义响应,handler 的"Forward 期间是否已写响应"判定 + // (failover 放弃换号的依据)必须扣除这部分字节,见 + // OpenAICompactKeepaliveAdjustedWrittenSize。 + accounting *openAICompactSSEKeepaliveAccounting + stop chan struct{} } // StartOpenAICompactSSEKeepalive 为已标记 body-signal 客户端流式的 compact @@ -61,8 +88,9 @@ func startOpenAISSEKeepalive(c *gin.Context, interval time.Duration) func() { } originalWriter := c.Writer k := &openAICompactSSEKeepalive{ - writer: originalWriter, - stop: make(chan struct{}), + writer: originalWriter, + accounting: openAICompactSSEKeepaliveAccountingFor(c), + stop: make(chan struct{}), } c.Set(openAICompactSSEKeepaliveKey, k) wrappedWriter := &openAICompactKeepaliveWriter{ResponseWriter: originalWriter, k: k} @@ -117,7 +145,7 @@ func (k *openAICompactSSEKeepalive) beat() bool { k.started = true } n, err := k.writer.Write([]byte(": keepalive\n\n")) - k.bytes += n + k.accounting.add(n) if err != nil { k.stopped = true return false @@ -159,7 +187,8 @@ func StopOpenAICompactSSEKeepaliveCommitted(c *gin.Context) bool { } k.mu.Lock() k.markStoppedLocked() - committed := k.started + // 当前实例未心跳时,前一次尝试(或外层)的心跳器可能已把响应头提交为 200。 + committed := k.started || k.accounting.load() > 0 k.mu.Unlock() return committed } @@ -184,7 +213,7 @@ func OpenAICompactKeepaliveAdjustedWrittenSize(c *gin.Context) int { if k, valid := value.(*openAICompactSSEKeepalive); valid && k != nil { k.mu.Lock() size = k.writer.Size() - compactKeepaliveBytes = k.bytes + compactKeepaliveBytes = k.accounting.load() k.mu.Unlock() } } @@ -201,6 +230,19 @@ func OpenAICompactKeepaliveAdjustedWrittenSize(c *gin.Context) int { return -1 } +// openAICompactSSEKeepaliveAccountingFor 返回本请求共享的心跳字节计数, +// 首次调用时创建并存入 gin.Context。 +func openAICompactSSEKeepaliveAccountingFor(c *gin.Context) *openAICompactSSEKeepaliveAccounting { + if value, ok := c.Get(openAICompactSSEKeepaliveAccountingKey); ok { + if accounting, valid := value.(*openAICompactSSEKeepaliveAccounting); valid && accounting != nil { + return accounting + } + } + accounting := &openAICompactSSEKeepaliveAccounting{} + c.Set(openAICompactSSEKeepaliveAccountingKey, accounting) + return accounting +} + // openAICompactKeepaliveWriter 包装 gin.ResponseWriter:写侧方法先停拍心跳 // (互斥锁下建立 happens-before),读侧方法仅加锁不停拍——热路径的状态读取 // (如 Forward 前的 Size 快照)不能误杀心跳。心跳 goroutine 直接写内层 diff --git a/backend/internal/service/openai_compact_sse_keepalive_test.go b/backend/internal/service/openai_compact_sse_keepalive_test.go index 3703ea9f2a..e47ead103c 100644 --- a/backend/internal/service/openai_compact_sse_keepalive_test.go +++ b/backend/internal/service/openai_compact_sse_keepalive_test.go @@ -6,6 +6,7 @@ import ( "testing" "time" + "github.com/gin-gonic/gin" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" "github.com/tidwall/gjson" @@ -323,3 +324,88 @@ func TestWriteOpenAIFastPolicyBlockedResponse_BeforeKeepaliveCommit(t *testing.T require.Equal(t, http.StatusForbidden, rec.Code) require.Equal(t, "permission_error", gjson.Get(rec.Body.String(), "error.type").String()) } + +// keepaliveInstance 取出当前请求上的心跳器;测试用 time.Hour 间隔启动并手动 +// beat,不依赖 goroutine 调度时序。 +func keepaliveInstance(t *testing.T, c *gin.Context) *openAICompactSSEKeepalive { + t.Helper() + value, ok := c.Get(openAICompactSSEKeepaliveKey) + require.True(t, ok) + k, ok := value.(*openAICompactSSEKeepalive) + require.True(t, ok) + require.NotNil(t, k) + return k +} + +// 透传路径每次尝试都会新建心跳器:上一次尝试的注释字节仍在底层 writer 的 +// Size 里,必须跨实例累计扣除,否则下一次尝试会把旧心跳误判为语义输出。 +func TestOpenAICompactKeepaliveAdjustedWrittenSize_CumulativeAcrossRestarts(t *testing.T) { + c, rec := newCompactBridgeTestContext(t, true) + + stop := startOpenAISSEKeepalive(c, time.Hour) + require.True(t, keepaliveInstance(t, c).beat()) + stop() + require.Equal(t, -1, OpenAICompactKeepaliveAdjustedWrittenSize(c), "仅心跳时必须归一化为未写出") + require.Contains(t, rec.Body.String(), ": keepalive") + + stop = startOpenAISSEKeepalive(c, time.Hour) + require.Equal(t, -1, OpenAICompactKeepaliveAdjustedWrittenSize(c), "新实例尚未心跳时,旧实例的心跳字节也必须扣除") + require.False(t, openAIStreamClientOutputStarted(c, false)) + require.True(t, keepaliveInstance(t, c).beat()) + require.Equal(t, -1, OpenAICompactKeepaliveAdjustedWrittenSize(c), "两次尝试的心跳字节必须全部扣除") + + _, err := c.Writer.Write([]byte("real-output")) + require.NoError(t, err) + stop() + require.Equal(t, len("real-output"), OpenAICompactKeepaliveAdjustedWrittenSize(c), "语义输出仍须被识别") + require.True(t, openAIStreamClientOutputStarted(c, false)) +} + +// 上一次尝试的心跳已把响应头提交为 200 时,即使当前实例从未心跳, +// committed 判定也必须为真,写回方才会降级为流内终止事件。 +func TestStopOpenAICompactSSEKeepaliveCommitted_PreviousAttemptCommitted(t *testing.T) { + c, rec := newCompactBridgeTestContext(t, true) + + stop := startOpenAISSEKeepalive(c, time.Hour) + require.True(t, keepaliveInstance(t, c).beat()) + stop() + + stop = startOpenAISSEKeepalive(c, time.Hour) + defer stop() + require.True(t, StopOpenAICompactSSEKeepaliveCommitted(c)) + require.Equal(t, http.StatusOK, rec.Code) +} + +// 单次心跳器从未心跳时仍报告未提交(既有行为不变)。 +func TestStopOpenAICompactSSEKeepaliveCommitted_RestartWithoutBeats(t *testing.T) { + c, rec := newCompactBridgeTestContext(t, true) + + stop := startOpenAISSEKeepalive(c, time.Hour) + stop() + stop = startOpenAISSEKeepalive(c, time.Hour) + defer stop() + require.False(t, StopOpenAICompactSSEKeepaliveCommitted(c)) + require.Equal(t, -1, OpenAICompactKeepaliveAdjustedWrittenSize(c)) + require.Zero(t, rec.Body.Len()) +} + +// 外层心跳活跃时再启动内层心跳:两者共享同一累计计数,内层停止后外层已写的 +// 注释不能被重新算成语义输出。 +func TestOpenAICompactKeepaliveAdjustedWrittenSize_NestedKeepalives(t *testing.T) { + c, rec := newCompactBridgeTestContext(t, true) + + stopOuter := StartOpenAICompactSSEKeepalive(c, time.Hour) + outer := keepaliveInstance(t, c) + require.True(t, outer.beat()) + stopInner := startOpenAISSEKeepalive(c, time.Hour) + require.True(t, keepaliveInstance(t, c).beat()) + stopInner() + stopOuter() + + require.Equal(t, -1, OpenAICompactKeepaliveAdjustedWrittenSize(c), "嵌套心跳的注释字节必须全部扣除") + require.Equal(t, 2, strings.Count(rec.Body.String(), ": keepalive\n\n")) + + _, err := c.Writer.Write([]byte("real-output")) + require.NoError(t, err) + require.Equal(t, len("real-output"), OpenAICompactKeepaliveAdjustedWrittenSize(c)) +} From f90198a5ee971af481c0a68534158b938d56fc42 Mon Sep 17 00:00:00 2001 From: r266-tech Date: Wed, 25 Nov 2026 12:50:23 +0800 Subject: [PATCH 16/23] fix(codex): include Command Code image capabilities in model catalogs --- .../service/openai_codex_models_service.go | 15 ++++++-- .../openai_codex_models_service_test.go | 34 +++++++++++++++++++ 2 files changed, 47 insertions(+), 2 deletions(-) diff --git a/backend/internal/service/openai_codex_models_service.go b/backend/internal/service/openai_codex_models_service.go index 59ee8d459b..cee5511d5a 100644 --- a/backend/internal/service/openai_codex_models_service.go +++ b/backend/internal/service/openai_codex_models_service.go @@ -259,6 +259,7 @@ func loadCodexGroupCatalogAccounts(ctx context.Context, repo AccountRepository, PlatformDeepseek, PlatformMiniMax, PlatformOpenCodeGo, + PlatformCommandCode, }, false, ) @@ -1182,7 +1183,9 @@ func groupCodexModelSupportsImageInput( return false } } - if platform != PlatformOpenAI && platform != PlatformGrok && platform != PlatformDeepseek && platform != PlatformOpenCodeGo { + switch platform { + case PlatformOpenAI, PlatformGrok, PlatformDeepseek, PlatformOpenCodeGo, PlatformCommandCode: + default: return false } @@ -1321,7 +1324,7 @@ func accountCodexModelSupportsImageInput(account *Account, upstreamModel string) return false } switch account.Platform { - case PlatformOpenAI, PlatformDeepseek, PlatformOpenCodeGo: + case PlatformOpenAI, PlatformDeepseek, PlatformOpenCodeGo, PlatformCommandCode: if metadata, ok := account.GetUpstreamModelMetadata(upstreamModel); ok { if modalities := normalizeCodexInputModalities(metadata.InputModalities); len(modalities) > 0 { // Official GPT-6 Astra metadata briefly shipped with a stale @@ -1334,6 +1337,14 @@ func accountCodexModelSupportsImageInput(account *Account, upstreamModel string) return stringSliceContains(modalities, "image") } } + if account.IsCommandCode() { + // Only infer capabilities for the provider's own endpoints when a + // synced model has no input modalities. + model := strings.TrimPrefix(strings.TrimSpace(upstreamModel), "deepseek/") + return model == "deepseek-v4.1-flash" && + strings.TrimRight(account.GetOpenAIBaseURL(), "/") == DefaultCommandCodeBaseURL && + strings.TrimRight(account.GetCNProtocolBaseURL(APIProtocolResponses), "/") == DefaultCommandCodeBaseURL + } if strings.EqualFold(strings.TrimSpace(upstreamModel), "deepseek-v4-flash-vision-exp") { return account.Type == AccountTypeAPIKey } diff --git a/backend/internal/service/openai_codex_models_service_test.go b/backend/internal/service/openai_codex_models_service_test.go index b702eadc0f..7f21d64dfe 100644 --- a/backend/internal/service/openai_codex_models_service_test.go +++ b/backend/internal/service/openai_codex_models_service_test.go @@ -816,6 +816,9 @@ func TestBuildCodexModelsManifestForGroupUsesDeepSeekVisionCapabilities(t *testi return account } + customResponses := newAccount(1, PlatformCommandCode, "deepseek-v4.1-flash", nil) + customResponses.Credentials["api_base_urls"] = map[string]any{APIProtocolResponses: "https://example.test/v1"} + tests := []struct { name string platform string @@ -837,6 +840,36 @@ func TestBuildCodexModelsManifestForGroupUsesDeepSeekVisionCapabilities(t *testi accounts: []Account{newAccount(1, PlatformDeepseek, visionModel, nil)}, modalities: []any{"text", "image"}, }, + { + name: "Command Code bare ID", platform: PlatformCommandCode, + accounts: []Account{newAccount(1, PlatformCommandCode, "deepseek-v4.1-flash", nil)}, + modalities: []any{"text", "image"}, + }, + { + name: "Composite Command Code mapping", platform: PlatformComposite, + accounts: []Account{newAccount(1, PlatformCommandCode, "deepseek/deepseek-v4.1-flash", nil)}, + modalities: []any{"text", "image"}, + }, + { + name: "Command Code with a custom Responses endpoint", platform: PlatformCommandCode, + accounts: []Account{customResponses}, + modalities: []any{"text"}, + }, + { + name: "Command Code text-only override", platform: PlatformCommandCode, + accounts: []Account{newAccount(1, PlatformCommandCode, "deepseek/deepseek-v4.1-flash", []string{"text"})}, + modalities: []any{"text"}, + }, + { + name: "Command Code unknown model", platform: PlatformCommandCode, + accounts: []Account{newAccount(1, PlatformCommandCode, "unknown-model", nil)}, + modalities: []any{"text"}, + }, + { + name: "Command Code explicit vision metadata", platform: PlatformCommandCode, + accounts: []Account{newAccount(1, PlatformCommandCode, "other-model", []string{"text", "image"})}, + modalities: []any{"text", "image"}, + }, { name: "text-only DeepSeek Flash", platform: PlatformDeepseek, accounts: []Account{newAccount(1, PlatformDeepseek, "deepseek-v4-flash", nil)}, @@ -1129,6 +1162,7 @@ func TestBuildCodexModelsManifestForGroupLoadsAccountsOnce(t *testing.T) { require.Contains(t, repo.platforms, PlatformDeepseek) require.Contains(t, repo.platforms, PlatformMiniMax) require.Contains(t, repo.platforms, PlatformOpenCodeGo) + require.Contains(t, repo.platforms, PlatformCommandCode) require.NotContains(t, repo.platforms, PlatformComposite) } From b3fdd01f0bea95e2b9ce22dcffabec41dacb85be Mon Sep 17 00:00:00 2001 From: adam Date: Wed, 25 Nov 2026 12:59:28 +0800 Subject: [PATCH 17/23] =?UTF-8?q?fix(opencode):=20=E4=B8=8A=E6=B8=B8=20Use?= =?UTF-8?q?r-Agent=20=E7=89=88=E6=9C=AC=E6=9B=B4=E6=96=B0=E8=87=B3=201.19.?= =?UTF-8?q?6=20=E5=B9=B6=E6=94=AF=E6=8C=81=E7=8E=AF=E5=A2=83=E5=8F=98?= =?UTF-8?q?=E9=87=8F=E8=A6=86=E7=9B=96?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 出站到 opencode.ai 的规范 User-Agent 一直硬编码为 opencode/1.0.0,已明显落后于 真实客户端(opencode-ai npm 包当前为 1.19.6)。上游按 opencode/ 格式 校验客户端身份,陈旧的版本号本身会成为可识别的特征。 - 默认版本号更新为 1.19.6,注释说明跟随 opencode-ai 最新发布 - 新增 OPENCODE_USER_AGENT_VERSION 环境变量覆盖,后续升级无需改代码 - 版本号按三段 semver 校验,非法或空值回退内置默认 - 补充 Normalize/Resolve 与 UA 格式的单元测试 --- .../service/openai_opencode_session.go | 41 +++++++++++++++- .../service/openai_opencode_session_test.go | 47 +++++++++++++++++++ 2 files changed, 86 insertions(+), 2 deletions(-) diff --git a/backend/internal/service/openai_opencode_session.go b/backend/internal/service/openai_opencode_session.go index 3e3f5faea3..f14526a499 100644 --- a/backend/internal/service/openai_opencode_session.go +++ b/backend/internal/service/openai_opencode_session.go @@ -3,6 +3,8 @@ package service import ( "net/http" "net/url" + "os" + "regexp" "strconv" "strings" @@ -15,15 +17,50 @@ const ( openCodeSessionHeader = "X-OpenCode-Session" openCodeInboundBodyContextKey = "opencode_inbound_body" + // openCodeUserAgentVersionEnv 是 OpenCode 客户端 User-Agent 版本号的环境变量名。 + openCodeUserAgentVersionEnv = "OPENCODE_USER_AGENT_VERSION" + + // defaultOpenCodeUserAgentVersion 是内置的默认客户端版本号,跟随 + // opencode-ai npm 包(sst/opencode)的最新发布。 + defaultOpenCodeUserAgentVersion = "1.19.6" +) + +var ( + openCodeUserAgentVersionPattern = regexp.MustCompile(`^\d+\.\d+\.\d+$`) + // openCodeUpstreamUserAgent 是发往官方 OpenCode 上游的规范 User-Agent。 // opencode.ai 前置 Cloudflare 按客户端 UA 签名做 bot 拦截:Python-urllib 等 // 编程库 UA 会被 CF error code 1010 拒绝并返回 403。网关透传白名单放行 // user-agent,客户端自报身份原样到达上游会命中 WAF;该 403 再被计入账号 // 凭证类 strike,健康账号因此被自动禁用。取值沿用真实 opencode 客户端的 - // UA 格式(opencode/)。 - openCodeUpstreamUserAgent = "opencode/1.0.0" + // UA 格式(opencode/),版本号可通过 OPENCODE_USER_AGENT_VERSION 覆盖。 + openCodeUpstreamUserAgent = "opencode/" + defaultOpenCodeUserAgentVersion ) +func init() { + openCodeUpstreamUserAgent = "opencode/" + resolveOpenCodeUserAgentVersion(os.Getenv(openCodeUserAgentVersionEnv)) +} + +// resolveOpenCodeUserAgentVersion 返回当前生效的客户端版本号:合法的 +// OPENCODE_USER_AGENT_VERSION 优先,否则回退内置默认版本。 +func resolveOpenCodeUserAgentVersion(envValue string) string { + if version := NormalizeOpenCodeUserAgentVersion(envValue); version != "" { + return version + } + return defaultOpenCodeUserAgentVersion +} + +// NormalizeOpenCodeUserAgentVersion 校验并归一化 OpenCode User-Agent 版本号。 +// 只接受三段数字 semver(与真实 opencode 客户端版本格式一致),非法值返回空串, +// 调用方据此回退内置默认版本。 +func NormalizeOpenCodeUserAgentVersion(version string) string { + version = strings.TrimSpace(version) + if version == "" || !openCodeUserAgentVersionPattern.MatchString(version) { + return "" + } + return version +} + // rememberOpenCodeInboundBody keeps the client request body so protocol // conversion (Responses↔Anthropic↔Chat Completions) can still recover // prompt_cache_key / metadata.user_id after those fields are dropped. diff --git a/backend/internal/service/openai_opencode_session_test.go b/backend/internal/service/openai_opencode_session_test.go index 53341f8e26..0f7138dd5d 100644 --- a/backend/internal/service/openai_opencode_session_test.go +++ b/backend/internal/service/openai_opencode_session_test.go @@ -532,3 +532,50 @@ func TestOpenCodeSessionIsNotForwardedToOtherUpstreams(t *testing.T) { }) } } + +func TestNormalizeOpenCodeUserAgentVersion(t *testing.T) { + tests := []struct { + name string + input string + want string + }{ + {name: "valid semver", input: "1.19.6", want: "1.19.6"}, + {name: "trims surrounding spaces", input: " 1.19.6 ", want: "1.19.6"}, + {name: "rejects two segments", input: "1.19", want: ""}, + {name: "rejects four segments", input: "1.19.6.1", want: ""}, + {name: "rejects prefixed value", input: "opencode/1.19.6", want: ""}, + {name: "rejects non-numeric", input: "latest", want: ""}, + {name: "rejects empty", input: " ", want: ""}, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + require.Equal(t, tt.want, NormalizeOpenCodeUserAgentVersion(tt.input)) + }) + } +} + +func TestResolveOpenCodeUserAgentVersion(t *testing.T) { + tests := []struct { + name string + envValue string + want string + }{ + {name: "env override wins", envValue: "1.20.0", want: "1.20.0"}, + {name: "invalid env falls back to default", envValue: "not-a-version", want: defaultOpenCodeUserAgentVersion}, + {name: "empty env falls back to default", envValue: "", want: defaultOpenCodeUserAgentVersion}, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + require.Equal(t, tt.want, resolveOpenCodeUserAgentVersion(tt.envValue)) + }) + } +} + +func TestDefaultOpenCodeUpstreamUserAgentMatchesClientFormat(t *testing.T) { + // 上游按 opencode/ 识别客户端;无论默认值还是环境变量覆盖, + // 出站 UA 都必须保持该格式。 + require.Regexp(t, `^opencode/\d+\.\d+\.\d+$`, openCodeUpstreamUserAgent) + require.Regexp(t, `^\d+\.\d+\.\d+$`, defaultOpenCodeUserAgentVersion) +} From 1ba1ae8ef026f80a9282d9f2f7ea8098207f540a Mon Sep 17 00:00:00 2001 From: PMExtra Date: Wed, 25 Nov 2026 14:27:06 +0800 Subject: [PATCH 18/23] feat(proxy): show exit IP and last check time in proxy list - Expose latency_checked_at (from cached UpdatedAt) on admin proxy list - Show exit IP under location and last check time under created_at - Include region/city in quality check result - Quality check now updates row latency/IP/location on failure too, matching the backend snapshot Co-Authored-By: Claude Opus 5.5 --- backend/internal/handler/dto/mappers.go | 2 + backend/internal/handler/dto/types.go | 58 +++++++------- backend/internal/service/admin_proxy.go | 6 ++ backend/internal/service/admin_service.go | 2 + backend/internal/service/proxy.go | 1 + .../src/i18n/locales/en/admin/resources.ts | 1 + .../src/i18n/locales/zh/admin/resources.ts | 1 + frontend/src/types/index.ts | 3 + frontend/src/views/admin/ProxiesView.vue | 76 ++++++++++--------- 9 files changed, 86 insertions(+), 64 deletions(-) diff --git a/backend/internal/handler/dto/mappers.go b/backend/internal/handler/dto/mappers.go index 3adf2e2374..ab8884240e 100644 --- a/backend/internal/handler/dto/mappers.go +++ b/backend/internal/handler/dto/mappers.go @@ -562,6 +562,7 @@ func ProxyWithAccountCountFromService(p *service.ProxyWithAccountCount) *ProxyWi QualityGrade: p.QualityGrade, QualitySummary: p.QualitySummary, QualityChecked: p.QualityChecked, + LatencyChecked: p.LatencyChecked, } } @@ -607,6 +608,7 @@ func ProxyWithAccountCountFromServiceAdmin(p *service.ProxyWithAccountCount) *Ad QualityGrade: p.QualityGrade, QualitySummary: p.QualitySummary, QualityChecked: p.QualityChecked, + LatencyChecked: p.LatencyChecked, } } diff --git a/backend/internal/handler/dto/types.go b/backend/internal/handler/dto/types.go index d59be6a858..d79f33f692 100644 --- a/backend/internal/handler/dto/types.go +++ b/backend/internal/handler/dto/types.go @@ -461,20 +461,21 @@ type Proxy struct { type ProxyWithAccountCount struct { Proxy - AccountCount int64 `json:"account_count"` - LatencyMs *int64 `json:"latency_ms,omitempty"` - LatencyStatus string `json:"latency_status,omitempty"` - LatencyMessage string `json:"latency_message,omitempty"` - IPAddress string `json:"ip_address,omitempty"` - Country string `json:"country,omitempty"` - CountryCode string `json:"country_code,omitempty"` - Region string `json:"region,omitempty"` - City string `json:"city,omitempty"` - QualityStatus string `json:"quality_status,omitempty"` - QualityScore *int `json:"quality_score,omitempty"` - QualityGrade string `json:"quality_grade,omitempty"` - QualitySummary string `json:"quality_summary,omitempty"` - QualityChecked *int64 `json:"quality_checked,omitempty"` + AccountCount int64 `json:"account_count"` + LatencyMs *int64 `json:"latency_ms,omitempty"` + LatencyStatus string `json:"latency_status,omitempty"` + LatencyMessage string `json:"latency_message,omitempty"` + IPAddress string `json:"ip_address,omitempty"` + Country string `json:"country,omitempty"` + CountryCode string `json:"country_code,omitempty"` + Region string `json:"region,omitempty"` + City string `json:"city,omitempty"` + QualityStatus string `json:"quality_status,omitempty"` + QualityScore *int `json:"quality_score,omitempty"` + QualityGrade string `json:"quality_grade,omitempty"` + QualitySummary string `json:"quality_summary,omitempty"` + QualityChecked *int64 `json:"quality_checked,omitempty"` + LatencyChecked *time.Time `json:"latency_checked_at,omitempty"` } // AdminProxy 是管理员接口使用的 proxy DTO(包含密码等敏感字段)。 @@ -487,20 +488,21 @@ type AdminProxy struct { // AdminProxyWithAccountCount 是管理员接口使用的带账号统计的 proxy DTO。 type AdminProxyWithAccountCount struct { AdminProxy - AccountCount int64 `json:"account_count"` - LatencyMs *int64 `json:"latency_ms,omitempty"` - LatencyStatus string `json:"latency_status,omitempty"` - LatencyMessage string `json:"latency_message,omitempty"` - IPAddress string `json:"ip_address,omitempty"` - Country string `json:"country,omitempty"` - CountryCode string `json:"country_code,omitempty"` - Region string `json:"region,omitempty"` - City string `json:"city,omitempty"` - QualityStatus string `json:"quality_status,omitempty"` - QualityScore *int `json:"quality_score,omitempty"` - QualityGrade string `json:"quality_grade,omitempty"` - QualitySummary string `json:"quality_summary,omitempty"` - QualityChecked *int64 `json:"quality_checked,omitempty"` + AccountCount int64 `json:"account_count"` + LatencyMs *int64 `json:"latency_ms,omitempty"` + LatencyStatus string `json:"latency_status,omitempty"` + LatencyMessage string `json:"latency_message,omitempty"` + IPAddress string `json:"ip_address,omitempty"` + Country string `json:"country,omitempty"` + CountryCode string `json:"country_code,omitempty"` + Region string `json:"region,omitempty"` + City string `json:"city,omitempty"` + QualityStatus string `json:"quality_status,omitempty"` + QualityScore *int `json:"quality_score,omitempty"` + QualityGrade string `json:"quality_grade,omitempty"` + QualitySummary string `json:"quality_summary,omitempty"` + QualityChecked *int64 `json:"quality_checked,omitempty"` + LatencyChecked *time.Time `json:"latency_checked_at,omitempty"` } type ProxyAccountSummary struct { diff --git a/backend/internal/service/admin_proxy.go b/backend/internal/service/admin_proxy.go index bf0b89fe28..e9de1c9612 100644 --- a/backend/internal/service/admin_proxy.go +++ b/backend/internal/service/admin_proxy.go @@ -300,6 +300,8 @@ func (s *adminServiceImpl) CheckProxyQuality(ctx context.Context, id int64) (*Pr result.ExitIP = exitInfo.IP result.Country = exitInfo.Country result.CountryCode = exitInfo.CountryCode + result.Region = exitInfo.Region + result.City = exitInfo.City result.BaseLatencyMs = latencyMs result.Items = append(result.Items, ProxyQualityCheckItem{ Target: "base_connectivity", @@ -587,6 +589,10 @@ func (s *adminServiceImpl) attachProxyLatency(ctx context.Context, proxies []Pro proxies[i].QualityGrade = info.QualityGrade proxies[i].QualitySummary = info.QualitySummary proxies[i].QualityChecked = info.QualityCheckedAt + if !info.UpdatedAt.IsZero() { + checkedAt := info.UpdatedAt + proxies[i].LatencyChecked = &checkedAt + } } } diff --git a/backend/internal/service/admin_service.go b/backend/internal/service/admin_service.go index 87f4ffe5c9..fdd3580a05 100644 --- a/backend/internal/service/admin_service.go +++ b/backend/internal/service/admin_service.go @@ -605,6 +605,8 @@ type ProxyQualityCheckResult struct { ExitIP string `json:"exit_ip,omitempty"` Country string `json:"country,omitempty"` CountryCode string `json:"country_code,omitempty"` + Region string `json:"region,omitempty"` + City string `json:"city,omitempty"` BaseLatencyMs int64 `json:"base_latency_ms,omitempty"` PassedCount int `json:"passed_count"` WarnCount int `json:"warn_count"` diff --git a/backend/internal/service/proxy.go b/backend/internal/service/proxy.go index afd673a9f9..5bd537980e 100644 --- a/backend/internal/service/proxy.go +++ b/backend/internal/service/proxy.go @@ -66,6 +66,7 @@ type ProxyWithAccountCount struct { QualityGrade string QualitySummary string QualityChecked *int64 + LatencyChecked *time.Time } type ProxyAccountSummary struct { diff --git a/frontend/src/i18n/locales/en/admin/resources.ts b/frontend/src/i18n/locales/en/admin/resources.ts index 6b95adc0e9..1d1a47122d 100644 --- a/frontend/src/i18n/locales/en/admin/resources.ts +++ b/frontend/src/i18n/locales/en/admin/resources.ts @@ -123,6 +123,7 @@ export default { batchTest: 'Test All Proxies', testFailed: 'Failed', latencyFailed: 'Connection failed', + lastCheckedAt: 'Checked {time}', batchTestEmpty: 'No proxies available for testing', batchTestDone: 'Batch test completed for {count} proxies', batchTestFailed: 'Batch test failed', diff --git a/frontend/src/i18n/locales/zh/admin/resources.ts b/frontend/src/i18n/locales/zh/admin/resources.ts index c07bd5a2e8..f68fd1938c 100644 --- a/frontend/src/i18n/locales/zh/admin/resources.ts +++ b/frontend/src/i18n/locales/zh/admin/resources.ts @@ -140,6 +140,7 @@ export default { batchTest: '批量测试', testFailed: '失败', latencyFailed: '链接失败', + lastCheckedAt: '检测于 {time}', batchTestEmpty: '暂无可测试的代理', batchTestDone: '批量测试完成,共测试 {count} 个代理', batchTestFailed: '批量测试失败', diff --git a/frontend/src/types/index.ts b/frontend/src/types/index.ts index 25ecc4f66b..688a805e79 100644 --- a/frontend/src/types/index.ts +++ b/frontend/src/types/index.ts @@ -986,6 +986,7 @@ export interface Proxy { quality_grade?: string quality_summary?: string quality_checked?: number + latency_checked_at?: string expires_at: string | null fallback_mode: 'none' | 'proxy' | 'direct' backup_proxy_id?: number | null @@ -1019,6 +1020,8 @@ export interface ProxyQualityCheckResult { exit_ip?: string country?: string country_code?: string + region?: string + city?: string base_latency_ms?: number passed_count: number warn_count: number diff --git a/frontend/src/views/admin/ProxiesView.vue b/frontend/src/views/admin/ProxiesView.vue index 4eac7e6e90..e0ff03d1e8 100644 --- a/frontend/src/views/admin/ProxiesView.vue +++ b/frontend/src/views/admin/ProxiesView.vue @@ -184,17 +184,22 @@ @@ -253,7 +258,12 @@