diff --git a/.github/fixtures/pr838-ui/Dockerfile b/.github/fixtures/pr838-ui/Dockerfile new file mode 100644 index 000000000000..b13039db180f --- /dev/null +++ b/.github/fixtures/pr838-ui/Dockerfile @@ -0,0 +1,7 @@ +FROM alpine:3.23 +WORKDIR /app +RUN mkdir -p /app/data +COPY server /app/sub2api +COPY resources /app/resources +ENV DATA_DIR=/app/data +ENTRYPOINT ["/app/sub2api"] diff --git a/.github/fixtures/pr838-ui/compose.yml b/.github/fixtures/pr838-ui/compose.yml new file mode 100644 index 000000000000..e00c41100749 --- /dev/null +++ b/.github/fixtures/pr838-ui/compose.yml @@ -0,0 +1,52 @@ +# Disposable Actions installation. No upstream, SMTP, host config or egress. +services: + postgres: + image: postgres:18.1-alpine3.23 + container_name: pr838-ui-pg + environment: + POSTGRES_PASSWORD: fixture-only-postgres + POSTGRES_DB: sub2api_test + networks: [isolated] + healthcheck: + test: [CMD-SHELL, "pg_isready -U postgres -d sub2api_test"] + interval: 2s + timeout: 3s + retries: 45 + redis: + image: redis:8.4-alpine + command: [redis-server, --save, "", --appendonly, "no"] + networks: [isolated] + healthcheck: + test: [CMD, redis-cli, ping] + interval: 2s + timeout: 3s + retries: 45 + app: + image: pr838-ui-app:${CANDIDATE:?required} + networks: [isolated] + environment: + AUTO_SETUP: "true" + ADMIN_EMAIL: reviewer@example.invalid + ADMIN_PASSWORD: Fixture-Only-838-Password! + JWT_SECRET: fixture-only-pr838-jwt-not-real-0123456789abcdef + DATABASE_HOST: postgres + DATABASE_USER: postgres + DATABASE_PASSWORD: fixture-only-postgres + DATABASE_DBNAME: sub2api_test + DATABASE_SSLMODE: disable + REDIS_HOST: redis + SERVER_HOST: 0.0.0.0 + SERVER_PORT: "8080" + SERVER_MODE: release + TZ: UTC + depends_on: + postgres: {condition: service_healthy} + redis: {condition: service_healthy} + healthcheck: + test: [CMD, wget, -q, -T, "3", -O, /dev/null, http://localhost:8080/health] + interval: 3s + timeout: 5s + retries: 90 +networks: + isolated: + internal: true diff --git a/.github/scripts/oauth429-weekly-only-evidence.py b/.github/scripts/oauth429-weekly-only-evidence.py index 8d0308f89bd3..55bdf66c836e 100644 --- a/.github/scripts/oauth429-weekly-only-evidence.py +++ b/.github/scripts/oauth429-weekly-only-evidence.py @@ -80,4 +80,14 @@ ] for name in required: assert "TestOAuth429WeeklyOnly" + name in passed, "missing regression: " + name + if mode == "green": + for name in ( + "TestCompatErrorPipelineCountsEachResponseOnce", + "TestFastPathThenGeneralHandler_CountsOne502UntilThreshold", + "TestPendingModel401_DoesNotDisableWholeAccount", + "TestCredential401_StillDisablesDespitePendingModelRule", + "TestOpenAIWSAfterOutput_Generic500AndExplicit502NeedAfterStream", + "TestMemoryTempUnschedTriggerDelayedResetKeepsNewRound", + ): + assert name in passed, "missing candidate-only regression: " + name print(f"Validated {mode.upper()}: {len(passed)} passed events, {len(failed)} failed events") diff --git a/.github/scripts/pr838-ui-browser.mjs b/.github/scripts/pr838-ui-browser.mjs new file mode 100644 index 000000000000..b8893ab10a8c --- /dev/null +++ b/.github/scripts/pr838-ui-browser.mjs @@ -0,0 +1,271 @@ +// Remote CI only. Complete production frontend, real auth/admin HTTP handlers, +// services/repositories and PostgreSQL/Redis. No persistence endpoint interception. +import assert from 'node:assert/strict' +import { execFileSync } from 'node:child_process' +import { createServer, request as httpRequest } from 'node:http' +import { readFileSync, writeFileSync, existsSync } from 'node:fs' +import { resolve, join, extname } from 'node:path' +import { pathToFileURL } from 'node:url' + +const output = process.env.EVIDENCE_DIR, origin = 'http://127.0.0.1:4198' +if (!output || process.env.GITHUB_ACTIONS !== 'true') throw Error('Isolated CI only') +const appOrigin = process.env.SUB2API_TEST_APP_ORIGIN +if (!appOrigin) throw Error('Disposable application origin required') +assert.equal(JSON.parse(readFileSync(join(output, 'network-internal.json'))), true) +const git = (...args) => execFileSync('git', args, { encoding: 'utf8' }).trim() +const manifest = { + candidate: git('rev-parse', 'HEAD'), baseline: process.env.BASELINE, + boundary: 'Complete unmodified before/after frontend entries and project Vite/Tailwind/plugins. Both use candidate backend through a loopback HTTP proxy, real authentication, service/repository and disposable PostgreSQL/Redis on a Docker internal network. Before screenshots are UI comparison only, not baseline backend behavior. No live upstream, SMTP, production or paid calls. Future notice C is a test-only announcement using the real badge/store.', + screenshots: [], scenarios: [], persistence: [], http: [], errors: [], external: [], complete: false, +} +for (const ref of [manifest.baseline, manifest.candidate]) { + manifest.source_blobs ??= {} + manifest.source_blobs[ref] = Object.fromEntries([ + 'frontend/src/components/account/CreateAccountModal.vue', 'frontend/src/components/account/EditAccountModal.vue', + 'frontend/src/components/common/BaseDialog.vue', 'frontend/src/components/common/NewFeatureBadge.vue', + 'frontend/src/stores/newFeatureNotices.ts', 'frontend/src/style.css', 'frontend/tailwind.config.js', 'frontend/vite.config.ts', + ].map(path => [path, git('rev-parse', `${ref}:${path}`)])) +} +let mode = 'before', browser, page +const mime = { '.html': 'text/html', '.js': 'text/javascript', '.css': 'text/css', '.svg': 'image/svg+xml', '.png': 'image/png', '.woff2': 'font/woff2' } +const server = createServer((req, res) => { + const pathname = new URL(req.url, origin).pathname + if (/^\/(?:api\/|setup\/|health$)/.test(pathname)) { + const upstream = httpRequest(appOrigin + req.url, { method: req.method, headers: { ...req.headers, host: new URL(appOrigin).host } }, response => { + if (/^\/api\/v1\/admin\/accounts(?:\/\d+)?$/.test(pathname)) manifest.http.push({ mode, method: req.method, path: pathname, status: response.statusCode }) + res.writeHead(response.statusCode, response.headers); response.pipe(res) + }) + upstream.on('error', error => { manifest.errors.push({ proxy: error.code }); res.writeHead(502); res.end() }) + req.pipe(upstream) + return + } + const root = resolve(output, mode + '-dist') + let file = resolve(root, '.' + decodeURIComponent(pathname)) + if (!file.startsWith(root + '/')) { res.writeHead(403); res.end(); return } + if (!existsSync(file) || !extname(file)) file = join(root, 'index.html') + res.setHeader('Content-Type', mime[extname(file)] || 'application/octet-stream') + res.end(readFileSync(file)) +}) +await new Promise(resolveReady => server.listen(4198, '127.0.0.1', resolveReady)) +const { chromium } = await import(pathToFileURL(process.env.SUB2API_PLAYWRIGHT_MODULE)) +const B = 'temp-unsched-stream-timing-count-window' +const text = { + en: { create: 'Create Account', edit: 'Edit', temp: 'Temp Unschedulable', add: 'Add Rule', presets: ['529 Overloaded', '429 Rate Limit', '503 Unavailable'], rule: n => `Rule #${n}` }, + zh: { create: '添加账号', edit: '编辑', temp: '临时不可调度', add: '添加规则', presets: ['529 过载', '429 限流', '503 维护'], rule: n => `规则 #${n}` }, +} +function pg(id) { + assert(Number.isSafeInteger(id) && id > 0) + return JSON.parse(execFileSync('docker', ['exec', 'pr838-ui-pg', 'psql', '-U', 'postgres', '-d', 'sub2api_test', '-tAX', '-c', + `SELECT json_build_object('id',id,'name',name,'rules',credentials->'temp_unschedulable_rules') FROM accounts WHERE id=${id}`], { encoding: 'utf8' }).trim()) +} +const dialog = () => page.getByRole('dialog').filter({ has: page.locator('#create-account-form, #edit-account-form') }) +const section = labels => dialog().locator('label').filter({ hasText: new RegExp(`^${labels.temp}$`) }).locator('..').locator('..').locator('..') +const close = async () => { await dialog().getByRole('button', { name: 'Close modal', exact: true }).click(); await dialog().waitFor({ state: 'hidden' }) } +async function screenshot(name, locator) { + await locator.scrollIntoViewIfNeeded() + await page.evaluate(async () => { await document.fonts.ready; await new Promise(r => requestAnimationFrame(() => requestAnimationFrame(r))) }) + await page.waitForFunction(() => !document.querySelector('.modal-enter-active')) + await locator.screenshot({ path: join(output, name), animations: 'disabled' }) + manifest.screenshots.push({ name, mode, frontend: mode === 'before' ? manifest.baseline : manifest.candidate, backend: manifest.candidate }) +} +async function login(labels) { + // Complete first-login acknowledgment on the ordinary profile page before + // entering administration. The baseline accounts page starts protected API + // requests immediately and produces a 423 rejection before acknowledgment. + await page.goto(origin + '/login?redirect=/profile') + await page.locator('#email').fill('reviewer@example.invalid') + await page.locator('#password').fill('Fixture-Only-838-Password!') + const response = page.waitForResponse(r => new URL(r.url()).pathname === '/api/v1/auth/login' && r.request().method() === 'POST') + await page.locator('button[type=submit]').click() + assert.equal((await response).status(), 200) + await page.waitForURL(url => url.pathname === '/profile') + // Actual first-login tour and compliance UI; no injected auth/consent state. + const tour = page.locator('.driver-popover') + if (await tour.waitFor({ state: 'visible', timeout: 3000 }).then(() => true, () => false)) { + await page.keyboard.press('Escape'); await tour.waitFor({ state: 'hidden' }) + } + const compliance = page.getByRole('dialog').filter({ has: page.locator('#admin-compliance-phrase') }) + if (await compliance.isVisible()) { + const phrase = await compliance.locator('label[for="admin-compliance-phrase"] + div').innerText() + await compliance.locator('#admin-compliance-phrase').fill(phrase) + const accepted = page.waitForResponse(r => new URL(r.url()).pathname === '/api/v1/admin/compliance/accept') + await compliance.locator('button.btn-primary').click() + assert.equal((await accepted).status(), 200); await compliance.waitFor({ state: 'hidden' }) + } + await page.goto(origin + '/admin/accounts') + if (await tour.waitFor({ state: 'visible', timeout: 3000 }).then(() => true, () => false)) { + await page.keyboard.press('Escape'); await tour.waitFor({ state: 'hidden' }) + } + await page.getByRole('button', { name: labels.create, exact: true }).waitFor() +} +async function api(method, path, body) { + const token = await page.evaluate(() => localStorage.getItem('auth_token')) + assert(token, 'real login token required') + const response = await page.request.fetch(origin + '/api/v1' + path, { method, headers: { Authorization: `Bearer ${token}` }, data: body }) + assert.equal(response.status(), 200, `${method} ${path}`) + const value = await response.json(); assert.equal(value.code, 0); return value.data +} +async function openEdit(name, labels) { + const row = page.getByRole('row').filter({ hasText: name }) + await row.getByRole('button', { name: labels.edit, exact: true }).click() + await page.locator('#edit-account-form').waitFor() +} +async function openCreate(labels) { + await page.getByRole('button', { name: labels.create, exact: true }).click() + await page.locator('#create-account-form').waitFor() + await dialog().getByRole('button', { name: /Claude Console/ }).click() + const header = section(labels).locator(':scope > div').first() + await header.getByRole('button').click() + await section(labels).getByRole('button', { name: labels.add, exact: true }).waitFor() +} +async function checkFields(before, counts, windows) { + assert.deepEqual(await dialog().getByTestId('temp-unsched-stream-before_stream').evaluateAll(nodes => nodes.map(n => n.getAttribute('aria-checked') === 'true')), before) + assert.deepEqual(await dialog().getByTestId('temp-unsched-trigger-count').evaluateAll(nodes => nodes.map(n => n.value)), counts) + assert.deepEqual(await dialog().getByTestId('temp-unsched-trigger-window').evaluateAll(nodes => nodes.map(n => n.value)), windows) +} +async function save(method) { + const response = page.waitForResponse(r => /^\/api\/v1\/admin\/accounts(?:\/\d+)?$/.test(new URL(r.url()).pathname) && r.request().method() === method) + await page.locator(`button[type=submit][form="${method === 'POST' ? 'create' : 'edit'}-account-form"]`).click() + const actual = await response; assert.equal(actual.status(), 200) + const sent = actual.request().postDataJSON(), body = await actual.json(); assert.equal(body.code, 0) + await dialog().waitFor({ state: 'hidden' }) + return { id: body.data.id, sent: { name: sent.name, rules: sent.credentials?.temp_unschedulable_rules } } +} +async function readback(id, expected, label) { + const value = await api('GET', '/admin/accounts/' + id), row = pg(id) + assert.deepEqual(value.credentials.temp_unschedulable_rules, expected) + assert.deepEqual(row.rules, expected) + manifest.persistence.push({ label, id, api: { name: value.name, rules: value.credentials.temp_unschedulable_rules }, pg: row }) +} +try { + browser = await chromium.launch({ headless: true }) + for (const lang of ['en', 'zh']) { + const labels = text[lang] + const context = await browser.newContext({ viewport: { width: 1440, height: 1800 }, locale: lang === 'en' ? 'en-US' : 'zh-CN', serviceWorkers: 'block' }) + await context.addInitScript(locale => localStorage.setItem('sub2api_locale', locale), lang) + await context.route('**/*', route => { + const url = new URL(route.request().url()) + if (url.origin === origin || ['data:', 'blob:', 'about:'].includes(url.protocol)) return route.continue() + manifest.external.push({ origin: url.origin, path: url.pathname }); return route.abort('blockedbyclient') + }) + page = await context.newPage(); page.setDefaultTimeout(20000) + page.on('pageerror', error => manifest.errors.push({ lang, mode, name: error.name, message: error.message, stack: error.stack, path: new URL(page.url()).pathname })) + mode = 'before'; await login(labels) + const legacyName = `PR838 ${lang} legacy529` + const legacy = await api('POST', '/admin/accounts', { name: legacyName, platform: 'anthropic', type: 'apikey', + credentials: { api_key: 'fixture-only-not-a-real-key', base_url: 'https://upstream.example.invalid', temp_unschedulable_enabled: true, + temp_unschedulable_rules: [{ error_code: 529, keywords: ['overloaded'], duration_minutes: 15, scope: 'model' }] }, concurrency: 1, priority: 50 }) + assert.equal(Object.hasOwn(pg(legacy.id).rules[0], 'stream_timing'), false) + await page.reload(); await openCreate(labels) + await section(labels).getByRole('button', { name: '+ ' + labels.presets[0], exact: true }).click() + assert.equal(await dialog().getByTestId('temp-unsched-trigger-count').count(), 0) + await screenshot(`before-create-${lang}.png`, section(labels)); await close() + await openEdit(legacyName, labels) + await screenshot(`before-edit-${lang}.png`, section(labels)); await close() + + mode = 'after'; await page.reload() + const userId = await page.evaluate(() => JSON.parse(localStorage.getItem('auth_user')).id) + const noticePage = async phase => { await page.goto(`${origin}/pr838-notices.html?phase=${phase}&user=${userId}`); await page.locator('h1').waitFor() } + if (lang === 'en') { + await noticePage('a'); await page.getByTestId('notice-A-0').getByTestId('new-feature-badge').click() + await noticePage('b') + assert.equal(await page.getByTestId('notice-A-0').getByTestId('new-feature-badge').count(), 0) + assert.equal(await page.getByTestId('new-feature-badge').count(), 2) + await screenshot('notice-B-after-A-dismissed.png', page.locator('main')) + await page.goto(origin + '/admin/accounts') + } + await openCreate(labels) + await section(labels).getByRole('button', { name: labels.add, exact: true }).click() + await checkFields([true], ['1'], ['5']) + assert.equal(await dialog().getByTestId('temp-unsched-stream-before_stream').evaluate(el => getComputedStyle(el).borderTopWidth), '2px', 'real Tailwind selection border') + assert.equal(await dialog().getByTestId('temp-unsched-stream-before_stream').evaluate(el => getComputedStyle(el).display), 'flex', 'real Tailwind layout') + await screenshot(`after-create-defaults-${lang}.png`, section(labels)) + for (const preset of labels.presets) await section(labels).getByRole('button', { name: '+ ' + preset, exact: true }).click() + await checkFields([true, false, false, false], ['1', '1', '1', '1'], ['5', '5', '5', '5']) + assert.equal(await section(labels).getByTestId('new-feature-badge').count(), 4) + const ruleCard = index => dialog().getByTestId('temp-unsched-trigger-count').nth(index).locator('..').locator('..').locator('..') + for (let index = 1; index <= 3; index++) await screenshot(`after-create-preset-${[529, 429, 503][index - 1]}-${lang}.png`, ruleCard(index)) + await dialog().locator('[data-tour="account-form-name"]').fill(`PR838 ${lang} created`) + await dialog().locator('input[type=password][required]').fill('fixture-only-not-a-real-key') + const firstRule = dialog().getByTestId('temp-unsched-trigger-count').first().locator('..').locator('..').locator('..') + await firstRule.locator('input[type=number]').nth(0).fill('502') + await firstRule.locator('input[type=number]').nth(1).fill('30') + await firstRule.locator('input[type=text]').first().fill('bad gateway') + const created = await save('POST') + assert.deepEqual(created.sent.rules.map(r => [r.stream_timing, r.trigger_count, r.trigger_window_minutes]), [ + ['before_stream', 1, 5], ['after_stream', 1, 5], ['after_stream', 1, 5], ['after_stream', 1, 5], + ]) + await readback(created.id, created.sent.rules, `${lang}: Create POST -> service/repository -> API and PG`) + await openEdit(`PR838 ${lang} created`, labels) + await checkFields([true, false, false, false], ['1', '1', '1', '1'], ['5', '5', '5', '5']) + await screenshot(`after-edit-created-readback-${lang}.png`, ruleCard(0)) + assert.equal(await section(labels).getByTestId('new-feature-badge').count(), 4) + await section(labels).getByTestId('new-feature-badge').first().click() + assert.equal(await section(labels).getByTestId('new-feature-badge').count(), 0, 'one click hides all four actual Edit locations') + await section(labels).getByRole('button', { name: labels.add, exact: true }).click() + for (const preset of labels.presets) await section(labels).getByRole('button', { name: '+ ' + preset, exact: true }).click() + await checkFields([true, false, false, false, true, false, false, false], Array(8).fill('1'), Array(8).fill('5')) + await screenshot(`after-edit-new-defaults-${lang}.png`, ruleCard(4)) + for (let index = 5; index <= 7; index++) await screenshot(`after-edit-preset-${[529, 429, 503][index - 5]}-${lang}.png`, ruleCard(index)) + await close() + await readback(created.id, created.sent.rules, `${lang}: Edit cancel discards unsaved new custom/preset rules`) + + await openEdit(legacyName, labels) + await checkFields([false], ['1'], ['1']) + await screenshot(`after-edit-legacy-defaults-${lang}.png`, section(labels)) + await dialog().locator('[data-tour="edit-account-form-name"]').fill(legacyName + ' renamed') + const renamed = await save('PUT') + assert.equal(Object.hasOwn(renamed.sent.rules[0], 'stream_timing'), false, 'rename-only request must omit legacy timing') + await readback(legacy.id, renamed.sent.rules, `${lang}: rename-only PUT keeps omitted legacy529 timing`) + await openEdit(legacyName + ' renamed', labels) + await dialog().getByTestId('temp-unsched-stream-before_stream').click() + await dialog().getByTestId('temp-unsched-trigger-count').fill('3') + await dialog().getByTestId('temp-unsched-trigger-window').fill('7') + const explicit = await save('PUT') + assert.deepEqual([explicit.sent.rules[0].stream_timing, explicit.sent.rules[0].trigger_count, explicit.sent.rules[0].trigger_window_minutes], ['before_stream', 3, 7]) + await readback(legacy.id, explicit.sent.rules, `${lang}: explicit timing/count/window PUT readback`) + await openEdit(legacyName + ' renamed', labels); await checkFields([true], ['3'], ['7']) + await screenshot(`after-edit-saved-readback-${lang}.png`, section(labels)) + // Real close/open interactions preserve one ID across all cards and Create/Edit. + assert.equal(await section(labels).getByTestId('new-feature-badge').count(), 0) + await close(); await openCreate(labels) + await section(labels).getByRole('button', { name: labels.add, exact: true }).click() + assert.equal(await section(labels).getByTestId('new-feature-badge').count(), 0) + await close(); await page.reload(); await openEdit(legacyName + ' renamed', labels) + assert.equal(await section(labels).getByTestId('new-feature-badge').count(), 0) + await screenshot(`after-edit-notice-hidden-reload-${lang}.png`, section(labels)); await close() + + if (lang === 'en') { + await noticePage('c') + assert.equal(await page.getByTestId('notice-B-1').getByTestId('new-feature-badge').count(), 0, 'actual administrator B remains hidden') + assert.equal(await page.getByTestId('notice-A-0').getByTestId('new-feature-badge').count(), 0) + assert.equal(await page.getByTestId('new-feature-badge').count(), 1) + assert.equal(await page.getByTestId('notice-C-3').getByTestId('new-feature-badge').count(), 1) + await screenshot('notice-C-independent-A-B-stay-hidden.png', page.locator('main')) + await page.reload(); await page.locator('h1').waitFor() + assert.equal(await page.getByTestId('new-feature-badge').count(), 1) + const dismissed = await page.evaluate(id => JSON.parse(localStorage.getItem('sub2api:new-feature-notices:v1:' + id)), userId) + assert(dismissed.includes(B)) + await page.goto(origin + '/admin/accounts') + await page.getByRole('button', { name: 'User menu', exact: true }).click() + await page.getByRole('button', { name: 'Logout', exact: true }).click() + await page.waitForURL(url => url.pathname === '/login') + await login(labels); await openEdit(legacyName + ' renamed', labels) + assert.equal(await section(labels).getByTestId('new-feature-badge').count(), 0) + await close() + manifest.scenarios.push({ name: 'A -> B multiple locations -> reload -> future C; actual B Create/Edit/reload/same-admin-login', passed: true, futureC: 'test-only registry; actual badge/store', actualUser: userId }) + } + manifest.scenarios.push({ lang, name: 'full administration Create/Edit, defaults/presets, rename-only omitted timing, explicit save, API + SQL readback', passed: true }) + await context.close() + } + assert.deepEqual(manifest.external, []); assert.deepEqual(manifest.errors, []) + manifest.complete = true +} catch (error) { + manifest.failure = { name: error.name, message: error.message, stack: error.stack } + if (page && !page.isClosed()) await page.screenshot({ path: join(output, 'failure.png'), fullPage: true }).catch(() => {}) + throw error +} finally { + writeFileSync(join(output, 'manifest.json'), JSON.stringify(manifest, null, 2) + '\n') + await browser?.close(); await new Promise(done => server.close(done)) +} +console.log('PR838 full administration and persistence acceptance passed.') diff --git a/.github/scripts/pr838-ui-build.mjs b/.github/scripts/pr838-ui-build.mjs new file mode 100644 index 000000000000..d9193fe5141b --- /dev/null +++ b/.github/scripts/pr838-ui-build.mjs @@ -0,0 +1,46 @@ +// CI only: unmodified complete application entry, project Vite/Tailwind/plugins. +// A separate test page exercises real NewFeatureBadge/store announcement epochs. +import { writeFileSync, rmSync, mkdirSync } from 'node:fs' +import { resolve, join } from 'node:path' +import { pathToFileURL } from 'node:url' + +const repo = resolve('.'), output = process.env.EVIDENCE_DIR +if (!output || process.env.GITHUB_ACTIONS !== 'true') throw Error('Isolated CI only') +mkdirSync(output, { recursive: true }) +const { build } = await import(pathToFileURL(join(repo, 'frontend/node_modules/vite/dist/node/index.js'))) +for (const mode of ['before', 'after']) { + const root = join(repo, mode === 'before' ? '.pr838-baseline/frontend' : 'frontend') + const extra = join(root, 'pr838-notices.html'), entry = join(root, '.pr838-notices.js') + try { + if (mode === 'after') { + writeFileSync(extra, '
', { flag: 'wx' }) + writeFileSync(entry, ` +import {createApp,h} from 'vue';import {createPinia} from 'pinia'; +import Badge from '/src/components/common/NewFeatureBadge.vue'; +import {NEW_FEATURE_NOTICES as ids} from '/src/constants/newFeatureNotices.ts'; +import {i18n,loadLocaleMessages} from '/src/i18n/index.ts';import '/src/style.css'; +async function mountNotices(){ +await loadLocaleMessages('en');i18n.global.locale.value='en'; +// Future C is deliberately a test-only registered ID, not a product announcement. +const registry={A:ids.vipAutoCredit,B:ids.tempUnschedStreamCountWindow,C:'fixture-pr838-future-announcement-C'}; +const p=new URLSearchParams(location.search), phase=p.get('phase')||'a',user=Number(p.get('user')); +if(!Number.isSafeInteger(user)||user<1)throw Error('Fictional fixture administrator required'); +const entries=phase==='a'?['A']:phase==='b'?['A','B','B']:['A','B','B','C']; +createApp({render:()=>h('main',{class:'p-6 space-y-4'},[ +h('h1',{},'CI fixture · actual badge/store · simulated announcement epochs'), +...entries.map((id,i)=>h('section',{'data-testid':'notice-'+id+'-'+i},[h('span',{},id),h(Badge,{noticeId:registry[id],userId:user})])) +])}).use(createPinia()).use(i18n).mount('#app'); +} +void mountNotices(); +`, { flag: 'wx' }) + } + process.chdir(root) + await build({ root, configFile: join(root, 'vite.config.ts'), build: { + outDir: join(output, mode + '-dist'), emptyOutDir: true, + rollupOptions: { input: mode === 'before' ? join(root, 'index.html') : { app: join(root, 'index.html'), notices: extra } }, + } }) + } finally { + process.chdir(repo) + if (mode === 'after') { rmSync(extra, { force: true }); rmSync(entry, { force: true }) } + } +} diff --git a/.github/scripts/pr838-ws-phase-evidence.py b/.github/scripts/pr838-ws-phase-evidence.py new file mode 100644 index 000000000000..65dfff1911c3 --- /dev/null +++ b/.github/scripts/pr838-ws-phase-evidence.py @@ -0,0 +1,48 @@ +"""Validate completed remote forwarding regressions; infrastructure is never RED.""" +import json +from pathlib import Path +import sys + +mode, filename, status = sys.argv[1:] +path = Path(filename) +events = [json.loads(line) for line in path.read_text().splitlines()] +output = "".join(event.get("Output", "") for event in events) + path.with_suffix(".stderr").read_text() +path.with_suffix(".log").write_text(output) +print(output) +assert events and not any(event["Action"] == "skip" for event in events), "missing execution or skipped regression" +assert not any(term in output.lower() for term in ( + "build failed", "setup failed", "undefined:", "no tests to run", "panic:", + "fatal error:", "warning: data race", "race detected", "signal:", + "segmentation fault", "test timed out", "unexpected fault", "out of memory", +)), "compilation, race, crash or infrastructure cannot satisfy behavior evidence" +started = {event["Test"] for event in events if event["Action"] == "run" and event.get("Test")} +finished = {event["Test"] for event in events if event["Action"] in ("pass", "fail") and event.get("Test")} +assert started and started == finished, "unfinished forwarding tests" +passed = {event.get("Test") for event in events if event["Action"] == "pass"} +failed = {event.get("Test") for event in events if event["Action"] == "fail"} +terminal = [event for event in events if not event.get("Test") and event["Action"] in ("pass", "fail")] +assert len(terminal) == 1, "missing completed package result" +root = "TestTempUnschedWSForwardAfterOutputSemantic429/" +for entry in ("v2", "ingress"): + assert root + entry + "/after_stream" in passed, "after_stream control missing: " + entry + if mode == "red": + assert root + entry + "/before_stream" in failed, "old source must fail the actual forwarding entry: " + entry + else: + assert root + entry + "/before_stream" in passed, "candidate failed the actual forwarding entry: " + entry +if mode == "red": + assert int(status) == 1 and terminal[0]["Action"] == "fail" + assert "semantic429 must respect the real output phase and count each response once" in output +else: + assert int(status) == 0 and not failed and terminal[0]["Action"] == "pass" + for name in ( + "TestCompatErrorPipelineCountsEachResponseOnce", + "TestFastPathThenGeneralHandler_CountsOne502UntilThreshold", + "TestPendingModel401_DoesNotDisableWholeAccount", + "TestCredential401_StillDisablesDespitePendingModelRule", + "TestOpenAIWSAfterOutput_Generic500AndExplicit502NeedAfterStream", + "TestMemoryTempUnschedTriggerDelayedResetKeepsNewRound", + "TestOAuth429WeeklyOnlyService", "TestOAuth429WeeklyOnlyWSForward", + "TestOAuth429WeeklyOnlyWSClientIngress", + ): + assert name in passed, "missing safety control: " + name +print(f"Validated WS PHASE {mode.upper()}: {len(passed)} passed events, {len(failed)} failed events") diff --git a/.github/workflows/oauth-degradation-native-controls.yml b/.github/workflows/oauth-degradation-native-controls.yml index 71957801e700..9b552d76d6f5 100644 --- a/.github/workflows/oauth-degradation-native-controls.yml +++ b/.github/workflows/oauth-degradation-native-controls.yml @@ -75,10 +75,37 @@ jobs: postgres: runs-on: ubuntu-latest timeout-minutes: 35 + # Same images as integration_harness_test.go. Provision before the race + # binary starts; keep its migrations, real connections and all regressions. + services: + postgres: + image: postgres:18.1-alpine3.23 + env: + POSTGRES_USER: postgres + POSTGRES_PASSWORD: postgres + POSTGRES_DB: sub2api_test + ports: + - 5432:5432 + options: >- + --health-cmd "pg_isready -U postgres -d sub2api_test" + --health-interval 5s + --health-timeout 5s + --health-retries 12 + redis: + image: redis:8.4-alpine + ports: + - 6379:6379 + options: >- + --health-cmd "redis-cli ping" + --health-interval 5s + --health-timeout 5s + --health-retries 12 env: CI: 'true' GOMAXPROCS: '2' GOFLAGS: '-p=2' + SUB2API_TEST_POSTGRES_DSN: 'postgres://postgres:postgres@127.0.0.1:5432/sub2api_test?sslmode=disable&TimeZone=UTC' + SUB2API_TEST_REDIS_URL: 'redis://127.0.0.1:6379/0' steps: - uses: actions/checkout@v6 with: diff --git a/.github/workflows/oauth429-weekly-only.yml b/.github/workflows/oauth429-weekly-only.yml index 946debfb7118..0bb7535e097d 100644 --- a/.github/workflows/oauth429-weekly-only.yml +++ b/.github/workflows/oauth429-weekly-only.yml @@ -52,10 +52,12 @@ jobs: git worktree add --detach "$RUNNER_TEMP/oauth429-red" "$CANDIDATE" while read -r expected target; do test "$(git rev-parse "$BASELINE:$target")" = "$expected" + candidate_blob=$(git rev-parse "$CANDIDATE:$target") git show "$BASELINE:$target" > "$RUNNER_TEMP/oauth429-red/$target" actual=$(git hash-object "$RUNNER_TEMP/oauth429-red/$target") test "$actual" = "$expected" printf '%s %s %s\n' "$BASELINE" "$actual" "$target" >> evidence/restored-blobs.txt + printf '%s %s %s\n' "$CANDIDATE" "$candidate_blob" "$target" >> evidence/candidate-source-blobs.txt done <<'BLOBS' ab9d5251a4acec7c17b0adb0f21ae59a71f89067 backend/internal/service/openai_disable_scheduling_429.go 849aec6c598b9ca5e94f218f76e7d7266505ae57 backend/internal/service/openai_gateway_service.go @@ -71,7 +73,6 @@ jobs: 0e4455ea613b07f2775c793346bd0b8fa0257fd5 backend/internal/service/openai_quota_service.go 26744ab312ed9552b375487d34052fd8b7f28da1 backend/internal/service/openai_quota_usage_snapshot.go BLOBS - git -C "$RUNNER_TEMP/oauth429-red" diff --stat > evidence/red-diff.txt git ls-files 'backend/internal/service/*429*test.go' 'backend/internal/repository/oauth429_weekly_only*test.go' > evidence/retained-tests.txt while IFS= read -r test_file; do candidate_blob=$(git hash-object "$test_file") @@ -80,6 +81,19 @@ jobs: printf '%s %s\n' "$candidate_blob" "$test_file" >> evidence/retained-test-blobs.txt done < evidence/retained-tests.txt git -C "$RUNNER_TEMP/oauth429-red" diff --exit-code -- '*_test.go' + # This later, unrelated regression requires the candidate-only WS + # stream-phase helper. Exclude it only from this disposable old-source + # checkout; GREEN explicitly runs all six tests with candidate sources. + excluded=backend/internal/service/temp_unsched_pending_test.go + if git cat-file -e "$BASELINE:$excluded" 2>/dev/null; then echo 'historical-exclusion-baseline-present' >&2; exit 1; fi + candidate_blob=$(git rev-parse "$CANDIDATE:$excluded") + test "$(git hash-object "$RUNNER_TEMP/oauth429-red/$excluded")" = "$candidate_blob" + if grep -q '^func TestOAuth429WeeklyOnly' "$excluded"; then echo 'historical-exclusion-target-regression' >&2; exit 1; fi + rm -- "$RUNNER_TEMP/oauth429-red/$excluded" + test ! -e "$RUNNER_TEMP/oauth429-red/$excluded" + printf '%s baseline=absent candidate=%s red=absent reason=candidate-only-WS-stream-phase-helper\n' "$excluded" "$candidate_blob" > evidence/excluded-tests.txt + git -C "$RUNNER_TEMP/oauth429-red" diff --exit-code -- '*_test.go' ":!$excluded" + git -C "$RUNNER_TEMP/oauth429-red" diff --stat > evidence/red-diff.txt - name: Require behavioral RED from unchanged service regressions shell: bash run: | @@ -183,7 +197,7 @@ jobs: git rev-parse HEAD HEAD^{tree} > evidence/candidate.txt git diff --exit-code set +e - (cd backend && go test -race -json -tags=unit ./internal/service -run '^Test(OAuth429WeeklyOnly|DisableScheduling429|RateLimitDisableSchedulingOn429|OpenAIGatewayDisableSchedulingOn429|Managed429WeeklyPolicy|Weekly429Threshold|TOTPRotationOn429|OpenAIStream429|OpenAIQuotaRecovery|CalculateOpenAI429ResetTime)' -count=1 -timeout=10m) > evidence/green.jsonl 2> evidence/green.stderr + (cd backend && go test -race -json -tags=unit ./internal/service -run '^Test(OAuth429WeeklyOnly|DisableScheduling429|RateLimitDisableSchedulingOn429|OpenAIGatewayDisableSchedulingOn429|Managed429WeeklyPolicy|Weekly429Threshold|TOTPRotationOn429|OpenAIStream429|OpenAIQuotaRecovery|CalculateOpenAI429ResetTime|CompatErrorPipelineCountsEachResponseOnce|FastPathThenGeneralHandler_CountsOne502UntilThreshold|PendingModel401_DoesNotDisableWholeAccount|Credential401_StillDisablesDespitePendingModelRule|OpenAIWSAfterOutput_Generic500AndExplicit502NeedAfterStream|MemoryTempUnschedTriggerDelayedResetKeepsNewRound)' -count=1 -timeout=10m) > evidence/green.jsonl 2> evidence/green.stderr result=$? set -e printf '%s\n' "$result" > evidence/green-exit.txt diff --git a/.github/workflows/pr838-compat-count.yml b/.github/workflows/pr838-compat-count.yml new file mode 100644 index 000000000000..a44c60a1172d --- /dev/null +++ b/.github/workflows/pr838-compat-count.yml @@ -0,0 +1,58 @@ +name: PR838 compatibility response counter +on: + push: + branches: [maintenance/pr838-compat-count-fix-20261114] + workflow_dispatch: +permissions: + contents: read +concurrency: + group: pr838-compat-count-${{ github.ref }} + cancel-in-progress: true +jobs: + counter: + runs-on: ubuntu-latest + timeout-minutes: 20 + steps: + - uses: actions/checkout@v6 + with: + fetch-depth: 0 + - uses: actions/setup-go@v6 + with: + go-version-file: backend/go.mod + cache-dependency-path: backend/go.sum + - name: Original PR head must fail the retained compatibility regression + shell: bash + run: | + set -euo pipefail + mkdir -p "$RUNNER_TEMP/pr838-counter" + git rev-parse HEAD > "$RUNNER_TEMP/pr838-counter/head.txt" + baseline=d2b2b246fc0235740e87c742b24be5a5c9e055e0 + targets=(backend/internal/service/openai_gateway_cc_pipeline.go backend/internal/service/openai_gateway_upstream_errors.go) + trap 'git restore --source=HEAD -- "${targets[@]}"' EXIT + for target in "${targets[@]}"; do + git show "$baseline:$target" > "$target" + test "$(git hash-object "$target")" = "$(git rev-parse "$baseline:$target")" + done + set +e + (cd backend && go test -tags=unit ./internal/service -run '^TestCompatErrorPipelineCountsEachResponseOnce$' -count=1 -v -timeout=3m) > "$RUNNER_TEMP/pr838-counter/red.log" 2>&1 + result=$? + set -e + cat "$RUNNER_TEMP/pr838-counter/red.log" + test "$result" -eq 1 + ! grep -Eiq 'build failed|undefined:|no tests to run|panic:|--- SKIP:' "$RUNNER_TEMP/pr838-counter/red.log" + grep -q 'same upstream response must be counted once across compatibility handlers' "$RUNNER_TEMP/pr838-counter/red.log" + git restore --source=HEAD -- "${targets[@]}" + trap - EXIT + git diff --exit-code + - name: Fixed compatibility pipeline and existing authentication controls + shell: bash + run: | + set -euo pipefail + (cd backend && go test -race -tags=unit ./internal/service -run '^Test(CompatErrorPipeline|FastPathThenGeneralHandler|PendingModel401|Credential401|OpenAIWSAfterOutput)' -count=1 -v -timeout=5m) 2>&1 | tee "$RUNNER_TEMP/pr838-counter/green.log" + grep -q -- '--- PASS: TestCompatErrorPipelineCountsEachResponseOnce' "$RUNNER_TEMP/pr838-counter/green.log" + ! grep -Eiq 'build failed|undefined:|no tests to run|panic:|--- SKIP:|DATA RACE' "$RUNNER_TEMP/pr838-counter/green.log" + - uses: actions/upload-artifact@v7 + if: always() + with: + name: pr838-compat-counter-${{ github.sha }} + path: ${{ runner.temp }}/pr838-counter/ diff --git a/.github/workflows/pr838-ui-acceptance.yml b/.github/workflows/pr838-ui-acceptance.yml new file mode 100644 index 000000000000..ea136e2a4020 --- /dev/null +++ b/.github/workflows/pr838-ui-acceptance.yml @@ -0,0 +1,117 @@ +name: PR838 isolated administration acceptance +on: + pull_request: + branches: [production] + paths: + - 'frontend/src/components/account/**' + - 'frontend/src/stores/newFeatureNotices.ts' + - 'frontend/src/constants/newFeatureNotices.ts' + - '.github/fixtures/pr838-ui/**' + - '.github/scripts/pr838-ui-*.mjs' + - '.github/workflows/pr838-ui-acceptance.yml' +permissions: + contents: read +concurrency: + group: pr838-ui-${{ github.event.pull_request.number || github.ref }} + cancel-in-progress: true +jobs: + administration: + runs-on: ubuntu-latest + timeout-minutes: 40 + env: + CANDIDATE: ${{ github.event.pull_request.head.sha }} + # Full production frontend before this feature; never overlay components. + BASELINE: b347249687db84dac3f5272189fda6cf86eb9035 + steps: + - uses: actions/checkout@v6 + with: + ref: ${{ env.CANDIDATE }} + fetch-depth: 0 + - uses: actions/checkout@v6 + with: + ref: ${{ env.BASELINE }} + path: .pr838-baseline + - uses: pnpm/action-setup@v6 + with: + version: 9 + - uses: actions/setup-node@v6 + with: + node-version: '22' + cache: pnpm + cache-dependency-path: frontend/pnpm-lock.yaml + - uses: actions/setup-go@v6 + with: + go-version-file: backend/go.mod + cache-dependency-path: backend/go.sum + - name: Configure isolated evidence paths after runner allocation + run: | + printf 'EVIDENCE_DIR=%s/pr838-ui\n' "$RUNNER_TEMP" >> "$GITHUB_ENV" + printf 'SUB2API_PLAYWRIGHT_MODULE=%s/pr838-browser/node_modules/playwright/index.mjs\n' "$RUNNER_TEMP" >> "$GITHUB_ENV" + - name: Prepare exact locked frontend and isolated browser + run: | + set -euo pipefail + mkdir -p "$EVIDENCE_DIR" + git rev-parse HEAD > "$EVIDENCE_DIR/candidate.txt" + git -C .pr838-baseline rev-parse HEAD > "$EVIDENCE_DIR/baseline.txt" + cmp frontend/package.json .pr838-baseline/frontend/package.json + cmp frontend/pnpm-lock.yaml .pr838-baseline/frontend/pnpm-lock.yaml + pnpm --dir frontend install --frozen-lockfile + ln -s "$GITHUB_WORKSPACE/frontend/node_modules" .pr838-baseline/frontend/node_modules + bash .github/scripts/ci-ubuntu-mirrors.sh + # The mirror transport stalled for the whole job while installing + # Chromium dependencies. Use the signed Ubuntu archive directly for + # this isolated runner, and bound each network attempt. + for mirror_list in /etc/apt/apt-mirrors.txt /etc/apt/apt-security-mirrors.txt; do + if [ -f "$mirror_list" ]; then + printf '%s\n' 'https://archive.ubuntu.com/ubuntu' | sudo tee "$mirror_list" >/dev/null + fi + done + printf '%s\n' 'Acquire::http::Timeout "30";' 'Acquire::https::Timeout "30";' 'Acquire::Retries "2";' | sudo tee /etc/apt/apt.conf.d/99-sub2api-ci-timeouts >/dev/null + npm install --prefix "$RUNNER_TEMP/pr838-browser" --no-save --ignore-scripts playwright@1.56.1 + node "$RUNNER_TEMP/pr838-browser/node_modules/playwright/cli.js" install --with-deps chromium + - name: Build complete before and after applications with project Vite and CSS + run: node .github/scripts/pr838-ui-build.mjs + - name: Build isolated real backend and pre-pull dependencies + run: | + set -euo pipefail + mkdir -p "$RUNNER_TEMP/pr838-runtime" + (cd backend && CGO_ENABLED=0 go build -trimpath -ldflags="-X main.Commit=$CANDIDATE" -o "$RUNNER_TEMP/pr838-runtime/server" ./cmd/server) + cp -R backend/resources "$RUNNER_TEMP/pr838-runtime/resources" + docker build -f .github/fixtures/pr838-ui/Dockerfile -t "pr838-ui-app:$CANDIDATE" "$RUNNER_TEMP/pr838-runtime" + docker compose -p pr838-ui -f .github/fixtures/pr838-ui/compose.yml pull postgres redis + docker compose -p pr838-ui -f .github/fixtures/pr838-ui/compose.yml up -d --wait --wait-timeout 300 + docker network inspect pr838-ui_isolated --format '{{json .Internal}}' > "$EVIDENCE_DIR/network-internal.json" + # Reach the isolated bridge directly from its host; published loopback + # ports were refused even after the in-container health check passed. + app_id=$(docker compose -p pr838-ui -f .github/fixtures/pr838-ui/compose.yml ps -q app) + app_ip=$(docker inspect --format '{{range .NetworkSettings.Networks}}{{.IPAddress}}{{end}}' "$app_id") + test -n "$app_ip" + app_origin="http://$app_ip:8080" + docker inspect --format '{{json .NetworkSettings}}' "$app_id" > "$EVIDENCE_DIR/container-network.json" + curl --noproxy '*' --fail --silent --show-error --connect-timeout 3 --max-time 10 --retry 3 --retry-connrefused "$app_origin/health" > "$EVIDENCE_DIR/host-health.json" + printf 'SUB2API_TEST_APP_ORIGIN=%s\n' "$app_origin" >> "$GITHUB_ENV" + - name: Actual administration, HTTP persistence, SQL readback and browser notices + run: | + set -euo pipefail + status=0 + node .github/scripts/pr838-ui-browser.mjs > "$EVIDENCE_DIR/browser.log" 2>&1 || status=$? + printf '%s\n' "$status" > "$EVIDENCE_DIR/browser-exit.txt" + cat "$EVIDENCE_DIR/browser.log" + exit "$status" + - name: Preserve logs and stop only disposable CI installation + if: always() + run: | + mkdir -p "$EVIDENCE_DIR" + docker compose -p pr838-ui -f .github/fixtures/pr838-ui/compose.yml logs --no-color > "$EVIDENCE_DIR/installation.log" 2>&1 + docker compose -p pr838-ui -f .github/fixtures/pr838-ui/compose.yml down -v + - uses: actions/upload-artifact@v7 + if: always() + with: + name: pr838-ui-${{ env.CANDIDATE }}-${{ github.run_attempt }} + path: | + ${{ runner.temp }}/pr838-ui/*.json + ${{ runner.temp }}/pr838-ui/*.txt + ${{ runner.temp }}/pr838-ui/*.log + ${{ runner.temp }}/pr838-ui/*.png + if-no-files-found: error + retention-days: 30 diff --git a/.github/workflows/pr838-ws-phase.yml b/.github/workflows/pr838-ws-phase.yml new file mode 100644 index 000000000000..040767c9ad00 --- /dev/null +++ b/.github/workflows/pr838-ws-phase.yml @@ -0,0 +1,146 @@ +name: PR838 WebSocket output phase +on: + pull_request: + branches: [production] + paths: + - 'backend/internal/service/openai_ws_*.go' + - 'backend/internal/service/temp_unsched*' + - 'backend/internal/service/ratelimit_service.go' + - 'backend/internal/repository/temp_unsched*' + - '.github/workflows/pr838-ws-phase.yml' + - '.github/scripts/pr838-ws-phase-evidence.py' +permissions: + contents: read +concurrency: + group: pr838-ws-phase-${{ github.event.pull_request.number || github.ref }} + cancel-in-progress: true +jobs: + forwarding: + runs-on: ubuntu-latest + timeout-minutes: 25 + strategy: + fail-fast: false + matrix: + behavior: [red, green] + env: + CANDIDATE: ${{ github.event.pull_request.head.sha }} + BEHAVIOR: ${{ matrix.behavior }} + steps: + - uses: actions/checkout@v6 + with: + ref: ${{ github.event.pull_request.head.sha }} + fetch-depth: 0 + - uses: actions/setup-go@v6 + with: + go-version-file: backend/go.mod + cache-dependency-path: backend/go.sum + - name: Exact candidate tests and bounded historical production sources + shell: bash + run: | + set -euo pipefail + mkdir -p evidence + test "$(git rev-parse HEAD)" = "$CANDIDATE" + git diff --exit-code + git rev-parse HEAD HEAD^{tree} > evidence/candidate.txt + baseline=cf2c96ddf377e60a3df7fdd636c37669d6167d17 + for target in backend/internal/service/openai_ws_forwarder_v2.go backend/internal/service/openai_ws_forwarder_ingress.go; do + original=$(git rev-parse "$baseline:$target") + candidate=$(git rev-parse "$CANDIDATE:$target") + if [ "$BEHAVIOR" = red ]; then git show "$baseline:$target" > "$target"; fi + actual=$(git hash-object "$target") + expected="$candidate" + if [ "$BEHAVIOR" = red ]; then expected="$original"; fi + test "$actual" = "$expected" + printf '%s baseline=%s candidate=%s actual=%s\n' "$target" "$original" "$candidate" "$actual" >> evidence/source-blobs.txt + done + git diff --exit-code -- '*_test.go' + target=backend/internal/service/temp_unsched_ws_forward_test.go + expected=$(git rev-parse "$CANDIDATE:$target") + test "$(git hash-object "$target")" = "$expected" + printf '%s %s\n' "$expected" "$target" > evidence/retained-tests.txt + printf 'No tests excluded; only the two listed production files restored in RED.\n' > evidence/compilation-boundary.txt + git diff --stat > evidence/source-diff.txt + - name: Real forwarding entries with race and unchanged safety controls + shell: bash + run: | + set -euo pipefail + regression='^TestTempUnschedWSForwardAfterOutputSemantic429$' + if [ "$BEHAVIOR" = green ]; then + regression='^Test(TempUnschedWSForwardAfterOutputSemantic429|CompatErrorPipeline|FastPathThenGeneralHandler|PendingModel401|Credential401|OpenAIWSAfterOutput|MemoryTempUnschedTrigger|OAuth429WeeklyOnly)' + fi + printf 'cd backend && go test -race -json -tags=unit ./internal/service -run %q -count=1 -timeout=10m\n' "$regression" > evidence/command.txt + set +e + (cd backend && go test -race -json -tags=unit ./internal/service -run "$regression" -count=1 -timeout=10m) > "evidence/$BEHAVIOR.jsonl" 2> "evidence/$BEHAVIOR.stderr" + result=$? + set -e + printf '%s\n' "$result" > evidence/exit.txt + python3 .github/scripts/pr838-ws-phase-evidence.py "$BEHAVIOR" "evidence/$BEHAVIOR.jsonl" "$result" + - uses: actions/upload-artifact@v7 + if: always() + with: + name: pr838-ws-phase-${{ matrix.behavior }}-${{ github.event.pull_request.head.sha }} + path: evidence/ + if-no-files-found: error + + redis-interleave: + runs-on: ubuntu-latest + timeout-minutes: 25 + services: + postgres: + image: postgres:18.1-alpine3.23 + env: + POSTGRES_USER: postgres + POSTGRES_PASSWORD: postgres + POSTGRES_DB: sub2api_test + ports: + - 5432:5432 + options: >- + --health-cmd "pg_isready -U postgres -d sub2api_test" + --health-interval 5s + --health-timeout 5s + --health-retries 12 + redis: + image: redis:8.4-alpine + ports: + - 6379:6379 + options: >- + --health-cmd "redis-cli ping" + --health-interval 5s + --health-timeout 5s + --health-retries 12 + env: + CI: 'true' + SUB2API_TEST_POSTGRES_DSN: 'host=127.0.0.1 port=5432 dbname=sub2api_test user=postgres password=postgres sslmode=disable TimeZone=UTC' + SUB2API_TEST_REDIS_URL: 'redis://127.0.0.1:6379/0' + steps: + - uses: actions/checkout@v6 + with: + ref: ${{ github.event.pull_request.head.sha }} + - uses: actions/setup-go@v6 + with: + go-version-file: backend/go.mod + cache-dependency-path: backend/go.sum + - name: Real Redis instances, PostgreSQL persistence and delayed Reset + shell: bash + env: + EXPECTED_HEAD: ${{ github.event.pull_request.head.sha }} + run: | + set -euo pipefail + mkdir -p evidence + test "$(git rev-parse HEAD)" = "$EXPECTED_HEAD" + git rev-parse HEAD > evidence/head.txt + set +e + (cd backend && go test -race -tags=integration ./internal/repository -run '^TestTempUnschedRealRedisCrossInstancePersistAndDelayedReset$' -count=1 -v -timeout=5m) > evidence/redis-interleave.log 2>&1 + result=$? + set -e + cat evidence/redis-interleave.log + printf '%s\n' "$result" > evidence/exit.txt + test "$result" -eq 0 + if grep -Eiq -- '--- SKIP:|no tests to run|WARNING: DATA RACE|panic:|fatal error:' evidence/redis-interleave.log; then exit 1; fi + grep -q -- '--- PASS: TestTempUnschedRealRedisCrossInstancePersistAndDelayedReset' evidence/redis-interleave.log + - uses: actions/upload-artifact@v7 + if: always() + with: + name: pr838-real-redis-${{ github.event.pull_request.head.sha }} + path: evidence/ + if-no-files-found: error diff --git a/backend/cmd/server/wire_gen.go b/backend/cmd/server/wire_gen.go index 22c81856778d..80007197c510 100644 --- a/backend/cmd/server/wire_gen.go +++ b/backend/cmd/server/wire_gen.go @@ -146,7 +146,8 @@ func initializeApplication(buildInfo handler.BuildInfo) (*Application, error) { httpUpstream := repository.ProvideHTTPUpstream(configConfig, settingService) leaderLockCache := repository.NewLeaderLockCache(redisClient) ollamaCloudUsageService := service.ProvideOllamaCloudUsageService(accountRepository, httpUpstream, settingService, secretEncryptor, configConfig, leaderLockCache, db) - rateLimitService := service.ProvideRateLimitService(accountRepository, usageLogRepository, configConfig, geminiQuotaService, tempUnschedCache, timeoutCounterCache, openAI403CounterCache, settingService, compositeTokenCacheInvalidator, ollamaCloudUsageService, accountOpsService, redisClient) + tempUnschedTriggerCounter := repository.NewTempUnschedTriggerCounter(redisClient) + rateLimitService := service.ProvideRateLimitService(accountRepository, usageLogRepository, configConfig, geminiQuotaService, tempUnschedCache, timeoutCounterCache, openAI403CounterCache, settingService, compositeTokenCacheInvalidator, ollamaCloudUsageService, accountOpsService, tempUnschedTriggerCounter, redisClient) identityCache := repository.NewIdentityCache(redisClient) identityService := service.NewIdentityService(identityCache) timingWheelService, err := service.ProvideTimingWheelService() diff --git a/backend/internal/handler/openai_issue805_owner_policy_test.go b/backend/internal/handler/openai_issue805_owner_policy_test.go index a1d76e71976d..bf54ba14623d 100644 --- a/backend/internal/handler/openai_issue805_owner_policy_test.go +++ b/backend/internal/handler/openai_issue805_owner_policy_test.go @@ -80,6 +80,28 @@ func issue805Owners(t *testing.T, client *redis.Client) map[string]string { return result } +// GJSON Get deliberately scans through an invalid prefix to the first array. +// A pending::[1,account,...] fence therefore exposes the same account ID +// as a committed record. Only a complete JSON route may seed a stable snapshot. +func issue805CompletedOwner(raw string, accountID int64) bool { + if !json.Valid([]byte(raw)) { + return false + } + record := gjson.Parse(raw) + return record.IsArray() && len(record.Array()) == 4 && record.Get("0").Int() == 1 && record.Get("1").Int() == accountID +} + +func TestIssue805OwnerSnapshotRequiresCommittedRecord(t *testing.T) { + route := `[1,1,"` + strings.Repeat("a", 64) + `","` + strings.Repeat("b", 64) + `"]` + pending := "pending:fixture-token:" + route + require.EqualValues(t, 1, gjson.Get(pending, "1").Int(), "the old account-only predicate accepts an unfinished fence") + require.False(t, issue805CompletedOwner(pending, 1), "pending ownership must never be captured as the immutable original route") + require.False(t, issue805CompletedOwner("failed", 1)) + require.False(t, issue805CompletedOwner("conflict", 1)) + require.False(t, issue805CompletedOwner(route, 2)) + require.True(t, issue805CompletedOwner(route, 1)) +} + func TestIssue805HTTPCompletedHistorySelectsAlternative(t *testing.T) { for _, stream := range []bool{false, true} { t.Run(fmt.Sprint("stream=", stream), func(t *testing.T) { diff --git a/backend/internal/handler/openai_issue805_ws_test.go b/backend/internal/handler/openai_issue805_ws_test.go index 142c6d0ca8e3..fc61397ce89d 100644 --- a/backend/internal/handler/openai_issue805_ws_test.go +++ b/backend/internal/handler/openai_issue805_ws_test.go @@ -149,7 +149,7 @@ func TestIssue805WSCompletedHistoryAcrossNodesAndTurns(t *testing.T) { return false } for _, raw := range owners { - if gjson.Get(raw, "1").Int() != 1 { + if !issue805CompletedOwner(raw, 1) { return false } } @@ -162,6 +162,7 @@ func TestIssue805WSCompletedHistoryAcrossNodesAndTurns(t *testing.T) { answer := issue715WSRead(t, consumer.clientConn) require.Equal(t, "response.completed", gjson.GetBytes(answer, "type").String(), string(answer)) require.Contains(t, string(answer), "existing ledger balance 18") + require.Contains(t, string(answer), "fixture-task-produced-by-B", "the ownership assertion requires an actually delivered new B item") require.Eventually(t, func() bool { owners := issue805Owners(t, probe) if len(owners) != 2 { @@ -172,7 +173,7 @@ func TestIssue805WSCompletedHistoryAcrossNodesAndTurns(t *testing.T) { if raw != old { return false } - } else if gjson.Get(raw, "1").Int() != 2 { + } else if !issue805CompletedOwner(raw, 2) { return false } } @@ -290,7 +291,7 @@ func TestIssue805WSRejectsUnsafeHistoryBeforeNetworkSend(t *testing.T) { return false } for _, raw := range owners { - if gjson.Get(raw, "1").Int() != 1 { + if !issue805CompletedOwner(raw, 1) { return false } } @@ -371,7 +372,7 @@ func TestIssue805WSNewBOutputWaitsForCrossNodeCommit(t *testing.T) { return false } for _, raw := range owners { - if gjson.Get(raw, "1").Int() != 1 { + if !issue805CompletedOwner(raw, 1) { return false } } @@ -427,7 +428,7 @@ func TestIssue805WSNewBOutputWaitsForCrossNodeCommit(t *testing.T) { if old, found := original[key]; found { require.Equal(t, old, raw) } else { - require.EqualValues(t, 2, gjson.Get(raw, "1").Int(), "new output must retain real B after commit") + require.True(t, issue805CompletedOwner(raw, 2), "new output must retain committed real B after commit: %s", raw) } } }) diff --git a/backend/internal/repository/temp_unsched_real_redis_integration_test.go b/backend/internal/repository/temp_unsched_real_redis_integration_test.go new file mode 100644 index 000000000000..11d4af8dd068 --- /dev/null +++ b/backend/internal/repository/temp_unsched_real_redis_integration_test.go @@ -0,0 +1,132 @@ +//go:build integration + +package repository + +import ( + "context" + "encoding/json" + "net/http" + "sync/atomic" + "testing" + "time" + + "github.com/Wei-Shaw/sub2api/internal/config" + "github.com/Wei-Shaw/sub2api/internal/service" + "github.com/redis/go-redis/v9" + "github.com/stretchr/testify/require" +) + +type tempUnschedPersistedRepo struct { + service.AccountRepository + writes atomic.Int64 +} + +func (r *tempUnschedPersistedRepo) SetModelRateLimit(ctx context.Context, id int64, model string, until time.Time, reason ...string) error { + if err := r.AccountRepository.SetModelRateLimit(ctx, id, model, until, reason...); err != nil { + return err + } + r.writes.Add(1) + return nil +} + +type tempUnschedResetCall struct{ key, epoch string } + +type tempUnschedDelayedReset struct { + service.TempUnschedTriggerCounter + entered chan tempUnschedResetCall + release <-chan struct{} +} + +func (c *tempUnschedDelayedReset) Reset(ctx context.Context, key, epoch string) error { + c.entered <- tempUnschedResetCall{key, epoch} + select { + case <-c.release: + return c.TempUnschedTriggerCounter.Reset(ctx, key, epoch) + case <-ctx.Done(): + return ctx.Err() + } +} + +// Independent service/counter/repository instances share real Redis and real +// PostgreSQL. The barrier is after A's durable write, immediately before its +// Reset; B completes the same round and starts another before A is released. +func TestTempUnschedRealRedisCrossInstancePersistAndDelayedReset(t *testing.T) { + ctx, cancel := context.WithTimeout(t.Context(), 15*time.Second) + defer cancel() + account := mustCreateAccount(t, testEntClient(t), &service.Account{ + Name: "fictional-temp-unsched-interleave", Platform: service.PlatformOpenAI, + Type: service.AccountTypeAPIKey, Status: service.StatusActive, Schedulable: true, Concurrency: 1, + Credentials: map[string]any{ + "api_key": "fictional-key", "temp_unschedulable_enabled": true, + "temp_unschedulable_rules": []any{map[string]any{ + "error_code": 502, "keywords": []any{"bad gateway"}, "scope": "model", + "duration_minutes": 5, "trigger_count": 2, "trigger_window_minutes": 5, + }}, + }, + }) + t.Cleanup(func() { + _, _ = integrationDB.ExecContext(context.Background(), "DELETE FROM scheduler_outbox WHERE account_id=$1", account.ID) + _, _ = integrationDB.ExecContext(context.Background(), "DELETE FROM accounts WHERE id=$1", account.ID) + }) + optionsA, optionsB := *integrationRedis.Options(), *integrationRedis.Options() + clientA, clientB := redis.NewClient(&optionsA), redis.NewClient(&optionsB) + t.Cleanup(func() { _ = clientA.Close(); _ = clientB.Close() }) + require.NoError(t, clientA.Ping(ctx).Err()) + require.NoError(t, clientB.Ping(ctx).Err()) + repoA := &tempUnschedPersistedRepo{AccountRepository: NewAccountRepository(integrationEntClient, integrationDB, nil)} + repoB := &tempUnschedPersistedRepo{AccountRepository: NewAccountRepository(integrationEntClient, integrationDB, nil)} + account, err := repoA.GetByID(ctx, account.ID) + require.NoError(t, err) + ratesA := service.NewRateLimitService(repoA, nil, &config.Config{}, nil, nil) + ratesB := service.NewRateLimitService(repoB, nil, &config.Config{}, nil, nil) + release := make(chan struct{}) + defer close(release) + barrier := &tempUnschedDelayedReset{TempUnschedTriggerCounter: NewTempUnschedTriggerCounter(clientA), entered: make(chan tempUnschedResetCall, 1), release: release} + ratesA.SetTempUnschedTriggerCounter(barrier) + ratesB.SetTempUnschedTriggerCounter(NewTempUnschedTriggerCounter(clientB)) + body := []byte(`{"error":{"message":"bad gateway"}}`) + require.False(t, ratesA.HandleUpstreamError(ctx, account, http.StatusBadGateway, nil, body, "gpt-5.1")) + finishedA := make(chan bool, 1) + go func() { + finishedA <- ratesA.HandleUpstreamError(ctx, account, http.StatusBadGateway, nil, body, "gpt-5.1") + }() + var old tempUnschedResetCall + select { + case old = <-barrier.entered: + case <-ctx.Done(): + t.Fatal("A did not reach Reset after its threshold/persistence boundary") + } + t.Cleanup(func() { _ = clientB.Del(context.Background(), old.key, old.key+":epoch").Err() }) + require.EqualValues(t, 1, repoA.writes.Load(), "A must durably persist before the Reset barrier") + var reason, status string + var schedulable bool + require.NoError(t, integrationDB.QueryRowContext(ctx, `SELECT extra->'model_rate_limits'->'gpt-5.1'->>'reason',status,schedulable FROM accounts WHERE id=$1`, account.ID).Scan(&reason, &status, &schedulable)) + var state map[string]any + require.NoError(t, json.Unmarshal([]byte(reason), &state)) + require.Equal(t, float64(2), state["trigger_count"]) + require.Equal(t, service.StatusActive, status) + require.True(t, schedulable) + // Another already in-flight failure completes the old epoch and deletes it. + require.True(t, ratesB.HandleUpstreamError(ctx, account, http.StatusBadGateway, nil, body, "gpt-5.1")) + require.EqualValues(t, 1, repoB.writes.Load()) + // A later in-flight failure begins a new epoch while A is still paused. + require.False(t, ratesB.HandleUpstreamError(ctx, account, http.StatusBadGateway, nil, body, "gpt-5.1")) + newEpoch, err := clientB.Get(ctx, old.key+":epoch").Result() + require.NoError(t, err) + require.NotEqual(t, old.epoch, newEpoch) + require.Equal(t, "1", clientB.Get(ctx, old.key).Val()) + // Release only A's old Reset; it must leave B's new round intact. + release <- struct{}{} + select { + case triggered := <-finishedA: + require.True(t, triggered) + case <-ctx.Done(): + t.Fatal("A's delayed Reset did not finish") + } + require.Equal(t, "1", clientB.Get(ctx, old.key).Val(), "old Reset must not delete a new Redis round") + require.Equal(t, newEpoch, clientB.Get(ctx, old.key+":epoch").Val()) + require.True(t, ratesB.HandleUpstreamError(ctx, account, http.StatusBadGateway, nil, body, "gpt-5.1")) + require.EqualValues(t, 2, repoB.writes.Load(), "the retained new round must reach its real persistence threshold") + require.EqualValues(t, 0, clientB.Exists(ctx, old.key, old.key+":epoch").Val()) + t.Log("real Redis: two independent clients/services; real PostgreSQL threshold writes; old Reset cannot erase the new epoch") +} diff --git a/backend/internal/repository/temp_unsched_trigger_counter.go b/backend/internal/repository/temp_unsched_trigger_counter.go new file mode 100644 index 000000000000..1ddbca85ee67 --- /dev/null +++ b/backend/internal/repository/temp_unsched_trigger_counter.go @@ -0,0 +1,136 @@ +package repository + +import ( + "context" + "fmt" + + "github.com/Wei-Shaw/sub2api/internal/service" + "github.com/redis/go-redis/v9" +) + +// tempUnschedTriggerIncrScript 在固定窗口内原子递增,并返回这一轮的 epoch。 +// 第一次写入同时记下 epoch 和 TTL。窗口到期后两个键一起消失,下一次从 1 重新计数。 +// epoch 缺失而计数还在时补一个新 epoch,不把已有计数清掉。 +var tempUnschedTriggerIncrScript = redis.NewScript(` + local key = KEYS[1] + local epochKey = KEYS[2] + local ttl = tonumber(ARGV[1]) + + local count = redis.call('INCR', key) + local epoch = redis.call('GET', epochKey) + if count == 1 or not epoch then + local now = redis.call('TIME') + epoch = now[1] .. ':' .. now[2] .. ':' .. tostring(math.random(1000000, 9999999)) + local epochTTL = ttl + if count ~= 1 then + local remain = redis.call('TTL', key) + if remain and remain > 0 then + epochTTL = remain + end + else + redis.call('EXPIRE', key, ttl) + end + redis.call('SET', epochKey, epoch, 'EX', epochTTL) + end + + return {count, epoch} +`) + +// tempUnschedTriggerResetScript 只删除仍属于这一轮的计数。 +// 冷却写入之后如果又开了新一轮,旧 epoch 的 Reset 必须留下新计数。 +var tempUnschedTriggerResetScript = redis.NewScript(` + local key = KEYS[1] + local epochKey = KEYS[2] + local epoch = ARGV[1] + local current = redis.call('GET', epochKey) + if current and current == epoch then + redis.call('DEL', key, epochKey) + return 1 + end + return 0 +`) + +type tempUnschedTriggerCounter struct { + rdb *redis.Client +} + +// NewTempUnschedTriggerCounter 创建跨实例共享的临时不可调度触发计数器。 +// rdb 为空时返回 nil,调用方改用进程内计数。 +func NewTempUnschedTriggerCounter(rdb *redis.Client) service.TempUnschedTriggerCounter { + if rdb == nil { + return nil + } + return &tempUnschedTriggerCounter{rdb: rdb} +} + +func tempUnschedTriggerEpochKey(key string) string { + return key + ":epoch" +} + +func (c *tempUnschedTriggerCounter) Increment(ctx context.Context, key string, windowMinutes int) (int64, string, error) { + if c == nil || c.rdb == nil { + return 0, "", fmt.Errorf("temp unsched trigger counter is nil") + } + if windowMinutes < 1 { + windowMinutes = 1 + } + ttlSeconds := windowMinutes * 60 + if ttlSeconds < 60 { + ttlSeconds = 60 + } + values, err := tempUnschedTriggerIncrScript.Run(ctx, c.rdb, []string{key, tempUnschedTriggerEpochKey(key)}, ttlSeconds).Slice() + if err != nil { + return 0, "", fmt.Errorf("increment temp unsched trigger count: %w", err) + } + if len(values) != 2 { + return 0, "", fmt.Errorf("increment temp unsched trigger count: unexpected redis reply") + } + count, err := redisReplyInt64(values[0]) + if err != nil { + return 0, "", fmt.Errorf("increment temp unsched trigger count: %w", err) + } + epoch, err := redisReplyString(values[1]) + if err != nil || epoch == "" { + return 0, "", fmt.Errorf("increment temp unsched trigger count: missing epoch") + } + return count, epoch, nil +} + +func (c *tempUnschedTriggerCounter) Reset(ctx context.Context, key string, epoch string) error { + if c == nil || c.rdb == nil { + return fmt.Errorf("temp unsched trigger counter is nil") + } + if epoch == "" { + return nil + } + if err := tempUnschedTriggerResetScript.Run(ctx, c.rdb, []string{key, tempUnschedTriggerEpochKey(key)}, epoch).Err(); err != nil { + return fmt.Errorf("reset temp unsched trigger count: %w", err) + } + return nil +} + +func redisReplyInt64(value any) (int64, error) { + switch typed := value.(type) { + case int64: + return typed, nil + case int: + return int64(typed), nil + case string: + var parsed int64 + _, err := fmt.Sscan(typed, &parsed) + return parsed, err + default: + return 0, fmt.Errorf("unexpected integer reply %T", value) + } +} + +func redisReplyString(value any) (string, error) { + switch typed := value.(type) { + case string: + return typed, nil + case []byte: + return string(typed), nil + default: + return "", fmt.Errorf("unexpected string reply %T", value) + } +} diff --git a/backend/internal/repository/temp_unsched_trigger_counter_test.go b/backend/internal/repository/temp_unsched_trigger_counter_test.go new file mode 100644 index 000000000000..7accae38e1bc --- /dev/null +++ b/backend/internal/repository/temp_unsched_trigger_counter_test.go @@ -0,0 +1,75 @@ +//go:build unit + +package repository + +import ( + "context" + "testing" + "time" + + "github.com/alicebob/miniredis/v2" + "github.com/redis/go-redis/v9" + "github.com/stretchr/testify/require" +) + +func TestTempUnschedTriggerCounterWindowAndReset(t *testing.T) { + server := miniredis.RunT(t) + server.SetTime(time.Unix(1_700_000_000, 0)) + client := redis.NewClient(&redis.Options{Addr: server.Addr()}) + t.Cleanup(func() { _ = client.Close() }) + counter := NewTempUnschedTriggerCounter(client) + require.NotNil(t, counter) + ctx := context.Background() + + key := "temp_unsched_trigger:7:0:account" + first, epoch, err := counter.Increment(ctx, key, 2) + require.NoError(t, err) + require.Equal(t, int64(1), first) + require.NotEmpty(t, epoch) + second, sameEpoch, err := counter.Increment(ctx, key, 2) + require.NoError(t, err) + require.Equal(t, int64(2), second) + require.Equal(t, epoch, sameEpoch) + + require.NoError(t, counter.Reset(ctx, key, epoch)) + restarted, restartedEpoch, err := counter.Increment(ctx, key, 2) + require.NoError(t, err) + require.Equal(t, int64(1), restarted) + require.NotEqual(t, epoch, restartedEpoch) + + server.FastForward(3 * time.Minute) + expired, _, err := counter.Increment(ctx, key, 2) + require.NoError(t, err) + require.Equal(t, int64(1), expired, "the fixed window expires and the next match starts a new count") +} + +func TestTempUnschedTriggerCounterDelayedResetKeepsNewRound(t *testing.T) { + server := miniredis.RunT(t) + client := redis.NewClient(&redis.Options{Addr: server.Addr()}) + t.Cleanup(func() { _ = client.Close() }) + counter := NewTempUnschedTriggerCounter(client) + ctx := context.Background() + key := "temp_unsched_trigger:9:1:model:gpt-5.4" + + _, oldEpoch, err := counter.Increment(ctx, key, 5) + require.NoError(t, err) + count, sameEpoch, err := counter.Increment(ctx, key, 5) + require.NoError(t, err) + require.Equal(t, int64(2), count) + require.Equal(t, oldEpoch, sameEpoch) + + require.NoError(t, counter.Reset(ctx, key, oldEpoch)) + next, newEpoch, err := counter.Increment(ctx, key, 5) + require.NoError(t, err) + require.Equal(t, int64(1), next) + require.NotEqual(t, oldEpoch, newEpoch) + + require.NoError(t, counter.Reset(ctx, key, oldEpoch)) + afterStaleReset, _, err := counter.Increment(ctx, key, 5) + require.NoError(t, err) + require.Equal(t, int64(2), afterStaleReset, "a delayed reset from the previous round must not delete the new count") +} + +func TestNewTempUnschedTriggerCounterNilRedis(t *testing.T) { + require.Nil(t, NewTempUnschedTriggerCounter(nil)) +} diff --git a/backend/internal/repository/wire.go b/backend/internal/repository/wire.go index 12e16cb1f88b..b9d01871710e 100644 --- a/backend/internal/repository/wire.go +++ b/backend/internal/repository/wire.go @@ -144,6 +144,7 @@ var ProviderSet = wire.NewSet( NewBillingCache, NewAPIKeyCache, NewTempUnschedCache, + NewTempUnschedTriggerCounter, NewTimeoutCounterCache, NewOpenAI403CounterCache, NewInternal500CounterCache, diff --git a/backend/internal/service/account.go b/backend/internal/service/account.go index 2698787724e8..53b99a067875 100644 --- a/backend/internal/service/account.go +++ b/backend/internal/service/account.go @@ -163,6 +163,16 @@ const ( TempUnschedScopeModel = "model" ) +// 临时不可调度规则在 accounts.credentials.temp_unschedulable_rules 中的流触发时机。 +// 缺省(空字符串)保持历史行为,见 TempUnschedulableRule.StreamTiming。 +const ( + // TempUnschedStreamBefore 只匹配流开始前的 HTTP 错误,不处理流已经开始后的失败。 + TempUnschedStreamBefore = "before_stream" + // TempUnschedStreamAfter 同时匹配流开始前的 HTTP 错误和流开始后的失败 + // (包括 OpenAI 中途 502 / 通用 upstream_error,且规则 error_code 为 502 时)。 + TempUnschedStreamAfter = "after_stream" +) + type TempUnschedulableRule struct { ErrorCode int `json:"error_code"` Keywords []string `json:"keywords"` @@ -171,6 +181,34 @@ type TempUnschedulableRule struct { // Scope 决定命中后的隔离粒度:account 暂停整个账号,model 只冷却本次请求的模型。 // 为空时模型已知且非 401 走模型级,否则账号级。 Scope string `json:"scope,omitempty"` + // StreamTiming 是 credentials JSON 键 stream_timing。 + // "" / 省略:兼容旧规则。流开始前的 HTTP 错误可匹配;流中途仅 401、凭据类 403、 + // 429、容量降载 503、529 可匹配。中途 502 / 通用 upstream_error 不匹配。 + // "before_stream":仅流开始前的 HTTP 错误。 + // "after_stream":流开始前和流开始后都可以,包括中途 502。 + StreamTiming string `json:"stream_timing,omitempty"` + // TriggerCount 是 credentials JSON 键 trigger_count:错误计数窗口内需要多少次匹配才冷却。 + // 省略或小于 1 按 1 处理(第一次匹配即触发,与旧行为一致)。 + TriggerCount int `json:"trigger_count,omitempty"` + // TriggerWindow 是 credentials JSON 键 trigger_window_minutes:从第一次匹配起累计次数的时间窗口。 + // 与 duration_minutes(冷却触发后暂停调度多久)相互独立。省略或小于 1 按 1 分钟处理,不借用 duration_minutes。 + TriggerWindow int `json:"trigger_window_minutes,omitempty"` +} + +// NormalizedTriggerCount 返回至少为 1 的触发次数。 +func (r TempUnschedulableRule) NormalizedTriggerCount() int { + if r.TriggerCount < 1 { + return 1 + } + return r.TriggerCount +} + +// TriggerWindowMinutes 返回错误计数窗口(分钟),至少 1 分钟。 +func (r TempUnschedulableRule) TriggerWindowMinutes() int { + if r.TriggerWindow < 1 { + return 1 + } + return r.TriggerWindow } func (a *Account) IsActive() bool { @@ -538,6 +576,9 @@ func (a *Account) GetTempUnschedulableRules() []TempUnschedulableRule { DurationMinutes: parseTempUnschedInt(entry["duration_minutes"]), Description: parseTempUnschedString(entry["description"]), Scope: normalizeTempUnschedScope(entry["scope"]), + StreamTiming: normalizeTempUnschedStreamTiming(entry["stream_timing"]), + TriggerCount: parseTempUnschedInt(entry["trigger_count"]), + TriggerWindow: parseTempUnschedInt(entry["trigger_window_minutes"]), } if rule.ErrorCode <= 0 || rule.DurationMinutes <= 0 || len(rule.Keywords) == 0 { @@ -562,6 +603,19 @@ func normalizeTempUnschedScope(raw any) string { } } +// normalizeTempUnschedStreamTiming 只认 before_stream / after_stream。 +// 缺省和无法识别的值都视为旧规则(空字符串),以保留历史中途匹配行为。 +func normalizeTempUnschedStreamTiming(raw any) string { + switch strings.ToLower(strings.TrimSpace(parseTempUnschedString(raw))) { + case TempUnschedStreamBefore: + return TempUnschedStreamBefore + case TempUnschedStreamAfter: + return TempUnschedStreamAfter + default: + return "" + } +} + func parseTempUnschedString(value any) string { s, ok := value.(string) if !ok { diff --git a/backend/internal/service/gateway_forward.go b/backend/internal/service/gateway_forward.go index 03f5ca93f3b7..089a2c6a158a 100644 --- a/backend/internal/service/gateway_forward.go +++ b/backend/internal/service/gateway_forward.go @@ -1030,9 +1030,32 @@ func (s *GatewayService) isStickyAccountUpstreamRestricted(ctx context.Context, return s.isUpstreamModelRestrictedByChannel(ctx, *groupID, account, requestedModel) } +// anthropicStreamErrorStatus 把 Claude SSE error.type 映射到临时不可调度规则使用的状态码。 +// 无法识别的类型返回 0,避免用臆造状态码误匹配规则。 +func anthropicStreamErrorStatus(body []byte) int { + switch strings.TrimSpace(gjson.GetBytes(body, "error.type").String()) { + case "overloaded_error": + return 529 + case "rate_limit_error": + return http.StatusTooManyRequests + case "authentication_error": + return http.StatusUnauthorized + case "permission_error": + return http.StatusForbidden + case "api_error": + return http.StatusInternalServerError + case "timeout_error": + return http.StatusGatewayTimeout + default: + return 0 + } +} + // sseStreamErrorEventFailover 把上游 HTTP 200 + SSE 流体内的 event:error 帧转为 // UpstreamFailoverError:尚未向客户端写出内容且错误类型为 overloaded_error 时按 529 // 处理并触发账号侧副作用,其余按 403;同时登记 stream_error 运维记录。 +// 客户端已经开始收到内容后,默认不触发临时不可调度;只有 stream_timing=after_stream +// 的规则可以按上面的语义状态码匹配。 func (s *GatewayService) sseStreamErrorEventFailover(ctx context.Context, c *gin.Context, account *Account, resp *http.Response, rawData, model string, outputStarted bool) *UpstreamFailoverError { body := []byte(rawData) semanticStatus := http.StatusForbidden @@ -1044,6 +1067,11 @@ func (s *GatewayService) sseStreamErrorEventFailover(ctx context.Context, c *gin Body: io.NopCloser(bytes.NewReader(body)), } s.handleFailoverSideEffects(ctx, syntheticResp, account, model) + } else if outputStarted && s != nil && s.rateLimitService != nil && account != nil { + if status := anthropicStreamErrorStatus(body); status > 0 { + phaseCtx := withTempUnschedStreamPhase(ctx, tempUnschedPhaseMidStreamOptIn) + _ = s.rateLimitService.attemptTempUnschedulable(phaseCtx, account, status, body, model) + } } upstreamMsg := sanitizeUpstreamErrorMessage( diff --git a/backend/internal/service/openai_account_runtime_block_fastpath.go b/backend/internal/service/openai_account_runtime_block_fastpath.go index 8413af0ebd43..7cbec892af19 100644 --- a/backend/internal/service/openai_account_runtime_block_fastpath.go +++ b/backend/internal/service/openai_account_runtime_block_fastpath.go @@ -160,6 +160,9 @@ func (s *OpenAIGatewayService) handleOpenAIAccountUpstreamError(ctx context.Cont } stateCtx, cancel := openAIAccountStateContext(ctx) defer cancel() + // Fastpath 和后面的通用错误处理会各自判断临时不可调度。绑在同一次 + // stateCtx 上,一条上游错误只会计数一次。 + stateCtx = bindTempUnschedAttempt(stateCtx) if s != nil { stateCtx = s.rateLimitService.observeAccountOps(stateCtx, account, statusCode, headers, responseBody) } diff --git a/backend/internal/service/openai_gateway_cc_pipeline.go b/backend/internal/service/openai_gateway_cc_pipeline.go index 7507be4cc2ae..692f217ee500 100644 --- a/backend/internal/service/openai_gateway_cc_pipeline.go +++ b/backend/internal/service/openai_gateway_cc_pipeline.go @@ -93,6 +93,24 @@ func (s *OpenAIGatewayService) readOpenAIUpstreamErrorWithCompleteness(resp *htt // failoverOpenAIUpstreamHTTPError 对 >=400 的上游响应做 failover 判定:命中时 // 记录 ops 事件、执行账号级错误处置并返回 *UpstreamFailoverError;未命中返回 // nil,调用方继续走各自端点格式的非 failover 错误处理链。 +const openAICompatTempUnschedAttemptKey = "openai_compat_temp_unsched_attempt" + +type openAICompatTempUnschedAttempt struct { + response *http.Response + accountID int64 + memo *tempUnschedAttemptMemo +} + +func openAICompatTempUnschedContext(c *gin.Context, response *http.Response, account *Account) context.Context { + ctx := c.Request.Context() + value, _ := c.Get(openAICompatTempUnschedAttemptKey) + checked, ok := value.(*openAICompatTempUnschedAttempt) + if ok && checked.response == response && account != nil && checked.accountID == account.ID { + return context.WithValue(ctx, tempUnschedAttemptMemoKey{}, checked.memo) + } + return ctx +} + func (s *OpenAIGatewayService) failoverOpenAIUpstreamHTTPError( ctx context.Context, c *gin.Context, @@ -105,6 +123,12 @@ func (s *OpenAIGatewayService) failoverOpenAIUpstreamHTTPError( shouldFailover := s.shouldFailoverOpenAIUpstreamResponse(account, resp.StatusCode, upstreamMsg, respBody) tempUnscheduled := false if c != nil && account != nil && account.Platform != PlatformGrok && !shouldFailover && !IsResponseCommitted(c) && s.rateLimitService != nil { + // The compatibility error writer processes this same response next if + // the threshold is pending. Share only this response's evaluation; + // another upstream attempt must receive its own counter observation. + memo := &tempUnschedAttemptMemo{} + ctx = context.WithValue(ctx, tempUnschedAttemptMemoKey{}, memo) + c.Set(openAICompatTempUnschedAttemptKey, &openAICompatTempUnschedAttempt{response: resp, accountID: account.ID, memo: memo}) tempUnscheduled = s.rateLimitService.CheckErrorPolicy(ctx, account, resp.StatusCode, respBody, upstreamModel) == ErrorPolicyTempUnscheduled shouldFailover = tempUnscheduled } diff --git a/backend/internal/service/openai_gateway_passthrough.go b/backend/internal/service/openai_gateway_passthrough.go index 7185dbdd4571..3399d77fd66b 100644 --- a/backend/internal/service/openai_gateway_passthrough.go +++ b/backend/internal/service/openai_gateway_passthrough.go @@ -1859,6 +1859,7 @@ func (s *OpenAIGatewayService) handleOpenAIStreamTerminalAccountSideEffectsWithC if isGrokContentPolicyRejection(http.StatusForbidden, payload) { return http.StatusForbidden, false } + ctx = withTempUnschedStreamPhase(ctx, tempUnschedPhaseMidStreamLegacy) s.handleGrokAccountUpstreamError(withGrokTeamRateLimitModel(ctx, firstNonEmpty(canonicalModel...)), account, statusCode, nil, payload) return statusCode, false } @@ -1883,8 +1884,22 @@ func (s *OpenAIGatewayService) handleOpenAIStreamTerminalAccountSideEffectsWithC // 只有 OAuth/SetupToken 的 Spark 配额 429 才需要保留 headers 读取明确的 5h/7d reset。 accountHeaders = openAIWSSemantic429Headers(account, model, headers) } + ctx = withTempUnschedStreamPhase(ctx, tempUnschedPhaseMidStreamLegacy) return statusCode, s.handleOpenAIAccountUpstreamError(ctx, account, statusCode, accountHeaders, payload, model) default: + // 中途 502 / 通用 upstream_error 默认不产生账号副作用。 + // 只有显式 stream_timing=after_stream 的规则可以在关键词匹配后冷却。 + if s == nil || s.rateLimitService == nil || account == nil || !account.ShouldHandleErrorCode(statusCode) { + return statusCode, false + } + ctx = withTempUnschedStreamPhase(ctx, tempUnschedPhaseMidStreamOptIn) + model := firstNonEmpty(canonicalModel...) + if model == "" { + model = firstNonEmpty(gjson.GetBytes(payload, "model").String(), gjson.GetBytes(payload, "response.model").String()) + } + if s.rateLimitService.attemptTempUnschedulable(ctx, account, statusCode, payload, model) == tempUnschedTriggered { + return statusCode, true + } return statusCode, false } } diff --git a/backend/internal/service/openai_gateway_upstream_errors.go b/backend/internal/service/openai_gateway_upstream_errors.go index 0d9a80ef7c6b..16f3fa9c7172 100644 --- a/backend/internal/service/openai_gateway_upstream_errors.go +++ b/backend/internal/service/openai_gateway_upstream_errors.go @@ -997,7 +997,7 @@ func (s *OpenAIGatewayService) handleCompatErrorResponse( modelForCooldown = requestedModel[0] } shouldDisable := s.handleOpenAIAccountUpstreamError( - c.Request.Context(), account, resp.StatusCode, resp.Header, body, modelForCooldown, + openAICompatTempUnschedContext(c, resp, account), account, resp.StatusCode, resp.Header, body, modelForCooldown, ) kind := "http_error" if shouldDisable { diff --git a/backend/internal/service/openai_ws_forwarder_ingress.go b/backend/internal/service/openai_ws_forwarder_ingress.go index 2ac3b0ec9170..157047cba2a2 100644 --- a/backend/internal/service/openai_ws_forwarder_ingress.go +++ b/backend/internal/service/openai_ws_forwarder_ingress.go @@ -1988,8 +1988,12 @@ func (s *OpenAIGatewayService) ProxyResponsesWebSocketFromClient( if eventType == "response.failed" && isOpenAIInvalidEncryptedContentSSE(upstreamMessage, eventType) { s.markOpenAIWSInvalidEncryptedContentLineageFromPayload(c, payload, "ingress_ws_invalid_encrypted_lineage_mark", account.ID, turn, upstreamMessage) } + // Captured before this frame is written. The terminal handler below runs + // after the write, and the failure frame itself must not count as output. + turnOutputStarted := wroteDownstream if eventType == "error" { - s.handleOpenAIWSErrorEventTransientFailure(openAI429LeaseObservation(ctx, lease), account, mappedModel, lease.HandshakeHeaders(), upstreamMessage) + eventCtx := openAIWSForwardStreamPhaseContext(openAI429LeaseObservation(ctx, lease), turnOutputStarted, upstreamMessage) + s.handleOpenAIWSErrorEventTransientFailure(eventCtx, account, mappedModel, lease.HandshakeHeaders(), upstreamMessage) errCodeRaw, errTypeRaw, errMsgRaw := parseOpenAIWSErrorEventFields(upstreamMessage) statusCode := openAIWSRejectedFieldRetryHTTPStatus(upstreamMessage) if !smartStrict && OpenAIWSAgentRecoveryCanRetry(ctx) && !wroteDownstream && statusCode == http.StatusBadRequest && rejectedFieldRetryState != nil { @@ -2015,7 +2019,7 @@ func (s *OpenAIGatewayService) ProxyResponsesWebSocketFromClient( } } } - s.persistOpenAIWSRateLimitSignal(openAI429LeaseObservation(ctx, lease), account, lease.HandshakeHeaders(), upstreamMessage, errCodeRaw, errTypeRaw, errMsgRaw, mappedModel) + s.persistOpenAIWSRateLimitSignal(eventCtx, account, lease.HandshakeHeaders(), upstreamMessage, errCodeRaw, errTypeRaw, errMsgRaw, mappedModel) fallbackReason, _ := classifyOpenAIWSErrorEventFromRaw(errCodeRaw, errTypeRaw, errMsgRaw) if fallbackReason == openAIWSFallbackReasonInvalidEncryptedContent { // 记录被上游拒绝的密文摘要;错误照旧透传,下一轮进场时按摘要预剥离。 @@ -2157,7 +2161,7 @@ func (s *OpenAIGatewayService) ProxyResponsesWebSocketFromClient( } } if isTerminalEvent { - terminalEvent := s.handleOpenAIWSTerminalTransientFailure(openAI429LeaseObservation(ctx, lease), account, mappedModel, lease.HandshakeHeaders(), upstreamMessage) + terminalEvent := s.handleOpenAIWSTerminalTransientFailure(openAIWSForwardStreamPhaseContext(openAI429LeaseObservation(ctx, lease), turnOutputStarted, upstreamMessage), account, mappedModel, lease.HandshakeHeaders(), upstreamMessage) // 客户端已断连时,上游连接的 session 状态不可信,标记 broken 避免回池复用。 if clientDisconnected { lease.MarkBroken() diff --git a/backend/internal/service/openai_ws_forwarder_support.go b/backend/internal/service/openai_ws_forwarder_support.go index 2da08dc464fa..ad5a087d02e2 100644 --- a/backend/internal/service/openai_ws_forwarder_support.go +++ b/backend/internal/service/openai_ws_forwarder_support.go @@ -316,6 +316,38 @@ func openAIWSPayloadTransientStatus(payload []byte) int { } } +// openAIWSForwardStreamPhaseContext stamps the temp-unsched phase for a websocket +// event. Before any client output, the default pre-stream phase still lets every +// rule match. After output has started, legacy mid-stream statuses keep their +// historical behavior and generic 500/502 failures require an explicit after_stream rule. +func openAIWSForwardStreamPhaseContext(ctx context.Context, outputStarted bool, payload []byte) context.Context { + if !outputStarted { + return ctx + } + if ctx == nil { + ctx = context.Background() + } + return withTempUnschedStreamPhase(ctx, openAIWSOutputStartedStreamPhase(payload)) +} + +func openAIWSOutputStartedStreamPhase(payload []byte) tempUnschedStreamPhase { + message := extractOpenAISSEErrorMessage(payload) + switch openAIStreamFailureStatus(payload, message) { + case http.StatusUnauthorized, http.StatusTooManyRequests, http.StatusServiceUnavailable, 529: + return tempUnschedPhaseMidStreamLegacy + case http.StatusForbidden: + if openAIStream403AccountFailure(payload, message) { + return tempUnschedPhaseMidStreamLegacy + } + } + switch openAIWSPayloadTransientStatus(payload) { + case http.StatusUnauthorized, http.StatusTooManyRequests, http.StatusServiceUnavailable, 529: + return tempUnschedPhaseMidStreamLegacy + default: + return tempUnschedPhaseMidStreamOptIn + } +} + func (s *OpenAIGatewayService) handleOpenAIWSTerminalTransientFailure(ctx context.Context, account *Account, canonicalModel string, headers http.Header, payload []byte) string { eventType, _, _ := parseOpenAIWSEventEnvelope(payload) terminalEvent := normalizeOpenAIWSTerminalEvent(eventType) @@ -716,6 +748,8 @@ func (s *OpenAIGatewayService) persistOpenAIWSRateLimitSignal(ctx context.Contex // 非空 responseBody 表示已建立连接后收到的语义错误事件;握手响应头 // 可能只是成功连接时的全局快照,不能用于普通模型的 429 账号级限流。 // 实际拨号 HTTP 429 使用 nil responseBody,必须保留响应头。 + // 保留调用方从真实输出状态传入的 stream phase;有事件体并不代表已输出 + // (例如 prewarm),不能在此把所有语义 429 一律视为流前或流中。 if len(responseBody) > 0 { ctx = context.WithValue(ctx, openAI429WeeklyHeadersKey{}, headers) headers = openAIWSSemantic429Headers(account, model, headers) diff --git a/backend/internal/service/openai_ws_forwarder_v2.go b/backend/internal/service/openai_ws_forwarder_v2.go index 3f70a8a5527c..71b707eee99d 100644 --- a/backend/internal/service/openai_ws_forwarder_v2.go +++ b/backend/internal/service/openai_ws_forwarder_v2.go @@ -944,6 +944,9 @@ readLoop: } imageCounter.AddSSEData(message) + // Snapshot before this event is flushed or emitted. A failure frame itself + // is not client output, so a before_stream rule must not see it as mid-stream. + wsOutputStarted := wroteDownstream if eventType == "error" || eventType == "response.failed" { markOpenAICyberPolicyEvent(c, message, http.StatusOK, usage) } @@ -955,9 +958,10 @@ readLoop: // account failover for a request the provider already received. flushBufferedStreamEvents("error_event") } - s.handleOpenAIWSErrorEventTransientFailure(openAI429LeaseObservation(ctx, lease), account, mappedModel, lease.HandshakeHeaders(), message) + eventCtx := openAIWSForwardStreamPhaseContext(openAI429LeaseObservation(ctx, lease), wsOutputStarted, message) + s.handleOpenAIWSErrorEventTransientFailure(eventCtx, account, mappedModel, lease.HandshakeHeaders(), message) errCodeRaw, errTypeRaw, errMsgRaw := parseOpenAIWSErrorEventFields(message) - s.persistOpenAIWSRateLimitSignal(openAI429LeaseObservation(ctx, lease), account, lease.HandshakeHeaders(), message, errCodeRaw, errTypeRaw, errMsgRaw, mappedModel) + s.persistOpenAIWSRateLimitSignal(eventCtx, account, lease.HandshakeHeaders(), message, errCodeRaw, errTypeRaw, errMsgRaw, mappedModel) errMsg := sanitizeUpstreamErrorMessage(strings.TrimSpace(errMsgRaw)) if errMsg == "" { errMsg = "Upstream websocket error" @@ -1082,7 +1086,7 @@ readLoop: if !clientDisconnected { markOpenAIWSClientVisibleFailure(c, eventType, message) } - upstreamTerminalEvent = s.handleOpenAIWSTerminalTransientFailure(openAI429LeaseObservation(ctx, lease), account, mappedModel, lease.HandshakeHeaders(), message) + upstreamTerminalEvent = s.handleOpenAIWSTerminalTransientFailure(openAIWSForwardStreamPhaseContext(openAI429LeaseObservation(ctx, lease), wsOutputStarted, message), account, mappedModel, lease.HandshakeHeaders(), message) // A terminal event must be the final JSON document in its WS message. // Ignore any tail for the completed client turn, but never reuse the // ambiguous upstream connection for another request. diff --git a/backend/internal/service/openai_ws_http_bridge.go b/backend/internal/service/openai_ws_http_bridge.go index 0d1813c87bfa..566d08dc4ba0 100644 --- a/backend/internal/service/openai_ws_http_bridge.go +++ b/backend/internal/service/openai_ws_http_bridge.go @@ -817,7 +817,7 @@ func (s *OpenAIGatewayService) proxyOpenAIWSHTTPBridgeTurn( return nil } if !failureAccountSideEffectsApplied { - failureAccountSideEffectsApplied = s.handleOpenAIWSFailureAccountSideEffects(ctx, account, mappedModel, resp.Header, bareErrorPayload) + failureAccountSideEffectsApplied = s.handleOpenAIWSFailureAccountSideEffects(openAIWSForwardStreamPhaseContext(ctx, wroteDownstream, bareErrorPayload), account, mappedModel, resp.Header, bareErrorPayload) } upstreamTerminalEvent = "response.failed" if clientDisconnected { @@ -981,7 +981,7 @@ func (s *OpenAIGatewayService) proxyOpenAIWSHTTPBridgeTurn( } if account.Platform != PlatformGrok && !failureAccountSideEffectsApplied { if eventType == "response.failed" || (!officialOpenAIResponses && shouldFailover && !requestScopedCapacity) { - failureAccountSideEffectsApplied = s.handleOpenAIWSFailureAccountSideEffects(ctx, account, mappedModel, resp.Header, upstreamMessage) + failureAccountSideEffectsApplied = s.handleOpenAIWSFailureAccountSideEffects(openAIWSForwardStreamPhaseContext(ctx, wroteDownstream, upstreamMessage), account, mappedModel, resp.Header, upstreamMessage) } } if wroteDownstream && requestScopedCapacity && !capacityFailoverSuppressedLogged { diff --git a/backend/internal/service/openai_ws_v2_passthrough_adapter.go b/backend/internal/service/openai_ws_v2_passthrough_adapter.go index 621f28013de9..5b25f8c8d58e 100644 --- a/backend/internal/service/openai_ws_v2_passthrough_adapter.go +++ b/backend/internal/service/openai_ws_v2_passthrough_adapter.go @@ -1594,7 +1594,7 @@ func (s *OpenAIGatewayService) proxyResponsesWebSocketV2Passthrough( errCodeRaw, errTypeRaw, errMsgRaw := parseOpenAIWSErrorEventFields(payload) isPreOutputRateLimit := eventType == "error" && !wroteDownstream && isOpenAIWSRateLimitError(errCodeRaw, errTypeRaw, errMsgRaw) if (eventType == "error" || eventType == "response.failed") && !failureAccountSideEffectsApplied && !isPreOutputRateLimit { - failureAccountSideEffectsApplied = s.handleOpenAIWSFailureAccountSideEffects(ctx, account, *activePolicyModel.Load(), handshakeHeaders, payload) + failureAccountSideEffectsApplied = s.handleOpenAIWSFailureAccountSideEffects(openAIWSForwardStreamPhaseContext(ctx, wroteDownstream, payload), account, *activePolicyModel.Load(), handshakeHeaders, payload) } if eventType != "error" { return nil diff --git a/backend/internal/service/quality_5xx_immediate_test.go b/backend/internal/service/quality_5xx_immediate_test.go index 0fa5b5879c76..0968cab7aa97 100644 --- a/backend/internal/service/quality_5xx_immediate_test.go +++ b/backend/internal/service/quality_5xx_immediate_test.go @@ -26,7 +26,7 @@ func TestQuality5xxProductionProviderAppliesBeforeReturning(t *testing.T) { rdb := queuetest.NewClient(mr.Addr()) defer func() { _ = rdb.Close() }() repo := &immediateQualityAccountRepo{} - svc := ProvideRateLimitService(repo, nil, &config.Config{}, nil, nil, nil, nil, nil, nil, nil, nil, rdb) + svc := ProvideRateLimitService(repo, nil, &config.Config{}, nil, nil, nil, nil, nil, nil, nil, nil, nil, rdb) require.NotNil(t, svc.qualityTrigger) defer func() { _ = svc.qualityTrigger.queue.Close() }() svc.observeQualityStatus(context.Background(), &Account{ID: 12, Type: AccountTypeOAuth}, 503) diff --git a/backend/internal/service/ratelimit_service.go b/backend/internal/service/ratelimit_service.go index 1c27aa2ff6eb..c50c46c1938a 100644 --- a/backend/internal/service/ratelimit_service.go +++ b/backend/internal/service/ratelimit_service.go @@ -20,21 +20,24 @@ import ( // RateLimitService 处理限流和过载状态管理 type RateLimitService struct { - accountOps *AccountOpsService - openAITOTP429Rotator openAITOTP429Rotator - qualityTrigger *quality5xxTrigger - accountRepo AccountRepository - usageRepo UsageLogRepository - cfg *config.Config - geminiQuotaService *GeminiQuotaService - tempUnschedCache TempUnschedCache - openAIAPIKeyHealth OpenAIAPIKeyHealthCache - timeoutCounterCache TimeoutCounterCache - openAI403CounterCache OpenAI403CounterCache - settingService *SettingService - tokenCacheInvalidator TokenCacheInvalidator - runtimeBlocker AccountRuntimeBlocker - openAIIPUnauthorized openAIIPUnauthorizedStreak + accountOps *AccountOpsService + openAITOTP429Rotator openAITOTP429Rotator + qualityTrigger *quality5xxTrigger + accountRepo AccountRepository + usageRepo UsageLogRepository + cfg *config.Config + geminiQuotaService *GeminiQuotaService + tempUnschedCache TempUnschedCache + tempUnschedTriggerCounter TempUnschedTriggerCounter + memoryTriggerOnce sync.Once + memoryTrigger TempUnschedTriggerCounter + openAIAPIKeyHealth OpenAIAPIKeyHealthCache + timeoutCounterCache TimeoutCounterCache + openAI403CounterCache OpenAI403CounterCache + settingService *SettingService + tokenCacheInvalidator TokenCacheInvalidator + runtimeBlocker AccountRuntimeBlocker + openAIIPUnauthorized openAIIPUnauthorizedStreak // ollamaCloudUsageProbe is the optional Ollama Cloud usage probe scheduler // injected via SetOllamaCloudUsageProbeScheduler. See // ratelimit_service_ollama_429.go for how real-Ollama 429s schedule an async @@ -118,6 +121,28 @@ func (s *RateLimitService) SetTimeoutCounterCache(cache TimeoutCounterCache) { s.timeoutCounterCache = cache } +// SetTempUnschedTriggerCounter 设置临时不可调度触发计数器。 +// 未设置时使用进程内固定窗口计数,测试可注入可控时钟实现。 +func (s *RateLimitService) SetTempUnschedTriggerCounter(counter TempUnschedTriggerCounter) { + if s == nil { + return + } + s.tempUnschedTriggerCounter = counter +} + +func (s *RateLimitService) activeTempUnschedTriggerCounter() TempUnschedTriggerCounter { + if s != nil && s.tempUnschedTriggerCounter != nil { + return s.tempUnschedTriggerCounter + } + if s == nil { + return newMemoryTempUnschedTriggerCounter(time.Now) + } + s.memoryTriggerOnce.Do(func() { + s.memoryTrigger = newMemoryTempUnschedTriggerCounter(time.Now) + }) + return s.memoryTrigger +} + func (s *RateLimitService) SetOpenAIAPIKeyHealthCache(cache OpenAIAPIKeyHealthCache) { s.openAIAPIKeyHealth = cache } @@ -328,9 +353,11 @@ func (s *RateLimitService) CheckErrorPolicy(ctx context.Context, account *Accoun if account.IsPoolMode() { // 池模式只跳过默认账号状态处理;管理员显式配置的临时不可调度规则仍应生效。 // 401 只在非凭据级且命中显式模型级规则时由规则处理,其余保留现有认证错误语义。 - if tempUnschedRulesApply(account, statusCode, responseBody, tempUnschedulableModel(ctx, nil)) && - s.tryTempUnschedulable(ctx, account, statusCode, responseBody) { - return ErrorPolicyTempUnscheduled + if stop, triggered := s.consumeTempUnschedAttempt(ctx, account, statusCode, responseBody); stop { + if triggered { + return ErrorPolicyTempUnscheduled + } + return ErrorPolicySkipped } return ErrorPolicySkipped } @@ -339,10 +366,14 @@ func (s *RateLimitService) CheckErrorPolicy(ctx context.Context, account *Accoun if statusCode == 529 { return ErrorPolicyMatched } - if s.tryTempUnschedulable(ctx, account, statusCode, responseBody, firstRequestedModel(requestedModel)) { + // CheckErrorPolicy 不套用 handleUpstreamError 的 401 凭据门闩。 + // OAuth / token_revoked 仍按规则冷却;次数未到则继续默认策略,且不把结果写成“已跳过”。 + switch s.attemptTempUnschedulable(ctx, account, statusCode, responseBody, firstRequestedModel(requestedModel)) { + case tempUnschedTriggered: return ErrorPolicyTempUnscheduled + default: + return ErrorPolicyNone } - return ErrorPolicyNone } // HandleUpstreamError 处理上游错误响应,标记账号状态 @@ -401,9 +432,12 @@ func (s *RateLimitService) handleUpstreamErrorAfterStreakReset(ctx context.Conte // 池模式默认不标记本地账号状态;但管理员显式配置的临时不可调度规则优先。 // 401 只在非凭据级且命中显式模型级规则时由规则处理,其余保留池模式现有的认证处理。 if account.IsPoolMode() && !customErrorCodesEnabled { - if tempUnschedRulesApply(account, statusCode, responseBody, tempUnschedulableModel(ctx, nil)) && - s.tryTempUnschedulable(ctx, account, statusCode, responseBody) { - return true + if stop, triggered := s.consumeTempUnschedAttempt(ctx, account, statusCode, responseBody); stop { + if triggered { + return true + } + slog.Info("pool_mode_temp_unsched_pending", "account_id", account.ID, "status_code", statusCode) + return false } slog.Info("pool_mode_error_skipped", "account_id", account.ID, "status_code", statusCode) return false @@ -450,12 +484,11 @@ func (s *RateLimitService) handleUpstreamErrorAfterStreakReset(ctx context.Conte } } - // 先尝试临时不可调度规则(401 仅限非凭据级且命中显式模型级规则) - // 如果匹配成功,直接返回,不执行后续禁用逻辑 - if tempUnschedRulesApply(account, statusCode, responseBody, tempUnschedulableModel(ctx, requestedModel)) { - if s.tryTempUnschedulable(ctx, account, statusCode, responseBody, firstRequestedModel(requestedModel)) { - return true - } + // 先尝试临时不可调度规则(401 仅限非凭据级且命中显式模型级规则)。 + // 达到阈值就冷却并返回;次数未到也到此为止,不能再落到后面的整账号停用。 + // 同一次上游错误若已在 fastpath 计过数,consume 会复用那次结果,不会再加一。 + if stop, triggered := s.consumeTempUnschedAttempt(ctx, account, statusCode, responseBody, firstRequestedModel(requestedModel)); stop { + return triggered } upstreamMsg := strings.TrimSpace(extractUpstreamErrorMessage(responseBody)) @@ -2875,6 +2908,70 @@ func tempUnschedulableModel(ctx context.Context, requestedModel []string) string return strings.TrimSpace(model) } +// tempUnschedStreamPhase 区分流开始前的 HTTP 错误和流已经开始后的失败。 +type tempUnschedStreamPhase int + +const ( + // tempUnschedPhasePreStream 是缺省阶段:所有规则都可匹配。 + tempUnschedPhasePreStream tempUnschedStreamPhase = iota + // tempUnschedPhaseMidStreamLegacy 是原本就会产生账号副作用的流中途状态 + // (401、凭据类 403、429、容量降载 503、529)。省略 stream_timing 的旧规则 + // 和 after_stream 可以匹配;before_stream 不可以。 + tempUnschedPhaseMidStreamLegacy + // tempUnschedPhaseMidStreamOptIn 只允许显式 after_stream 的规则。 + // 用于中途 502 / 通用 upstream_error,以及原本直接跳过副作用的中途失败。 + tempUnschedPhaseMidStreamOptIn +) + +type tempUnschedStreamPhaseContextKey struct{} + +func withTempUnschedStreamPhase(ctx context.Context, phase tempUnschedStreamPhase) context.Context { + if ctx == nil { + ctx = context.Background() + } + return context.WithValue(ctx, tempUnschedStreamPhaseContextKey{}, phase) +} + +func tempUnschedStreamPhaseFrom(ctx context.Context) tempUnschedStreamPhase { + if ctx == nil { + return tempUnschedPhasePreStream + } + phase, _ := ctx.Value(tempUnschedStreamPhaseContextKey{}).(tempUnschedStreamPhase) + return phase +} + +func ruleAllowsTempUnschedPhase(rule TempUnschedulableRule, phase tempUnschedStreamPhase) bool { + switch phase { + case tempUnschedPhaseMidStreamLegacy: + return rule.StreamTiming != TempUnschedStreamBefore + case tempUnschedPhaseMidStreamOptIn: + return rule.StreamTiming == TempUnschedStreamAfter + default: + return true + } +} + +func filterTempUnschedMatchesForPhase(matches []tempUnschedulableRuleMatch, phase tempUnschedStreamPhase) []tempUnschedulableRuleMatch { + if phase == tempUnschedPhasePreStream || len(matches) == 0 { + return matches + } + filtered := make([]tempUnschedulableRuleMatch, 0, len(matches)) + for _, match := range matches { + if ruleAllowsTempUnschedPhase(match.rule, phase) { + filtered = append(filtered, match) + } + } + return filtered +} + +type tempUnschedAttempt int + +const ( + tempUnschedNoMatch tempUnschedAttempt = iota + tempUnschedPending + tempUnschedTriggered +) + type tempUnschedulableRuleMatch struct { rule TempUnschedulableRule ruleIndex int @@ -2909,43 +3006,149 @@ func matchTempUnschedulableRules(account *Account, statusCode int, responseBody } func (s *RateLimitService) tryTempUnschedulable(ctx context.Context, account *Account, statusCode int, responseBody []byte, requestedModel ...string) bool { - if account == nil { - return false + return s.attemptTempUnschedulable(ctx, account, statusCode, responseBody, requestedModel...) == tempUnschedTriggered +} + +// consumeTempUnschedAttempt 对一次上游错误最多计数一次。 +// stop 表示规则已经接住这次错误:triggered 为冷却已写入,否则是次数未到,两种都不能再走默认停用。 +func (s *RateLimitService) consumeTempUnschedAttempt(ctx context.Context, account *Account, statusCode int, responseBody []byte, requestedModel ...string) (stop bool, triggered bool) { + if !tempUnschedRulesApply(account, statusCode, responseBody, tempUnschedulableModel(ctx, requestedModel)) { + return false, false + } + switch s.attemptTempUnschedulable(ctx, account, statusCode, responseBody, requestedModel...) { + case tempUnschedTriggered: + return true, true + case tempUnschedPending: + return true, false + default: + return false, false + } +} + +type tempUnschedAttemptMemo struct { + done bool + result tempUnschedAttempt +} + +type tempUnschedAttemptMemoKey struct{} + +// bindTempUnschedAttempt 让同一次上游错误上的多次规则判断共用一个结果。 +// 已绑定过的 context 保持原样,避免外层结果被内层空记录盖掉。 +func bindTempUnschedAttempt(ctx context.Context) context.Context { + if ctx == nil { + ctx = context.Background() + } + if _, ok := ctx.Value(tempUnschedAttemptMemoKey{}).(*tempUnschedAttemptMemo); ok { + return ctx + } + return context.WithValue(ctx, tempUnschedAttemptMemoKey{}, &tempUnschedAttemptMemo{}) +} + +func tempUnschedAttemptMemoFrom(ctx context.Context) *tempUnschedAttemptMemo { + if ctx == nil { + return nil + } + memo, _ := ctx.Value(tempUnschedAttemptMemoKey{}).(*tempUnschedAttemptMemo) + return memo +} + +func (s *RateLimitService) attemptTempUnschedulable(ctx context.Context, account *Account, statusCode int, responseBody []byte, requestedModel ...string) tempUnschedAttempt { + if memo := tempUnschedAttemptMemoFrom(ctx); memo != nil && memo.done { + return memo.result + } + result := s.evaluateTempUnschedulable(ctx, account, statusCode, responseBody, requestedModel...) + if memo := tempUnschedAttemptMemoFrom(ctx); memo != nil && !memo.done { + memo.done = true + memo.result = result + } + return result +} + +func (s *RateLimitService) evaluateTempUnschedulable(ctx context.Context, account *Account, statusCode int, responseBody []byte, requestedModel ...string) tempUnschedAttempt { + if account == nil || s == nil { + return tempUnschedNoMatch } if !account.IsTempUnschedulableEnabled() { - return false + return tempUnschedNoMatch } - matches := matchTempUnschedulableRules(account, statusCode, responseBody) + matches := filterTempUnschedMatchesForPhase(matchTempUnschedulableRules(account, statusCode, responseBody), tempUnschedStreamPhaseFrom(ctx)) if len(matches) == 0 { - return false + return tempUnschedNoMatch } modelKey := tempUnschedulableModel(ctx, requestedModel) - // 401 首次命中可临时不可调度(给 token 刷新窗口); - // 若历史上已因 401 进入过临时不可调度,则本次应升级为 error(返回 false 交由默认错误逻辑处理)。 - // Antigravity 跳过:其 401 由 applyErrorPolicy 的 temp_unschedulable_rules 自行控制,无需升级逻辑。 + // 401 首次达到触发次数时可临时不可调度(给 token 刷新窗口); + // 若历史上已因 401 进入过临时不可调度,则本次应升级为 error(返回未匹配,交由默认错误逻辑处理)。 + // 次数未达到阈值时不升级。Antigravity 跳过:其 401 由规则自行控制。 // 模型级命中只冷却模型、不写账号级状态,不参与升级。 + escalateFirst := false if statusCode == http.StatusUnauthorized && account.Platform != PlatformAntigravity && !tempUnschedHitUsesModelScope(account, matches[0].rule, modelKey, statusCode, responseBody) { reason := account.TempUnschedulableReason - // 缓存可能没有 reason,从 DB 回退读取 - if reason == "" { + if reason == "" && s.accountRepo != nil { if dbAcc, err := s.accountRepo.GetByID(ctx, account.ID); err == nil && dbAcc != nil { reason = dbAcc.TempUnschedulableReason } } if wasTempUnschedByStatusCode(reason, statusCode) { + escalateFirst = true + } + } + sawPending := false + for i, match := range matches { + modelScoped := tempUnschedHitUsesModelScope(account, match.rule, modelKey, statusCode, responseBody) + reached, count, epoch := s.observeTempUnschedTrigger(ctx, account, match.rule, match.ruleIndex, modelScoped, modelKey) + if !reached { + sawPending = true + continue + } + if i == 0 && escalateFirst { slog.Info("401_escalated_to_error", "account_id", account.ID, "reason", "previous temp-unschedulable was also 401") - return false + return tempUnschedNoMatch } - } - for _, match := range matches { - if s.triggerTempUnschedulable(ctx, account, match.rule, match.ruleIndex, statusCode, match.matchedKeyword, responseBody, modelKey) { - return true + if s.triggerTempUnschedulable(ctx, account, match.rule, match.ruleIndex, statusCode, match.matchedKeyword, responseBody, count, epoch, modelKey) { + return tempUnschedTriggered } } + if sawPending { + return tempUnschedPending + } + return tempUnschedNoMatch +} - return false +func (s *RateLimitService) observeTempUnschedTrigger(ctx context.Context, account *Account, rule TempUnschedulableRule, ruleIndex int, modelScoped bool, modelKey string) (bool, int64, string) { + threshold := rule.NormalizedTriggerCount() + if threshold <= 1 { + return true, 1, "" + } + window := rule.TriggerWindowMinutes() + key := tempUnschedTriggerCounterKey(account.ID, ruleIndex, modelScoped, modelKey) + count, epoch, err := s.activeTempUnschedTriggerCounter().Increment(ctx, key, window) + if err != nil { + slog.Warn("temp_unsched_trigger_count_failed", "account_id", account.ID, "rule_index", ruleIndex, "error", err) + return false, 0, "" + } + if count < int64(threshold) { + slog.Info("temp_unsched_trigger_pending", + "account_id", account.ID, + "rule_index", ruleIndex, + "count", count, + "threshold", threshold, + "window_minutes", window, + ) + return false, count, "" + } + return true, count, epoch +} + +func (s *RateLimitService) resetTempUnschedTriggerCount(ctx context.Context, accountID int64, ruleIndex int, modelScoped bool, modelKey, epoch string) { + if epoch == "" { + return + } + key := tempUnschedTriggerCounterKey(accountID, ruleIndex, modelScoped, modelKey) + if err := s.activeTempUnschedTriggerCounter().Reset(ctx, key, epoch); err != nil { + slog.Warn("temp_unsched_trigger_count_reset_failed", "account_id", accountID, "rule_index", ruleIndex, "error", err) + } } func wasTempUnschedByStatusCode(reason string, statusCode int) bool { @@ -2980,7 +3183,7 @@ func matchTempUnschedKeyword(bodyLower string, keywords []string) string { return "" } -func (s *RateLimitService) triggerTempUnschedulable(ctx context.Context, account *Account, rule TempUnschedulableRule, ruleIndex int, statusCode int, matchedKeyword string, responseBody []byte, requestedModel ...string) bool { +func (s *RateLimitService) triggerTempUnschedulable(ctx context.Context, account *Account, rule TempUnschedulableRule, ruleIndex int, statusCode int, matchedKeyword string, responseBody []byte, triggerCount int64, triggerEpoch string, requestedModel ...string) bool { if account == nil { return false } @@ -2992,6 +3195,7 @@ func (s *RateLimitService) triggerTempUnschedulable(ctx context.Context, account until := now.Add(time.Duration(rule.DurationMinutes) * time.Minute) modelKey := firstRequestedModel(requestedModel) modelScoped := tempUnschedHitUsesModelScope(account, rule, modelKey, statusCode, responseBody) + threshold := rule.NormalizedTriggerCount() state := &TempUnschedState{ UntilUnix: until.Unix(), @@ -3002,6 +3206,11 @@ func (s *RateLimitService) triggerTempUnschedulable(ctx context.Context, account ErrorMessage: truncateTempUnschedMessage(responseBody, tempUnschedMessageMaxBytes), Scope: TempUnschedScopeAccount, } + if threshold > 1 { + state.TriggerCount = triggerCount + state.TriggerThreshold = threshold + state.TriggerWindowMinutes = rule.TriggerWindowMinutes() + } if modelScoped { state.Scope = TempUnschedScopeModel state.Model = modelKey @@ -3024,7 +3233,10 @@ func (s *RateLimitService) triggerTempUnschedulable(ctx context.Context, account // failed; never widen a model-scoped failure into an account-wide block. return true } - slog.Info("account_model_temp_unschedulable", "account_id", account.ID, "model", modelKey, "until", until, "rule_index", ruleIndex, "rule_scope", rule.Scope, "status_code", statusCode) + if threshold > 1 { + s.resetTempUnschedTriggerCount(ctx, account.ID, ruleIndex, true, modelKey, triggerEpoch) + } + slog.Info("account_model_temp_unschedulable", "account_id", account.ID, "model", modelKey, "until", until, "rule_index", ruleIndex, "rule_scope", rule.Scope, "status_code", statusCode, "trigger_count", triggerCount, "trigger_threshold", threshold) return true } @@ -3033,6 +3245,9 @@ func (s *RateLimitService) triggerTempUnschedulable(ctx context.Context, account slog.Warn("temp_unsched_set_failed", "account_id", account.ID, "error", err) return false } + if threshold > 1 { + s.resetTempUnschedTriggerCount(ctx, account.ID, ruleIndex, false, modelKey, triggerEpoch) + } if s.tempUnschedCache != nil { if err := s.tempUnschedCache.SetTempUnsched(ctx, account.ID, state); err != nil { diff --git a/backend/internal/service/temp_unsched.go b/backend/internal/service/temp_unsched.go index 67ecb8e70ec5..5cfae5a03d1e 100644 --- a/backend/internal/service/temp_unsched.go +++ b/backend/internal/service/temp_unsched.go @@ -33,6 +33,14 @@ type OpenAIAPIKeyHealthCache interface { RecordOpenAIAPIKeyHealthFailure(ctx context.Context, accountID int64, windowMinutes, threshold int) (count int64, tripped bool, err error) } +// TempUnschedTriggerCounter 在固定时间窗口内累计临时不可调度规则的匹配次数。 +// 窗口从第一次匹配开始,到期后键自动消失。冷却写入成功后,调用方用 Increment +// 返回的 epoch 做 Reset:只有 epoch 仍是这一轮时才删除,迟到的 Reset 不能清掉新一轮计数。 +type TempUnschedTriggerCounter interface { + Increment(ctx context.Context, key string, windowMinutes int) (count int64, epoch string, err error) + Reset(ctx context.Context, key string, epoch string) error +} + // TimeoutCounterCache 超时计数器缓存接口 type TimeoutCounterCache interface { // IncrementTimeoutCount 增加账户的超时计数,返回当前计数值 diff --git a/backend/internal/service/temp_unsched_pending_test.go b/backend/internal/service/temp_unsched_pending_test.go new file mode 100644 index 000000000000..7d2b547f76b7 --- /dev/null +++ b/backend/internal/service/temp_unsched_pending_test.go @@ -0,0 +1,231 @@ +//go:build unit + +package service + +import ( + "context" + "io" + "net/http" + "net/http/httptest" + "strings" + "testing" + "time" + + "github.com/Wei-Shaw/sub2api/internal/config" + "github.com/gin-gonic/gin" + "github.com/stretchr/testify/require" +) + +func TestCompatErrorPipelineCountsEachResponseOnce(t *testing.T) { + repo := &tempUnschedPendingRepo{} + limits, counter := newCountedTempUnschedService(repo) + gateway := &OpenAIGatewayService{rateLimitService: limits} + account := tempUnschedTimingAccount(map[string]any{ + "error_code": float64(400), "keywords": []any{"temporary fixture"}, + "duration_minutes": float64(10), "scope": "model", "trigger_count": float64(3), + }) + body := []byte(`{"error":{"message":"temporary fixture","type":"invalid_request_error"}}`) + for attempt := 1; attempt <= 3; attempt++ { + c, _ := gin.CreateTestContext(httptest.NewRecorder()) + c.Request = httptest.NewRequest(http.MethodPost, "/v1/chat/completions", nil) + resp := &http.Response{StatusCode: 400, Header: http.Header{}, Body: io.NopCloser(strings.NewReader(string(body)))} + failover := gateway.failoverOpenAIUpstreamHTTPError(c.Request.Context(), c, account, resp, body, "temporary fixture", "gpt-5.4") + if attempt < 3 { + require.Nil(t, failover) + _, err := gateway.handleChatCompletionsErrorResponse(resp, c, account, "gpt-5.4") + require.Error(t, err) + var unexpected *UpstreamFailoverError + require.NotErrorAs(t, err, &unexpected) + require.Empty(t, repo.modelReasons, "one response cannot satisfy the multi-error threshold") + } else { + require.NotNil(t, failover) + require.Len(t, repo.modelReasons, 1) + } + require.Equal(t, attempt, counter.hits, "same upstream response must be counted once across compatibility handlers") + } +} + +type tempUnschedPendingRepo struct { + recordingTempUnschedRepo + setErrorCalls int + lastError string +} + +func (r *tempUnschedPendingRepo) SetError(_ context.Context, _ int64, msg string) error { + r.setErrorCalls++ + r.lastError = msg + return nil +} + +type countingTempUnschedTrigger struct { + inner *memoryTempUnschedTriggerCounter + hits int + resetEpochs []string +} + +func (c *countingTempUnschedTrigger) Increment(ctx context.Context, key string, windowMinutes int) (int64, string, error) { + c.hits++ + return c.inner.Increment(ctx, key, windowMinutes) +} + +func (c *countingTempUnschedTrigger) Reset(ctx context.Context, key, epoch string) error { + c.resetEpochs = append(c.resetEpochs, epoch) + return c.inner.Reset(ctx, key, epoch) +} + +func newCountedTempUnschedService(repo *tempUnschedPendingRepo) (*RateLimitService, *countingTempUnschedTrigger) { + limits := NewRateLimitService(repo, nil, &config.Config{}, nil, nil) + counter := &countingTempUnschedTrigger{inner: newMemoryTempUnschedTriggerCounter(time.Now)} + limits.SetTempUnschedTriggerCounter(counter) + return limits, counter +} + +func TestFastPathThenGeneralHandler_CountsOne502UntilThreshold(t *testing.T) { + repo := &tempUnschedPendingRepo{} + limits, counter := newCountedTempUnschedService(repo) + gateway := &OpenAIGatewayService{rateLimitService: limits} + account := tempUnschedTimingAccount(map[string]any{ + "error_code": float64(http.StatusBadGateway), + "keywords": []any{"bad gateway"}, + "duration_minutes": float64(10), + "scope": "model", + "trigger_count": float64(2), + "trigger_window_minutes": float64(5), + }) + body := []byte(`{"error":{"message":"bad gateway","type":"upstream_error"}}`) + + disabled := gateway.handleOpenAIAccountUpstreamError(context.Background(), account, http.StatusBadGateway, http.Header{}, body, "gpt-5.4") + require.False(t, disabled) + require.Equal(t, 1, counter.hits, "fastpath and the general handler must share one count") + require.Empty(t, repo.modelReasons) + require.Zero(t, repo.setErrorCalls) + require.Empty(t, repo.reasons) + + disabled = gateway.handleOpenAIAccountUpstreamError(context.Background(), account, http.StatusBadGateway, http.Header{}, body, "gpt-5.4") + require.True(t, disabled) + require.Equal(t, 2, counter.hits) + require.Len(t, repo.modelReasons, 1) + require.Zero(t, repo.setErrorCalls) + require.NotEmpty(t, counter.resetEpochs) + require.NotEmpty(t, counter.resetEpochs[0]) +} + +func TestPendingModel401_DoesNotDisableWholeAccount(t *testing.T) { + repo := &tempUnschedPendingRepo{} + limits, counter := newCountedTempUnschedService(repo) + account := tempUnschedTimingAccount(map[string]any{ + "error_code": float64(http.StatusUnauthorized), + "keywords": []any{"unauthorized"}, + "duration_minutes": float64(10), + "scope": "model", + "trigger_count": float64(3), + "trigger_window_minutes": float64(5), + }) + body := []byte(`{"error":{"message":"unauthorized","type":"invalid_request_error"}}`) + + disabled := limits.HandleUpstreamError(context.Background(), account, http.StatusUnauthorized, http.Header{}, body, "gpt-5.4") + require.False(t, disabled) + require.Zero(t, repo.setErrorCalls) + require.Empty(t, repo.modelReasons) + require.Equal(t, 1, counter.hits) + + gateway := &OpenAIGatewayService{rateLimitService: limits} + disabled = gateway.handleOpenAIAccountUpstreamError(context.Background(), account, http.StatusUnauthorized, http.Header{}, body, "gpt-5.4") + require.False(t, disabled) + require.Zero(t, repo.setErrorCalls) + require.Empty(t, repo.modelReasons) + require.Equal(t, 2, counter.hits, "the fastpath must not count the same 401 again in general handling") +} + +func TestCredential401_StillDisablesDespitePendingModelRule(t *testing.T) { + bodies := [][]byte{ + []byte(`{"error":{"code":"token_revoked","message":"unauthorized"}}`), + []byte(`{"error":{"code":"token_invalidated","message":"unauthorized"}}`), + []byte(`{"detail":"Unauthorized"}`), + } + for _, body := range bodies { + repo := &tempUnschedPendingRepo{} + limits, counter := newCountedTempUnschedService(repo) + account := tempUnschedTimingAccount(map[string]any{ + "error_code": float64(http.StatusUnauthorized), + "keywords": []any{"unauthorized"}, + "duration_minutes": float64(10), + "scope": "model", + "trigger_count": float64(3), + "trigger_window_minutes": float64(5), + }) + + disabled := limits.HandleUpstreamError(context.Background(), account, http.StatusUnauthorized, http.Header{}, body, "gpt-5.4") + require.True(t, disabled, string(body)) + require.Equal(t, 1, repo.setErrorCalls, string(body)) + require.Empty(t, repo.modelReasons) + require.Zero(t, counter.hits, string(body)) + } +} + +func TestOpenAIWSAfterOutput_Generic500AndExplicit502NeedAfterStream(t *testing.T) { + repo := &tempUnschedPendingRepo{} + limits := NewRateLimitService(repo, nil, &config.Config{}, nil, nil) + gateway := &OpenAIGatewayService{rateLimitService: limits} + before := func(status int, keyword string) *Account { + return tempUnschedTimingAccount(map[string]any{ + "error_code": float64(status), + "keywords": []any{keyword}, + "duration_minutes": float64(5), + "scope": "model", + "stream_timing": TempUnschedStreamBefore, + }) + } + after := func(status int, keyword string) *Account { + account := before(status, keyword) + rules := account.Credentials["temp_unschedulable_rules"].([]any) + rule := rules[0].(map[string]any) + rule["stream_timing"] = TempUnschedStreamAfter + return account + } + + upstreamError := []byte(`{"type":"error","error":{"type":"upstream_error","code":"upstream_error","message":"upstream_error"}}`) + require.Equal(t, http.StatusInternalServerError, openAIWSPayloadTransientStatus(upstreamError)) + outputCtx := openAIWSForwardStreamPhaseContext(context.Background(), true, upstreamError) + require.Equal(t, tempUnschedPhaseMidStreamOptIn, tempUnschedStreamPhaseFrom(outputCtx)) + + gateway.handleOpenAIWSErrorEventTransientFailure(outputCtx, before(http.StatusInternalServerError, "upstream_error"), "gpt-5.4", nil, upstreamError) + require.Empty(t, repo.modelReasons, "a before_stream rule must not cool a generic upstream_error after output started") + + gateway.handleOpenAIWSErrorEventTransientFailure(outputCtx, after(http.StatusInternalServerError, "upstream_error"), "gpt-5.4", nil, upstreamError) + require.Len(t, repo.modelReasons, 1) + repo.modelReasons = nil + + failed := []byte(`{"type":"response.failed","response":{"error":{"status_code":502,"message":"bad gateway"}}}`) + require.Equal(t, http.StatusBadGateway, openAIWSPayloadTransientStatus(failed)) + failedCtx := openAIWSForwardStreamPhaseContext(context.Background(), true, failed) + require.Equal(t, tempUnschedPhaseMidStreamOptIn, tempUnschedStreamPhaseFrom(failedCtx)) + require.True(t, gateway.handleOpenAIWSFailureAccountSideEffects(failedCtx, before(http.StatusBadGateway, "bad gateway"), "gpt-5.4", nil, failed)) + require.Empty(t, repo.modelReasons, "an explicit 502 response.failed after output must not match before_stream") + + require.True(t, gateway.handleOpenAIWSFailureAccountSideEffects(context.Background(), before(http.StatusBadGateway, "bad gateway"), "gpt-5.4", nil, failed)) + require.Len(t, repo.modelReasons, 1, "the same before_stream rule still matches before output starts") +} + +func TestMemoryTempUnschedTriggerDelayedResetKeepsNewRound(t *testing.T) { + now := time.Unix(1_700_000_000, 0) + counter := newMemoryTempUnschedTriggerCounter(func() time.Time { return now }) + ctx := context.Background() + key := "temp_unsched_trigger:3:0:model:gpt-5.4" + + _, oldEpoch, err := counter.Increment(ctx, key, 5) + require.NoError(t, err) + _, oldEpoch, err = counter.Increment(ctx, key, 5) + require.NoError(t, err) + require.NoError(t, counter.Reset(ctx, key, oldEpoch)) + + count, newEpoch, err := counter.Increment(ctx, key, 5) + require.NoError(t, err) + require.Equal(t, int64(1), count) + require.NotEqual(t, oldEpoch, newEpoch) + + require.NoError(t, counter.Reset(ctx, key, oldEpoch)) + count, _, err = counter.Increment(ctx, key, 5) + require.NoError(t, err) + require.Equal(t, int64(2), count) +} diff --git a/backend/internal/service/temp_unsched_stream_timing_test.go b/backend/internal/service/temp_unsched_stream_timing_test.go new file mode 100644 index 000000000000..7317f35e4b7f --- /dev/null +++ b/backend/internal/service/temp_unsched_stream_timing_test.go @@ -0,0 +1,314 @@ +//go:build unit + +package service + +import ( + "context" + "encoding/json" + "net/http" + "net/http/httptest" + "testing" + "time" + + "github.com/Wei-Shaw/sub2api/internal/config" + "github.com/gin-gonic/gin" + "github.com/stretchr/testify/require" +) + +type recordingTempUnschedRepo struct { + AccountRepository + reasons []string + modelReasons []string +} + +func (r *recordingTempUnschedRepo) SetTempUnschedulable(_ context.Context, _ int64, _ time.Time, reason string) error { + r.reasons = append(r.reasons, reason) + return nil +} + +func (r *recordingTempUnschedRepo) SetModelRateLimit(_ context.Context, _ int64, _ string, _ time.Time, reason ...string) error { + if len(reason) > 0 { + r.modelReasons = append(r.modelReasons, reason[0]) + } else { + r.modelReasons = append(r.modelReasons, "") + } + return nil +} + +func (r *recordingTempUnschedRepo) GetByID(_ context.Context, id int64) (*Account, error) { + return &Account{ID: id}, nil +} + +func (r *recordingTempUnschedRepo) SetOverloaded(context.Context, int64, time.Time) error { return nil } +func (r *recordingTempUnschedRepo) SetRateLimited(context.Context, int64, time.Time) error { + return nil +} + +func tempUnschedTimingAccount(rules ...map[string]any) *Account { + raw := make([]any, 0, len(rules)) + for _, rule := range rules { + raw = append(raw, rule) + } + return &Account{ + ID: 77, + Platform: PlatformOpenAI, + Type: AccountTypeAPIKey, + Credentials: map[string]any{ + "temp_unschedulable_enabled": true, + "temp_unschedulable_rules": raw, + }, + Status: StatusActive, + Schedulable: true, + } +} + +func TestGetTempUnschedulableRules_MissingFieldsKeepLegacyDefaults(t *testing.T) { + account := tempUnschedTimingAccount(map[string]any{ + "error_code": float64(502), + "keywords": []any{"bad gateway"}, + "duration_minutes": float64(5), + "description": "legacy", + }) + + rules := account.GetTempUnschedulableRules() + require.Len(t, rules, 1) + require.Empty(t, rules[0].StreamTiming) + require.Equal(t, 1, rules[0].NormalizedTriggerCount()) + require.Equal(t, 1, rules[0].TriggerWindowMinutes(), "omitted trigger_window_minutes does not borrow duration_minutes") + require.Equal(t, 0, rules[0].TriggerCount, "omitted trigger_count stays unset so callers can tell it was missing") +} + +func TestGetTempUnschedulableRules_ParsesExplicitTimingAndCount(t *testing.T) { + account := tempUnschedTimingAccount(map[string]any{ + "error_code": "502", + "keywords": []any{"upstream_error"}, + "duration_minutes": float64(8), + "stream_timing": " AFTER_STREAM ", + "trigger_count": "3", + "trigger_window_minutes": "15", + "scope": "account", + }) + + rules := account.GetTempUnschedulableRules() + require.Len(t, rules, 1) + require.Equal(t, TempUnschedStreamAfter, rules[0].StreamTiming) + require.Equal(t, 3, rules[0].NormalizedTriggerCount()) + require.Equal(t, 15, rules[0].TriggerWindowMinutes()) + require.Equal(t, TempUnschedScopeAccount, rules[0].Scope) + + unknown := tempUnschedTimingAccount(map[string]any{ + "error_code": float64(429), + "keywords": []any{"rate limit"}, + "duration_minutes": float64(2), + "stream_timing": "whenever", + "trigger_count": float64(0), + }) + parsed := unknown.GetTempUnschedulableRules() + require.Empty(t, parsed[0].StreamTiming, "unrecognized timing stays legacy") + require.Equal(t, 1, parsed[0].NormalizedTriggerCount()) +} + +func TestAttemptTempUnschedulable_StreamPhaseAndTriggerCount(t *testing.T) { + body := []byte(`{"error":{"type":"upstream_error","message":"bad gateway"}}`) + rateBody := []byte(`{"error":{"message":"rate limit exceeded"}}`) + repo := &recordingTempUnschedRepo{} + svc := NewRateLimitService(repo, nil, &config.Config{}, nil, nil) + now := time.Date(2026, 11, 12, 12, 0, 0, 0, time.UTC) + clock := now + svc.SetTempUnschedTriggerCounter(newMemoryTempUnschedTriggerCounter(func() time.Time { return clock })) + + legacy502 := tempUnschedTimingAccount(map[string]any{ + "error_code": float64(502), + "keywords": []any{"bad gateway"}, + "duration_minutes": float64(5), + "scope": "account", + }) + require.Equal(t, tempUnschedTriggered, svc.attemptTempUnschedulable(context.Background(), legacy502, http.StatusBadGateway, body)) + require.Len(t, repo.reasons, 1) + repo.reasons = nil + + require.Equal(t, tempUnschedNoMatch, svc.attemptTempUnschedulable( + withTempUnschedStreamPhase(context.Background(), tempUnschedPhaseMidStreamOptIn), + legacy502, http.StatusBadGateway, body, + ), "omitted stream_timing must not match generic mid-stream 502") + repo.reasons = nil + require.Equal(t, tempUnschedTriggered, svc.attemptTempUnschedulable( + withTempUnschedStreamPhase(context.Background(), tempUnschedPhaseMidStreamLegacy), + legacy502, http.StatusBadGateway, body, + ), "legacy phase is the existing 401/429/503/529 side-effect path and still matches omitted timing") + + before502 := tempUnschedTimingAccount(map[string]any{ + "error_code": float64(502), + "keywords": []any{"bad gateway"}, + "duration_minutes": float64(5), + "scope": "account", + "stream_timing": TempUnschedStreamBefore, + }) + require.Equal(t, tempUnschedTriggered, svc.attemptTempUnschedulable(context.Background(), before502, http.StatusBadGateway, body)) + require.Equal(t, tempUnschedNoMatch, svc.attemptTempUnschedulable( + withTempUnschedStreamPhase(context.Background(), tempUnschedPhaseMidStreamOptIn), + before502, http.StatusBadGateway, body, + )) + repo.reasons = nil + + legacy429 := tempUnschedTimingAccount(map[string]any{ + "error_code": float64(429), + "keywords": []any{"rate limit"}, + "duration_minutes": float64(10), + "scope": "account", + }) + midLegacy := withTempUnschedStreamPhase(context.Background(), tempUnschedPhaseMidStreamLegacy) + require.Equal(t, tempUnschedTriggered, svc.attemptTempUnschedulable(midLegacy, legacy429, http.StatusTooManyRequests, rateBody)) + + before429 := tempUnschedTimingAccount(map[string]any{ + "error_code": float64(429), + "keywords": []any{"rate limit"}, + "duration_minutes": float64(10), + "scope": "account", + "stream_timing": TempUnschedStreamBefore, + }) + require.Equal(t, tempUnschedNoMatch, svc.attemptTempUnschedulable(midLegacy, before429, http.StatusTooManyRequests, rateBody)) + require.Equal(t, tempUnschedTriggered, svc.attemptTempUnschedulable(context.Background(), before429, http.StatusTooManyRequests, rateBody)) + repo.reasons = nil + + counted := tempUnschedTimingAccount(map[string]any{ + "error_code": float64(502), + "keywords": []any{"bad gateway"}, + "duration_minutes": float64(10), + "scope": "account", + "stream_timing": TempUnschedStreamAfter, + "trigger_count": float64(3), + "trigger_window_minutes": float64(10), + }) + optIn := withTempUnschedStreamPhase(context.Background(), tempUnschedPhaseMidStreamOptIn) + require.Equal(t, tempUnschedPending, svc.attemptTempUnschedulable(optIn, counted, http.StatusBadGateway, body)) + require.Equal(t, tempUnschedPending, svc.attemptTempUnschedulable(optIn, counted, http.StatusBadGateway, body)) + require.Empty(t, repo.reasons) + require.Equal(t, tempUnschedTriggered, svc.attemptTempUnschedulable(optIn, counted, http.StatusBadGateway, body)) + require.Len(t, repo.reasons, 1) + var state TempUnschedState + require.NoError(t, json.Unmarshal([]byte(repo.reasons[0]), &state)) + require.Equal(t, int64(3), state.TriggerCount) + require.Equal(t, 3, state.TriggerThreshold) + require.Equal(t, 10, state.TriggerWindowMinutes) + + // Cooldown resets the window, so the next matches start again at 1. + repo.reasons = nil + require.Equal(t, tempUnschedPending, svc.attemptTempUnschedulable(optIn, counted, http.StatusBadGateway, body)) + require.Empty(t, repo.reasons) + + // The fixed window expires with trigger_window_minutes, even if the threshold was not reached. + clock = now.Add(11 * time.Minute) + require.Equal(t, tempUnschedPending, svc.attemptTempUnschedulable(optIn, counted, http.StatusBadGateway, body)) + require.Equal(t, tempUnschedPending, svc.attemptTempUnschedulable(optIn, counted, http.StatusBadGateway, body)) + require.Empty(t, repo.reasons) + require.Equal(t, tempUnschedTriggered, svc.attemptTempUnschedulable(optIn, counted, http.StatusBadGateway, body)) +} + +func TestOpenAIStreamTerminal_MidStream502OnlyWhenOptedIn(t *testing.T) { + repo := &recordingTempUnschedRepo{} + svc := &OpenAIGatewayService{rateLimitService: NewRateLimitService(repo, nil, &config.Config{}, nil, nil)} + payload := []byte(`{"type":"error","error":{"type":"upstream_error","code":"upstream_error","message":"bad gateway"}}`) + account := func(timing any, count any) *Account { + rule := map[string]any{ + "error_code": float64(http.StatusBadGateway), + "keywords": []any{"upstream_error", "bad gateway"}, + "duration_minutes": float64(5), + "scope": "account", + } + if timing != nil { + rule["stream_timing"] = timing + } + if count != nil { + rule["trigger_count"] = count + } + return tempUnschedTimingAccount(rule) + } + + status, disabled := svc.handleOpenAIStreamTerminalAccountSideEffects(nil, account(nil, nil), payload, "bad gateway", nil, "gpt-test") + require.Equal(t, http.StatusBadGateway, status) + require.False(t, disabled) + require.Empty(t, repo.reasons) + + status, disabled = svc.handleOpenAIStreamTerminalAccountSideEffects(nil, account(TempUnschedStreamBefore, nil), payload, "bad gateway", nil, "gpt-test") + require.Equal(t, http.StatusBadGateway, status) + require.False(t, disabled) + require.Empty(t, repo.reasons) + + status, disabled = svc.handleOpenAIStreamTerminalAccountSideEffects(nil, account(TempUnschedStreamAfter, float64(2)), payload, "bad gateway", nil, "gpt-test") + require.Equal(t, http.StatusBadGateway, status) + require.False(t, disabled, "the first of two required matches must not cool the account") + require.Empty(t, repo.reasons) +} + +func TestOpenAIStreamTerminal_MidStream502OptInFiresOnSecondHit(t *testing.T) { + repo := &recordingTempUnschedRepo{} + limits := NewRateLimitService(repo, nil, &config.Config{}, nil, nil) + svc := &OpenAIGatewayService{rateLimitService: limits} + payload := []byte(`{"type":"error","error":{"type":"upstream_error","message":"bad gateway"}}`) + account := tempUnschedTimingAccount(map[string]any{ + "error_code": float64(http.StatusBadGateway), + "keywords": []any{"bad gateway"}, + "duration_minutes": float64(5), + "scope": "account", + "stream_timing": TempUnschedStreamAfter, + "trigger_count": float64(2), + "trigger_window_minutes": float64(5), + }) + + _, disabled := svc.handleOpenAIStreamTerminalAccountSideEffects(nil, account, payload, "bad gateway", nil, "gpt-test") + require.False(t, disabled) + require.Empty(t, repo.reasons) + + status, disabled := svc.handleOpenAIStreamTerminalAccountSideEffects(nil, account, payload, "bad gateway", nil, "gpt-test") + require.Equal(t, http.StatusBadGateway, status) + require.True(t, disabled) + require.Len(t, repo.reasons, 1) + var state TempUnschedState + require.NoError(t, json.Unmarshal([]byte(repo.reasons[0]), &state)) + require.Equal(t, int64(2), state.TriggerCount) + require.Equal(t, 2, state.TriggerThreshold) + require.Equal(t, 5, state.TriggerWindowMinutes) +} + +func TestSSEStreamError_MidStreamOverloadRequiresOptIn(t *testing.T) { + gin.SetMode(gin.TestMode) + rec := httptest.NewRecorder() + c, _ := gin.CreateTestContext(rec) + c.Request = httptest.NewRequest(http.MethodPost, "/v1/messages", nil) + repo := &recordingTempUnschedRepo{} + svc := &GatewayService{rateLimitService: NewRateLimitService(repo, nil, &config.Config{}, nil, nil)} + resp := &http.Response{Header: http.Header{}, StatusCode: http.StatusOK} + body := `{"type":"error","error":{"type":"overloaded_error","message":"Overloaded"}}` + account := func(timing any) *Account { + rule := map[string]any{ + "error_code": float64(529), + "keywords": []any{"Overloaded"}, + "duration_minutes": float64(15), + "scope": "model", + } + if timing != nil { + rule["stream_timing"] = timing + } + got := tempUnschedTimingAccount(rule) + got.Platform = PlatformAnthropic + return got + } + + err := svc.sseStreamErrorEventFailover(context.Background(), c, account(nil), resp, body, "claude-sonnet", true) + require.NotNil(t, err) + require.Equal(t, http.StatusForbidden, err.StatusCode) + require.Empty(t, repo.modelReasons) + require.Empty(t, repo.reasons) + + _ = svc.sseStreamErrorEventFailover(context.Background(), c, account(TempUnschedStreamBefore), resp, body, "claude-sonnet", true) + require.Empty(t, repo.modelReasons) + + _ = svc.sseStreamErrorEventFailover(context.Background(), c, account(TempUnschedStreamAfter), resp, body, "claude-sonnet", true) + require.Len(t, repo.modelReasons, 1) + var state TempUnschedState + require.NoError(t, json.Unmarshal([]byte(repo.modelReasons[0]), &state)) + require.Equal(t, TempUnschedScopeModel, state.Scope) + require.Equal(t, "claude-sonnet", state.Model) + require.Equal(t, 529, state.StatusCode) +} diff --git a/backend/internal/service/temp_unsched_trigger_counter.go b/backend/internal/service/temp_unsched_trigger_counter.go new file mode 100644 index 000000000000..6a86fbc3a13e --- /dev/null +++ b/backend/internal/service/temp_unsched_trigger_counter.go @@ -0,0 +1,87 @@ +package service + +import ( + "context" + "fmt" + "strings" + "sync" + "time" +) + +// memoryTempUnschedTriggerCounter 是单进程固定窗口计数器。 +// Redis 不可用时使用它,测试也可以注入可控时钟。 +type memoryTempUnschedTriggerCounter struct { + mu sync.Mutex + now func() time.Time + items map[string]tempUnschedTriggerEntry + seq int64 +} + +type tempUnschedTriggerEntry struct { + count int64 + expires time.Time + epoch string +} + +func newMemoryTempUnschedTriggerCounter(now func() time.Time) *memoryTempUnschedTriggerCounter { + if now == nil { + now = time.Now + } + return &memoryTempUnschedTriggerCounter{ + now: now, + items: make(map[string]tempUnschedTriggerEntry), + } +} + +func (c *memoryTempUnschedTriggerCounter) Increment(_ context.Context, key string, windowMinutes int) (int64, string, error) { + if c == nil { + return 0, "", fmt.Errorf("temp unsched trigger counter is nil") + } + if windowMinutes < 1 { + windowMinutes = 1 + } + now := c.now() + c.mu.Lock() + defer c.mu.Unlock() + entry, ok := c.items[key] + if !ok || !entry.expires.After(now) { + c.seq++ + entry = tempUnschedTriggerEntry{ + count: 1, + expires: now.Add(time.Duration(windowMinutes) * time.Minute), + epoch: fmt.Sprintf("%d:%d", now.UnixNano(), c.seq), + } + c.items[key] = entry + return entry.count, entry.epoch, nil + } + entry.count++ + c.items[key] = entry + return entry.count, entry.epoch, nil +} + +func (c *memoryTempUnschedTriggerCounter) Reset(_ context.Context, key string, epoch string) error { + if c == nil { + return fmt.Errorf("temp unsched trigger counter is nil") + } + if epoch == "" { + return nil + } + c.mu.Lock() + defer c.mu.Unlock() + entry, ok := c.items[key] + if !ok || entry.epoch != epoch { + return nil + } + delete(c.items, key) + return nil +} + +func tempUnschedTriggerCounterKey(accountID int64, ruleIndex int, modelScoped bool, modelKey string) string { + if modelScoped { + modelKey = strings.TrimSpace(modelKey) + if modelKey != "" { + return fmt.Sprintf("temp_unsched_trigger:%d:%d:model:%s", accountID, ruleIndex, modelKey) + } + } + return fmt.Sprintf("temp_unsched_trigger:%d:%d:account", accountID, ruleIndex) +} diff --git a/backend/internal/service/temp_unsched_ws_forward_test.go b/backend/internal/service/temp_unsched_ws_forward_test.go new file mode 100644 index 000000000000..a277ed9ea4ab --- /dev/null +++ b/backend/internal/service/temp_unsched_ws_forward_test.go @@ -0,0 +1,189 @@ +//go:build unit + +package service + +import ( + "context" + "net/http" + "net/http/httptest" + "strings" + "sync/atomic" + "testing" + "time" + + coderws "github.com/coder/websocket" + "github.com/gin-gonic/gin" + "github.com/gorilla/websocket" + "github.com/stretchr/testify/require" +) + +type tempUnschedWSForwardRepo struct { + openAIWSRateLimitSignalRepo + modelReasons []string + errors int + scheduling []bool +} + +func (r *tempUnschedWSForwardRepo) SetModelRateLimit(_ context.Context, _ int64, _ string, _ time.Time, reason ...string) error { + r.modelReasons = append(r.modelReasons, strings.Join(reason, "")) + return nil +} + +func (r *tempUnschedWSForwardRepo) SetError(context.Context, int64, string) error { + r.errors++ + return nil +} + +func (r *tempUnschedWSForwardRepo) SetSchedulable(_ context.Context, _ int64, value bool) error { + r.scheduling = append(r.scheduling, value) + return nil +} + +type tempUnschedWSForwardCounter struct { + inner *memoryTempUnschedTriggerCounter + hits int +} + +func (c *tempUnschedWSForwardCounter) Increment(ctx context.Context, key string, window int) (int64, string, error) { + c.hits++ + return c.inner.Increment(ctx, key, window) +} + +func (c *tempUnschedWSForwardCounter) Reset(ctx context.Context, key, epoch string) error { + return c.inner.Reset(ctx, key, epoch) +} + +// Both cases enter a public gateway forwarding method and send a real upstream +// output delta before semantic 429. No phase flag or side-effect helper is called +// by the fixture. The before/after controls share the identical transport. +func TestTempUnschedWSForwardAfterOutputSemantic429(t *testing.T) { + gin.SetMode(gin.TestMode) + for _, entry := range []string{"v2", "ingress"} { + for _, timing := range []string{TempUnschedStreamBefore, TempUnschedStreamAfter} { + t.Run(entry+"/"+timing, func(t *testing.T) { + var peers atomic.Int64 + upstream := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + conn, err := (&websocket.Upgrader{CheckOrigin: func(*http.Request) bool { return true }}).Upgrade(w, r, nil) + if err != nil { + t.Error(err) + return + } + defer conn.Close() + var request map[string]any + if err := conn.ReadJSON(&request); err != nil { + t.Error(err) + return + } + peers.Add(1) + for _, frame := range []string{ + `{"type":"response.output_text.delta","response_id":"resp_phase_fixture","delta":"visible-token"}`, + `{"type":"error","error":{"type":"rate_limit_error","code":"rate_limit_exceeded","message":"fixture rate limit reached"}}`, + } { + if err := conn.WriteMessage(websocket.TextMessage, []byte(frame)); err != nil { + t.Error(err) + return + } + } + })) + defer upstream.Close() + cfg := newOpenAIWSV2TestConfig() + cfg.Security.URLAllowlist.Enabled = false + cfg.Security.URLAllowlist.AllowInsecureHTTP = true + account := tempUnschedTimingAccount(map[string]any{ + "error_code": float64(429), "keywords": []any{"rate_limit_exceeded"}, + "scope": "model", "duration_minutes": float64(5), "stream_timing": timing, + "trigger_count": float64(3), "trigger_window_minutes": float64(5), + }) + account.Concurrency = 1 + account.Extra = map[string]any{"responses_websockets_v2_enabled": true} + for key, value := range openAIWSQuotaTestCredentials(AccountTypeAPIKey, upstream.URL) { + account.Credentials[key] = value + } + repo := &tempUnschedWSForwardRepo{openAIWSRateLimitSignalRepo: openAIWSRateLimitSignalRepo{ + stubOpenAIAccountRepo: stubOpenAIAccountRepo{accounts: []Account{*account}}, + }} + rates := NewRateLimitService(repo, nil, cfg, nil, nil) + counter := &tempUnschedWSForwardCounter{inner: newMemoryTempUnschedTriggerCounter(time.Now)} + rates.SetTempUnschedTriggerCounter(counter) + httpFallback := &httpUpstreamRecorder{} + pool := newOpenAIWSConnPool(cfg) + defer pool.Close() + pool.setClientDialerForTest(&openAIWSQuotaLocalDialer{url: "ws" + strings.TrimPrefix(upstream.URL, "http")}) + gateway := &OpenAIGatewayService{accountRepo: repo, rateLimitService: rates, httpUpstream: httpFallback, + cache: &stubGatewayCache{}, cfg: cfg, openaiWSResolver: NewOpenAIWSProtocolResolver(cfg), + toolCorrector: NewCodexToolCorrector(), openaiWSPool: pool} + for attempt := 1; attempt <= 3; attempt++ { + if entry == "v2" { + recorder := httptest.NewRecorder() + c, _ := gin.CreateTestContext(recorder) + c.Request = httptest.NewRequest(http.MethodPost, "/v1/responses", nil) + c.Request.Header.Set("User-Agent", "unit-test-agent/1.0") + _, err := gateway.Forward(t.Context(), c, account, []byte(`{"model":"gpt-5.1","stream":true,"input":"fixture"}`)) + require.Error(t, err) + require.Contains(t, recorder.Body.String(), "visible-token", "Forward must deliver output before semantic429") + require.Contains(t, recorder.Body.String(), "rate_limit_exceeded") + } else { + tempUnschedWSForwardIngress(t, gateway, account) + } + wantHits, wantCooldowns := 0, 0 + if timing == TempUnschedStreamAfter { + wantHits = attempt + if attempt == 3 { + wantCooldowns = 1 + } + } + require.Equal(t, wantHits, counter.hits, "semantic429 must respect the real output phase and count each response once") + require.Len(t, repo.modelReasons, wantCooldowns, "pending matches cannot cool before the third independent failure") + require.Zero(t, repo.errors, "pending model failures cannot permanently disable the account") + require.Empty(t, repo.scheduling, "semantic429 cannot change permanent scheduling for an API key") + require.EqualValues(t, attempt, peers.Load(), "each attempt must reach the real upstream") + require.Nil(t, httpFallback.lastReq, "the fixture must stay on its WebSocket forwarding entry") + } + }) + } + } +} + +func tempUnschedWSForwardIngress(t *testing.T, gateway *OpenAIGatewayService, account *Account) { + t.Helper() + done := make(chan error, 1) + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + conn, err := coderws.Accept(w, r, nil) + if err != nil { + done <- err + return + } + defer conn.CloseNow() + ctx, cancel := context.WithTimeout(r.Context(), 10*time.Second) + defer cancel() + _, first, err := conn.Read(ctx) + if err != nil { + done <- err + return + } + c, _ := gin.CreateTestContext(httptest.NewRecorder()) + c.Request = r.Clone(ctx) + c.Request.Header.Set("User-Agent", "unit-test-agent/1.0") + done <- gateway.ProxyResponsesWebSocketFromClient(ctx, c, conn, account, "fictional-key", first, nil) + })) + defer server.Close() + ctx, cancel := context.WithTimeout(t.Context(), 15*time.Second) + defer cancel() + client, _, err := coderws.Dial(ctx, "ws"+strings.TrimPrefix(server.URL, "http"), nil) + require.NoError(t, err) + defer client.CloseNow() + require.NoError(t, client.Write(ctx, coderws.MessageText, []byte(`{"type":"response.create","model":"gpt-5.1","stream":true,"input":"fixture"}`))) + _, output, err := client.Read(ctx) + require.NoError(t, err) + require.Contains(t, string(output), "visible-token", "ingress must deliver output before semantic429") + _, failure, err := client.Read(ctx) + require.NoError(t, err) + require.Contains(t, string(failure), "rate_limit_exceeded") + client.CloseNow() + select { + case err := <-done: + require.NotErrorIs(t, err, context.DeadlineExceeded) + case <-ctx.Done(): + t.Fatal("ingress forwarding did not terminate after the client closed") + } +} diff --git a/backend/internal/service/wire.go b/backend/internal/service/wire.go index 47afa11cd360..f5292274376d 100644 --- a/backend/internal/service/wire.go +++ b/backend/internal/service/wire.go @@ -620,10 +620,13 @@ func ProvideRateLimitService( tokenCacheInvalidator TokenCacheInvalidator, ollamaCloudUsage *OllamaCloudUsageService, accountOps *AccountOpsService, + tempUnschedTriggerCounter TempUnschedTriggerCounter, rdb *redis.Client, ) *RateLimitService { svc := NewRateLimitService(accountRepo, usageRepo, cfg, geminiQuotaService, tempUnschedCache) svc.accountOps = accountOps + // Redis 计数让多实例共享同一条规则的错误累计;rdb 为空时构造器返回 nil,服务回退到进程内窗口。 + svc.SetTempUnschedTriggerCounter(tempUnschedTriggerCounter) if rdb != nil { svc.qualityTrigger = &quality5xxTrigger{queue: qualityqueue.NewRedis(rdb)} } diff --git a/docs/testing/oauth429-weekly-only.md b/docs/testing/oauth429-weekly-only.md index 7d16d22e9583..ca5ecf58074e 100644 --- a/docs/testing/oauth429-weekly-only.md +++ b/docs/testing/oauth429-weekly-only.md @@ -6,6 +6,30 @@ stream/WS sites that separate permanent-policy evidence from temporary cooldown All public fixtures are fictional. Local work is static only; dynamic evidence is produced by `.github/workflows/oauth429-weekly-only.yml` on GitHub Actions. +## Historical-source compilation boundary + +The service RED worktree starts at the exact candidate SHA and restores only the +13 pinned production blobs listed in the workflow from the baseline above. +`restored-blobs.txt` and `candidate-source-blobs.txt` record both sides. The old +WS implementation intentionally remains unchanged: adding the newer +`openAIWSForwardStreamPhaseContext` helper would alter the counterexample. + +Only `backend/internal/service/temp_unsched_pending_test.go` is excluded from +this disposable service RED worktree. It is absent at the baseline and its WS +test references that candidate-only helper; none of its tests or fixtures is a +weekly429 regression dependency. `excluded-tests.txt` records its exact +candidate blob and the reason. The candidate checkout keeps the entire file; +the race-enabled GREEN command and evidence validator require all six of its +top-level regressions to pass, including response counting, pending/credential +401 controls, WS stream phase and delayed counter reset. + +All weekly429 service/repository test blobs stay identical to the candidate, +with the full list and hashes in `retained-tests.txt` and +`retained-test-blobs.txt`. No other test modification is allowed in the service +RED worktree. Cache, expiry and PostgreSQL query RED worktrees retain all tests +and their existing source boundaries. A compile/setup failure, skip, panic or +missing target assertion still cannot satisfy the behavioral RED validator. + An opted-in OAuth owner is permanently disabled only on an actual upstream 429 when valid explicitly identified 10080-minute usage is strictly above its own threshold (default 98). Primary and secondary are judged independently. A 5h, diff --git a/frontend/src/components/account/CreateAccountModal.vue b/frontend/src/components/account/CreateAccountModal.vue index cc369e28c836..3df3e4523a01 100644 --- a/frontend/src/components/account/CreateAccountModal.vue +++ b/frontend/src/components/account/CreateAccountModal.vue @@ -2767,6 +2767,7 @@ class="input" :placeholder="t('admin.accounts.tempUnschedulable.durationPlaceholder')" /> +

