diff --git a/.github/fixtures/pelican-question-e2e/navigation.test.mjs b/.github/fixtures/pelican-question-e2e/navigation.test.mjs new file mode 100644 index 000000000000..ebf22c4adaff --- /dev/null +++ b/.github/fixtures/pelican-question-e2e/navigation.test.mjs @@ -0,0 +1,111 @@ +import assert from 'node:assert/strict' +import { EventEmitter } from 'node:events' +import test from 'node:test' +import { createPageNavigation } from '../../scripts/pelican-complete-rounds.mjs' + +class Page extends EventEmitter { + calls = [] + // A document lifecycle state alone is not an in-flight request barrier. + async waitForLoadState() {} + async goto(url, options) { this.calls.push({ url, options }) } + async reload(options) { this.calls.push({ reload: true, options }) } +} +const nextTask = () => new Promise(resolve => setImmediate(resolve)) + +for (const action of ['goto', 'reload']) { + test(`${action}: drains auth/settings and subsequent requests before unloading`, async () => { + const page = new Page() + const navigation = createPageNavigation(page) + const auth = {}, settings = {}, followup = {} + page.emit('request', auth) + page.emit('request', settings) + const done = action === 'goto' ? navigation.goto('http://app:8080/admin/accounts') : navigation.reload() + await nextTask() + assert.equal(page.calls.length, 0, 'navigation must wait for outstanding bootstrap requests') + page.emit('requestfinished', auth) + page.emit('request', followup) + page.emit('requestfinished', settings) + await nextTask() + assert.equal(page.calls.length, 0, 'a request added during drain must also complete') + page.emit('requestfinished', followup) + await done + assert.equal(page.calls.length, 1) + assert.equal(page.calls[0].options.waitUntil, 'load') + }) +} + +test('failed requests still reach the strict error guard without filtering', async () => { + const page = new Page() + const failures = [] + page.on('requestfailed', request => failures.push(request)) + const navigation = createPageNavigation(page) + const failed = { reason: 'net::ERR_ABORTED' } + page.emit('request', failed) + const done = navigation.settle() + page.emit('requestfailed', failed) + await done + assert.deepEqual(failures, [failed]) + assert.throws(() => assert.equal(failures.length, 0, 'no failed browser requests')) +}) + +test('navigation waits for destination requests before returning', async () => { + const page = new Page() + const navigation = createPageNavigation(page) + const pending = {} + page.goto = async (url, options) => { page.calls.push({ url, options }); page.emit('request', pending) } + let returned = false + const done = navigation.goto('http://app:8080/admin/accounts').then(() => { returned = true }) + await nextTask() + assert.equal(returned, false) + page.emit('requestfinished', pending) + await done + assert.equal(returned, true) +}) + +test('srcdoc preview detachment cannot strand navigation on a stale networkidle lifecycle', async () => { + const page = new Page() + page.waitForLoadState = async state => { + assert.equal(state, 'load', 'use document readiness plus tracked request completion, not the stranded networkidle flag') + } + const navigation = createPageNavigation(page) + await navigation.goto('http://app:8080/admin/pelican-tests') + assert.equal(page.calls.length, 1) + assert.equal(page.calls[0].options.waitUntil, 'load') +}) + +test('an unfinished request still fails at the unchanged twenty-second deadline', async t => { + t.mock.timers.enable({ apis: ['setTimeout', 'Date'], now: 0 }) + const page = new Page() + const navigation = createPageNavigation(page) + page.emit('request', {}) + let failed = false + const done = assert.rejects(navigation.settle(), /browser requests did not finish before navigation/) + .then(() => { failed = true }) + await Promise.resolve() + t.mock.timers.tick(19_999) + await Promise.resolve() + assert.equal(failed, false) + t.mock.timers.tick(1) + await done + assert.equal(failed, true) + assert.equal(page.calls.length, 0) +}) + +test('document readiness consumes the same deadline rather than granting another twenty seconds', async t => { + t.mock.timers.enable({ apis: ['setTimeout', 'Date'], now: 0 }) + const page = new Page() + page.waitForLoadState = () => new Promise(resolve => setTimeout(resolve, 15_000)) + const navigation = createPageNavigation(page) + page.emit('request', {}) + let failed = false + const done = assert.rejects(navigation.settle(), /browser requests did not finish before navigation/) + .then(() => { failed = true }) + t.mock.timers.tick(15_000) + await Promise.resolve() + t.mock.timers.tick(4_999) + await Promise.resolve() + assert.equal(failed, false) + t.mock.timers.tick(1) + await done + assert.equal(failed, true) +}) diff --git a/.github/scripts/free-fast-cost-evidence.py b/.github/scripts/free-fast-cost-evidence.py new file mode 100644 index 000000000000..e76afbd7a815 --- /dev/null +++ b/.github/scripts/free-fast-cost-evidence.py @@ -0,0 +1,38 @@ +#!/usr/bin/env python3 +"""Reject setup failures, skips and absent tests in remote Go evidence.""" +import json +import re +import sys +from pathlib import Path + +mode, filename, *required = sys.argv[1:] +raw = Path(filename).read_text() +assert not re.search(r'build failed|undefined:|panic:|panic_recovered|fatal error:|runtime error:|WARNING: DATA RACE|no tests to run', raw, re.I), 'setup, panic, race or missing-tests failure' +events = [json.loads(line) for line in raw.splitlines() if line.startswith('{')] +assert events, 'no Go JSON events' +assert not any(e.get('Action') == 'skip' for e in events), 'skipped tests' +for name in required: + selected = [e for e in events if e.get('Test') == name] + assert selected, f'missing test {name}' + action = 'fail' if mode == 'red' else 'pass' + assert any(e.get('Action') == action for e in selected), f'{name}: expected {action}' + if mode == 'red': + output = ''.join(e.get('Output', '') for e in events + if e.get('Test') == name or e.get('Test', '').startswith(name + '/')) + marker = ('Standard cache prices must be persisted from the resolved quote' if name.endswith('CachePrices') + else 'restricted admin must expose the immutable customer Standard quote' if name.endswith('ScopedAdmin') + else 'user/admin DTO must expose the immutable customer Standard quote' if name.endswith('DTO') + else 'stored usage must retain the customer Standard quote' if name.endswith('Persistence') + else 'Free Fast must persist the Standard customer cost snapshot') + assert marker in output, f'{name}: missing target business assertion' +if mode == 'red': + assert any(marker in raw for marker in [ + 'Free Fast must persist the Standard customer cost snapshot', + 'user/admin DTO must expose the immutable customer Standard quote', + 'restricted admin must expose the immutable customer Standard quote', + 'Standard cache prices must be persisted from the resolved quote', + 'stored usage must retain the customer Standard quote', + ]), 'RED did not reach a target business assertion' +else: + assert not any(e.get('Action') == 'fail' for e in events), 'GREEN has failures' +print(f'{mode}: verified {len(required)} required tests; no setup errors, panic, race or skips') diff --git a/.github/scripts/free-fast-customer-cost-browser.mjs b/.github/scripts/free-fast-customer-cost-browser.mjs new file mode 100644 index 000000000000..f676f6f80528 --- /dev/null +++ b/.github/scripts/free-fast-customer-cost-browser.mjs @@ -0,0 +1,149 @@ +// Real shared UsageTable + real styles/locales, with synthetic data only. +import assert from 'node:assert/strict' +import { execFile } from 'node:child_process' +import { promisify } from 'node:util' +const exec = promisify(execFile) +import { createRequire } from 'node:module' +import { createHash } from 'node:crypto' +import fs from 'node:fs/promises' +import path from 'node:path' +import { pathToFileURL } from 'node:url' + +const root = process.cwd() +const frontend = path.join(root, 'frontend') +const output = process.env.FREE_FAST_SCREENSHOT_DIR +assert.ok(output, 'FREE_FAST_SCREENSHOT_DIR must point outside the source tree') +const base = '0e8e97aa23afd8e88a61ea64a84a8fb84f1bfdc6' +const head = (await exec('git', ['rev-parse', 'HEAD'], { encoding: 'utf8' })).stdout.trim() +const req = createRequire(path.join(frontend, 'package.json')) +const { createServer } = req('vite') +const vue = req('@vitejs/plugin-vue').default +const browserReq = createRequire(path.join(process.env.PLAYWRIGHT_ROOT, 'package.json')) +const { chromium } = browserReq('playwright') +await fs.mkdir(output, { recursive: true }) +const before = path.join(output, 'before-source') +await fs.mkdir(before, { recursive: true }) +// Export the complete baseline source, including transitive non-frontend assets. +const archive = path.join(output, 'baseline-source.tar') +await exec('git', ['archive', '--output=' + archive, base]) +await exec('tar', ['-xf', archive, '-C', before]) +await fs.symlink(path.join(frontend, 'node_modules'), path.join(before, 'frontend/node_modules')).catch(e => { if (e.code !== 'EEXIST') throw e }) +const fixtureFile = 'src/components/admin/usage/__tests__/fixtures/freeFastCustomerCost.ts' +const fixture = await fs.readFile(path.join(frontend, fixtureFile), 'utf8') +const manifest = { complete: false, base, head, fixtureSha256: createHash('sha256').update(fixture).digest('hex'), harnessSha256: createHash('sha256').update(await fs.readFile(new URL(import.meta.url))).digest('hex'), synthetic: true, source: 'real Vue shared UsageTable, real DataTable, popover/dialog, locales and style.css', screenshots: [], errors: [], requests: [] } +const browser = await chromium.launch({ headless: true, args: ['--no-sandbox'] }) +try { + for (const revision of ['before', 'after']) { + const source = revision === 'before' ? path.join(before, 'frontend') : frontend + const component = await fs.readFile(path.join(source, 'src/components/admin/usage/UsageTable.vue')) + const componentHash = createHash('sha256').update(component).digest('hex') + const html = `
` + const tailwindConfig = (await import(pathToFileURL(path.join(source, 'tailwind.config.js')).href)).default + process.chdir(source) + const server = await createServer({ root: source, configFile: false, envFile: false, + cacheDir: path.join(output, 'vite-cache-' + revision), + define: { __INTLIFY_JIT_COMPILATION__: true }, + css: { postcss: { plugins: [ + req('tailwindcss')({ ...tailwindConfig, content: [path.join(source, 'index.html'), path.join(source, 'src/**/*.{vue,js,ts,jsx,tsx}')] }), + req('autoprefixer')(), + ] } }, + plugins: [vue(), { name: 'synthetic-cost-page', + resolveId(id) { if (id === 'fixture:cost') return '\0fixture:cost' }, + load(id) { if (id === '\0fixture:cost') return fixture }, + configureServer(vite) { + vite.middlewares.use((request, response, next) => { + if (request.url?.split('?')[0] !== '/') return next() + response.setHeader('Content-Type', 'text/html') + void vite.transformIndexHtml('/', html).then(text => response.end(text)) + }) + } }], + resolve: { alias: { '@': path.join(source, 'src'), 'vue-i18n': 'vue-i18n/dist/vue-i18n.runtime.esm-bundler.js' } }, + server: { host: '127.0.0.1', port: 4189, strictPort: true, fs: { allow: [source, frontend] } }, + optimizeDeps: { entries: [], include: ['vue', 'pinia', 'vue-i18n', 'axios'] }, + }) + await server.listen() + try { + for (const fixtureName of ['exact', 'mixed']) for (const locale of ['en', 'zh']) for (const role of ['user', 'admin']) for (const size of ['desktop', 'mobile']) { + const viewport = size === 'mobile' ? { width: 390, height: 844 } : { width: 1280, height: 900 } + const context = await browser.newContext({ viewport, colorScheme: 'light', timezoneId: 'UTC', locale: locale === 'zh' ? 'zh-CN' : 'en-US' }) + await context.route('**/*', async route => { + const url = new URL(route.request().url()) + if (url.origin !== 'http://127.0.0.1:4189') throw new Error('Unexpected external request: ' + url.origin) + if (url.pathname.startsWith('/api/')) { + manifest.requests.push(url.pathname) + return route.fulfill({ json: { code: 0, data: {} } }) + } + return route.continue() + }) + const page = await context.newPage() + page.on('pageerror', error => manifest.errors.push(error.message)) + await page.goto(`http://127.0.0.1:4189/?lang=${locale}&role=${role}&fixture=${fixtureName}`, { waitUntil: 'networkidle' }) + const button = page.getByRole('button', { name: locale === 'zh' ? '费用明细' : 'Cost Breakdown', exact: true }) + // Use the actual accessible label even when a locale changes its translation. + const costButton = await button.count() ? button : page.locator('button[aria-expanded]').filter({ has: page.locator('.text-green-600') }) + await costButton.click() + const panel = page.locator(size === 'mobile' ? '[role="dialog"]' : '[role="tooltip"]') + await panel.waitFor({ state: 'visible' }) + // Capture the settled dialog, not a partially transparent enter frame. + await panel.evaluate(async element => { + await Promise.all(element.getAnimations({ subtree: true }) + .filter(animation => animation.effect?.getComputedTiming().iterations !== Infinity) + .map(animation => animation.finished)) + }) + const text = await panel.innerText() + assert.ok(text.includes(revision === 'after' ? '$10.0000' : '$20.0000'), text) + assert.ok(text.includes(revision === 'after' ? '$50.0000' : '$100.0000'), text) + const amounts = fixtureName === 'exact' + ? (revision === 'after' ? ['0.08345000', '0.00680000', '0.01496250', '0.03746900', '0.14268150'] : ['0.16690000', '0.01360000', '0.01496250', '0.07493800', '0.27040050']) + : (revision === 'after' ? ['0.08345000', '0.00680000', '0.00046250', '0.00001700', '0.09072950'] : ['0.16690000', '0.01360000', '0.00046250', '0.00003400', '0.18099650']) + for (const value of amounts) assert.ok(text.includes('$' + value), text) + assert.ok(text.includes(fixtureName === 'exact' ? '$0.07134075' : '$0.04536475'), text) + if (revision === 'after') { + assert.ok((await panel.getByTestId('cache-unit-read').innerText()).includes('$1.0000')) + assert.ok((await panel.getByTestId('cache-unit-write_30m').innerText()).includes('$12.5000')) + if (fixtureName === 'mixed') assert.ok((await panel.getByTestId('cache-unit-write_12h').innerText()).includes('$25.0000')) + assert.ok(text.includes(locale === 'zh' ? '缓存读取单价' : 'Cache read price'), text) + assert.ok(text.includes(locale === 'zh' ? '缓存写入单价(30m)' : 'Cache write price (30m)'), text) + } + assert.ok(text.includes('Fast'), text) + assert.ok(!/Free Fast|Fast 加速免费|按 Standard 计费/.test(text), text) + const bounds = await panel.boundingBox() + assert.ok(bounds && bounds.x >= 0 && bounds.x + bounds.width <= viewport.width + 1 && bounds.y >= 0 && bounds.y + bounds.height <= viewport.height + 1, JSON.stringify(bounds)) + const contentBounds = await panel.locator('.bg-gray-900').boundingBox() + assert.ok(contentBounds && contentBounds.x >= 0 && contentBounds.y >= 0 && contentBounds.x + contentBounds.width <= viewport.width + 1 && contentBounds.y + contentBounds.height <= viewport.height + 1, JSON.stringify(contentBounds)) + assert.ok(await page.evaluate(() => document.documentElement.scrollWidth <= innerWidth)) + const computedStyle = await panel.locator('.bg-gray-900').evaluate(element => { + const css = getComputedStyle(element) + return { background: css.backgroundColor, fontSize: css.fontSize, padding: css.paddingLeft, border: css.borderTopWidth } + }) + assert.equal(computedStyle.background, 'rgb(17, 24, 39)', JSON.stringify(computedStyle)) + assert.equal(computedStyle.fontSize, '12px') + assert.equal(computedStyle.padding, '12px') + assert.equal(computedStyle.border, '1px') + const name = `${fixtureName}-${revision}-${locale}-${role}-${size}.png` + await page.screenshot({ path: path.join(output, name), fullPage: true, animations: 'disabled' }) + const digest = createHash('sha256').update(await fs.readFile(path.join(output, name))).digest('hex') + manifest.screenshots.push({ file: name, sha256: digest, componentSha256: componentHash, fixtureName, revision, locale, role, viewport, bounds, contentBounds, computedStyle, text }) + await context.close() + } + } finally { await server.close(); process.chdir(root) } + } + assert.deepEqual(manifest.errors, []) + assert.equal(manifest.screenshots.length, 32) + manifest.complete = true +} finally { + await browser.close() + await fs.writeFile(path.join(output, 'manifest.json'), JSON.stringify(manifest, null, 2) + '\n') +} diff --git a/.github/scripts/pelican-complete-rounds.mjs b/.github/scripts/pelican-complete-rounds.mjs index ce1eb6dbd2bc..e49b5ef68445 100644 --- a/.github/scripts/pelican-complete-rounds.mjs +++ b/.github/scripts/pelican-complete-rounds.mjs @@ -6,10 +6,47 @@ import { nextDifferentNominal, questionAt, bankVersion } from './pelican-nominal const unwrap = value => value?.data ?? value const pause = () => new Promise(resolve => setTimeout(resolve, 250)) +// Track real request completion across repeated document navigations. A +// previously reached lifecycle state alone cannot prevent a later auth/settings +// request from being aborted by the harness. Failures remain in the caller's +// strict requestfailed inventory; this barrier never filters or retries them. +export function createPageNavigation(page) { + const pending = new Set() + const waiters = new Set() + page.on('request', request => pending.add(request)) + const completed = request => { + pending.delete(request) + if (!pending.size) for (const resolve of [...waiters]) resolve() + } + page.on('requestfinished', completed) + page.on('requestfailed', completed) + const settle = async () => { + const deadline = Date.now() + 20_000 + // A completed background fetch followed by a srcdoc preview lifecycle can + // remove networkidle without restarting its timer (Playwright 1.56.1). + // Document load + our real completion inventory does not depend on that + // stale frame flag. Keep one 20s deadline, including document readiness. + await page.waitForLoadState('load', { timeout: 20_000 }) + while (pending.size) await new Promise((resolve, reject) => { + const done = () => { clearTimeout(timer); waiters.delete(done); resolve() } + const timer = setTimeout(() => { + waiters.delete(done) + reject(new Error('browser requests did not finish before navigation')) + }, Math.max(0, deadline - Date.now())) + waiters.add(done) + }) + } + return { + settle, + async goto(url) { await settle(); await page.goto(url, { waitUntil: 'load' }); await settle() }, + async reload() { await settle(); await page.reload({ waitUntil: 'load' }); await settle() }, + } +} + // Called only after the original real application scenarios have succeeded. // All writes except next_run_at go through existing authenticated UI controls. export async function completeScheduledRounds(c) { - const { db, page, origin, accounts, groups, plans, groupPlanId, groupId, model, + const { db, page, navigation, origin, accounts, groups, plans, groupPlanId, groupId, model, dialog, openAccount, checkSnapshot, readPlans, readResults, readGroupPlan, readGroupResults, fixtureControl, capturesNow, save, evidence, state } = c const initial = { account: await readResults(), group: await readGroupResults() } @@ -19,9 +56,7 @@ export async function completeScheduledRounds(c) { const tables = { account: 'scheduled_test_plans', group: 'pelican_group_test_plans' } async function accountHistory(label, expected) { - // Finish background metrics before deliberate document navigation; keep request failures strict. - await page.waitForLoadState('networkidle') - await page.goto(`${origin}/admin/accounts`) + await navigation.goto(`${origin}/admin/accounts`) const projections = [] for (const account of accounts) { await openAccount(account) @@ -96,9 +131,7 @@ export async function completeScheduledRounds(c) { async function groupHistory(label, expected) { const listed = page.waitForResponse(response => new URL(response.url()).pathname === '/api/v1/admin/pelican-group-test-results' && response.request().method() === 'GET' && response.status() === 200) - // Finish background metrics before deliberate document navigation; keep request failures strict. - await page.waitForLoadState('networkidle') - await page.goto(`${origin}/admin/pelican-tests`) + await navigation.goto(`${origin}/admin/pelican-tests`) const response = await listed const list = unwrap(await response.json()) assert.equal(list.total, expected.length) @@ -275,9 +308,7 @@ export async function completeScheduledRounds(c) { async function editAccount(mode) { state.active_gate = `ui-edit-account-${mode}` - // Finish background metrics before deliberate document navigation; keep request failures strict. - await page.waitForLoadState('networkidle') - await page.goto(`${origin}/admin/accounts`) + await navigation.goto(`${origin}/admin/accounts`) await openAccount(accounts[0]) await dialog().getByRole('button', { name: 'Scheduled tests', exact: true }).click() await dialog().getByRole('button', { name: 'Edit Plan', exact: true }).click() @@ -303,9 +334,7 @@ export async function completeScheduledRounds(c) { assert.deepEqual(stored.pelican_config, body.pelican_config) await form.waitFor({ state: 'hidden' }) await dialog().getByRole('button', { name: 'Close modal', exact: true }).click() - // Finish background metrics before deliberate document navigation; keep request failures strict. - await page.waitForLoadState('networkidle') - await page.reload() + await navigation.reload() await openAccount(accounts[0]) const listRead = page.waitForResponse(response => new URL(response.url()).pathname === `/api/v1/admin/accounts/${accounts[0].id}/scheduled-test-plans` && response.request().method() === 'GET') @@ -330,9 +359,7 @@ export async function completeScheduledRounds(c) { async function editGroup(mode) { state.active_gate = `ui-edit-group-${mode}` - // Finish background metrics before deliberate document navigation; keep request failures strict. - await page.waitForLoadState('networkidle') - await page.goto(`${origin}/admin/pelican-tests`) + await navigation.goto(`${origin}/admin/pelican-tests`) await page.getByTestId(`pelican-plan-edit-${groupPlanId}`).click() const form = page.getByTestId('pelican-test-editor') await form.getByTestId('pelican-mode-select').selectOption(mode) @@ -354,12 +381,10 @@ export async function completeScheduledRounds(c) { const stored = await readGroupPlan() assert.deepEqual(stored.pelican_config, body.pelican_config) await form.waitFor({ state: 'hidden' }) - await page.waitForLoadState('networkidle') + await navigation.settle() const listRead = page.waitForResponse(response => new URL(response.url()).pathname === '/api/v1/admin/pelican-group-tests' && response.request().method() === 'GET') - // Finish background metrics before deliberate document navigation; keep request failures strict. - await page.waitForLoadState('networkidle') - await page.reload() + await navigation.reload() const listResponse = await listRead assert.equal(listResponse.status(), 200) const list = unwrap(await listResponse.json()) diff --git a/.github/scripts/pelican-question-e2e.mjs b/.github/scripts/pelican-question-e2e.mjs index 01b2149f316b..f1aa03da440e 100644 --- a/.github/scripts/pelican-question-e2e.mjs +++ b/.github/scripts/pelican-question-e2e.mjs @@ -7,7 +7,7 @@ import { readFileSync, writeFileSync, appendFileSync, mkdirSync } from 'node:fs' import { join } from 'node:path' import { createRequire } from 'node:module' import { bindDetailResponse } from './pelican-detail-identity.mjs' -import { completeScheduledRounds } from './pelican-complete-rounds.mjs' +import { completeScheduledRounds, createPageNavigation } from './pelican-complete-rounds.mjs' const evidence = process.env.EVIDENCE_DIR || '/evidence' const upstreamOrigin = 'https://fake-upstream:4199' @@ -203,6 +203,7 @@ async function browser() { } }) page = await context.newPage() + const navigation = createPageNavigation(page) page.setDefaultTimeout(20_000) page.on('requestfailed', request => { const url = new URL(request.url()) @@ -226,9 +227,7 @@ async function browser() { prompt_mode: input.prompt_mode, pelican_question: input.pelican_question }) } }) - // Finish background metrics before deliberate document navigation; keep request failures strict. - await page.waitForLoadState('networkidle') - await page.goto(`${origin}/login?redirect=/admin/accounts`) + await navigation.goto(`${origin}/login?redirect=/admin/accounts`) await page.locator('#email').fill('reviewer@example.invalid') await page.locator('#password').fill('Fixture-Only-795-Password!') const login = page.waitForResponse(response => new URL(response.url()).pathname === '/api/v1/auth/login' && response.request().method() === 'POST') @@ -251,16 +250,14 @@ async function browser() { // Requests made before first-install acknowledgement are gated by the real // middleware. Preserve their diagnostics, then reload the real page so its // initial account query runs after acknowledgement has persisted. - await page.waitForLoadState('networkidle') + await navigation.settle() state.bootstrap = { blocked: [...state.blocked], requestFailures: [...state.requestFailures], pageErrors: [...state.pageErrors], consoleErrors: [...state.consoleErrors] } assert.equal(state.blocked.length, 0, 'bootstrap must not request external resources') assert.equal(state.requestFailures.length, 0, 'bootstrap transport must complete') state.pageErrors = [] state.consoleErrors = [] - // Finish background metrics before deliberate document navigation; keep request failures strict. - await page.waitForLoadState('networkidle') - await page.reload() + await navigation.reload() await page.getByRole('row').filter({ hasText: accounts[0].name }).waitFor() assert.ok(await page.locator('link[rel=stylesheet]').count(), 'real application CSS loaded') state.scenarios.push({ name: stage, status: 'passed', entry: '/admin/accounts' }) @@ -378,9 +375,7 @@ async function browser() { state.scenarios.push({ name: stage, status: 'passed', question_repetition_permitted: true }) stage = 'manual-localstorage-reload-history-dom' - // Finish background metrics before deliberate document navigation; keep request failures strict. - await page.waitForLoadState('networkidle') - await page.reload() + await navigation.reload() assert.deepEqual((await readRecords(accounts[0]))[0], aRecord) assert.deepEqual((await readRecords(accounts[1]))[0], bRecord) await openAccount(accounts[1]) @@ -400,9 +395,7 @@ async function browser() { await detail.getByRole('button', { name: 'Close', exact: true }).click() await panel.getByRole('button', { name: 'Close', exact: true }).click() await dialog().getByRole('button', { name: 'Close modal', exact: true }).click() - // Finish background metrics before deliberate document navigation; keep request failures strict. - await page.waitForLoadState('networkidle') - await page.goto(`${origin}/admin/pelican-tests`) + await navigation.goto(`${origin}/admin/pelican-tests`) await page.getByTestId('pelican-tests-create').click() const editor = page.getByTestId('pelican-test-editor') await editor.getByRole('button').first().click() @@ -432,9 +425,7 @@ async function browser() { boundary: 'disabled creation only; no scheduled RunDue, /run or result acceptance claimed' }) stage = 'account-scheduled-ui-create-a-b' - // Finish background metrics before deliberate document navigation; keep request failures strict. - await page.waitForLoadState('networkidle') - await page.goto(`${origin}/admin/accounts`) + await navigation.goto(`${origin}/admin/accounts`) const plans = [] const planProjection = plan => ({ id: String(plan.id), account_id: String(plan.account_id), model_id: plan.model_id, enabled: plan.enabled, cron_expression: plan.cron_expression, @@ -712,9 +703,7 @@ async function browser() { } stage = 'group-scheduled-ui-enable' - // Finish background metrics before deliberate document navigation; keep request failures strict. - await page.waitForLoadState('networkidle') - await page.goto(`${origin}/admin/pelican-tests`) + await navigation.goto(`${origin}/admin/pelican-tests`) const groupPlanId = String(created.id) const groupId = groups[0].id const groupPlanPath = `/api/v1/admin/pelican-group-tests/${groupPlanId}` @@ -951,13 +940,14 @@ async function browser() { } stage = 'complete-scheduled-rounds' - await completeScheduledRounds({ db, page, origin, accounts, groups, plans, groupPlanId, groupId, model, + await completeScheduledRounds({ db, page, navigation, origin, accounts, groups, plans, groupPlanId, groupId, model, dialog, openAccount, checkSnapshot, readPlans, readResults, readGroupPlan, readGroupResults, fixtureControl, capturesNow, save, evidence, state }) assert.deepEqual(forbiddenRuns, [], 'all successor rounds must use real RunDue') assert.equal(manualRequests.length, 4, 'successor rounds cannot be manual submissions') stage = 'post-bootstrap-browser-and-provider-error-lists' + await navigation.settle() const finalCaptures = await (await fetch(`${upstreamOrigin}/__fixture/captures`)).json() assert.deepEqual(finalCaptures.rejected, []) assert.equal(state.blocked.length, 0, 'browser may contact only app origin') diff --git a/.github/scripts/test_free_fast_cost_evidence.py b/.github/scripts/test_free_fast_cost_evidence.py new file mode 100644 index 000000000000..4adf7075e6ae --- /dev/null +++ b/.github/scripts/test_free_fast_cost_evidence.py @@ -0,0 +1,39 @@ +import json +from pathlib import Path +import subprocess +import sys +import tempfile +import unittest + +SCRIPT = Path(__file__).with_name('free-fast-cost-evidence.py') +NAME = 'TestFreeFastCustomerCostSnapshot' +MARKER = 'Free Fast must persist the Standard customer cost snapshot' + +class EvidenceTest(unittest.TestCase): + def check_log(self, mode, events, good): + with tempfile.TemporaryDirectory() as directory: + log = Path(directory) / 'events.jsonl' + log.write_text('\n'.join(json.dumps(e) for e in events)) + result = subprocess.run([sys.executable, str(SCRIPT), mode, str(log), NAME], capture_output=True) + self.assertEqual(result.returncode == 0, good, result.stderr.decode()) + + def test_green(self): + self.check_log('green', [{'Action': 'pass', 'Test': NAME}], True) + + def test_business_red(self): + self.check_log('red', [{'Action': 'output', 'Test': NAME, 'Output': MARKER}, {'Action': 'fail', 'Test': NAME}], True) + + def test_reject_bad_evidence(self): + for output in ['panic:', 'panic_recovered', 'WARNING: DATA RACE', 'no tests to run', 'build failed', 'undefined: symbol']: + with self.subTest(output=output): + self.check_log('green', [{'Action': 'output', 'Test': NAME, 'Output': output}, {'Action': 'pass', 'Test': NAME}], False) + + def test_reject_missing_tests_and_skips(self): + for events in [[{'Action': 'pass'}], [{'Action': 'skip', 'Test': NAME}], [{'Action': 'skip', 'Test': 'Other'}, {'Action': 'pass', 'Test': NAME}]]: + self.check_log('green', events, False) + + def test_reject_unrelated_red(self): + self.check_log('red', [{'Action': 'output', 'Test': 'Other', 'Output': MARKER}, {'Action': 'fail', 'Test': NAME}], False) + +if __name__ == '__main__': + unittest.main() diff --git a/.github/workflows/free-fast-customer-cost-details.yml b/.github/workflows/free-fast-customer-cost-details.yml new file mode 100644 index 000000000000..21ea6a248eca --- /dev/null +++ b/.github/workflows/free-fast-customer-cost-details.yml @@ -0,0 +1,192 @@ +name: Free Fast customer cost details +on: + pull_request: + branches: [production] + paths: + - 'backend/**' + - 'frontend/src/components/admin/usage/**' + - 'frontend/src/utils/customerCostDetails.ts' + - 'frontend/src/types/index.ts' + - '.github/workflows/free-fast-customer-cost-details.yml' + - '.github/scripts/free-fast-*' + - '.github/scripts/test_free_fast_cost_evidence.py' + workflow_dispatch: +permissions: + contents: read +concurrency: + group: free-fast-cost-${{ github.event.pull_request.number || github.ref }} + cancel-in-progress: true +jobs: + backend: + runs-on: ubuntu-latest + timeout-minutes: 55 + env: + GOMAXPROCS: '2' + GOFLAGS: '-p=1' + GOMEMLIMIT: 3500MiB + GOGC: '30' + SUB2API_TEST_POSTGRES_DSN: postgres://fixture:fixture@localhost:15432/free_fast?sslmode=disable + SUB2API_TEST_REDIS_URL: redis://localhost:16379/0 + services: + postgres: + image: postgres:16-alpine + env: + POSTGRES_USER: fixture + POSTGRES_PASSWORD: fixture + POSTGRES_DB: free_fast + ports: ['15432:5432'] + options: --health-cmd "pg_isready -U fixture -d free_fast" --health-interval 5s --health-timeout 5s --health-retries 10 + redis: + image: redis:7-alpine + ports: ['16379:6379'] + options: --health-cmd "redis-cli ping" --health-interval 5s --health-timeout 5s --health-retries 10 + steps: + - uses: actions/checkout@v6 + with: + ref: ${{ github.event.pull_request.head.sha || github.sha }} + - uses: actions/setup-go@v6 + with: + go-version-file: backend/go.mod + cache-dependency-path: backend/go.sum + - name: Verify evidence rejection guards + run: python3 -m unittest discover -s .github/scripts -p 'test_free_fast_cost_evidence.py' + - name: Generate Ent and retain reproducibility patch + run: | + mkdir -p "$RUNNER_TEMP/free-fast" + git rev-parse HEAD HEAD^{tree} > "$RUNNER_TEMP/free-fast/head.txt" + (cd backend && go generate ./ent) + git diff -- backend/ent > "$RUNNER_TEMP/free-fast/ent-generated.patch" + - name: GREEN service and DTO business evidence + shell: bash + run: | + set -euo pipefail + (cd backend && go test -race -json -tags=unit ./internal/service ./internal/handler/dto ./internal/handler/admin ./internal/repository -run '^Test(FreeFastCustomerCost|OpenAIGatewayServiceRecordUsage_FreeOpenAIFast|GroupBillsOpenAIFast|UsageLogStaticInsertShape|PrepareUsageLogInsert|UsageLogRepositoryCreate|ScanUsageLogRequestTypeAndLegacyFallback)' -count=1 -timeout=15m) > "$RUNNER_TEMP/free-fast/green-unit.jsonl" 2>&1 + python3 .github/scripts/free-fast-cost-evidence.py green "$RUNNER_TEMP/free-fast/green-unit.jsonl" TestFreeFastCustomerCostSnapshot TestFreeFastCustomerCostVariants TestFreeFastCustomerCostDTO TestFreeFastCustomerCostScopedAdmin TestFreeFastCustomerCostCachePrices TestFreeFastCustomerCostCacheDTO TestUsageLogStaticInsertShape_PlaceholdersMatchArgTypes TestScanUsageLogRequestTypeAndLegacyFallback + - name: GREEN all insertion paths, immutable history and durable replay + shell: bash + run: | + set -euo pipefail + (cd backend && go test -json -tags=integration ./internal/repository -run '^TestFreeFastCustomerCost' -count=1 -timeout=15m) > "$RUNNER_TEMP/free-fast/green-sql.jsonl" 2>&1 + python3 .github/scripts/free-fast-cost-evidence.py green "$RUNNER_TEMP/free-fast/green-sql.jsonl" TestFreeFastCustomerCostPersistence TestFreeFastCustomerCostDurableReplay TestFreeFastCustomerCostMigration TestFreeFastCustomerCostCachePersistence + - name: Same tests against pinned production code must reach business RED + shell: bash + run: | + set -euo pipefail + baseline=0e8e97aa23afd8e88a61ea64a84a8fb84f1bfdc6 + git fetch --no-tags --depth=1 origin "$baseline" + for file in backend/internal/service/openai_gateway_usage.go backend/internal/service/usage_log.go backend/internal/handler/dto/types.go backend/internal/handler/dto/mappers.go backend/internal/handler/admin/scoped_admin_usage_response.go backend/internal/repository/usage_log_repo_insert.go backend/internal/repository/usage_log_repo_query.go; do + git show "$baseline:$file" > "$file" + test "$(git hash-object "$file")" = "$(git rev-parse "$baseline:$file")" + done + # Tests stay byte-for-byte at candidate HEAD. Keep the new additive + # DB column so a missing migration can never qualify as business RED. + set +e + (cd backend && go test -race -json -tags=unit ./internal/service ./internal/handler/dto ./internal/handler/admin -run '^TestFreeFastCustomerCost(Snapshot|Variants|DTO|ScopedAdmin)$' -count=1 -timeout=15m) > "$RUNNER_TEMP/free-fast/red-unit.jsonl" 2>&1 + unit_exit=$? + (cd backend && go test -json -tags=integration ./internal/repository -run '^TestFreeFastCustomerCostPersistence$' -count=1 -timeout=15m) > "$RUNNER_TEMP/free-fast/red-sql.jsonl" 2>&1 + sql_exit=$? + set -e + test "$unit_exit" -ne 0 + test "$sql_exit" -ne 0 + python3 .github/scripts/free-fast-cost-evidence.py red "$RUNNER_TEMP/free-fast/red-unit.jsonl" TestFreeFastCustomerCostSnapshot TestFreeFastCustomerCostVariants TestFreeFastCustomerCostDTO TestFreeFastCustomerCostScopedAdmin + python3 .github/scripts/free-fast-cost-evidence.py red "$RUNNER_TEMP/free-fast/red-sql.jsonl" TestFreeFastCustomerCostPersistence + - name: Cache-price snapshot business RED against pre-cache producer + shell: bash + run: | + set -euo pipefail + # Restore candidate production paths after the original baseline RED. + git restore backend/internal/service/openai_gateway_usage.go backend/internal/service/usage_log.go backend/internal/handler/dto/types.go backend/internal/handler/dto/mappers.go backend/internal/handler/admin/scoped_admin_usage_response.go backend/internal/repository/usage_log_repo_insert.go backend/internal/repository/usage_log_repo_query.go + baseline=6826ea7c13459f0fb8080b0753da4b8ae73dd383 + git fetch --no-tags --depth=1 origin "$baseline" + git show "$baseline:backend/internal/service/customer_cost_details.go" > backend/internal/service/customer_cost_details.go + test "$(git hash-object backend/internal/service/customer_cost_details.go)" = "$(git rev-parse "$baseline:backend/internal/service/customer_cost_details.go")" + set +e + (cd backend && go test -json -tags=unit ./internal/service -run '^TestFreeFastCustomerCostCachePrices$' -count=1 -timeout=15m) > "$RUNNER_TEMP/free-fast/red-cache.jsonl" 2>&1 + code=$? + set -e + test "$code" -ne 0 + python3 .github/scripts/free-fast-cost-evidence.py red "$RUNNER_TEMP/free-fast/red-cache.jsonl" TestFreeFastCustomerCostCachePrices + - name: Require committed generated code + if: always() + run: test ! -s "$RUNNER_TEMP/free-fast/ent-generated.patch" + - uses: actions/upload-artifact@v7 + if: always() + with: + name: free-fast-backend-${{ github.event.pull_request.head.sha || github.sha }} + path: ${{ runner.temp }}/free-fast + if-no-files-found: error + frontend: + env: + NODE_OPTIONS: --max-old-space-size=4096 + runs-on: ubuntu-latest + timeout-minutes: 25 + steps: + - uses: actions/checkout@v6 + with: + ref: ${{ github.event.pull_request.head.sha || github.sha }} + - 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 + - run: pnpm --dir frontend install --frozen-lockfile + - name: GREEN complete affected suite, lint and typecheck + run: | + mkdir -p "$RUNNER_TEMP/free-fast-ui" + pnpm --dir frontend exec vitest run src/components/admin/usage/__tests__/UsageTable.spec.ts src/components/admin/usage/__tests__/UsageDetailPopover.spec.ts --maxWorkers=1 --minWorkers=1 --reporter=json --outputFile="$RUNNER_TEMP/free-fast-ui/green.json" + pnpm --dir frontend lint:check + pnpm --dir frontend typecheck + pnpm --dir frontend build + - name: RED same DOM assertions against original shared component + shell: bash + run: | + set -euo pipefail + git fetch --no-tags --depth=1 origin 0e8e97aa23afd8e88a61ea64a84a8fb84f1bfdc6 + cp frontend/src/components/admin/usage/UsageTable.vue "$RUNNER_TEMP/free-fast-ui/UsageTable.vue" + git show 0e8e97aa23afd8e88a61ea64a84a8fb84f1bfdc6:frontend/src/components/admin/usage/UsageTable.vue > frontend/src/components/admin/usage/UsageTable.vue + set +e + pnpm --dir frontend exec vitest run src/components/admin/usage/__tests__/UsageTable.spec.ts --maxWorkers=1 --minWorkers=1 --reporter=json --outputFile="$RUNNER_TEMP/free-fast-ui/red.json" + code=$? + set -e + cp "$RUNNER_TEMP/free-fast-ui/UsageTable.vue" frontend/src/components/admin/usage/UsageTable.vue + test "$code" -ne 0 + python3 - "$RUNNER_TEMP/free-fast-ui" <<'PY' + import json,sys,pathlib + p=pathlib.Path(sys.argv[1]) + for mode in ('green','red'): + data=json.loads((p/(mode+'.json')).read_text()) + assert data['numPendingTests']==0, data + assert data['numTotalTests']>=70, data + if mode=='green': assert data['numFailedTests']==0, data + else: + assertions=[a for r in data['testResults'] for a in r['assertionResults']] + target=[a for a in assertions if 'shows Standard unit prices' in a['fullName']] + assert len(target)==2 and all(a['status']=='failed' for a in target),target + assert all('$10.00' in '\n'.join(a['failureMessages']) for a in target),target + aliases=[a for a in assertions if 'F1 fast alias with missing or invalid snapshot' in a['fullName']] + assert len(aliases)==4 and all(a['status']=='failed' for a in aliases),aliases + cache=[a for a in assertions if 'G1 displays saved Standard cache read and distinct TTL unit prices' in a['fullName']] + assert len(cache)==2 and all(a['status']=='failed' for a in cache),cache + assert all('cache-unit-read' in '\n'.join(a['failureMessages']) for a in cache),cache + PY + - name: Install isolated browser + run: | + npm install --prefix "$RUNNER_TEMP/free-fast-browser" --no-save --ignore-scripts playwright@1.56.1 + "$RUNNER_TEMP/free-fast-browser/node_modules/.bin/playwright" install --with-deps chromium + - name: Real Vue bilingual before/after screenshots + env: + PLAYWRIGHT_ROOT: ${{ runner.temp }}/free-fast-browser/node_modules/playwright + FREE_FAST_SCREENSHOT_DIR: ${{ runner.temp }}/free-fast-ui/screenshots + run: node .github/scripts/free-fast-customer-cost-browser.mjs + - uses: actions/upload-artifact@v7 + if: always() + with: + name: free-fast-ui-${{ github.event.pull_request.head.sha || github.sha }} + path: | + ${{ runner.temp }}/free-fast-ui/*.json + ${{ runner.temp }}/free-fast-ui/screenshots/*.png + ${{ runner.temp }}/free-fast-ui/screenshots/manifest.json + if-no-files-found: error diff --git a/.github/workflows/pelican-random-questions.yml b/.github/workflows/pelican-random-questions.yml index bd3f282db981..46fbe81b2c3c 100644 --- a/.github/workflows/pelican-random-questions.yml +++ b/.github/workflows/pelican-random-questions.yml @@ -118,7 +118,7 @@ jobs: shell: bash run: | set -euo pipefail - node --test harness/.github/fixtures/pelican-question-e2e/detail-identity.test.mjs harness/.github/fixtures/pelican-question-e2e/nominal-round.test.mjs \ + node --test harness/.github/fixtures/pelican-question-e2e/detail-identity.test.mjs harness/.github/fixtures/pelican-question-e2e/nominal-round.test.mjs harness/.github/fixtures/pelican-question-e2e/navigation.test.mjs \ | tee "$EVIDENCE_DIR/detail-identity-synthetic.tap" - name: Build and prefetch before runtime isolation (CI only) shell: bash diff --git a/.gitignore b/.gitignore index d3c130bf8293..f7940b038204 100644 --- a/.gitignore +++ b/.gitignore @@ -239,3 +239,10 @@ issues/ tools/local-worker/ !docs/key-risk-patrol.md + +# Reproducible Free Fast customer-cost evidence runners. +!/.github/scripts/ +!/.github/scripts/free-fast-customer-cost-browser.mjs +!/.github/scripts/free-fast-cost-evidence.py +!/.github/scripts/test_free_fast_cost_evidence.py +/.github/scripts/__pycache__/ diff --git a/backend/ent/migrate/schema.go b/backend/ent/migrate/schema.go index 8a7c564b1151..d01e2f720814 100644 --- a/backend/ent/migrate/schema.go +++ b/backend/ent/migrate/schema.go @@ -1958,6 +1958,7 @@ var ( {Name: "video_resolution", Type: field.TypeString, Nullable: true, Size: 10}, {Name: "video_duration_seconds", Type: field.TypeInt, Nullable: true}, {Name: "cache_ttl_overridden", Type: field.TypeBool, Default: false}, + {Name: "customer_cost_details", Type: field.TypeJSON, Nullable: true}, {Name: "queue_timing", Type: field.TypeJSON, Nullable: true}, {Name: "created_at", Type: field.TypeTime, SchemaType: map[string]string{"postgres": "timestamptz"}}, {Name: "api_key_id", Type: field.TypeInt64}, @@ -1974,31 +1975,31 @@ var ( ForeignKeys: []*schema.ForeignKey{ { Symbol: "usage_logs_api_keys_usage_logs", - Columns: []*schema.Column{UsageLogsColumns[48]}, + Columns: []*schema.Column{UsageLogsColumns[49]}, RefColumns: []*schema.Column{APIKeysColumns[0]}, OnDelete: schema.NoAction, }, { Symbol: "usage_logs_accounts_usage_logs", - Columns: []*schema.Column{UsageLogsColumns[49]}, + Columns: []*schema.Column{UsageLogsColumns[50]}, RefColumns: []*schema.Column{AccountsColumns[0]}, OnDelete: schema.NoAction, }, { Symbol: "usage_logs_groups_usage_logs", - Columns: []*schema.Column{UsageLogsColumns[50]}, + Columns: []*schema.Column{UsageLogsColumns[51]}, RefColumns: []*schema.Column{GroupsColumns[0]}, OnDelete: schema.SetNull, }, { Symbol: "usage_logs_users_usage_logs", - Columns: []*schema.Column{UsageLogsColumns[51]}, + Columns: []*schema.Column{UsageLogsColumns[52]}, RefColumns: []*schema.Column{UsersColumns[0]}, OnDelete: schema.NoAction, }, { Symbol: "usage_logs_user_subscriptions_usage_logs", - Columns: []*schema.Column{UsageLogsColumns[52]}, + Columns: []*schema.Column{UsageLogsColumns[53]}, RefColumns: []*schema.Column{UserSubscriptionsColumns[0]}, OnDelete: schema.SetNull, }, @@ -2007,32 +2008,32 @@ var ( { Name: "usagelog_user_id", Unique: false, - Columns: []*schema.Column{UsageLogsColumns[51]}, + Columns: []*schema.Column{UsageLogsColumns[52]}, }, { Name: "usagelog_api_key_id", Unique: false, - Columns: []*schema.Column{UsageLogsColumns[48]}, + Columns: []*schema.Column{UsageLogsColumns[49]}, }, { Name: "usagelog_account_id", Unique: false, - Columns: []*schema.Column{UsageLogsColumns[49]}, + Columns: []*schema.Column{UsageLogsColumns[50]}, }, { Name: "usagelog_group_id", Unique: false, - Columns: []*schema.Column{UsageLogsColumns[50]}, + Columns: []*schema.Column{UsageLogsColumns[51]}, }, { Name: "usagelog_subscription_id", Unique: false, - Columns: []*schema.Column{UsageLogsColumns[52]}, + Columns: []*schema.Column{UsageLogsColumns[53]}, }, { Name: "usagelog_created_at", Unique: false, - Columns: []*schema.Column{UsageLogsColumns[47]}, + Columns: []*schema.Column{UsageLogsColumns[48]}, }, { Name: "usagelog_model", @@ -2052,17 +2053,17 @@ var ( { Name: "usagelog_user_id_created_at", Unique: false, - Columns: []*schema.Column{UsageLogsColumns[51], UsageLogsColumns[47]}, + Columns: []*schema.Column{UsageLogsColumns[52], UsageLogsColumns[48]}, }, { Name: "usagelog_api_key_id_created_at", Unique: false, - Columns: []*schema.Column{UsageLogsColumns[48], UsageLogsColumns[47]}, + Columns: []*schema.Column{UsageLogsColumns[49], UsageLogsColumns[48]}, }, { Name: "usagelog_group_id_created_at", Unique: false, - Columns: []*schema.Column{UsageLogsColumns[50], UsageLogsColumns[47]}, + Columns: []*schema.Column{UsageLogsColumns[51], UsageLogsColumns[48]}, }, }, } diff --git a/backend/ent/mutation.go b/backend/ent/mutation.go index b3093b4de7b8..9fc968d799a3 100644 --- a/backend/ent/mutation.go +++ b/backend/ent/mutation.go @@ -53082,6 +53082,7 @@ type UsageLogMutation struct { video_duration_seconds *int addvideo_duration_seconds *int cache_ttl_overridden *bool + customer_cost_details *map[string]interface{} queue_timing *map[string]interface{} created_at *time.Time clearedFields map[string]struct{} @@ -55796,6 +55797,55 @@ func (m *UsageLogMutation) ResetCacheTTLOverridden() { m.cache_ttl_overridden = nil } +// SetCustomerCostDetails sets the "customer_cost_details" field. +func (m *UsageLogMutation) SetCustomerCostDetails(value map[string]interface{}) { + m.customer_cost_details = &value +} + +// CustomerCostDetails returns the value of the "customer_cost_details" field in the mutation. +func (m *UsageLogMutation) CustomerCostDetails() (r map[string]interface{}, exists bool) { + v := m.customer_cost_details + if v == nil { + return + } + return *v, true +} + +// OldCustomerCostDetails returns the old "customer_cost_details" field's value of the UsageLog entity. +// If the UsageLog object wasn't provided to the builder, the object is fetched from the database. +// An error is returned if the mutation operation is not UpdateOne, or the database query fails. +func (m *UsageLogMutation) OldCustomerCostDetails(ctx context.Context) (v map[string]interface{}, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldCustomerCostDetails is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldCustomerCostDetails requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldCustomerCostDetails: %w", err) + } + return oldValue.CustomerCostDetails, nil +} + +// ClearCustomerCostDetails clears the value of the "customer_cost_details" field. +func (m *UsageLogMutation) ClearCustomerCostDetails() { + m.customer_cost_details = nil + m.clearedFields[usagelog.FieldCustomerCostDetails] = struct{}{} +} + +// CustomerCostDetailsCleared returns if the "customer_cost_details" field was cleared in this mutation. +func (m *UsageLogMutation) CustomerCostDetailsCleared() bool { + _, ok := m.clearedFields[usagelog.FieldCustomerCostDetails] + return ok +} + +// ResetCustomerCostDetails resets all changes to the "customer_cost_details" field. +func (m *UsageLogMutation) ResetCustomerCostDetails() { + m.customer_cost_details = nil + delete(m.clearedFields, usagelog.FieldCustomerCostDetails) +} + // SetQueueTiming sets the "queue_timing" field. func (m *UsageLogMutation) SetQueueTiming(value map[string]interface{}) { m.queue_timing = &value @@ -56050,7 +56100,7 @@ func (m *UsageLogMutation) Type() string { // order to get all numeric fields that were incremented/decremented, call // AddedFields(). func (m *UsageLogMutation) Fields() []string { - fields := make([]string, 0, 52) + fields := make([]string, 0, 53) if m.platform != nil { fields = append(fields, usagelog.FieldPlatform) } @@ -56201,6 +56251,9 @@ func (m *UsageLogMutation) Fields() []string { if m.cache_ttl_overridden != nil { fields = append(fields, usagelog.FieldCacheTTLOverridden) } + if m.customer_cost_details != nil { + fields = append(fields, usagelog.FieldCustomerCostDetails) + } if m.queue_timing != nil { fields = append(fields, usagelog.FieldQueueTiming) } @@ -56315,6 +56368,8 @@ func (m *UsageLogMutation) Field(name string) (ent.Value, bool) { return m.VideoDurationSeconds() case usagelog.FieldCacheTTLOverridden: return m.CacheTTLOverridden() + case usagelog.FieldCustomerCostDetails: + return m.CustomerCostDetails() case usagelog.FieldQueueTiming: return m.QueueTiming() case usagelog.FieldCreatedAt: @@ -56428,6 +56483,8 @@ func (m *UsageLogMutation) OldField(ctx context.Context, name string) (ent.Value return m.OldVideoDurationSeconds(ctx) case usagelog.FieldCacheTTLOverridden: return m.OldCacheTTLOverridden(ctx) + case usagelog.FieldCustomerCostDetails: + return m.OldCustomerCostDetails(ctx) case usagelog.FieldQueueTiming: return m.OldQueueTiming(ctx) case usagelog.FieldCreatedAt: @@ -56791,6 +56848,13 @@ func (m *UsageLogMutation) SetField(name string, value ent.Value) error { } m.SetCacheTTLOverridden(v) return nil + case usagelog.FieldCustomerCostDetails: + v, ok := value.(map[string]interface{}) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetCustomerCostDetails(v) + return nil case usagelog.FieldQueueTiming: v, ok := value.(map[string]interface{}) if !ok { @@ -57198,6 +57262,9 @@ func (m *UsageLogMutation) ClearedFields() []string { if m.FieldCleared(usagelog.FieldVideoDurationSeconds) { fields = append(fields, usagelog.FieldVideoDurationSeconds) } + if m.FieldCleared(usagelog.FieldCustomerCostDetails) { + fields = append(fields, usagelog.FieldCustomerCostDetails) + } if m.FieldCleared(usagelog.FieldQueueTiming) { fields = append(fields, usagelog.FieldQueueTiming) } @@ -57287,6 +57354,9 @@ func (m *UsageLogMutation) ClearField(name string) error { case usagelog.FieldVideoDurationSeconds: m.ClearVideoDurationSeconds() return nil + case usagelog.FieldCustomerCostDetails: + m.ClearCustomerCostDetails() + return nil case usagelog.FieldQueueTiming: m.ClearQueueTiming() return nil @@ -57448,6 +57518,9 @@ func (m *UsageLogMutation) ResetField(name string) error { case usagelog.FieldCacheTTLOverridden: m.ResetCacheTTLOverridden() return nil + case usagelog.FieldCustomerCostDetails: + m.ResetCustomerCostDetails() + return nil case usagelog.FieldQueueTiming: m.ResetQueueTiming() return nil diff --git a/backend/ent/runtime/runtime.go b/backend/ent/runtime/runtime.go index e113d4a963f3..bd84c75608bc 100644 --- a/backend/ent/runtime/runtime.go +++ b/backend/ent/runtime/runtime.go @@ -2455,7 +2455,7 @@ func init() { // usagelog.DefaultCacheTTLOverridden holds the default value on creation for the cache_ttl_overridden field. usagelog.DefaultCacheTTLOverridden = usagelogDescCacheTTLOverridden.Default.(bool) // usagelogDescCreatedAt is the schema descriptor for created_at field. - usagelogDescCreatedAt := usagelogFields[51].Descriptor() + usagelogDescCreatedAt := usagelogFields[52].Descriptor() // usagelog.DefaultCreatedAt holds the default value on creation for the created_at field. usagelog.DefaultCreatedAt = usagelogDescCreatedAt.Default.(func() time.Time) userMixin := schema.User{}.Mixin() diff --git a/backend/ent/schema/usage_log.go b/backend/ent/schema/usage_log.go index 230db74d7d3a..eca010ef7ae0 100644 --- a/backend/ent/schema/usage_log.go +++ b/backend/ent/schema/usage_log.go @@ -191,6 +191,8 @@ func (UsageLog) Fields() []ent.Field { field.Bool("cache_ttl_overridden"). Default(false), + field.JSON("customer_cost_details", map[string]any{}).Optional().Immutable().Comment("Request-time Standard customer cost display snapshot; NULL is unknown history"), + field.JSON("queue_timing", map[string]any{}).Optional().Comment("Explicit measured server/forward boundaries; NULL means unknown"), // 时间戳(只有 created_at,日志不可修改) diff --git a/backend/ent/usagelog.go b/backend/ent/usagelog.go index f141cfddbd19..18198576e24d 100644 --- a/backend/ent/usagelog.go +++ b/backend/ent/usagelog.go @@ -123,6 +123,8 @@ type UsageLog struct { VideoDurationSeconds *int `json:"video_duration_seconds,omitempty"` // CacheTTLOverridden holds the value of the "cache_ttl_overridden" field. CacheTTLOverridden bool `json:"cache_ttl_overridden,omitempty"` + // Request-time Standard customer cost display snapshot; NULL is unknown history + CustomerCostDetails map[string]interface{} `json:"customer_cost_details,omitempty"` // Explicit measured server/forward boundaries; NULL means unknown QueueTiming map[string]interface{} `json:"queue_timing,omitempty"` // CreatedAt holds the value of the "created_at" field. @@ -210,7 +212,7 @@ func (*UsageLog) scanValues(columns []string) ([]any, error) { values := make([]any, len(columns)) for i := range columns { switch columns[i] { - case usagelog.FieldImageSizeBreakdown, usagelog.FieldQueueTiming: + case usagelog.FieldImageSizeBreakdown, usagelog.FieldCustomerCostDetails, usagelog.FieldQueueTiming: values[i] = new([]byte) case usagelog.FieldUpstreamModelMismatch, usagelog.FieldLongContextBillingApplied, usagelog.FieldStream, usagelog.FieldCacheTTLOverridden: values[i] = new(sql.NullBool) @@ -568,6 +570,14 @@ func (_m *UsageLog) assignValues(columns []string, values []any) error { } else if value.Valid { _m.CacheTTLOverridden = value.Bool } + case usagelog.FieldCustomerCostDetails: + if value, ok := values[i].(*[]byte); !ok { + return fmt.Errorf("unexpected type %T for field customer_cost_details", values[i]) + } else if value != nil && len(*value) > 0 { + if err := json.Unmarshal(*value, &_m.CustomerCostDetails); err != nil { + return fmt.Errorf("unmarshal field customer_cost_details: %w", err) + } + } case usagelog.FieldQueueTiming: if value, ok := values[i].(*[]byte); !ok { return fmt.Errorf("unexpected type %T for field queue_timing", values[i]) @@ -839,6 +849,9 @@ func (_m *UsageLog) String() string { builder.WriteString("cache_ttl_overridden=") builder.WriteString(fmt.Sprintf("%v", _m.CacheTTLOverridden)) builder.WriteString(", ") + builder.WriteString("customer_cost_details=") + builder.WriteString(fmt.Sprintf("%v", _m.CustomerCostDetails)) + builder.WriteString(", ") builder.WriteString("queue_timing=") builder.WriteString(fmt.Sprintf("%v", _m.QueueTiming)) builder.WriteString(", ") diff --git a/backend/ent/usagelog/usagelog.go b/backend/ent/usagelog/usagelog.go index 50fcfab714aa..6d232df6e3b3 100644 --- a/backend/ent/usagelog/usagelog.go +++ b/backend/ent/usagelog/usagelog.go @@ -114,6 +114,8 @@ const ( FieldVideoDurationSeconds = "video_duration_seconds" // FieldCacheTTLOverridden holds the string denoting the cache_ttl_overridden field in the database. FieldCacheTTLOverridden = "cache_ttl_overridden" + // FieldCustomerCostDetails holds the string denoting the customer_cost_details field in the database. + FieldCustomerCostDetails = "customer_cost_details" // FieldQueueTiming holds the string denoting the queue_timing field in the database. FieldQueueTiming = "queue_timing" // FieldCreatedAt holds the string denoting the created_at field in the database. @@ -220,6 +222,7 @@ var Columns = []string{ FieldVideoResolution, FieldVideoDurationSeconds, FieldCacheTTLOverridden, + FieldCustomerCostDetails, FieldQueueTiming, FieldCreatedAt, } diff --git a/backend/ent/usagelog/where.go b/backend/ent/usagelog/where.go index 5f1d636fe8a5..87abe5fe809e 100644 --- a/backend/ent/usagelog/where.go +++ b/backend/ent/usagelog/where.go @@ -2685,6 +2685,16 @@ func CacheTTLOverriddenNEQ(v bool) predicate.UsageLog { return predicate.UsageLog(sql.FieldNEQ(FieldCacheTTLOverridden, v)) } +// CustomerCostDetailsIsNil applies the IsNil predicate on the "customer_cost_details" field. +func CustomerCostDetailsIsNil() predicate.UsageLog { + return predicate.UsageLog(sql.FieldIsNull(FieldCustomerCostDetails)) +} + +// CustomerCostDetailsNotNil applies the NotNil predicate on the "customer_cost_details" field. +func CustomerCostDetailsNotNil() predicate.UsageLog { + return predicate.UsageLog(sql.FieldNotNull(FieldCustomerCostDetails)) +} + // QueueTimingIsNil applies the IsNil predicate on the "queue_timing" field. func QueueTimingIsNil() predicate.UsageLog { return predicate.UsageLog(sql.FieldIsNull(FieldQueueTiming)) diff --git a/backend/ent/usagelog_create.go b/backend/ent/usagelog_create.go index 66aa26efc3f9..6538bee13bb3 100644 --- a/backend/ent/usagelog_create.go +++ b/backend/ent/usagelog_create.go @@ -679,6 +679,12 @@ func (_c *UsageLogCreate) SetNillableCacheTTLOverridden(v *bool) *UsageLogCreate return _c } +// SetCustomerCostDetails sets the "customer_cost_details" field. +func (_c *UsageLogCreate) SetCustomerCostDetails(v map[string]interface{}) *UsageLogCreate { + _c.mutation.SetCustomerCostDetails(v) + return _c +} + // SetQueueTiming sets the "queue_timing" field. func (_c *UsageLogCreate) SetQueueTiming(v map[string]interface{}) *UsageLogCreate { _c.mutation.SetQueueTiming(v) @@ -1228,6 +1234,10 @@ func (_c *UsageLogCreate) createSpec() (*UsageLog, *sqlgraph.CreateSpec) { _spec.SetField(usagelog.FieldCacheTTLOverridden, field.TypeBool, value) _node.CacheTTLOverridden = value } + if value, ok := _c.mutation.CustomerCostDetails(); ok { + _spec.SetField(usagelog.FieldCustomerCostDetails, field.TypeJSON, value) + _node.CustomerCostDetails = value + } if value, ok := _c.mutation.QueueTiming(); ok { _spec.SetField(usagelog.FieldQueueTiming, field.TypeJSON, value) _node.QueueTiming = value @@ -2290,6 +2300,9 @@ func (u *UsageLogUpsert) ClearQueueTiming() *UsageLogUpsert { func (u *UsageLogUpsertOne) UpdateNewValues() *UsageLogUpsertOne { u.create.conflict = append(u.create.conflict, sql.ResolveWithNewValues()) u.create.conflict = append(u.create.conflict, sql.ResolveWith(func(s *sql.UpdateSet) { + if _, exists := u.create.mutation.CustomerCostDetails(); exists { + s.SetIgnore(usagelog.FieldCustomerCostDetails) + } if _, exists := u.create.mutation.CreatedAt(); exists { s.SetIgnore(usagelog.FieldCreatedAt) } @@ -3557,6 +3570,9 @@ func (u *UsageLogUpsertBulk) UpdateNewValues() *UsageLogUpsertBulk { u.create.conflict = append(u.create.conflict, sql.ResolveWithNewValues()) u.create.conflict = append(u.create.conflict, sql.ResolveWith(func(s *sql.UpdateSet) { for _, b := range u.create.builders { + if _, exists := b.mutation.CustomerCostDetails(); exists { + s.SetIgnore(usagelog.FieldCustomerCostDetails) + } if _, exists := b.mutation.CreatedAt(); exists { s.SetIgnore(usagelog.FieldCreatedAt) } diff --git a/backend/ent/usagelog_update.go b/backend/ent/usagelog_update.go index c33242968ba4..9540d5f72537 100644 --- a/backend/ent/usagelog_update.go +++ b/backend/ent/usagelog_update.go @@ -1514,6 +1514,9 @@ func (_u *UsageLogUpdate) sqlSave(ctx context.Context) (_node int, err error) { if value, ok := _u.mutation.CacheTTLOverridden(); ok { _spec.SetField(usagelog.FieldCacheTTLOverridden, field.TypeBool, value) } + if _u.mutation.CustomerCostDetailsCleared() { + _spec.ClearField(usagelog.FieldCustomerCostDetails, field.TypeJSON) + } if value, ok := _u.mutation.QueueTiming(); ok { _spec.SetField(usagelog.FieldQueueTiming, field.TypeJSON, value) } @@ -3197,6 +3200,9 @@ func (_u *UsageLogUpdateOne) sqlSave(ctx context.Context) (_node *UsageLog, err if value, ok := _u.mutation.CacheTTLOverridden(); ok { _spec.SetField(usagelog.FieldCacheTTLOverridden, field.TypeBool, value) } + if _u.mutation.CustomerCostDetailsCleared() { + _spec.ClearField(usagelog.FieldCustomerCostDetails, field.TypeJSON) + } if value, ok := _u.mutation.QueueTiming(); ok { _spec.SetField(usagelog.FieldQueueTiming, field.TypeJSON, value) } diff --git a/backend/internal/handler/admin/scoped_admin_usage_response.go b/backend/internal/handler/admin/scoped_admin_usage_response.go index 62db750aec81..4a5d25e9d478 100644 --- a/backend/internal/handler/admin/scoped_admin_usage_response.go +++ b/backend/internal/handler/admin/scoped_admin_usage_response.go @@ -43,6 +43,7 @@ func scopedAdminUsageLogResponse(record *service.UsageLog) gin.H { "total_cost": usage.TotalCost, "actual_cost": usage.ActualCost, "rate_multiplier": usage.RateMultiplier, + "customer_cost_details": usage.CustomerCostDetails, "long_context_billing_applied": usage.LongContextBillingApplied, "billing_type": usage.BillingType, "request_type": usage.RequestType, diff --git a/backend/internal/handler/admin/scoped_admin_usage_response_test.go b/backend/internal/handler/admin/scoped_admin_usage_response_test.go index c43e9015f40b..4aaca25952bf 100644 --- a/backend/internal/handler/admin/scoped_admin_usage_response_test.go +++ b/backend/internal/handler/admin/scoped_admin_usage_response_test.go @@ -90,3 +90,52 @@ func TestScopedAdminUsageListEmptyRemainsArray(t *testing.T) { require.Equal(t, 200, w.Code) require.Contains(t, w.Body.String(), `"items":[]`) } + +func TestFreeFastCustomerCostScopedAdmin(t *testing.T) { + gin.SetMode(gin.TestMode) + row := service.UsageLog{ID: 12, UserID: 7, APIKeyID: 8, AccountID: 11, RequestID: "synthetic-cost", Model: "synthetic-astra", TotalCost: .2704005, ActualCost: .07134075} + // JSON retains baseline compilability, and unknown/private metadata must not + // sneak through the typed numeric quote into the restricted response. + const quote = `{"version":2,"cache_cost_details":[{"kind":"write_30m","tokens":1197,"unit_price":0.0000125},{"kind":"read","tokens":37469,"unit_price":0.000001}],"free_fast":true,"input_cost":0.08345,"output_cost":0.0068,"image_input_cost":0,"image_output_cost":0,"cache_creation_cost":0.0149625,"cache_read_cost":0.037469,"total_cost":0.1426815,"actual_cost":0.07134075,"multiplier":0.5}` + require.NoError(t, json.Unmarshal([]byte(`{"CustomerCostDetails":`+quote+`}`), &row)) + row.User = &service.User{ID: 7, Email: "private-customer@example.invalid", Notes: "private-notes"} + row.APIKey = &service.APIKey{ID: 8, Key: "private-key"} + row.Account = &service.Account{ID: 11, Credentials: map[string]any{"access_token": "private-credential"}} + row.Group = &service.Group{ID: 9, Name: "private-group"} + row.Subscription = &service.UserSubscription{ID: 10, User: row.User, Group: row.Group} + for _, scoped := range []bool{true, false} { + t.Run(map[bool]string{true: "restricted", false: "full"}[scoped], func(t *testing.T) { + repo := &scopedUsageResponseRepo{records: []service.UsageLog{row}} + h := NewUsageHandler(service.NewUsageService(repo, nil, nil, nil), nil, nil, nil) + r := gin.New() + r.Use(func(c *gin.Context) { + if scoped { + c.Request = c.Request.WithContext(adminaccess.WithPrincipal(c.Request.Context(), &adminaccess.Principal{Policy: adminaccess.Policy{GlobalPermissions: []string{"usage.read"}}})) + } + }) + r.GET("/api/v1/admin/usage", h.List) + w := httptest.NewRecorder() + r.ServeHTTP(w, httptest.NewRequest("GET", "/api/v1/admin/usage", nil)) + require.Equal(t, 200, w.Code) + var response struct { + Data struct { + Items []map[string]json.RawMessage `json:"items"` + } `json:"data"` + } + require.NoError(t, json.Unmarshal(w.Body.Bytes(), &response)) + require.Len(t, response.Data.Items, 1) + item := response.Data.Items[0] + require.Contains(t, item, "customer_cost_details", "restricted admin must expose the immutable customer Standard quote") + require.JSONEq(t, quote, string(item["customer_cost_details"])) + require.JSONEq(t, "0.2704005", string(item["total_cost"])) + require.JSONEq(t, "0.07134075", string(item["actual_cost"])) + if scoped { + for _, field := range []string{"user", "api_key", "account", "group", "subscription", "credentials", "balance"} { + require.NotContains(t, item, field) + } + require.NotContains(t, w.Body.String(), "private-") + } + require.Equal(t, "private-key", repo.records[0].APIKey.Key) + }) + } +} diff --git a/backend/internal/handler/dto/free_fast_customer_cost_test.go b/backend/internal/handler/dto/free_fast_customer_cost_test.go new file mode 100644 index 000000000000..674302328d8b --- /dev/null +++ b/backend/internal/handler/dto/free_fast_customer_cost_test.go @@ -0,0 +1,42 @@ +package dto + +import ( + "encoding/json" + "testing" + + "github.com/Wei-Shaw/sub2api/internal/service" + "github.com/stretchr/testify/require" +) + +func TestFreeFastCustomerCostDTO(t *testing.T) { + row := &service.UsageLog{InputCost: .00142, OutputCost: .0019, TotalCost: .00332, ActualCost: .000996} + require.NoError(t, json.Unmarshal([]byte(`{"CustomerCostDetails":{"version":1,"free_fast":true,"input_cost":0.00071,"output_cost":0.00095,"total_cost":0.00166,"actual_cost":0.000996,"multiplier":0.6}}`), row)) + for _, mapped := range []any{UsageLogFromService(row), UsageLogFromServiceForUser(row, false), UsageLogFromServiceAdmin(row)} { + raw, err := json.Marshal(mapped) + require.NoError(t, err) + var data map[string]any + require.NoError(t, json.Unmarshal(raw, &data)) + detail, ok := data["customer_cost_details"].(map[string]any) + require.True(t, ok, "user/admin DTO must expose the immutable customer Standard quote") + require.InDelta(t, .00071, detail["input_cost"], 1e-12) + require.InDelta(t, .00332, data["total_cost"], 1e-12) + require.InDelta(t, .000996, data["actual_cost"], 1e-12) + } + legacy, err := json.Marshal(UsageLogFromService(&service.UsageLog{})) + require.NoError(t, err) + require.NotContains(t, string(legacy), "customer_cost_details") +} + +func TestFreeFastCustomerCostCacheDTO(t *testing.T) { + row := &service.UsageLog{} + require.NoError(t, json.Unmarshal([]byte(`{"CustomerCostDetails":{"version":2,"free_fast":true,"cache_cost_details":[{"kind":"write_12h","tokens":13,"unit_price":0.000025}]}}`), row)) + for _, mapped := range []any{UsageLogFromService(row), UsageLogFromServiceForUser(row, false), UsageLogFromServiceAdmin(row)} { + raw, err := json.Marshal(mapped) + require.NoError(t, err) + var data map[string]json.RawMessage + require.NoError(t, json.Unmarshal(raw, &data)) + var snapshot map[string]json.RawMessage + require.NoError(t, json.Unmarshal(data["customer_cost_details"], &snapshot)) + require.JSONEq(t, `[{"kind":"write_12h","tokens":13,"unit_price":0.000025}]`, string(snapshot["cache_cost_details"]), "customer cache price DTO parity") + } +} diff --git a/backend/internal/handler/dto/mappers.go b/backend/internal/handler/dto/mappers.go index 97ac14b5203c..9e1fb1ec5cc2 100644 --- a/backend/internal/handler/dto/mappers.go +++ b/backend/internal/handler/dto/mappers.go @@ -756,6 +756,7 @@ func usageLogFromServiceUser(l *service.UsageLog) UsageLog { QueueWaitMs: l.QueueWaitMs, QueueTiming: l.QueueTiming, ContentTiming: l.ContentTiming, + CustomerCostDetails: l.CustomerCostDetails, ImageCount: l.ImageCount, ImageSize: l.ImageSize, ImageInputSize: l.ImageInputSize, diff --git a/backend/internal/handler/dto/types.go b/backend/internal/handler/dto/types.go index 4bd2bb0e7613..cfc681bb2917 100644 --- a/backend/internal/handler/dto/types.go +++ b/backend/internal/handler/dto/types.go @@ -621,13 +621,14 @@ type BatchUpdateRedeemCodesRequest struct { // UsageLog 是普通用户接口使用的 usage log DTO(不包含管理员字段)。 type UsageLog struct { - ContentTiming *requesttiming.ContentObservation `json:"content_timing,omitempty"` - ID int64 `json:"id"` - UserID int64 `json:"user_id"` - APIKeyID int64 `json:"api_key_id"` - AccountID int64 `json:"account_id"` - RequestID string `json:"request_id"` - Model string `json:"model"` + CustomerCostDetails *service.CustomerCostDetails `json:"customer_cost_details,omitempty"` + ContentTiming *requesttiming.ContentObservation `json:"content_timing,omitempty"` + ID int64 `json:"id"` + UserID int64 `json:"user_id"` + APIKeyID int64 `json:"api_key_id"` + AccountID int64 `json:"account_id"` + RequestID string `json:"request_id"` + Model string `json:"model"` // ServiceTier records the OpenAI service tier used for billing, e.g. "priority" / "flex". ServiceTier *string `json:"service_tier,omitempty"` // ReasoningEffort is the client-requested effort (mapping-hidden, like Model). diff --git a/backend/internal/handler/pr610_queue_wait_test.go b/backend/internal/handler/pr610_queue_wait_test.go index 398748b8bd43..39d0b05f7f83 100644 --- a/backend/internal/handler/pr610_queue_wait_test.go +++ b/backend/internal/handler/pr610_queue_wait_test.go @@ -181,6 +181,13 @@ func (s *pr610TimingScenario) prepareTurn() { if phase == "switch_account" { d = 5 * time.Second } + if s.realtime && s.retry { + // This real retry fixture needs separation from the 380ms + // queue ceiling even when the runner overschedules a sleep. + // Keep both actual acquisitions, at 10ms each; the rejected + // network attempt below alone lasts longer than the ceiling. + d = time.Second + } s.advance(d) close(b.release) case <-time.After(3 * time.Second): @@ -249,7 +256,11 @@ func (s *pr610TimingScenario) serveHTTP(w http.ResponseWriter, r *http.Request, return true } if s.retry && s.attempts.Add(1) == 1 { - s.advance(7 * time.Second) + delay := 7 * time.Second + if s.realtime { + delay = 40 * time.Second // advance scales to 400ms of real network wait + } + s.advance(delay) w.Header().Set("Content-Type", "application/json") w.WriteHeader(http.StatusBadRequest) _, _ = io.WriteString(w, `{"error":{"type":"invalid_request_error","code":"invalid_parameter","param":"truncation","message":"Unsupported parameter: truncation"}}`) @@ -429,6 +440,8 @@ func TestPR610RealBridgeRetryDenominator(t *testing.T) { row := got.log require.GreaterOrEqual(t, *row.DurationMs, 85, "rejected-field network time must stay in legacy TPS denominator") require.Less(t, *row.QueueWaitMs, 380, "rejected-field network time must not move into queue") + require.GreaterOrEqual(t, *row.QueueWaitMs, 20, "both real acquisition barriers must still count") + require.GreaterOrEqual(t, *row.DurationMs, 415, "400ms rejection plus 20ms successful response must stay in legacy duration") } func (s *pr610TimingScenario) startHolder(serverURL, key string, gateway *service.OpenAIGatewayService) { diff --git a/backend/internal/repository/free_fast_customer_cost_integration_test.go b/backend/internal/repository/free_fast_customer_cost_integration_test.go new file mode 100644 index 000000000000..4788119b91ba --- /dev/null +++ b/backend/internal/repository/free_fast_customer_cost_integration_test.go @@ -0,0 +1,159 @@ +//go:build integration + +package repository + +import ( + "context" + "encoding/json" + "fmt" + "testing" + "time" + + "github.com/Wei-Shaw/sub2api/internal/service" + "github.com/Wei-Shaw/sub2api/migrations" + "github.com/stretchr/testify/require" +) + +// The JSON seed keeps the same test executable against the old production +// structs; a missing snapshot must fail a business assertion, not compilation. +func TestFreeFastCustomerCostPersistence(t *testing.T) { + ctx := context.Background() + client := testEntClient(t) + repo := newUsageLogRepositoryWithSQL(client, integrationDB) + stamp := fmt.Sprint(time.Now().UnixNano()) + user := mustCreateUser(t, client, &service.User{Email: "cost-" + stamp + "@example.invalid"}) + key := mustCreateApiKey(t, client, &service.APIKey{UserID: user.ID, Key: "synthetic-cost-" + stamp, Name: "Fixture"}) + account := mustCreateAccount(t, client, &service.Account{Name: "Fixture", Platform: "openai"}) + t.Cleanup(func() { + for _, row := range []struct { + sql string + id int64 + }{ + {"DELETE FROM usage_logs WHERE user_id=$1", user.ID}, {"DELETE FROM api_keys WHERE id=$1", key.ID}, + {"DELETE FROM accounts WHERE id=$1", account.ID}, {"DELETE FROM users WHERE id=$1", user.ID}, + } { + _, err := integrationDB.ExecContext(ctx, row.sql, row.id) + require.NoError(t, err) + } + }) + const snapshot = `{"version":1,"free_fast":true,"input_cost":0.00071,"output_cost":0.00095,"image_input_cost":0,"image_output_cost":0,"cache_creation_cost":0,"cache_read_cost":0,"total_cost":0.00166,"actual_cost":0.000996,"multiplier":0.6}` + for _, mode := range []string{"single", "batch", "best-effort-single", "best-effort-batch", "legacy"} { + t.Run(mode, func(t *testing.T) { + log := &service.UsageLog{UserID: user.ID, APIKeyID: key.ID, AccountID: account.ID, RequestID: "cost-" + stamp + mode, + Model: "synthetic-astra", InputTokens: 71, OutputTokens: 19, InputCost: .00142, OutputCost: .0019, TotalCost: .00332, ActualCost: .000996, RateMultiplier: .6, CreatedAt: time.Now().UTC()} + if mode != "legacy" { + require.NoError(t, json.Unmarshal([]byte(`{"CustomerCostDetails":`+snapshot+`}`), log)) + } + prepared := prepareUsageLogInsert(log) + var err error + switch mode { + case "single", "legacy": + _, err = repo.createSingle(ctx, integrationDB, log) + case "batch": + k := usageLogBatchKey(log.RequestID, log.APIKeyID) + _, _, _, err = repo.batchInsertUsageLogs(integrationDB, []string{k}, map[string]usageLogInsertPrepared{k: prepared}) + case "best-effort-single": + err = execUsageLogInsertNoResult(ctx, integrationDB, prepared) + case "best-effort-batch": + q, args := buildUsageLogBestEffortInsertQuery([]usageLogInsertPrepared{prepared}) + _, err = integrationDB.ExecContext(ctx, q, args...) + } + require.NoError(t, err) + stored, err := scanUsageLog(integrationDB.QueryRowContext(ctx, "SELECT "+usageLogSelectColumns+" FROM usage_logs WHERE request_id=$1 AND api_key_id=$2", log.RequestID, key.ID)) + require.NoError(t, err) + raw, err := json.Marshal(stored) + require.NoError(t, err) + var fields map[string]json.RawMessage + require.NoError(t, json.Unmarshal(raw, &fields)) + if mode == "legacy" { + require.True(t, len(fields["CustomerCostDetails"]) == 0 || string(fields["CustomerCostDetails"]) == "null") + return + } + require.NotEmpty(t, fields["CustomerCostDetails"], "stored usage must retain the customer Standard quote") + require.JSONEq(t, snapshot, string(fields["CustomerCostDetails"])) + require.InDelta(t, .00332, stored.TotalCost, 1e-10) + require.InDelta(t, .000996, stored.ActualCost, 1e-10) + // Repeated insertion must retain the first snapshot, not rewrite history. + require.NoError(t, json.Unmarshal([]byte(`{"CustomerCostDetails":{"version":99}}`), log)) + _, err = repo.createSingle(ctx, integrationDB, log) + require.NoError(t, err) + var saved string + require.NoError(t, integrationDB.QueryRowContext(ctx, "SELECT customer_cost_details::text FROM usage_logs WHERE request_id=$1 AND api_key_id=$2", log.RequestID, key.ID).Scan(&saved)) + require.JSONEq(t, snapshot, saved) + }) + } +} + +func TestFreeFastCustomerCostDurableReplay(t *testing.T) { + ctx := context.Background() + repo, cmd, usage, _ := durableBillingFixture(t) + cmd.BalanceCost, cmd.APIKeyQuotaCost = .000996, .000996 + usage.InputCost, usage.OutputCost, usage.TotalCost, usage.ActualCost = .00142, .0019, .00332, .000996 + const snapshot = `{"version":1,"free_fast":true,"input_cost":0.00071,"output_cost":0.00095,"image_input_cost":0,"image_output_cost":0,"cache_creation_cost":0,"cache_read_cost":0,"total_cost":0.00166,"actual_cost":0.000996,"multiplier":0.6}` + require.NoError(t, json.Unmarshal([]byte(`{"CustomerCostDetails":`+snapshot+`}`), &usage)) + require.NoError(t, repo.StageUsageBilling(ctx, &cmd, &usage)) + // A later retry sees different config/display data; the first event wins. + require.NoError(t, json.Unmarshal([]byte(`{"CustomerCostDetails":{"version":99}}`), &usage)) + require.NoError(t, repo.StageUsageBilling(ctx, &cmd, &usage)) + key := service.UsageBillingEventKey{RequestID: cmd.RequestID, APIKeyID: cmd.APIKeyID} + for i := 0; i < 2; i++ { + _, err := repo.ApplyStagedUsageBilling(ctx, key) + require.NoError(t, err) + } + var saved string + require.NoError(t, repo.db.QueryRowContext(ctx, "SELECT customer_cost_details::text FROM usage_logs WHERE request_id=$1 AND api_key_id=$2", cmd.RequestID, cmd.APIKeyID).Scan(&saved)) + require.JSONEq(t, snapshot, saved) + var balance, quota string + require.NoError(t, repo.db.QueryRowContext(ctx, "SELECT balance::text FROM users WHERE id=$1", cmd.UserID).Scan(&balance)) + require.NoError(t, repo.db.QueryRowContext(ctx, "SELECT quota_used::text FROM api_keys WHERE id=$1", cmd.APIKeyID).Scan("a)) + require.Equal(t, "99.99900400", balance) + require.Equal(t, "0.00099600", quota) +} + +func TestFreeFastCustomerCostMigration(t *testing.T) { + ctx := context.Background() + tx, err := integrationDB.BeginTx(ctx, nil) + require.NoError(t, err) + defer func() { _ = tx.Rollback() }() + // A connection-local synthetic old table makes the upgrade test independent + // of deployed data and the migration harness's already-current schema. + _, err = tx.ExecContext(ctx, `CREATE TEMP TABLE usage_logs (id bigint, total_cost numeric, actual_cost numeric) ON COMMIT DROP; + INSERT INTO usage_logs VALUES(1,0.00332,0.000996)`) + require.NoError(t, err) + sql, err := migrations.FS.ReadFile("379_usage_customer_cost_details.sql") + require.NoError(t, err) + for i := 0; i < 2; i++ { + _, err = tx.ExecContext(ctx, string(sql)) + require.NoError(t, err) + } + var unchanged bool + require.NoError(t, tx.QueryRowContext(ctx, `SELECT customer_cost_details IS NULL AND total_cost=0.00332 AND actual_cost=0.000996 FROM usage_logs WHERE id=1`).Scan(&unchanged)) + require.True(t, unchanged, "migration must leave old charges intact with unknown display evidence") +} + +func TestFreeFastCustomerCostCachePersistence(t *testing.T) { + ctx := context.Background() + repo, cmd, usage, _ := durableBillingFixture(t) + const snapshot = `{"version":2,"free_fast":true,"input_cost":0.08345,"output_cost":0.0068,"image_input_cost":0,"image_output_cost":0,"cache_creation_cost":0.0004625,"cache_read_cost":0.000017,"total_cost":0.0907295,"actual_cost":0.04536475,"multiplier":0.5,"cache_cost_details":[{"kind":"write_30m","tokens":11,"unit_price":0.0000125},{"kind":"write_12h","tokens":13,"unit_price":0.000025},{"kind":"read","tokens":17,"unit_price":0.000001}]}` + cmd.BalanceCost, cmd.APIKeyQuotaCost = .04536475, .04536475 + usage.TotalCost, usage.ActualCost = .2704005, .04536475 + require.NoError(t, json.Unmarshal([]byte(`{"CustomerCostDetails":`+snapshot+`}`), &usage)) + require.NoError(t, repo.StageUsageBilling(ctx, &cmd, &usage)) + key := service.UsageBillingEventKey{RequestID: cmd.RequestID, APIKeyID: cmd.APIKeyID} + for i := 0; i < 2; i++ { + _, err := repo.ApplyStagedUsageBilling(ctx, key) + require.NoError(t, err) + } + stored, err := scanUsageLog(repo.db.QueryRowContext(ctx, "SELECT "+usageLogSelectColumns+" FROM usage_logs WHERE request_id=$1 AND api_key_id=$2", cmd.RequestID, cmd.APIKeyID)) + require.NoError(t, err) + raw, err := json.Marshal(stored) + require.NoError(t, err) + var fields map[string]json.RawMessage + require.NoError(t, json.Unmarshal(raw, &fields)) + require.JSONEq(t, snapshot, string(fields["CustomerCostDetails"]), "cache prices must survive durable SQL storage and readback") + require.InDelta(t, .2704005, stored.TotalCost, 1e-10) + require.InDelta(t, .04536475, stored.ActualCost, 1e-10) + var quota string + require.NoError(t, repo.db.QueryRowContext(ctx, "SELECT quota_used::text FROM api_keys WHERE id=$1", cmd.APIKeyID).Scan("a)) + require.Equal(t, "0.04536475", quota, "display cache prices cannot change or repeat the command") +} diff --git a/backend/internal/repository/usage_log_repo_insert.go b/backend/internal/repository/usage_log_repo_insert.go index 7471b768fe43..3029981b3c3c 100644 --- a/backend/internal/repository/usage_log_repo_insert.go +++ b/backend/internal/repository/usage_log_repo_insert.go @@ -91,6 +91,7 @@ var usageLogInsertArgTypes = [...]string{ "timestamptz", // created_at "jsonb", // queue_timing "text", // platform + "jsonb", // customer_cost_details } const ( @@ -296,14 +297,15 @@ func (r *usageLogRepository) createSingle(ctx context.Context, sqlq sqlExecutor, cache_creation_12h_tokens, created_at, queue_timing, - platform + platform, + customer_cost_details ) VALUES ( $1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13, $14, $15, $16, $17, $18, $19, $20, $21, $22, $23, $24, $25, - $26, $27, $28, $29, $30, $31, $32, $33, $34, $35, $36, $37, $38, $39, $40, $41, $42, $43, $44, $45, $46, $47, $48, $49, $50, $51, $52, $53, $54, $55, $56, $57, $58, $59, $60, $61, $62, $63, $64, $65, $66, $67 + $26, $27, $28, $29, $30, $31, $32, $33, $34, $35, $36, $37, $38, $39, $40, $41, $42, $43, $44, $45, $46, $47, $48, $49, $50, $51, $52, $53, $54, $55, $56, $57, $58, $59, $60, $61, $62, $63, $64, $65, $66, $67, $68 ) ON CONFLICT (request_id, api_key_id) DO NOTHING RETURNING id, created_at @@ -761,7 +763,8 @@ func buildUsageLogBatchInsertQuery(keys []string, preparedByKey map[string]usage cache_creation_12h_tokens, created_at, queue_timing, - platform + platform, + customer_cost_details ) AS (VALUES `) // Each batch row prepends the synthetic input_index before the 61 @@ -861,7 +864,8 @@ func buildUsageLogBatchInsertQuery(keys []string, preparedByKey map[string]usage cache_creation_12h_tokens, created_at, queue_timing, - platform + platform, + customer_cost_details ) SELECT user_id, @@ -930,7 +934,8 @@ func buildUsageLogBatchInsertQuery(keys []string, preparedByKey map[string]usage cache_creation_12h_tokens, created_at, queue_timing, - platform + platform, + customer_cost_details FROM input ON CONFLICT (request_id, api_key_id) DO NOTHING RETURNING request_id, api_key_id, id, created_at @@ -1039,7 +1044,8 @@ func buildUsageLogBestEffortInsertQuery(preparedList []usageLogInsertPrepared) ( cache_creation_12h_tokens, created_at, queue_timing, - platform + platform, + customer_cost_details ) AS (VALUES `) args := make([]any, 0, len(preparedList)*60) @@ -1134,7 +1140,8 @@ func buildUsageLogBestEffortInsertQuery(preparedList []usageLogInsertPrepared) ( cache_creation_12h_tokens, created_at, queue_timing, - platform + platform, + customer_cost_details ) SELECT user_id, @@ -1203,7 +1210,8 @@ func buildUsageLogBestEffortInsertQuery(preparedList []usageLogInsertPrepared) ( cache_creation_12h_tokens, created_at, queue_timing, - platform + platform, + customer_cost_details FROM input ON CONFLICT (request_id, api_key_id) DO NOTHING `) @@ -1280,14 +1288,15 @@ func execUsageLogInsertNoResult(ctx context.Context, sqlq sqlExecutor, prepared cache_creation_12h_tokens, created_at, queue_timing, - platform + platform, + customer_cost_details ) VALUES ( $1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13, $14, $15, $16, $17, $18, $19, $20, $21, $22, $23, $24, $25, - $26, $27, $28, $29, $30, $31, $32, $33, $34, $35, $36, $37, $38, $39, $40, $41, $42, $43, $44, $45, $46, $47, $48, $49, $50, $51, $52, $53, $54, $55, $56, $57, $58, $59, $60, $61, $62, $63, $64, $65, $66, $67 + $26, $27, $28, $29, $30, $31, $32, $33, $34, $35, $36, $37, $38, $39, $40, $41, $42, $43, $44, $45, $46, $47, $48, $49, $50, $51, $52, $53, $54, $55, $56, $57, $58, $59, $60, $61, $62, $63, $64, $65, $66, $67, $68 ) ON CONFLICT (request_id, api_key_id) DO NOTHING `, prepared.args...) @@ -1312,6 +1321,12 @@ func prepareUsageLogInsert(log *service.UsageLog) usageLogInsertPrepared { duration := nullInt(log.DurationMs) firstToken := nullInt(log.FirstTokenMs) queueWait := nullInt(log.QueueWaitMs) + var customerCostDetails any + if log.CustomerCostDetails != nil { + if raw, err := json.Marshal(log.CustomerCostDetails); err == nil { + customerCostDetails = string(raw) + } + } var queueTiming any if log.QueueTiming != nil { raw, _ := json.Marshal(log.QueueTiming) @@ -1423,6 +1438,7 @@ func prepareUsageLogInsert(log *service.UsageLog) usageLogInsertPrepared { createdAt, queueTiming, nullString(&log.Platform), + customerCostDetails, }, } } diff --git a/backend/internal/repository/usage_log_repo_insert_shape_unit_test.go b/backend/internal/repository/usage_log_repo_insert_shape_unit_test.go index 8c4ce8572ffb..eeaa3714a437 100644 --- a/backend/internal/repository/usage_log_repo_insert_shape_unit_test.go +++ b/backend/internal/repository/usage_log_repo_insert_shape_unit_test.go @@ -6,6 +6,7 @@ import ( "context" "database/sql" "regexp" + "slices" "strconv" "strings" "testing" @@ -129,7 +130,14 @@ func TestPrepareUsageLogInsert_UpstreamRequestIDArgWiring(t *testing.T) { }) require.Len(t, prepared.args, len(usageLogInsertArgTypes)) - idx := len(prepared.args) - 8 + // The SELECT list starts with the generated id; all remaining columns + // share prepareUsageLogInsert's order. Appended fields must not move this + // assertion onto session_id (or another nullable text argument). + columns := strings.Split(usageLogSelectColumns, ", ") + require.Len(t, columns, len(prepared.args)+1) + idx := slices.Index(columns, "upstream_request_id") - 1 + require.GreaterOrEqual(t, idx, 0) + require.Equal(t, "session_id", columns[idx+2]) arg, ok := prepared.args[idx].(sql.NullString) require.True(t, ok, "upstream_request_id arg should be sql.NullString, got %T", prepared.args[idx]) require.True(t, arg.Valid) diff --git a/backend/internal/repository/usage_log_repo_query.go b/backend/internal/repository/usage_log_repo_query.go index ea8b1b3c2d50..ad7d1b83640f 100644 --- a/backend/internal/repository/usage_log_repo_query.go +++ b/backend/internal/repository/usage_log_repo_query.go @@ -19,7 +19,7 @@ import ( "github.com/Wei-Shaw/sub2api/internal/service" ) -const usageLogSelectColumns = "id, user_id, api_key_id, account_id, request_id, model, requested_model, upstream_model, upstream_response_model, upstream_model_mismatch, group_id, subscription_id, input_tokens, output_tokens, cache_creation_tokens, cache_read_tokens, cache_creation_5m_tokens, cache_creation_1h_tokens, image_output_tokens, image_output_cost, image_input_tokens, image_input_cost, input_cost, output_cost, cache_creation_cost, cache_read_cost, total_cost, actual_cost, rate_multiplier, account_rate_multiplier, billing_type, request_type, stream, openai_ws_mode, duration_ms, first_token_ms, queue_wait_ms, user_agent, ip_address, image_count, image_size, image_input_size, image_output_size, image_size_source, image_size_breakdown, video_count, video_resolution, video_duration_seconds, service_tier, reasoning_effort, requested_reasoning_effort, inbound_endpoint, upstream_endpoint, cache_ttl_overridden, long_context_billing_applied, channel_id, model_mapping_chain, billing_tier, billing_mode, account_stats_cost, upstream_request_id, session_id, native_compaction_v2, cache_creation_30m_tokens, cache_creation_12h_tokens, created_at, queue_timing, platform" +const usageLogSelectColumns = "id, user_id, api_key_id, account_id, request_id, model, requested_model, upstream_model, upstream_response_model, upstream_model_mismatch, group_id, subscription_id, input_tokens, output_tokens, cache_creation_tokens, cache_read_tokens, cache_creation_5m_tokens, cache_creation_1h_tokens, image_output_tokens, image_output_cost, image_input_tokens, image_input_cost, input_cost, output_cost, cache_creation_cost, cache_read_cost, total_cost, actual_cost, rate_multiplier, account_rate_multiplier, billing_type, request_type, stream, openai_ws_mode, duration_ms, first_token_ms, queue_wait_ms, user_agent, ip_address, image_count, image_size, image_input_size, image_output_size, image_size_source, image_size_breakdown, video_count, video_resolution, video_duration_seconds, service_tier, reasoning_effort, requested_reasoning_effort, inbound_endpoint, upstream_endpoint, cache_ttl_overridden, long_context_billing_applied, channel_id, model_mapping_chain, billing_tier, billing_mode, account_stats_cost, upstream_request_id, session_id, native_compaction_v2, cache_creation_30m_tokens, cache_creation_12h_tokens, created_at, queue_timing, platform, customer_cost_details" func (r *usageLogRepository) GetByID(ctx context.Context, id int64) (log *service.UsageLog, err error) { query := "SELECT " + usageLogSelectColumns + " FROM usage_logs WHERE id = $1" @@ -507,6 +507,7 @@ func scanUsageLog(scanner interface{ Scan(...any) error }) (*service.UsageLog, e cacheCreation30m int cacheCreation12h int createdAt time.Time + customerCostDetails sql.NullString queueTiming sql.NullString platform sql.NullString ) @@ -580,6 +581,7 @@ func scanUsageLog(scanner interface{ Scan(...any) error }) (*service.UsageLog, e &createdAt, &queueTiming, &platform, + &customerCostDetails, ); err != nil { return nil, err } @@ -621,6 +623,12 @@ func scanUsageLog(scanner interface{ Scan(...any) error }) (*service.UsageLog, e LongContextBillingApplied: longContextBillingApplied, CreatedAt: createdAt, } + if customerCostDetails.Valid { + var detail service.CustomerCostDetails + if json.Unmarshal([]byte(customerCostDetails.String), &detail) == nil { + log.CustomerCostDetails = &detail + } + } if queueTiming.Valid { var timing service.QueueTiming if err := json.Unmarshal([]byte(queueTiming.String), &timing); err != nil { diff --git a/backend/internal/repository/usage_log_repo_request_type_test.go b/backend/internal/repository/usage_log_repo_request_type_test.go index 4884649206f5..e3636b13b96d 100644 --- a/backend/internal/repository/usage_log_repo_request_type_test.go +++ b/backend/internal/repository/usage_log_repo_request_type_test.go @@ -108,6 +108,7 @@ func TestUsageLogRepositoryCreateSyncRequestTypeAndLegacyFields(t *testing.T) { createdAt, sqlmock.AnyArg(), // queue_timing sql.NullString{}, // platform + nil, // customer_cost_details ). WillReturnRows(sqlmock.NewRows([]string{"id", "created_at"}).AddRow(int64(99), createdAt)) @@ -208,6 +209,7 @@ func TestUsageLogRepositoryCreate_PersistsServiceTier(t *testing.T) { createdAt, sqlmock.AnyArg(), // queue_timing sql.NullString{}, // platform + nil, // customer_cost_details ). WillReturnRows(sqlmock.NewRows([]string{"id", "created_at"}).AddRow(int64(100), createdAt)) @@ -288,8 +290,8 @@ func TestPrepareUsageLogInsert_PersistsNativeCompactionV2WithoutChangingRequestT prepared := prepareUsageLogInsert(log) require.Len(t, prepared.args, len(usageLogInsertArgTypes)) - require.Equal(t, "boolean", usageLogInsertArgTypes[len(usageLogInsertArgTypes)-6]) - require.Equal(t, true, prepared.args[len(prepared.args)-6]) + require.Equal(t, "boolean", usageLogInsertArgTypes[len(usageLogInsertArgTypes)-7]) + require.Equal(t, true, prepared.args[len(prepared.args)-7]) require.Equal(t, int16(service.RequestTypeStream), prepared.args[30]) require.Equal(t, service.RequestTypeStream, log.RequestType) require.True(t, log.Stream) @@ -976,6 +978,7 @@ func TestScanUsageLogRequestTypeAndLegacyFallback(t *testing.T) { now, sql.NullString{}, // queue_timing sql.NullString{}, // platform + sql.NullString{}, // customer_cost_details }}) require.NoError(t, err) require.Equal(t, 2, log.ImageCount) @@ -1061,6 +1064,7 @@ func TestScanUsageLogRequestTypeAndLegacyFallback(t *testing.T) { now, sql.NullString{}, // queue_timing sql.NullString{}, // platform + sql.NullString{}, // customer_cost_details }}) require.NoError(t, err) require.NotNil(t, log.ServiceTier) @@ -1129,6 +1133,7 @@ func TestScanUsageLogRequestTypeAndLegacyFallback(t *testing.T) { now, sql.NullString{}, // queue_timing sql.NullString{}, // platform + sql.NullString{}, // customer_cost_details }}) require.NoError(t, err) require.NotNil(t, log.ServiceTier) @@ -1198,6 +1203,7 @@ func TestScanUsageLogRequestTypeAndLegacyFallback(t *testing.T) { now, sql.NullString{}, // queue_timing sql.NullString{}, // platform + sql.NullString{}, // customer_cost_details }}) require.NoError(t, err) require.NotNil(t, log.ServiceTier) diff --git a/backend/internal/repository/usage_log_session_id_unit_test.go b/backend/internal/repository/usage_log_session_id_unit_test.go index 8487a23e80dc..8c8649598493 100644 --- a/backend/internal/repository/usage_log_session_id_unit_test.go +++ b/backend/internal/repository/usage_log_session_id_unit_test.go @@ -30,7 +30,7 @@ func newSessionIDUsageLog(sessionID *string) *service.UsageLog { // TestPrepareUsageLogInsert_SessionIDArgWiring pins the session_id column to the // arg slice / arg-type table so the five INSERT column lists stay in sync. session_id -// is immediately before native_compaction_v2; created_at, queue_timing and platform follow. +// is immediately before native_compaction_v2; created_at, queue_timing, platform and customer_cost_details follow. func TestPrepareUsageLogInsert_SessionIDArgWiring(t *testing.T) { sessionID := "sess-persisted-123" prepared := prepareUsageLogInsert(newSessionIDUsageLog(&sessionID)) @@ -38,16 +38,16 @@ func TestPrepareUsageLogInsert_SessionIDArgWiring(t *testing.T) { require.Len(t, prepared.args, len(usageLogInsertArgTypes), "prepared args must match the arg-type table length") - // session_id precedes native_compaction_v2, both TTL counters, created_at, queue_timing and platform. - sessionArg := prepared.args[len(prepared.args)-7] + // session_id precedes native_compaction_v2, both TTL counters, created_at, queue_timing, platform and customer_cost_details. + sessionArg := prepared.args[len(prepared.args)-8] ns, ok := sessionArg.(sql.NullString) require.True(t, ok, "session_id arg should be a sql.NullString, got %T", sessionArg) require.True(t, ns.Valid) require.Equal(t, sessionID, ns.String) - require.Equal(t, "text", usageLogInsertArgTypes[len(usageLogInsertArgTypes)-7], + require.Equal(t, "text", usageLogInsertArgTypes[len(usageLogInsertArgTypes)-8], "session_id arg type must be text") - require.Equal(t, "boolean", usageLogInsertArgTypes[len(usageLogInsertArgTypes)-6], + require.Equal(t, "boolean", usageLogInsertArgTypes[len(usageLogInsertArgTypes)-7], "native_compaction_v2 arg type must be boolean") } @@ -55,14 +55,14 @@ func TestPrepareUsageLogInsert_SessionIDArgWiring(t *testing.T) { // persisted as SQL NULL rather than an empty string. func TestPrepareUsageLogInsert_SessionIDNullWhenAbsent(t *testing.T) { prepared := prepareUsageLogInsert(newSessionIDUsageLog(nil)) - sessionArg := prepared.args[len(prepared.args)-7] + sessionArg := prepared.args[len(prepared.args)-8] ns, ok := sessionArg.(sql.NullString) require.True(t, ok, "session_id arg should be a sql.NullString, got %T", sessionArg) require.False(t, ns.Valid, "absent session id must be NULL, not empty string") empty := "" preparedEmpty := prepareUsageLogInsert(newSessionIDUsageLog(&empty)) - nsEmpty := preparedEmpty.args[len(preparedEmpty.args)-7].(sql.NullString) + nsEmpty := preparedEmpty.args[len(preparedEmpty.args)-8].(sql.NullString) require.False(t, nsEmpty.Valid, "empty session id must also be NULL") } diff --git a/backend/internal/service/billing_service.go b/backend/internal/service/billing_service.go index c8d0c3a1fab6..6ba10fdc51e8 100644 --- a/backend/internal/service/billing_service.go +++ b/backend/internal/service/billing_service.go @@ -200,9 +200,10 @@ type UsageTokens struct { // CostBreakdown 费用明细 type CostBreakdown struct { - modelBillingMultiplier float64 // Customer-only model surcharge; zero means 1x. - InputCost float64 // 文本输入费用(不含图片输入,图片输入单独记入 ImageInputCost) - ImageInputCost float64 // 图片输入 token 费用(如 gpt-image-2 图片编辑) + customerCacheCosts []CustomerCacheCostDetail // Display-only evidence from this exact calculation. + modelBillingMultiplier float64 // Customer-only model surcharge; zero means 1x. + InputCost float64 // 文本输入费用(不含图片输入,图片输入单独记入 ImageInputCost) + ImageInputCost float64 // 图片输入 token 费用(如 gpt-image-2 图片编辑) OutputCost float64 ImageOutputCost float64 CacheCreationCost float64 @@ -225,6 +226,9 @@ func applyCostBreakdownMultiplier(cost *CostBreakdown, multiplier float64) { cost.CacheReadCost *= multiplier cost.TotalCost *= multiplier cost.ActualCost *= multiplier + for i := range cost.customerCacheCosts { + cost.customerCacheCosts[i].UnitPrice *= multiplier + } } func isClaudeFable51Model(model string) bool { @@ -1813,6 +1817,7 @@ func (s *BillingService) computeTokenBreakdown( bd.CacheCreationCost + bd.CacheReadCost bd.ActualCost = bd.TotalCost * rateMultiplier bd.LongContextBillingApplied = baselineCost != nil && bd.ActualCost > baselineCost.ActualCost + bd.customerCacheCosts = resolvedCustomerCacheCosts(cacheCreationPricing, tokens, cacheCreationPrice, cacheCreationMultiplier, cacheReadPrice, tierMultiplier) return bd } diff --git a/backend/internal/service/customer_cache_cost_details.go b/backend/internal/service/customer_cache_cost_details.go new file mode 100644 index 000000000000..e2a9b5ac1f0b --- /dev/null +++ b/backend/internal/service/customer_cache_cost_details.go @@ -0,0 +1,46 @@ +package service + +// CustomerCacheCostDetail records the actual priced, disjoint token bucket. +// UnitPrice is per token before the customer multiplier, including resolved +// context/time/reasoning adjustments. It is display evidence only. +type CustomerCacheCostDetail struct { + Kind string `json:"kind"` + Tokens int `json:"tokens"` + UnitPrice float64 `json:"unit_price"` +} + +// Called with the same selected prices and normalized buckets used by +// computeTokenBreakdown. Never resolves a second catalogue/group quote. +func resolvedCustomerCacheCosts(pricing *ModelPricing, tokens UsageTokens, writePrice, writeMultiplier, readPrice, tierMultiplier float64) []CustomerCacheCostDetail { + lines := make([]CustomerCacheCostDetail, 0, 4) + add := func(kind string, count int, price float64) { + if count > 0 { + lines = append(lines, CustomerCacheCostDetail{Kind: kind, Tokens: count, UnitPrice: price * tierMultiplier}) + } + } + if _, ok := openAICacheCreationTTLCost(tokens, writePrice, pricing.CacheCreation12hPricePerToken); ok { + longPrice := writePrice + if pricing.CacheCreation12hPricePerToken != nil { + longPrice = *pricing.CacheCreation12hPricePerToken + } + add("write_30m", tokens.CacheCreation30mTokens, writePrice*writeMultiplier) + add("write_12h", tokens.CacheCreation12hTokens, longPrice*writeMultiplier) + } else if pricing.SupportsCacheBreakdown && (pricing.CacheCreation5mPrice > 0 || pricing.CacheCreation1hPrice > 0) { + short, long := normalizeCacheCreationBreakdown(tokens) + if short == 0 && long == 0 && tokens.CacheCreationTokens > 0 { + short = tokens.CacheCreationTokens + } + add("write_5m", short, pricing.CacheCreation5mPrice*writeMultiplier) + add("write_1h", long, pricing.CacheCreation1hPrice*writeMultiplier) + } else { + add("write", tokens.CacheCreationTokens, writePrice*writeMultiplier) + } + imageRead := min(max(tokens.ImageCacheReadTokens, 0), max(tokens.CacheReadTokens, 0)) + if imageRead > 0 && pricing.ImageCacheReadPricePerToken > 0 { + add("read", tokens.CacheReadTokens-imageRead, readPrice) + add("read_image", imageRead, pricing.ImageCacheReadPricePerToken) + } else { + add("read", tokens.CacheReadTokens, readPrice) + } + return lines +} diff --git a/backend/internal/service/customer_cost_details.go b/backend/internal/service/customer_cost_details.go new file mode 100644 index 000000000000..818f00b33657 --- /dev/null +++ b/backend/internal/service/customer_cost_details.go @@ -0,0 +1,60 @@ +package service + +import ( + "math" + "slices" +) + +// CustomerCostDetails is display-only, immutable request-time evidence. Costs +// are Standard components before the customer rate; upstream UsageLog monetary +// fields and the billing command remain authoritative and unchanged. +type CustomerCostDetails struct { + CacheCostDetails []CustomerCacheCostDetail `json:"cache_cost_details,omitempty"` + Version int `json:"version"` + FreeFast bool `json:"free_fast"` + InputCost float64 `json:"input_cost"` + OutputCost float64 `json:"output_cost"` + ImageInputCost float64 `json:"image_input_cost"` + ImageOutputCost float64 `json:"image_output_cost"` + CacheCreationCost float64 `json:"cache_creation_cost"` + CacheReadCost float64 `json:"cache_read_cost"` + TotalCost float64 `json:"total_cost"` + ActualCost float64 `json:"actual_cost"` + Multiplier float64 `json:"multiplier"` +} + +// Capture the calculation that actually supplied the customer charge. Never +// reconstruct a Standard quote from Priority totals or current group settings. +// Non-token/additive tool charges have no complete token breakdown here, so +// leave their display evidence unknown instead of allocating those fees to tokens. +func newFreeFastCustomerCostDetails(cost *CostBreakdown, multiplier float64) *CustomerCostDetails { + if cost == nil || (cost.BillingMode != "" && cost.BillingMode != string(BillingModeToken)) { + return nil + } + sum := cost.InputCost + cost.OutputCost + cost.ImageInputCost + cost.ImageOutputCost + cost.CacheCreationCost + cost.CacheReadCost + for _, value := range []float64{cost.InputCost, cost.OutputCost, cost.ImageInputCost, cost.ImageOutputCost, cost.CacheCreationCost, cost.CacheReadCost, cost.TotalCost, cost.ActualCost, multiplier} { + if math.IsNaN(value) || math.IsInf(value, 0) || value < 0 { + return nil + } + } + if math.Abs(sum-cost.TotalCost) > 1e-12*math.Max(1, cost.TotalCost) { + return nil + } + // The gateway supplies its resolved personal/group/peak rate and the + // Standard quote's model surcharge. Reasoning and context are already + // applied to the component prices. Keep the rate even for zero quotes. + if math.Abs(sum*multiplier-cost.ActualCost) > 1e-12*math.Max(1, cost.ActualCost) { + return nil + } + version := 1 + if cost.customerCacheCosts != nil { + version = 2 + } + return &CustomerCostDetails{Version: version, FreeFast: true, + CacheCostDetails: slices.Clone(cost.customerCacheCosts), + InputCost: cost.InputCost, OutputCost: cost.OutputCost, + ImageInputCost: cost.ImageInputCost, ImageOutputCost: cost.ImageOutputCost, + CacheCreationCost: cost.CacheCreationCost, CacheReadCost: cost.CacheReadCost, + TotalCost: cost.TotalCost, ActualCost: cost.ActualCost, Multiplier: multiplier, + } +} diff --git a/backend/internal/service/free_fast_customer_cost_test.go b/backend/internal/service/free_fast_customer_cost_test.go new file mode 100644 index 000000000000..061e628fbe71 --- /dev/null +++ b/backend/internal/service/free_fast_customer_cost_test.go @@ -0,0 +1,378 @@ +package service + +import ( + "context" + "encoding/json" + "fmt" + "testing" + "time" + + "github.com/stretchr/testify/require" +) + +// JSON keeps this business regression compilable on the production baseline. +func TestFreeFastCustomerCostSnapshot(t *testing.T) { + usageRepo := &openAIRecordUsageLogRepoStub{inserted: true} + svc := newOpenAIRecordUsageServiceForTest(usageRepo, &openAIRecordUsageUserRepoStub{}, &openAIRecordUsageSubRepoStub{}, nil) + svc.resolver = NewModelPricingResolver(nil, svc.billingService) + gid := int64(77) + tier := "priority" + inputPrice, outputPrice, cacheWrite, cacheRead := 10e-6, 50e-6, 12.5e-6, 1e-6 + key := &APIKey{ID: 1020, GroupID: &gid, Group: &Group{ + ID: gid, Platform: PlatformOpenAI, Hydrated: true, RateMultiplier: 0.6, FreeOpenAIFast: true, + ModelPricing: []ChannelModelPricing{{Models: []string{"gpt-5.4"}, BillingMode: BillingModeToken, + InputPrice: &inputPrice, OutputPrice: &outputPrice, CacheWritePrice: &cacheWrite, CacheReadPrice: &cacheRead}}, + }} + err := svc.RecordUsage(context.Background(), &OpenAIRecordUsageInput{ + Result: &OpenAIForwardResult{RequestID: "synthetic-customer-cost", Model: "gpt-5.4", ServiceTier: &tier, + Usage: OpenAIUsage{InputTokens: 71, OutputTokens: 19}, Duration: time.Second}, + APIKey: key, User: &User{ID: 2020}, Account: &Account{ID: 3020, Platform: PlatformOpenAI, Type: AccountTypeOAuth}, + }) + require.NoError(t, err) + require.NotNil(t, usageRepo.lastLog) + require.InDelta(t, 0.00332, usageRepo.lastLog.TotalCost, 1e-10) + require.InDelta(t, 0.000996, usageRepo.lastLog.ActualCost, 1e-10) + raw, err := json.Marshal(usageRepo.lastLog) + require.NoError(t, err) + var saved map[string]any + require.NoError(t, json.Unmarshal(raw, &saved)) + detail, ok := saved["CustomerCostDetails"].(map[string]any) + require.True(t, ok, "Free Fast must persist the Standard customer cost snapshot") + require.Equal(t, true, detail["free_fast"]) + require.InDelta(t, 0.00071, detail["input_cost"], 1e-12) + require.InDelta(t, 0.00095, detail["output_cost"], 1e-12) + require.InDelta(t, 0.00166, detail["total_cost"], 1e-12) + require.InDelta(t, 0.6, detail["multiplier"], 1e-12) +} + +func TestFreeFastCustomerCostVariants(t *testing.T) { + for _, tc := range []struct { + name string + input, output, write30m, write12h, read int + personal, model, reasoning float64 + long bool + contextDisabled bool + }{ + {name: "exact screenshot", input: 8345, output: 136, write30m: 1197, read: 37469}, + {name: "mixed cache TTL", input: 71, output: 19, write30m: 11, write12h: 13, read: 17}, + {name: "personal model reasoning", input: 71, output: 19, write30m: 11, write12h: 13, read: 17, personal: .3, model: 3, reasoning: 1.7}, + {name: "whole request threshold", input: 272000, output: 19}, + {name: "whole request above threshold", input: 272001, output: 19, long: true}, + {name: "cache crosses context tier", input: 271990, output: 19, write30m: 5, write12h: 6, read: 7, long: true}, + {name: "context gate disabled above threshold", input: 272001, output: 19, contextDisabled: true}, + } { + t.Run(tc.name, func(t *testing.T) { + repo := &openAIRecordUsageLogRepoStub{inserted: true} + rates := &openAIUserGroupRateRepoStub{} + rate := .5 + if tc.personal > 0 { + rates.rate = &tc.personal + rate = tc.personal + } + svc := newOpenAIRecordUsageServiceForTest(repo, &openAIRecordUsageUserRepoStub{}, &openAIRecordUsageSubRepoStub{}, rates) + // Pin synthetic catalogue evidence: Priority doubles input/output/read, + // but NOT writes. The unrelated built-in fallback has different + // cache ratios and is not an oracle for the screenshot contract. + svc.billingService = NewBillingService(svc.cfg, &PricingService{pricingData: map[string]*LiteLLMModelPricing{ + "gpt-6.2-astra": { + InputCostPerToken: 10e-6, InputCostPerTokenPriority: 20e-6, + OutputCostPerToken: 50e-6, OutputCostPerTokenPriority: 100e-6, + CacheCreationInputTokenCost: 12.5e-6, CacheCreationInputTokenCostPriority: 12.5e-6, + CacheReadInputTokenCost: 1e-6, CacheReadInputTokenCostPriority: 2e-6, + LongContextInputTokenThreshold: 272000, + LongContextInputCostMultiplier: 2, LongContextOutputCostMultiplier: 1.5, + }, + }}) + svc.resolver = NewModelPricingResolver(nil, svc.billingService) + if tc.model > 0 { + svc.settingService = modelBillingSettings(t, ModelBillingConfig{Enabled: true, Rules: []ModelBillingRule{{Model: "gpt-6.2-astra", Multiplier: tc.model}}}) + rate *= tc.model + } + gid := int64(77) + tier, effort := "priority", "high" + in, out, write, write12h, read := 10e-6, 50e-6, 12.5e-6, 25e-6, 1e-6 + hiIn, hiOut, hiWrite, hiWrite12h, hiRead := 20e-6, 75e-6, 25e-6, 50e-6, 2e-6 + maxTokens := 272000 + pricing := ChannelModelPricing{Models: []string{"gpt-6.2-astra"}, BillingMode: BillingModeToken, + InputPrice: &in, OutputPrice: &out, CacheWritePrice: &write, CacheWrite12hPrice: &write12h, CacheReadPrice: &read, + Intervals: []PricingInterval{ + {MinTokens: 0, MaxTokens: &maxTokens, InputPrice: &in, OutputPrice: &out, CacheWritePrice: &write, CacheWrite12hPrice: &write12h, CacheReadPrice: &read}, + {MinTokens: 272001, InputPrice: &hiIn, OutputPrice: &hiOut, CacheWritePrice: &hiWrite, CacheWrite12hPrice: &hiWrite12h, CacheReadPrice: &hiRead}, + }, + } + if tc.reasoning > 0 { + pricing.ReasoningEffortMultipliers = map[string]float64{"high": tc.reasoning} + } + group := &Group{ID: gid, Platform: PlatformOpenAI, Hydrated: true, FreeOpenAIFast: true, RateMultiplier: .5, + LongContextPricingEnabled: !tc.contextDisabled, ModelPricing: []ChannelModelPricing{pricing}} + // Group token cards deliberately ignore custom intervals. Exercise + // the real catalogue whole-request tier and its group gate instead; + // the disabled case must stay at base rates despite these intervals. + resolved := svc.resolver.Resolve(context.Background(), PricingInput{Model: "gpt-6.2-astra", GroupID: &gid, Group: group}) + require.Equal(t, PricingSourceGroup, resolved.Source) + require.Empty(t, resolved.Intervals) + require.Equal(t, 272000, resolved.BasePricing.LongContextInputThreshold) + err := svc.RecordUsage(context.Background(), &OpenAIRecordUsageInput{ + Result: &OpenAIForwardResult{RequestID: "synthetic-" + tc.name, Model: "gpt-6.2-astra", ServiceTier: &tier, ReasoningEffort: &effort, + Duration: time.Second, Usage: OpenAIUsage{InputTokens: tc.input + tc.write30m + tc.write12h + tc.read, + OutputTokens: tc.output, CacheCreationInputTokens: tc.write30m + tc.write12h, + CacheCreation30mInputTokens: tc.write30m, CacheCreation12hInputTokens: tc.write12h, CacheReadInputTokens: tc.read}}, + APIKey: &APIKey{ID: 1020, GroupID: &gid, Group: group}, User: &User{ID: 2020}, + Account: &Account{ID: 3020, Platform: PlatformOpenAI, Type: AccountTypeOAuth}, + }) + require.NoError(t, err) + log := repo.lastLog + require.NotNil(t, log) + raw, err := json.Marshal(log) + require.NoError(t, err) + var saved map[string]any + require.NoError(t, json.Unmarshal(raw, &saved)) + d, ok := saved["CustomerCostDetails"].(map[string]any) + require.True(t, ok, "Free Fast must persist the Standard customer cost snapshot") + if tc.long { + in, out, write, write12h, read = hiIn, hiOut, hiWrite, hiWrite12h, hiRead + } + reasoning := tc.reasoning + if reasoning == 0 { + reasoning = 1 + } + // Preserve the quotation's operation order: computeTokenBreakdown + // sums input/output/write/read before reasoning; customer rate is + // applied before reasoning, then the model surcharge. Random map + // iteration can straddle the eight-decimal half boundary by 1 ULP. + expected := []struct { + field string + amount float64 + }{ + {"input_cost", float64(tc.input) * in}, + {"output_cost", float64(tc.output) * out}, + {"cache_creation_cost", float64(tc.write30m)*write + float64(tc.write12h)*write12h}, + {"cache_read_cost", float64(tc.read) * read}, + } + total := 0.0 + for _, component := range expected { + require.InDelta(t, component.amount*reasoning, d[component.field], 1e-10, component.field) + total += component.amount + } + customerRate, modelRate := .5, 1.0 + if tc.personal > 0 { + customerRate = tc.personal + } + if tc.model > 0 { + modelRate = tc.model + } + actual := total * customerRate + actual *= reasoning + actual *= modelRate + require.InDelta(t, total*reasoning, d["total_cost"], 1e-10) + require.InDelta(t, rate, d["multiplier"], 1e-10) + require.InDelta(t, QuantizeUsageBillingAmount(actual), log.ActualCost, 1e-10) + if tc.name == "personal model reasoning" { + // Exact decimal fixture: .0021395 × .3 × 1.7 × 3 = + // .003273435, rounded half-away-from-zero at eight places. + require.Equal(t, .00327344, log.ActualCost) + } + require.Equal(t, "priority", *log.ServiceTier) + require.Equal(t, tc.long, log.LongContextBillingApplied) + require.EqualValues(t, 2, d["version"]) + if tc.write30m+tc.write12h+tc.read > 0 { + lines, ok := d["cache_cost_details"].([]any) + require.True(t, ok, "recorded usage must carry the same resolved Standard cache prices") + expectedPrices := map[string]float64{"write_30m": write * reasoning, "write_12h": write12h * reasoning, "read": read * reasoning} + expectedTokens := map[string]int{"write_30m": tc.write30m, "write_12h": tc.write12h, "read": tc.read} + for _, value := range lines { + line, ok := value.(map[string]any) + require.True(t, ok, "cache price entry must be an object") + kind, ok := line["kind"].(string) + require.True(t, ok, "cache price kind must be a string") + require.Contains(t, expectedPrices, kind) + require.InDelta(t, expectedPrices[kind], line["unit_price"], 1e-16) + require.EqualValues(t, expectedTokens[kind], line["tokens"]) + delete(expectedTokens, kind) + } + for _, count := range expectedTokens { + require.Zero(t, count) + } + } + if tc.name == "exact screenshot" { + require.InDelta(t, .1669, log.InputCost, 1e-10) + require.InDelta(t, .0136, log.OutputCost, 1e-10) + require.InDelta(t, .0149625, log.CacheCreationCost, 1e-10) + require.InDelta(t, .074938, log.CacheReadCost, 1e-10) + require.InDelta(t, .2704005, log.TotalCost, 1e-10) + require.InDelta(t, .07134075, log.ActualCost, 1e-10) + } + // The persisted evidence must not change when today's group configuration changes. + group.FreeOpenAIFast = false + group.RateMultiplier = 9 + *group.ModelPricing[0].InputPrice = 999 + after, err := json.Marshal(log) + require.NoError(t, err) + require.JSONEq(t, string(raw), string(after)) + }) + } +} + +func TestFreeFastCustomerCostCache1h(t *testing.T) { + // The shared quote calculation also supports 5m/1h buckets. Snapshot their + // actual Standard sum; never halve the aggregate Priority cache-write cost. + billing := &BillingService{} + price := &ModelPricing{InputPricePerToken: 10e-6, OutputPricePerToken: 50e-6, + CacheCreationPricePerToken: 12.5e-6, CacheReadPricePerToken: 1e-6, + SupportsCacheBreakdown: true, CacheCreation5mPrice: 12.5e-6, CacheCreation1hPrice: 20e-6} + tokens := UsageTokens{InputTokens: 71, OutputTokens: 19, CacheCreationTokens: 24, CacheCreation5mTokens: 11, CacheCreation1hTokens: 13, CacheReadTokens: 17} + quote := billing.computeTokenBreakdown(price, tokens, .6, "", false) + detail := newFreeFastCustomerCostDetails(quote, .6) + require.NotNil(t, detail) + require.InDelta(t, 11*12.5e-6+13*20e-6, detail.CacheCreationCost, 1e-12) + require.InDelta(t, 17e-6, detail.CacheReadCost, 1e-12) + require.InDelta(t, detail.TotalCost*.6, detail.ActualCost, 1e-12) +} + +func TestFreeFastCustomerCostControls(t *testing.T) { + for _, tc := range []struct { + tier string + free bool + platform string + }{ + {"priority", false, PlatformOpenAI}, {"default", true, PlatformOpenAI}, {"flex", true, PlatformOpenAI}, {"priority", true, PlatformAnthropic}, + } { + t.Run(tc.tier+"/"+tc.platform+"/"+fmt.Sprint(tc.free), func(t *testing.T) { + repo := &openAIRecordUsageLogRepoStub{inserted: true} + svc := newOpenAIRecordUsageServiceForTest(repo, &openAIRecordUsageUserRepoStub{}, &openAIRecordUsageSubRepoStub{}, nil) + gid := int64(77) + err := svc.RecordUsage(context.Background(), &OpenAIRecordUsageInput{ + Result: &OpenAIForwardResult{RequestID: "synthetic-control", Model: "gpt-5.4", ServiceTier: &tc.tier, Duration: time.Second, Usage: OpenAIUsage{InputTokens: 71, OutputTokens: 19}}, + APIKey: &APIKey{ID: 1020, GroupID: &gid, Group: &Group{ID: gid, Platform: PlatformOpenAI, Hydrated: true, RateMultiplier: .6, FreeOpenAIFast: tc.free}}, + User: &User{ID: 2020}, Account: &Account{ID: 3020, Platform: tc.platform, Type: AccountTypeOAuth}, + }) + require.NoError(t, err) + raw, err := json.Marshal(repo.lastLog) + require.NoError(t, err) + var saved map[string]any + require.NoError(t, json.Unmarshal(raw, &saved)) + require.Nil(t, saved["CustomerCostDetails"], "controls must not claim a Free Fast quote") + }) + } +} + +func TestFreeFastCustomerCostCatalogueLongContext(t *testing.T) { + billing := &BillingService{} + price := &ModelPricing{InputPricePerToken: 10e-6, OutputPricePerToken: 50e-6, + CacheCreationPricePerToken: 12.5e-6, CacheReadPricePerToken: 1e-6, + LongContextInputThreshold: 272000, LongContextInputMultiplier: 2, LongContextOutputMultiplier: 1.5} + for _, input := range []int{271980, 271981} { + tokens := UsageTokens{InputTokens: input, OutputTokens: 19, CacheCreationTokens: 11, CacheCreation30mTokens: 11, CacheReadTokens: 9} + quote := billing.computeTokenBreakdown(price, tokens, .6, "", true) + detail := newFreeFastCustomerCostDetails(quote, .6) + require.NotNil(t, detail) + inputFactor, outputFactor := 1.0, 1.0 + if input > 271980 { + inputFactor, outputFactor = 2, 1.5 + } + require.InDelta(t, float64(input)*10e-6*inputFactor, detail.InputCost, 1e-10) + require.InDelta(t, 19*50e-6*outputFactor, detail.OutputCost, 1e-10) + require.InDelta(t, 11*12.5e-6*inputFactor, detail.CacheCreationCost, 1e-10) + require.InDelta(t, 9*1e-6*inputFactor, detail.CacheReadCost, 1e-10) + require.InDelta(t, detail.TotalCost*.6, detail.ActualCost, 1e-10) + } +} + +func TestFreeFastCustomerCostZeroQuoteKeepsEffectiveRate(t *testing.T) { + detail := newFreeFastCustomerCostDetails(&CostBreakdown{BillingMode: string(BillingModeToken)}, 1.8) + require.NotNil(t, detail) + require.Equal(t, 1.8, detail.Multiplier, "a zero quote must retain the actual resolved rate, not infer 0/0") + require.Zero(t, detail.TotalCost) + require.Zero(t, detail.ActualCost) +} + +// JSON assertions also compile before cache-price snapshots exist, so remote +// source-overlay RED must fail on missing evidence, never on setup/compilation. +func TestFreeFastCustomerCostCachePrices(t *testing.T) { + for _, tc := range []struct { + name string + long, zero, hour bool + reasoning float64 + }{ + {name: "mixed 30m 12h read"}, {name: "whole context", long: true}, + {name: "reasoning", reasoning: 1.7}, {name: "explicit zero prices", zero: true}, {name: "5m 1h", hour: true}, + } { + t.Run(tc.name, func(t *testing.T) { + read, short, long := 1e-6, 12.5e-6, 25e-6 + if tc.zero { + read, short, long = 0, 0, 0 + } + pricing := &ModelPricing{InputPricePerToken: 10e-6, OutputPricePerToken: 50e-6, + CacheReadPricePerToken: read, CacheCreationPricePerToken: short, CacheCreation12hPricePerToken: &long, + LongContextInputThreshold: 100, LongContextInputMultiplier: 2, LongContextOutputMultiplier: 1.5} + tokens := UsageTokens{InputTokens: 71, OutputTokens: 19, CacheReadTokens: 17, CacheCreationTokens: 24, CacheCreation30mTokens: 11, CacheCreation12hTokens: 13} + kindShort, kindLong := "write_30m", "write_12h" + if tc.hour { + pricing.SupportsCacheBreakdown = true + pricing.CacheCreation5mPrice = short + pricing.CacheCreation1hPrice = long + tokens.CacheCreation30mTokens = 0 + tokens.CacheCreation12hTokens = 0 + tokens.CacheCreation5mTokens = 11 + tokens.CacheCreation1hTokens = 13 + kindShort, kindLong = "write_5m", "write_1h" + } + quote := (&BillingService{}).computeTokenBreakdown(pricing, tokens, .3, "", tc.long) + reasoning := tc.reasoning + if reasoning == 0 { + reasoning = 1 + } + applyCostBreakdownMultiplier(quote, reasoning) + // Customer model surcharge belongs in the effective multiplier, not prices. + quote.ActualCost *= 3 + snapshot := newFreeFastCustomerCostDetails(quote, .3*3) + raw, err := json.Marshal(snapshot) + require.NoError(t, err) + var detail map[string]any + require.NoError(t, json.Unmarshal(raw, &detail)) + require.EqualValues(t, 2, detail["version"], "Standard cache prices must be persisted from the resolved quote") + lines, ok := detail["cache_cost_details"].([]any) + require.True(t, ok, "Standard cache prices must be persisted from the resolved quote") + require.Len(t, lines, 3) + factor := reasoning + if tc.long { + factor *= 2 + } + expected := map[string]struct { + count int + price float64 + }{"read": {17, read * factor}, kindShort: {11, short * factor}, kindLong: {13, long * factor}} + writeSum, readSum := 0.0, 0.0 + for _, value := range lines { + line, ok := value.(map[string]any) + require.True(t, ok, "cache price entry must be an object") + kind, ok := line["kind"].(string) + require.True(t, ok, "cache price kind must be a string") + want, exists := expected[kind] + require.True(t, exists, kind) + require.EqualValues(t, want.count, line["tokens"]) + require.InDelta(t, want.price, line["unit_price"], 1e-16, kind) + unitPrice, ok := line["unit_price"].(float64) + require.True(t, ok, "cache unit price must be numeric") + count, ok := line["tokens"].(float64) + require.True(t, ok, "cache token count must be numeric") + cost := unitPrice * count + if kind == "read" { + readSum += cost + } else { + writeSum += cost + } + delete(expected, kind) + } + require.Empty(t, expected) + require.InDelta(t, quote.CacheCreationCost, writeSum, 1e-12) + require.InDelta(t, quote.CacheReadCost, readSum, 1e-12) + // Later policy changes cannot mutate saved price evidence. + pricing.CacheReadPricePerToken = 999 + long = 999 + after, err := json.Marshal(snapshot) + require.NoError(t, err) + require.JSONEq(t, string(raw), string(after)) + }) + } +} diff --git a/backend/internal/service/openai_gateway_usage.go b/backend/internal/service/openai_gateway_usage.go index 5cbc169a54de..79e206ecaefd 100644 --- a/backend/internal/service/openai_gateway_usage.go +++ b/backend/internal/service/openai_gateway_usage.go @@ -348,6 +348,7 @@ func (s *OpenAIGatewayService) RecordUsage(ctx context.Context, input *OpenAIRec // Free Fast changes only the customer charge. Keep priority TotalCost and // service_tier for upstream accounting, but evaluate ActualCost once more at // the Standard tier using the same channel, peak, and long-context policy. + var customerCostDetails *CustomerCostDetails if groupBillsOpenAIFastAtStandard(apiKey, billingAccount, serviceTier) { standardCost, standardErr := s.calculateOpenAIRecordUsageCost( ctx, @@ -371,6 +372,7 @@ func (s *OpenAIGatewayService) RecordUsage(ctx context.Context, input *OpenAIRec // usage row instead of dropping it on the Standard re-evaluation. if standardErr == nil && cost != nil && standardCost != nil { cost.ActualCost = standardCost.ActualCost + customerCostDetails = newFreeFastCustomerCostDetails(standardCost, multiplier*costModelBillingMultiplier(standardCost)) } } @@ -436,6 +438,7 @@ func (s *OpenAIGatewayService) RecordUsage(ctx context.Context, input *OpenAIRec s.excelOAuthReauth.recordConnectionUsage(ctx, account.ID, apiKey.ID, result.AuthConnectionID, requestID) } usageLog := &UsageLog{ + CustomerCostDetails: customerCostDetails, Platform: account.Platform, UserID: user.ID, APIKeyID: apiKey.ID, @@ -485,6 +488,10 @@ func (s *OpenAIGatewayService) RecordUsage(ctx context.Context, input *OpenAIRec factor := float64(1 + result.HeaderTimeoutRetries) cost.TotalCost *= factor cost.ActualCost *= factor + if customerCostDetails != nil { + customerCostDetails.Multiplier *= factor + customerCostDetails.ActualCost *= factor + } } if cost != nil { usageLog.InputCost = cost.InputCost diff --git a/backend/internal/service/usage_log.go b/backend/internal/service/usage_log.go index b45e2d84055d..5087923b515c 100644 --- a/backend/internal/service/usage_log.go +++ b/backend/internal/service/usage_log.go @@ -103,6 +103,7 @@ func ApplyLegacyRequestFields(requestType RequestType, fallbackStream bool, fall } type UsageLog struct { + CustomerCostDetails *CustomerCostDetails // Platform snapshots the concrete upstream provider at request time. Empty is unknown legacy data. Platform string ContentTiming *requesttiming.ContentObservation diff --git a/backend/migrations/379_usage_customer_cost_details.sql b/backend/migrations/379_usage_customer_cost_details.sql new file mode 100644 index 000000000000..c29544b6cd99 --- /dev/null +++ b/backend/migrations/379_usage_customer_cost_details.sql @@ -0,0 +1,5 @@ +-- Display-only request snapshot. NULL means no historical Standard quote is +-- available; deliberately do not backfill from current group configuration. +ALTER TABLE usage_logs ADD COLUMN IF NOT EXISTS customer_cost_details JSONB; +COMMENT ON COLUMN usage_logs.customer_cost_details IS + 'Immutable customer Standard cost components when Free Fast actually applied; never used for billing'; diff --git a/docs/screenshots/free-fast-customer-cost-details.md b/docs/screenshots/free-fast-customer-cost-details.md new file mode 100644 index 000000000000..7ba0ee225b12 --- /dev/null +++ b/docs/screenshots/free-fast-customer-cost-details.md @@ -0,0 +1,69 @@ +# Customer cost details evidence + +Free Fast already charges the customer using a Standard calculation while +retaining the request's real service tier and Priority cost columns. The existing +shared cost popup now uses the saved Standard display snapshot: component amounts +and their sum are before the effective customer multiplier. The saved multiplier +explains `actual_cost`. No new label, badge, banner or explanatory UI copy is added. + +`customer_cost_details` is optional, versioned request evidence. It is captured +only when the Standard calculation actually supplies the Free Fast charge, then +stored with the append-only usage row and durable billing event. It is never an +input to billing, pricing, ledger updates or account statistics. Migration 379 adds +a nullable JSONB column without backfilling old records. An older binary can +ignore the column; reverting the binary does not delete saved evidence. + +For old complete token-only Priority records whose charge cannot be reconciled +with their stored components/rate, the customer component and price fields show +the existing unknown-value dash. Current group configuration never determines +historical pricing. Mixed image, per-request or additive-tool records without a +snapshot retain their existing recorded display; a differing total alone does +not prove Free Fast. Unknown/non-token/additive quotes are not invented. Normal +paid Priority, Standard and Flex displays retain their existing behavior. + +The synthetic fixture is deliberately independent of customer data: + +| Component | Recorded Priority | Customer Standard | +| --- | ---: | ---: | +| Input: 8,345 tokens | 0.16690000 | 0.08345000 | +| Output: 136 tokens | 0.01360000 | 0.00680000 | +| Cache creation: 1,197 tokens, 30m | 0.01496250 | 0.01496250 | +| Cache read: 37,469 tokens | 0.07493800 | 0.03746900 | +| Original total | 0.27040050 | 0.14268150 | + +Standard total × 0.50 = 0.07134075 charged. Unit prices are 10/50 per million +input/output tokens; the request tier remains Fast. Cache creation demonstrates +why dividing every Priority component or total by two is incorrect. + +Run `.github/scripts/free-fast-customer-cost-browser.mjs` from the repository root +with `PLAYWRIGHT_ROOT` pointing at an installed Playwright package or its parent, +and `FREE_FAST_SCREENSHOT_DIR` pointing outside the source tree. The harness uses +the complete source at baseline `0e8e97aa23afd8e88a61ea64a84a8fb84f1bfdc6`, then the +candidate shared Vue component, with real styles, locale messages and synthetic +HTTP/data fixtures. It captures 16 before/after views covering English/Chinese, +user/admin and desktop/mobile, after asserting the mathematical values, CSS and +viewport geometry. Its manifest includes fixture/harness/component/image hashes, +viewport sizes and actual DOM text. + +Screenshot files belong in native GitHub PR attachments, never in this directory. +Download each uploaded attachment and compare its SHA256 with the manifest before +embedding it in the PR. The harness and CI workflow are reproducible evidence +runners, not a claim that their checks have already passed: consult the PR's +actual validation table and current-head CI results. + + +Snapshot version 2 adds disjoint cache-price evidence (`kind`, `tokens`, per-token +`unit_price`) from the same resolved Standard calculation. Reasoning/time/context +adjustments follow the component prices; the customer multiplier remains separate. +Version 1 keeps its known aggregates and shows unknown cache unit prices. No +migration/backfill is needed for the additive JSON field. Invalid or inconsistent +version 2 cache evidence is rejected rather than projected from current settings. +Restricted administrators receive the typed numeric snapshot through the explicit +allowlist, without nested user/key/account/group/subscription data. + +The extended harness captures 32 new images: exact and mixed 30m/12h fixtures × +before/after × English/Chinese × user/admin × desktop/mobile. Save them in a new +artifact directory; the original 16 images at capture commit 50f906972 and their +native attachments retain their original identity and hashes. The new matrix +asserts read $1, short write $12.5, long write $25 per million tokens alongside +component totals. Only the manifest's own head identifies a new capture. diff --git a/frontend/src/components/admin/usage/UsageTable.vue b/frontend/src/components/admin/usage/UsageTable.vue index b18d7a1dca06..a41676c7cbbb 100644 --- a/frontend/src/components/admin/usage/UsageTable.vue +++ b/frontend/src/components/admin/usage/UsageTable.vue @@ -438,37 +438,37 @@