{{ t('admin.accounts.tempUnschedulable.durationHint') }}

@@ -2806,6 +2807,72 @@

{{ t('admin.accounts.tempUnschedulable.scopeHint') }}

+
+
+ + +
+
+ +
+

{{ t('admin.accounts.tempUnschedulable.streamTimingHint') }}

+
+
+ + +

{{ t('admin.accounts.tempUnschedulable.triggerCountHint') }}

+
+
+ + +

{{ t('admin.accounts.tempUnschedulable.triggerWindowHint') }}

+
>(() => [ + { + value: 'before_stream', + label: t('admin.accounts.tempUnschedulable.streamTimingBefore'), + description: t('admin.accounts.tempUnschedulable.streamTimingBeforeDesc') + }, + { + value: 'after_stream', + label: t('admin.accounts.tempUnschedulable.streamTimingAfter'), + description: t('admin.accounts.tempUnschedulable.streamTimingAfterDesc') + } +]) const tempUnschedPresets = computed(() => [ { @@ -5188,7 +5273,10 @@ const tempUnschedPresets = computed(() => [ keywords: 'overloaded, too many', duration_minutes: 60, description: t('admin.accounts.tempUnschedulable.presets.overloadDesc'), - scope: 'model' as const + scope: 'model' as const, + stream_timing: 'after_stream' as const, + trigger_count: 1, + trigger_window_minutes: 5 } }, { @@ -5198,7 +5286,10 @@ const tempUnschedPresets = computed(() => [ keywords: 'rate limit, too many requests', duration_minutes: 10, description: t('admin.accounts.tempUnschedulable.presets.rateLimitDesc'), - scope: 'model' as const + scope: 'model' as const, + stream_timing: 'after_stream' as const, + trigger_count: 1, + trigger_window_minutes: 5 } }, { @@ -5208,7 +5299,10 @@ const tempUnschedPresets = computed(() => [ keywords: 'unavailable, maintenance', duration_minutes: 30, description: t('admin.accounts.tempUnschedulable.presets.unavailableDesc'), - scope: 'model' as const + scope: 'model' as const, + stream_timing: 'after_stream' as const, + trigger_count: 1, + trigger_window_minutes: 5 } } ]) @@ -5605,7 +5699,10 @@ const addTempUnschedRule = (preset?: TempUnschedRuleForm) => { keywords: '', duration_minutes: 30, description: '', - scope: 'model' + scope: 'model', + stream_timing: 'before_stream', + trigger_count: 1, + trigger_window_minutes: 5 }) } @@ -5629,6 +5726,9 @@ const buildTempUnschedRules = (rules: TempUnschedRuleForm[]) => { duration_minutes: number description: string scope: TempUnschedulableScope + stream_timing: TempUnschedulableStreamTiming + trigger_count: number + trigger_window_minutes: number }> = [] for (const rule of rules) { @@ -5649,7 +5749,10 @@ const buildTempUnschedRules = (rules: TempUnschedRuleForm[]) => { keywords, duration_minutes: Math.trunc(duration), description: rule.description.trim(), - scope: rule.scope + scope: rule.scope, + stream_timing: rule.stream_timing === 'after_stream' ? 'after_stream' : 'before_stream', + trigger_count: resolveTempUnschedTriggerCount(rule.trigger_count), + trigger_window_minutes: resolveTempUnschedTriggerWindow(rule.trigger_window_minutes) }) } @@ -5681,6 +5784,22 @@ const splitTempUnschedKeywords = (value: string) => { .filter((item) => item.length > 0) } +function resolveTempUnschedTriggerCount(value: unknown): number { + const num = Number(value) + if (!Number.isFinite(num) || num < 1) { + return 1 + } + return Math.min(1000, Math.trunc(num)) +} + +function resolveTempUnschedTriggerWindow(value: unknown): number { + const num = Number(value) + if (!Number.isFinite(num) || num < 1) { + return 1 + } + return Math.trunc(num) +} + const needsMixedChannelCheck = (platform: AccountPlatform) => platform === 'antigravity' || platform === 'anthropic' const buildMixedChannelDetails = (resp?: CheckMixedChannelResponse) => { diff --git a/frontend/src/components/account/EditAccountModal.vue b/frontend/src/components/account/EditAccountModal.vue index f9dcee5c6ca6..0e3ed85cfb42 100644 --- a/frontend/src/components/account/EditAccountModal.vue +++ b/frontend/src/components/account/EditAccountModal.vue @@ -1835,6 +1835,7 @@ class="input" :placeholder="t('admin.accounts.tempUnschedulable.durationPlaceholder')" /> +

{{ t('admin.accounts.tempUnschedulable.durationHint') }}

@@ -1874,6 +1875,72 @@

{{ t('admin.accounts.tempUnschedulable.scopeHint') }}

+
+
+ + +
+
+ +
+

{{ t('admin.accounts.tempUnschedulable.streamTimingHint') }}

+
+
+ + +

{{ t('admin.accounts.tempUnschedulable.triggerCountHint') }}

+
+
+ + +

{{ t('admin.accounts.tempUnschedulable.triggerWindowHint') }}

+
>(() => [ + { + value: 'before_stream', + label: t('admin.accounts.tempUnschedulable.streamTimingBefore'), + description: t('admin.accounts.tempUnschedulable.streamTimingBeforeDesc') + }, + { + value: 'after_stream', + label: t('admin.accounts.tempUnschedulable.streamTimingAfter'), + description: t('admin.accounts.tempUnschedulable.streamTimingAfterDesc') + } +]) const tempUnschedPresets = computed(() => [ { @@ -4911,7 +4997,10 @@ const tempUnschedPresets = computed(() => [ keywords: 'overloaded, too many', duration_minutes: 60, description: t('admin.accounts.tempUnschedulable.presets.overloadDesc'), - scope: 'model' as const + scope: 'model' as const, + stream_timing: 'after_stream' as const, + trigger_count: 1, + trigger_window_minutes: 5 } }, { @@ -4921,7 +5010,10 @@ const tempUnschedPresets = computed(() => [ keywords: 'rate limit, too many requests', duration_minutes: 10, description: t('admin.accounts.tempUnschedulable.presets.rateLimitDesc'), - scope: 'model' as const + scope: 'model' as const, + stream_timing: 'after_stream' as const, + trigger_count: 1, + trigger_window_minutes: 5 } }, { @@ -4931,7 +5023,10 @@ const tempUnschedPresets = computed(() => [ keywords: 'unavailable, maintenance', duration_minutes: 30, description: t('admin.accounts.tempUnschedulable.presets.unavailableDesc'), - scope: 'model' as const + scope: 'model' as const, + stream_timing: 'after_stream' as const, + trigger_count: 1, + trigger_window_minutes: 5 } } ]) @@ -5758,9 +5853,9 @@ const removeErrorCode = (code: number) => { } } -const addTempUnschedRule = (preset?: TempUnschedRuleForm) => { +const addTempUnschedRule = (preset?: Omit) => { if (preset) { - tempUnschedRules.value.push({ ...preset }) + tempUnschedRules.value.push({ ...preset, stream_timing_explicit: true }) return } tempUnschedRules.value.push({ @@ -5768,10 +5863,19 @@ const addTempUnschedRule = (preset?: TempUnschedRuleForm) => { keywords: '', duration_minutes: 30, description: '', - scope: 'model' + scope: 'model', + stream_timing: 'before_stream', + stream_timing_explicit: true, + trigger_count: 1, + trigger_window_minutes: 5 }) } +function chooseTempUnschedStreamTiming(rule: TempUnschedRuleForm, timing: TempUnschedulableStreamTiming) { + rule.stream_timing = timing + rule.stream_timing_explicit = true +} + const removeTempUnschedRule = (index: number) => { tempUnschedRules.value.splice(index, 1) } @@ -5792,6 +5896,9 @@ const buildTempUnschedRules = (rules: TempUnschedRuleForm[]) => { duration_minutes: number description: string scope: TempUnschedulableScope + stream_timing?: TempUnschedulableStreamTiming + trigger_count: number + trigger_window_minutes: number }> = [] for (const rule of rules) { @@ -5807,13 +5914,19 @@ const buildTempUnschedRules = (rules: TempUnschedRuleForm[]) => { if (keywords.length === 0) { continue } - out.push({ + const next: (typeof out)[number] = { error_code: Math.trunc(errorCode), keywords, duration_minutes: Math.trunc(duration), description: rule.description.trim(), - scope: rule.scope - }) + scope: rule.scope, + trigger_count: resolveTempUnschedTriggerCount(rule.trigger_count), + trigger_window_minutes: resolveTempUnschedTriggerWindow(rule.trigger_window_minutes) + } + if (rule.stream_timing_explicit) { + next.stream_timing = rule.stream_timing === 'after_stream' ? 'after_stream' : 'before_stream' + } + out.push(next) } return out @@ -5916,7 +6029,11 @@ function loadTempUnschedRules(credentials?: Record) { keywords: formatTempUnschedKeywords(entry.keywords), duration_minutes: toPositiveNumber(entry.duration_minutes), description: typeof entry.description === 'string' ? entry.description : '', - scope: resolveTempUnschedScope(entry.scope, errorCode) + scope: resolveTempUnschedScope(entry.scope, errorCode), + stream_timing: explicitTempUnschedStreamTiming(entry.stream_timing) ?? resolveTempUnschedStreamTiming(entry.stream_timing, errorCode), + stream_timing_explicit: explicitTempUnschedStreamTiming(entry.stream_timing) !== null, + trigger_count: resolveTempUnschedTriggerCount(entry.trigger_count), + trigger_window_minutes: resolveTempUnschedTriggerWindow(entry.trigger_window_minutes) } }) } @@ -6034,6 +6151,46 @@ function resolveTempUnschedScope(value: unknown, errorCode: number | null): Temp return errorCode === 401 ? 'account' : 'model' } +function explicitTempUnschedStreamTiming(value: unknown): TempUnschedulableStreamTiming | null { + const timing = typeof value === 'string' ? value.trim().toLowerCase() : '' + if (timing === 'before_stream' || timing === 'after_stream') { + return timing + } + return null +} + +// 旧规则没有 stream_timing。表单仍按当前后端行为回显一个选项: +// 401/403/429/503/529 今天可以在部分流中途触发,其余错误码(含 502)不可以。 +// 回显不等于迁移。未改这个选项时保存必须继续省略 stream_timing, +// 否则一次只改账号名的保存会把 Anthropic 529 旧规则写成 after_stream, +// 让原本不处理的流输出后 overloaded_error 开始冷却。 +function resolveTempUnschedStreamTiming(value: unknown, errorCode: number | null): TempUnschedulableStreamTiming { + const explicit = explicitTempUnschedStreamTiming(value) + if (explicit) { + return explicit + } + if (errorCode != null && [401, 403, 429, 503, 529].includes(errorCode)) { + return 'after_stream' + } + return 'before_stream' +} + +function resolveTempUnschedTriggerCount(value: unknown): number { + const num = Number(value) + if (!Number.isFinite(num) || num < 1) { + return 1 + } + return Math.min(1000, Math.trunc(num)) +} + +function resolveTempUnschedTriggerWindow(value: unknown): number { + const num = Number(value) + if (!Number.isFinite(num) || num < 1) { + return 1 + } + return Math.trunc(num) +} + const splitTempUnschedKeywords = (value: string) => { return value .split(/[,;]/) diff --git a/frontend/src/components/account/__tests__/EditAccountModal.spec.ts b/frontend/src/components/account/__tests__/EditAccountModal.spec.ts index c6f12fdcda5d..a8fd3806ba6d 100644 --- a/frontend/src/components/account/__tests__/EditAccountModal.spec.ts +++ b/frontend/src/components/account/__tests__/EditAccountModal.spec.ts @@ -3114,6 +3114,10 @@ describe('EditAccountModal gemini explicit cache upstream switch', () => { }) describe('EditAccountModal temp-unschedulable rule scope', () => { + beforeEach(() => { + setActivePinia(createPinia()) + }) + function buildAccountWithTempUnschedRules(rules: Array>) { const account = buildAccount() return { @@ -3187,6 +3191,127 @@ describe('EditAccountModal temp-unschedulable rule scope', () => { expect(checkedScopes(wrapper)).toEqual(['temp-unsched-scope-model']) wrapper.unmount() }) + + const checkedStreamTimings = (wrapper: ReturnType) => + wrapper + .findAll('[data-testid^="temp-unsched-stream-"][aria-checked="true"]') + .map((radio) => radio.attributes('data-testid')) + + it('shows a timing choice and count for saved rules that omit the new fields', async () => { + const account = buildAccountWithTempUnschedRules([ + { error_code: 429, keywords: ['rate limit'], duration_minutes: 10 }, + { error_code: 502, keywords: ['bad gateway'], duration_minutes: 5 } + ]) + updateAccountMock.mockResolvedValue(account) + const wrapper = mountModal(account) + + expect(checkedStreamTimings(wrapper)).toEqual([ + 'temp-unsched-stream-after_stream', + 'temp-unsched-stream-before_stream' + ]) + const announcements = wrapper.findAllComponents(NewFeatureBadge).filter( + (badge) => badge.props('noticeId') === NEW_FEATURE_NOTICES.tempUnschedStreamCountWindow + ) + expect(announcements).toHaveLength(2) + expect(announcements.every((badge) => badge.props('userId') === 41)).toBe(true) + await announcements[0].get('button').trigger('click') + expect( + wrapper.findAllComponents(NewFeatureBadge).filter( + (badge) => badge.props('noticeId') === NEW_FEATURE_NOTICES.tempUnschedStreamCountWindow && badge.find('button').exists() + ) + ).toHaveLength(0) + const counts = wrapper.findAll('[data-testid="temp-unsched-trigger-count"]') + expect(counts).toHaveLength(2) + expect((counts[0].element as HTMLInputElement).value).toBe('1') + expect((counts[1].element as HTMLInputElement).value).toBe('1') + const windows = wrapper.findAll('[data-testid="temp-unsched-trigger-window"]') + expect(windows).toHaveLength(2) + expect((windows[0].element as HTMLInputElement).value).toBe('1') + expect((windows[1].element as HTMLInputElement).value).toBe('1') + + await counts[1].setValue('3') + await windows[1].setValue('8') + await wrapper.get('form#edit-account-form').trigger('submit.prevent') + + expect(savedRules()).toMatchObject([ + { error_code: 429, trigger_count: 1, trigger_window_minutes: 1 }, + { error_code: 502, trigger_count: 3, trigger_window_minutes: 8 } + ]) + expect(savedRules()[0]).not.toHaveProperty('stream_timing') + expect(savedRules()[1]).not.toHaveProperty('stream_timing') + wrapper.unmount() + }) + + it('keeps an omitted legacy 529 timing when only another account field is saved', async () => { + const account = buildAccountWithTempUnschedRules([ + { + error_code: 529, + keywords: ['Overloaded'], + duration_minutes: 15, + description: 'legacy overload', + scope: 'model' + } + ]) + account.platform = 'anthropic' + account.name = 'Claude relay' + updateAccountMock.mockResolvedValue(account) + const wrapper = mountModal(account) + + expect(checkedStreamTimings(wrapper)).toEqual(['temp-unsched-stream-after_stream']) + await wrapper.get('[data-tour="edit-account-form-name"]').setValue('Claude relay renamed') + await wrapper.get('form#edit-account-form').trigger('submit.prevent') + + expect(updateAccountMock).toHaveBeenCalledWith( + account.id, + expect.objectContaining({ name: 'Claude relay renamed' }) + ) + expect(savedRules()).toHaveLength(1) + expect(savedRules()[0]).toMatchObject({ + error_code: 529, + keywords: ['Overloaded'], + duration_minutes: 15, + description: 'legacy overload', + scope: 'model' + }) + expect(savedRules()[0]).not.toHaveProperty('stream_timing') + wrapper.unmount() + }) + + it('writes stream_timing only after the operator changes that control', async () => { + const account = buildAccountWithTempUnschedRules([ + { error_code: 529, keywords: ['Overloaded'], duration_minutes: 15, scope: 'model' } + ]) + updateAccountMock.mockResolvedValue(account) + const wrapper = mountModal(account) + + await wrapper.get('[data-testid="temp-unsched-stream-before_stream"]').trigger('click') + await wrapper.get('form#edit-account-form').trigger('submit.prevent') + + expect(savedRules()[0]).toMatchObject({ error_code: 529, stream_timing: 'before_stream' }) + wrapper.unmount() + }) + + it('defaults a custom rule to before-stream and count 1, and presets to after-stream', async () => { + const wrapper = mountModal(buildAccountWithTempUnschedRules([])) + + const addRule = wrapper + .findAll('button') + .find((button) => button.text().includes('admin.accounts.tempUnschedulable.addRule')) + await addRule!.trigger('click') + expect(checkedStreamTimings(wrapper)).toEqual(['temp-unsched-stream-before_stream']) + expect((wrapper.get('[data-testid="temp-unsched-trigger-count"]').element as HTMLInputElement).value).toBe('1') + expect((wrapper.get('[data-testid="temp-unsched-trigger-window"]').element as HTMLInputElement).value).toBe('5') + + const preset = wrapper + .findAll('button') + .find((button) => button.text().includes('admin.accounts.tempUnschedulable.presets.overloadLabel')) + await preset!.trigger('click') + expect(checkedStreamTimings(wrapper)).toEqual([ + 'temp-unsched-stream-before_stream', + 'temp-unsched-stream-after_stream' + ]) + wrapper.unmount() + }) }) diff --git a/frontend/src/constants/newFeatureNotices.ts b/frontend/src/constants/newFeatureNotices.ts index 4d88a3902b10..64989f14bc74 100644 --- a/frontend/src/constants/newFeatureNotices.ts +++ b/frontend/src/constants/newFeatureNotices.ts @@ -58,4 +58,5 @@ export const NEW_FEATURE_NOTICES = { openaiImageHeaderTimeoutGroups: 'openai-image-header-timeout-groups-initial-announcement', oauthInitialModelSelection: 'oauth-initial-model-selection-initial-announcement', usageRateCard: 'usage-rpm-tpm-card-initial-announcement', + tempUnschedStreamCountWindow: 'temp-unsched-stream-timing-count-window', } as const diff --git a/frontend/src/i18n/locales/en/admin/accounts.ts b/frontend/src/i18n/locales/en/admin/accounts.ts index 0e6c1c370971..13341bee39b7 100644 --- a/frontend/src/i18n/locales/en/admin/accounts.ts +++ b/frontend/src/i18n/locales/en/admin/accounts.ts @@ -615,6 +615,7 @@ export default { errorCodePlaceholder: 'e.g. 429', durationMinutes: 'Duration (minutes)', durationPlaceholder: 'e.g. 30', + durationHint: 'How long scheduling stays paused after cooldown starts. Independent of the error-count window.', keywords: 'Keywords', keywordsPlaceholder: 'e.g. overloaded, too many requests', keywordsHint: 'Separate keywords with commas; any keyword match will trigger.', @@ -624,6 +625,18 @@ export default { scopeAccount: 'Account', scopeAccountDesc: 'Pause scheduling for the whole account', scopeHint: 'Model-scoped rules fall back to account scope when the request model cannot be identified.', + streamTiming: 'Trigger timing', + streamTimingBefore: 'Before stream only', + streamTimingBeforeDesc: 'Cool down only on HTTP errors before the upstream stream starts', + streamTimingAfter: 'Also after stream starts', + streamTimingAfterDesc: 'Also cool down on failures after the stream has started, including mid-stream 502', + streamTimingHint: 'Before stream only ignores failures after the stream has started. Saved rules without this field keep current behavior: mid-stream 401/403/429/503/529 can still match, and mid-stream 502 does not unless you choose also after stream starts.', + triggerCount: 'Errors needed to start cooldown', + triggerCountPlaceholder: 'e.g. 1', + triggerCountHint: 'Starting from the first matching error, cooldown begins once the required count is reached inside the error-count window. Counting starts over when the window expires or after cooldown ends. Minimum 1. Saved rules without this field still trigger on the first match.', + triggerWindowMinutes: 'Error-count window (minutes)', + triggerWindowPlaceholder: 'e.g. 5', + triggerWindowHint: 'Starting from the first matching error, matching errors are counted during this window. Once the count is reached, the model enters cooldown. If the required count is not reached before the window expires, counting starts over.', description: 'Description', descriptionPlaceholder: 'Optional note for this rule', rulesInvalid: 'Add at least one rule with error code, keywords, and duration.', diff --git a/frontend/src/i18n/locales/zh/admin/accounts.ts b/frontend/src/i18n/locales/zh/admin/accounts.ts index 6f6f52992e9b..b85edcf86320 100644 --- a/frontend/src/i18n/locales/zh/admin/accounts.ts +++ b/frontend/src/i18n/locales/zh/admin/accounts.ts @@ -663,6 +663,7 @@ export default { errorCodePlaceholder: '例如 429', durationMinutes: '持续时间(分钟)', durationPlaceholder: '例如 30', + durationHint: '冷却一旦触发后,暂停调度的时长。与「错误计数窗口」无关。', keywords: '关键词', keywordsPlaceholder: '例如 overloaded, too many requests', keywordsHint: '多个关键词用逗号分隔,匹配时必须命中其中之一。', @@ -672,6 +673,18 @@ export default { scopeAccount: '账户级', scopeAccountDesc: '暂停整个账号的调度', scopeHint: '无法识别请求模型时,模型级规则按账户级处理。', + streamTiming: '触发时机', + streamTimingBefore: '仅流开始前', + streamTimingBeforeDesc: '只在上游流开始前的 HTTP 错误上触发', + streamTimingAfter: '流开始后也可以', + streamTimingAfterDesc: '流已开始后的失败也会触发,包括中途 502', + streamTimingHint: '「仅流开始前」不会处理流已经开始后的失败。未单独保存过的旧规则仍按当前行为:401/403/429/503/529 可在流中途触发,502 不会,除非改成「流开始后也可以」。', + triggerCount: '触发冷却需要的错误次数', + triggerCountPlaceholder: '例如 1', + triggerCountHint: '从第一次出现匹配的错误起,达到「错误计数窗口」内的累计次数后开始冷却。窗口到期或冷却结束后重新计数。最少 1 次;未填写的旧规则按 1 次处理。', + triggerWindowMinutes: '错误计数窗口(分钟)', + triggerWindowPlaceholder: '例如 5', + triggerWindowHint: '从第一次出现匹配的错误起,在设置的时间内累计错误次数,次数达到后,模型进入冷却。如窗口期未达到冷却所需次数,则重新计数。', description: '描述', descriptionPlaceholder: '可选,便于记忆规则用途', rulesInvalid: '请至少填写一条包含错误码、关键词和时长的规则。', diff --git a/frontend/src/types/index.ts b/frontend/src/types/index.ts index ee69fb8dd0ea..dd8dd7bedf4b 100644 --- a/frontend/src/types/index.ts +++ b/frontend/src/types/index.ts @@ -1109,6 +1109,11 @@ export interface GeminiCredentials { export type TempUnschedulableScope = 'account' | 'model' +// before_stream:仅流开始前的 HTTP 错误。 +// after_stream:流开始前和流开始后都可以,包括中途 502。 +// 省略时后端保持旧行为:中途 401/403/429/503/529 仍可触发,中途 502 不触发。 +export type TempUnschedulableStreamTiming = 'before_stream' | 'after_stream' + export interface TempUnschedulableRule { error_code: number keywords: string[] @@ -1116,6 +1121,13 @@ export interface TempUnschedulableRule { description: string // 作用范围:account 暂停整个账号,model 只冷却本次请求的模型;缺省时 401 按 account、其余按 model 处理。 scope?: TempUnschedulableScope + // credentials JSON 键 stream_timing。 + stream_timing?: TempUnschedulableStreamTiming + // credentials JSON 键 trigger_count。省略或小于 1 时按 1 次处理。 + trigger_count?: number + // credentials JSON 键 trigger_window_minutes。从第一次匹配起累计次数的时间窗口。 + // 与 duration_minutes 相互独立。省略或小于 1 时按 1 分钟处理。 + trigger_window_minutes?: number } export interface TempUnschedulableState {