diff --git a/.github/scripts/account-probe-penalty-screenshot.mjs b/.github/scripts/account-probe-penalty-screenshot.mjs new file mode 100644 index 000000000000..a81b404e1522 --- /dev/null +++ b/.github/scripts/account-probe-penalty-screenshot.mjs @@ -0,0 +1,55 @@ +// Actual account setting component with synthetic state; no production access. +import { execFileSync } from 'node:child_process' +import { createRequire } from 'node:module' +import { mkdirSync, writeFileSync, rmSync } from 'node:fs' +import { join, resolve } from 'node:path' +import { pathToFileURL } from 'node:url' +const root = resolve('frontend'), output = process.env.SCREENSHOT_DIR +if (!output || !process.env.PLAYWRIGHT_ROOT) throw Error('Missing screenshot configuration') +mkdirSync(output, { recursive: true }) +const require = createRequire(join(root, 'package.json')) +const { build, preview } = await import(pathToFileURL(join(root, 'node_modules/vite/dist/node/index.js')).href) +const vue = (await import(pathToFileURL(require.resolve('@vitejs/plugin-vue')).href)).default +const { chromium } = await import(pathToFileURL(join(process.env.PLAYWRIGHT_ROOT, 'index.mjs')).href) +const tailwind = (await import(pathToFileURL(join(root, 'tailwind.config.js')).href)).default +const prefix = `.probe-penalty-${process.pid}`, files = [] +const create = (name, text) => { const path = join(root, name); writeFileSync(path, text, { flag: 'wx' }); files.push(path); return path } +let server, browser +try { + const html = create(prefix + '.html', `
`) + create(prefix + '.js', ` +import {createApp,defineComponent,ref,h} from 'vue'; import {createPinia} from 'pinia'; import {createI18n} from 'vue-i18n'; +import {useAuthStore} from '/src/stores/auth.ts'; import Setting from '/src/components/account/ProbePenaltySettings.vue'; +import zh from '/src/i18n/locales/zh/index.ts'; import '/src/style.css'; +const app=createApp(defineComponent({setup(){const enabled=ref(false),minimum=ref(.001);return()=>h('main',{class:'p-6 bg-white dark:bg-dark-900'},[h('h1',{class:'text-lg mb-4 dark:text-white'},'账号管理 / 编辑虚构 Claude 账号'),h(Setting,{enabled:enabled.value,minimum:minimum.value,'onUpdate:enabled':v=>enabled.value=v,'onUpdate:minimum':v=>minimum.value=v})])}})); +const pinia=createPinia();app.use(pinia);useAuthStore().user={id:41,role:'admin',email:'admin@example.invalid'}; +app.use(createI18n({legacy:false,locale:'zh-CN',messages:{'zh-CN':zh}})).mount('#app'); +`) + await build({ root, configFile: false, base: './', resolve: { alias: { '@': join(root, 'src') } }, plugins: [vue()], + css: { postcss: { plugins: [require('tailwindcss')({ ...tailwind, content: [html, join(root, 'src/**/*.{vue,js,ts}')] }), require('autoprefixer')()] } }, + build: { outDir: join(output, 'build'), emptyOutDir: true, rollupOptions: { input: html } } }) + server = await preview({ root, configFile: false, build: { outDir: join(output, 'build') }, preview: { host: '127.0.0.1', port: 4198, strictPort: true } }) + browser = await chromium.launch({ headless: true }) + const page = await browser.newPage({ viewport: { width: 1000, height: 620 } }), errors = [] + page.on('pageerror', e => errors.push(e.message)) + await page.route('**/*', route => new URL(route.request().url()).origin === 'http://127.0.0.1:4198' ? route.continue() : route.abort()) + await page.goto(`http://127.0.0.1:4198/${prefix}.html`) + const card = page.locator('[data-testid="probe-penalty-settings"]') + await card.waitFor() + await page.locator('main').screenshot({ path: join(output, 'disabled.png') }) + await page.locator('[data-testid="probe-penalty-enabled"]').check() + if (await page.locator('[data-testid="probe-penalty-minimum"]').inputValue() !== '0.001') throw Error('Wrong default minimum') + await page.locator('main').screenshot({ path: join(output, 'enabled.png') }) + await page.evaluate(() => document.documentElement.classList.add('dark')) + await page.locator('main').screenshot({ path: join(output, 'dark.png') }) + await card.locator('[data-testid="new-feature-badge"]').click() + await page.reload(); await card.waitFor() + if (await card.locator('[data-testid="new-feature-badge"]').count()) throw Error('Dismissal did not persist') + if (errors.length) throw Error(errors.join('\n')) + writeFileSync(join(output, 'manifest.json'), JSON.stringify({ commit: execFileSync('git', ['rev-parse', 'HEAD'], { encoding: 'utf8' }).trim(), scope: 'actual ProbePenaltySettings component with synthetic parent state, not full account page or production', screenshots: ['disabled.png', 'enabled.png', 'dark.png'], errors }, null, 2)) +} finally { + if (browser) await browser.close() + if (server) await new Promise(resolve => server.httpServer.close(resolve)) + for (const file of files) rmSync(file, { force: true }) + rmSync(join(output, 'build'), { recursive: true, force: true }) +} diff --git a/.github/scripts/prepare-image-usage-free-fast-red.py b/.github/scripts/prepare-image-usage-free-fast-red.py index f526fb9ce3fb..83991ace77c2 100644 --- a/.github/scripts/prepare-image-usage-free-fast-red.py +++ b/.github/scripts/prepare-image-usage-free-fast-red.py @@ -23,6 +23,7 @@ # backporting either the cache-price producer or UltraFast behavior. addition = ('\n\tImageMinimumCharge float64 `json:"image_minimum_charge,omitempty"`\n' '\tImageMinimumChargeAdjustment float64 `json:"image_minimum_charge_adjustment,omitempty"`\n' + '\tProbePenalty *ProbePenaltyReceipt `json:"probe_penalty,omitempty"`\n' '\tFreeUltrafast bool `json:"free_ultrafast,omitempty"`\n' '\tCacheCostDetails []CustomerCacheCostDetail `json:"cache_cost_details,omitempty"`\n') else: diff --git a/.github/scripts/upstream-v0222-red-fixtures.txt b/.github/scripts/upstream-v0222-red-fixtures.txt index c32568127134..64a3d6f43142 100644 --- a/.github/scripts/upstream-v0222-red-fixtures.txt +++ b/.github/scripts/upstream-v0222-red-fixtures.txt @@ -191,3 +191,7 @@ backend/internal/service/ciallo_test.go # Controls diagnostics require the newer recovery APIs, not historical RED sources. backend/internal/service/openai_409_controls_diagnostics_test.go backend/internal/handler/openai_owner_conflict_diagnostics_test.go + +# Probe penalty tests use receipt types absent from historical WS sources. +backend/internal/handler/probe_penalty_response_test.go +backend/internal/service/account_probe_penalty_test.go diff --git a/.github/workflows/account-probe-penalty.yml b/.github/workflows/account-probe-penalty.yml new file mode 100644 index 000000000000..38f9c981280c --- /dev/null +++ b/.github/workflows/account-probe-penalty.yml @@ -0,0 +1,42 @@ +name: Account probe penalty UI +on: + workflow_dispatch: + pull_request: + branches: [production] + paths: + - 'frontend/src/components/account/ProbePenaltySettings.vue' + - '.github/scripts/account-probe-penalty-screenshot.mjs' + - '.github/workflows/account-probe-penalty.yml' +permissions: + contents: read +jobs: + screenshots: + runs-on: ubuntu-24.04 + timeout-minutes: 15 + steps: + - uses: actions/checkout@v6 + with: + ref: ${{ github.event.pull_request.head.sha || github.sha }} + - uses: pnpm/action-setup@v4 + 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: Install isolated browser + run: | + npm install --prefix "$RUNNER_TEMP/probe-browser" --no-save --ignore-scripts playwright@1.56.1 + "$RUNNER_TEMP/probe-browser/node_modules/.bin/playwright" install --with-deps chromium + - name: Render actual account setting + env: + PLAYWRIGHT_ROOT: ${{ runner.temp }}/probe-browser/node_modules/playwright + SCREENSHOT_DIR: ${{ runner.temp }}/probe-ui + run: node .github/scripts/account-probe-penalty-screenshot.mjs + - uses: actions/upload-artifact@v7 + if: always() + with: + name: account-probe-penalty-ui-${{ github.event.pull_request.head.sha || github.sha }} + path: ${{ runner.temp }}/probe-ui diff --git a/backend/internal/handler/gateway_compat_stream_usage_test.go b/backend/internal/handler/gateway_compat_stream_usage_test.go index 31e9367e8f32..7118183bbba9 100644 --- a/backend/internal/handler/gateway_compat_stream_usage_test.go +++ b/backend/internal/handler/gateway_compat_stream_usage_test.go @@ -72,7 +72,7 @@ func runCompatStreamUsageHandler(t *testing.T, endpoint, upstreamStream string, return runCompatStreamUsageHandlerWithDelivery(t, endpoint, upstreamStream, closeUpstream, nil, "") } -func runCompatStreamUsageHandlerWithDelivery(t *testing.T, endpoint, upstreamStream string, closeUpstream bool, durable service.UsageBillingRepository, baseURL string) compatStreamUsageRun { +func runCompatStreamUsageHandlerWithDelivery(t *testing.T, endpoint, upstreamStream string, closeUpstream bool, durable service.UsageBillingRepository, baseURL string, accountExtra ...map[string]any) compatStreamUsageRun { t.Helper() cfg := &config.Config{Gateway: config.GatewayConfig{StreamDataIntervalTimeout: 1}} cfg.Security.URLAllowlist.AllowPrivateHosts = true @@ -85,6 +85,9 @@ func runCompatStreamUsageHandlerWithDelivery(t *testing.T, endpoint, upstreamStr Credentials: map[string]any{"api_key": "test-key"}, AccountGroups: []service.AccountGroup{{AccountID: 9301, GroupID: groupID}}, } + if len(accountExtra) > 0 { + account.Extra = accountExtra[0] + } snapshot := service.NewSchedulerSnapshotService(&fakeSchedulerCache{accounts: []*service.Account{account}}, nil, nil, nil, nil) run := compatStreamUsageRun{ rec: httptest.NewRecorder(), @@ -126,6 +129,9 @@ func runCompatStreamUsageHandlerWithDelivery(t *testing.T, endpoint, upstreamStr } body := `{"model":"claude-sonnet-4.5","stream":true,"input":"hello"}` + if endpoint == "messages" { + body = `{"model":"claude-sonnet-4.5","stream":true,"max_tokens":32,"messages":[{"role":"user","content":"hello"}]}` + } if endpoint == "chat/completions" { body = `{"model":"claude-sonnet-4.5","stream":true,"messages":[{"role":"user","content":"hello"}]}` } @@ -136,7 +142,9 @@ func runCompatStreamUsageHandlerWithDelivery(t *testing.T, endpoint, upstreamStr c.Set(string(middleware.ContextKeyAPIKey), apiKey) c.Set(string(middleware.ContextKeyUser), middleware.AuthSubject{UserID: 9303}) - if endpoint == "chat/completions" { + if endpoint == "messages" { + h.Messages(c) + } else if endpoint == "chat/completions" { h.ChatCompletions(c) } else { h.Responses(c) diff --git a/backend/internal/handler/gateway_handler.go b/backend/internal/handler/gateway_handler.go index 59ae41723109..c5f3f299b232 100644 --- a/backend/internal/handler/gateway_handler.go +++ b/backend/internal/handler/gateway_handler.go @@ -926,12 +926,52 @@ func (h *GatewayHandler) Messages(c *gin.Context) { } // 记录 Forward 前已写入字节数,Forward 后若增加则说明 SSE 内容已发,禁止 failover writerSizeBeforeForward := c.Writer.Size() + var probeResponse *probePenaltyResponse + if account.ProbePenaltyMinimum() > 0 { + if !h.gatewayService.ProbePenaltySettlementEnabled() { + if queueRelease != nil { + queueRelease() + } + if accountReleaseFunc != nil { + accountReleaseFunc() + } + h.handleStreamingAwareError(c, http.StatusServiceUnavailable, "api_error", "Probe penalty requires durable settlement", streamStarted) + return + } + probeResponse, err = newProbePenaltyResponse(c.Writer, attemptParsedReq.Stream) + if err != nil { + if queueRelease != nil { + queueRelease() + } + if accountReleaseFunc != nil { + accountReleaseFunc() + } + h.handleStreamingAwareError(c, http.StatusServiceUnavailable, "api_error", "Probe penalty response unavailable", streamStarted) + return + } + defer probeResponse.close() + c.Writer = probeResponse + } if account.Platform == service.PlatformAntigravity && account.Type != service.AccountTypeAPIKey { result, err = h.antigravityGatewayService.Forward(requestCtx, c, account, attemptBody, hasBoundSession) } else { result, err = h.gatewayService.Forward(requestCtx, c, account, attemptParsedReq) } + if probeResponse != nil { + c.Writer = probeResponse.ResponseWriter + if err == nil { + err = probeResponse.validate() + } + if err != nil && probeResponse.size >= 0 { + if probeResponse.status >= http.StatusBadRequest { + _ = probeResponse.finish(nil) + } else { + probeResponse.settlementError() + } + } + } + // 兜底释放串行锁(正常情况已通过回调提前释放) if queueRelease != nil { queueRelease() @@ -975,8 +1015,8 @@ func (h *GatewayHandler) Messages(c *gin.Context) { forceCacheBilling := fs.ForceCacheBilling quotaPlatform := service.QuotaPlatform(c.Request.Context(), currentAPIKey) sessionID := service.ExtractClientSessionID(c) - h.submitUsageRecordTask(c.Request.Context(), func(ctx context.Context) { - if err := h.gatewayService.RecordUsage(ctx, &service.RecordUsageInput{ + record := func(ctx context.Context) error { + return h.gatewayService.RecordUsage(ctx, &service.RecordUsageInput{ Result: result, QuotaPlatform: quotaPlatform, APIKey: currentAPIKey, @@ -993,15 +1033,23 @@ func (h *GatewayHandler) Messages(c *gin.Context) { ForceCacheBilling: forceCacheBilling, APIKeyService: h.apiKeyService, ChannelUsageFields: clientRequestedUsageFields(c, channelMapping, reqModel, result.UpstreamModel), - }); err != nil { - logger.L().With( - zap.String("component", "handler.gateway.messages"), - zap.Int64("user_id", subject.UserID), - zap.Int64("api_key_id", currentAPIKey.ID), - zap.Any("group_id", currentAPIKey.GroupID), - zap.String("model", reqModel), - zap.Int64("account_id", account.ID), - ).Error("gateway.record_usage_failed", zap.Error(err)) + }) + } + if probeResponse != nil && err == nil { + result.ProbePenaltyEligible = true + if billingErr := record(service.WithProbePenaltyResult(context.WithoutCancel(c.Request.Context()), result)); billingErr != nil { + reqLog.Error("gateway.probe_penalty_settlement_failed", zap.Error(billingErr)) + probeResponse.settlementError() + return + } + if responseErr := probeResponse.finish(result); responseErr != nil { + reqLog.Error("gateway.probe_penalty_response_failed", zap.Error(responseErr)) + } + return + } + h.submitUsageRecordTask(c.Request.Context(), func(ctx context.Context) { + if billingErr := record(ctx); billingErr != nil { + reqLog.Error("gateway.record_usage_failed", zap.Error(billingErr)) } }) } diff --git a/backend/internal/handler/gateway_handler_chat_completions.go b/backend/internal/handler/gateway_handler_chat_completions.go index 582511403bca..2b502d96ae1b 100644 --- a/backend/internal/handler/gateway_handler_chat_completions.go +++ b/backend/internal/handler/gateway_handler_chat_completions.go @@ -306,6 +306,26 @@ func (h *GatewayHandler) ChatCompletions(c *gin.Context) { } var result *service.ForwardResult setActualUpstreamEndpoint(c, "") + var probeResponse *probePenaltyResponse + if account.ProbePenaltyMinimum() > 0 { + if !h.gatewayService.ProbePenaltySettlementEnabled() { + if accountReleaseFunc != nil { + accountReleaseFunc() + } + h.chatCompletionsErrorResponse(c, http.StatusServiceUnavailable, "api_error", "Probe penalty requires durable settlement") + return + } + probeResponse, err = newProbePenaltyResponse(c.Writer, reqStream) + if err != nil { + if accountReleaseFunc != nil { + accountReleaseFunc() + } + h.chatCompletionsErrorResponse(c, http.StatusServiceUnavailable, "api_error", "Probe penalty response unavailable") + return + } + defer probeResponse.close() + c.Writer = probeResponse + } if account.Platform == service.PlatformGemini { if h.geminiCompatService == nil { h.chatCompletionsErrorResponse(c, http.StatusBadGateway, "upstream_error", "Gemini compatibility service is not configured") @@ -329,6 +349,20 @@ func (h *GatewayHandler) ChatCompletions(c *gin.Context) { result, err = h.gatewayService.ForwardAsChatCompletions(c.Request.Context(), c, account, forwardBody, parsedReq) } + if probeResponse != nil { + c.Writer = probeResponse.ResponseWriter + if err == nil { + err = probeResponse.validate() + } + if err != nil && probeResponse.size >= 0 { + if probeResponse.status >= http.StatusBadRequest { + _ = probeResponse.finish(nil) + } else { + probeResponse.settlementError() + } + } + } + if accountReleaseFunc != nil { accountReleaseFunc() } @@ -348,8 +382,8 @@ func (h *GatewayHandler) ChatCompletions(c *gin.Context) { quotaPlatform := service.QuotaPlatform(c.Request.Context(), apiKey) sessionID := service.ExtractClientSessionID(c) stampForwardRequestedReasoningEffort(result, service.RequestedReasoningEffortFromContext(c.Request.Context())) - h.submitUsageRecordTask(c.Request.Context(), func(ctx context.Context) { - if err := h.gatewayService.RecordUsage(ctx, &service.RecordUsageInput{ + record := func(ctx context.Context) error { + return h.gatewayService.RecordUsage(ctx, &service.RecordUsageInput{ Result: result, QuotaPlatform: quotaPlatform, APIKey: apiKey, @@ -365,11 +399,23 @@ func (h *GatewayHandler) ChatCompletions(c *gin.Context) { APIKeyService: h.apiKeyService, SessionID: sessionID, ChannelUsageFields: clientRequestedUsageFields(c, channelMapping, reqModel, result.UpstreamModel), - }); err != nil { - reqLog.Error("gateway.cc.record_usage_failed", - zap.Int64("account_id", account.ID), - zap.Error(err), - ) + }) + } + if probeResponse != nil && err == nil { + result.ProbePenaltyEligible = true + if billingErr := record(service.WithProbePenaltyResult(context.WithoutCancel(c.Request.Context()), result)); billingErr != nil { + reqLog.Error("gateway.probe_penalty_settlement_failed", zap.Error(billingErr)) + probeResponse.settlementError() + return + } + if responseErr := probeResponse.finish(result); responseErr != nil { + reqLog.Error("gateway.probe_penalty_response_failed", zap.Error(responseErr)) + } + return + } + h.submitUsageRecordTask(c.Request.Context(), func(ctx context.Context) { + if billingErr := record(ctx); billingErr != nil { + reqLog.Error("gateway.record_usage_failed", zap.Error(billingErr)) } }) } diff --git a/backend/internal/handler/gateway_handler_responses.go b/backend/internal/handler/gateway_handler_responses.go index 1f3ce43a046d..bd6dcc1f347c 100644 --- a/backend/internal/handler/gateway_handler_responses.go +++ b/backend/internal/handler/gateway_handler_responses.go @@ -294,6 +294,26 @@ func (h *GatewayHandler) Responses(c *gin.Context) { } var result *service.ForwardResult setActualUpstreamEndpoint(c, "") + var probeResponse *probePenaltyResponse + if account.ProbePenaltyMinimum() > 0 { + if !h.gatewayService.ProbePenaltySettlementEnabled() { + if accountReleaseFunc != nil { + accountReleaseFunc() + } + h.responsesErrorResponse(c, http.StatusServiceUnavailable, "api_error", "Probe penalty requires durable settlement") + return + } + probeResponse, err = newProbePenaltyResponse(c.Writer, reqStream) + if err != nil { + if accountReleaseFunc != nil { + accountReleaseFunc() + } + h.responsesErrorResponse(c, http.StatusServiceUnavailable, "api_error", "Probe penalty response unavailable") + return + } + defer probeResponse.close() + c.Writer = probeResponse + } if shouldUseAntigravityCompat(account) { if h.antigravityGatewayService == nil { h.responsesErrorResponse(c, http.StatusBadGateway, "upstream_error", "Antigravity compatibility service is not configured") @@ -325,6 +345,20 @@ func (h *GatewayHandler) Responses(c *gin.Context) { result, err = h.gatewayService.ForwardAsResponses(requestCtx, c, account, forwardBody, parsedReq) } + if probeResponse != nil { + c.Writer = probeResponse.ResponseWriter + if err == nil { + err = probeResponse.validate() + } + if err != nil && probeResponse.size >= 0 { + if probeResponse.status >= http.StatusBadRequest { + _ = probeResponse.finish(nil) + } else { + probeResponse.settlementError() + } + } + } + if accountReleaseFunc != nil { accountReleaseFunc() } @@ -344,8 +378,8 @@ func (h *GatewayHandler) Responses(c *gin.Context) { quotaPlatform := service.QuotaPlatform(c.Request.Context(), apiKey) sessionID := service.ExtractClientSessionID(c) stampForwardRequestedReasoningEffort(result, service.RequestedReasoningEffortFromContext(c.Request.Context())) - h.submitUsageRecordTask(c.Request.Context(), func(ctx context.Context) { - if err := h.gatewayService.RecordUsage(ctx, &service.RecordUsageInput{ + record := func(ctx context.Context) error { + return h.gatewayService.RecordUsage(ctx, &service.RecordUsageInput{ Result: result, QuotaPlatform: quotaPlatform, APIKey: apiKey, @@ -361,11 +395,23 @@ func (h *GatewayHandler) Responses(c *gin.Context) { APIKeyService: h.apiKeyService, SessionID: sessionID, ChannelUsageFields: clientRequestedUsageFields(c, channelMapping, reqModel, result.UpstreamModel), - }); err != nil { - reqLog.Error("gateway.responses.record_usage_failed", - zap.Int64("account_id", account.ID), - zap.Error(err), - ) + }) + } + if probeResponse != nil && err == nil { + result.ProbePenaltyEligible = true + if billingErr := record(service.WithProbePenaltyResult(context.WithoutCancel(c.Request.Context()), result)); billingErr != nil { + reqLog.Error("gateway.probe_penalty_settlement_failed", zap.Error(billingErr)) + probeResponse.settlementError() + return + } + if responseErr := probeResponse.finish(result); responseErr != nil { + reqLog.Error("gateway.probe_penalty_response_failed", zap.Error(responseErr)) + } + return + } + h.submitUsageRecordTask(c.Request.Context(), func(ctx context.Context) { + if billingErr := record(ctx); billingErr != nil { + reqLog.Error("gateway.record_usage_failed", zap.Error(billingErr)) } }) } diff --git a/backend/internal/handler/probe_penalty_response.go b/backend/internal/handler/probe_penalty_response.go new file mode 100644 index 000000000000..ef887e22f8c9 --- /dev/null +++ b/backend/internal/handler/probe_penalty_response.go @@ -0,0 +1,287 @@ +package handler + +import ( + "bytes" + "encoding/json" + "errors" + "io" + "net/http" + "strings" + + "github.com/Wei-Shaw/sub2api/internal/service" + "github.com/gin-gonic/gin" + "github.com/tidwall/gjson" + "github.com/tidwall/sjson" +) + +// Keep text deltas streaming. Only terminal usage/success is held until the +// canonical ledger commits. Non-streaming bodies use the existing private spool. +type probePenaltyResponse struct { + *imageBillingResponse + pending []byte + tail []byte + live bool + holding bool + jsonMode bool + seenBody bool + observedUsage bool + protocol string +} + +func newProbePenaltyResponse(w gin.ResponseWriter, stream bool) (*probePenaltyResponse, error) { + spool, err := newImageBillingResponse(w, stream) + if err != nil { + return nil, err + } + return &probePenaltyResponse{imageBillingResponse: spool, jsonMode: !stream}, nil +} + +func (w *probePenaltyResponse) WriteString(s string) (int, error) { return w.Write([]byte(s)) } +func (w *probePenaltyResponse) Write(b []byte) (int, error) { + if !w.seenBody && len(bytes.TrimSpace(b)) > 0 { + first := bytes.TrimSpace(b) + if first[0] != ':' { + w.seenBody = true + w.jsonMode = first[0] == '{' || !strings.Contains(w.header.Get("Content-Type"), "text/event-stream") + } + } + if w.jsonMode { + return w.imageBillingResponse.Write(b) + } + w.WriteHeaderNow() + w.size += len(b) + w.pending = append(w.pending, b...) + for { + end, separator := bytes.Index(w.pending, []byte("\n\n")), 2 + if crlf := bytes.Index(w.pending, []byte("\r\n\r\n")); crlf >= 0 && (end < 0 || crlf < end) { + end, separator = crlf, 4 + } + if end < 0 { + break + } + block := w.pending[:end+separator] + payload := probeEventData(block) + if gjson.GetBytes(payload, "message.usage").IsObject() || gjson.GetBytes(payload, "usage").IsObject() { + w.observedUsage = true + } + kind := gjson.GetBytes(payload, "type").String() + if strings.HasPrefix(kind, "response.") { + w.protocol = "responses" + } + if gjson.GetBytes(payload, "object").String() == "chat.completion.chunk" { + w.protocol = "chat" + } + finish := gjson.GetBytes(payload, "choices.0.finish_reason") + if kind == "message_delta" || kind == "message_stop" || kind == "response.completed" || kind == "response.incomplete" || kind == "response.failed" || (finish.Exists() && finish.Type != gjson.Null) || gjson.GetBytes(payload, "usage").IsObject() || bytes.Equal(payload, []byte("[DONE]")) { + w.holding = true + } + if w.holding { + w.tail = append(w.tail, block...) + } else { + if !w.live { + w.commitHeaders() + w.live = true + } + if _, err := w.ResponseWriter.Write(block); err != nil { + w.failure = err + return 0, err + } + } + w.pending = w.pending[end+separator:] + } + if len(w.pending)+len(w.tail) > 1<<20 { + w.failure = errors.New("probe penalty terminal response exceeds 1 MiB") + return 0, w.failure + } + return len(b), nil +} +func (w *probePenaltyResponse) Flush() { + if w.live { + w.ResponseWriter.Flush() + } +} + +func probeEventData(block []byte) []byte { + var lines [][]byte + for _, line := range bytes.Split(block, []byte("\n")) { + line = bytes.TrimSuffix(line, []byte("\r")) + if data, ok := bytes.CutPrefix(line, []byte("data:")); ok { + lines = append(lines, bytes.TrimPrefix(data, []byte(" "))) + } + } + return bytes.Join(lines, []byte("\n")) +} + +func (w *probePenaltyResponse) body() ([]byte, error) { + if w.failure != nil { + return nil, w.failure + } + if w.jsonMode { + if _, err := w.file.Seek(0, io.SeekStart); err != nil { + return nil, err + } + return io.ReadAll(io.LimitReader(w.file, imageBillingResponseLimit+1)) + } + return append(bytes.Clone(w.tail), w.pending...), nil +} +func (w *probePenaltyResponse) validate() error { + body, err := w.body() + if err != nil { + return err + } + if w.status >= http.StatusBadRequest { + return errors.New("probe penalty response is not successful") + } + if w.jsonMode { + if !gjson.ValidBytes(body) || (gjson.GetBytes(body, "type").String() != "message" && gjson.GetBytes(body, "object").String() != "chat.completion" && gjson.GetBytes(body, "object").String() != "response") || !gjson.GetBytes(body, "usage").IsObject() { + return errors.New("probe penalty requires a Claude message with usage") + } + return nil + } + usage, stop, terminal := w.observedUsage, false, false + for _, block := range bytes.Split(bytes.ReplaceAll(body, []byte("\r\n"), []byte("\n")), []byte("\n\n")) { + payload := probeEventData(block) + switch gjson.GetBytes(payload, "type").String() { + case "message_delta": + terminal = true + usage = usage || gjson.GetBytes(payload, "usage").IsObject() + case "message_stop": + stop = true + case "response.completed", "response.incomplete": + terminal = true + usage, stop = gjson.GetBytes(payload, "response.usage").IsObject(), true + case "error", "response.failed": + return errors.New("probe penalty response contains an error") + } + if gjson.GetBytes(payload, "usage.completion_tokens").Exists() { + terminal = true + usage = true + } + if bytes.Equal(payload, []byte("[DONE]")) { + stop = true + } + } + if !usage || !stop || !terminal { + return errors.New("probe penalty requires completed Claude stream usage") + } + return nil +} + +func rewriteProbeUsage(body []byte, result *service.ForwardResult) ([]byte, error) { + if result == nil || result.ProbePenalty == nil { + return body, nil + } + prefix := "" + if kind := gjson.GetBytes(body, "type").String(); kind == "response.completed" || kind == "response.incomplete" { + prefix = "response." + } + original := gjson.GetBytes(body, prefix+"usage") + if !original.Exists() { + original = gjson.Parse("null") + } + body, err := sjson.SetRawBytes(body, prefix+"upstream_usage", []byte(original.Raw)) + if err != nil { + return nil, err + } + // Preserve all input/cache details from the existing protocol converter. + output := "output_tokens" + if gjson.GetBytes(body, prefix+"object").String() == "chat.completion" || gjson.GetBytes(body, "object").String() == "chat.completion.chunk" { + output = "completion_tokens" + } + body, err = sjson.SetBytes(body, prefix+"usage."+output, result.ProbePenalty.BillingOutputTokens) + if err != nil { + return nil, err + } + if original.Get("total_tokens").Exists() { + body, err = sjson.SetBytes(body, prefix+"usage.total_tokens", original.Get("total_tokens").Int()-original.Get(output).Int()+int64(result.ProbePenalty.BillingOutputTokens)) + if err != nil { + return nil, err + } + } + if gjson.GetBytes(body, "type").String() == "message_delta" || gjson.GetBytes(body, "type").String() == "message" { + for key, value := range map[string]int{"input_tokens": result.Usage.InputTokens, "cache_creation_input_tokens": result.Usage.CacheCreationInputTokens, "cache_read_input_tokens": result.Usage.CacheReadInputTokens} { + body, err = sjson.SetBytes(body, "usage."+key, value) + if err != nil { + return nil, err + } + } + } + metadata := map[string]any{"usage_kind": "billing_equivalent", "probe_penalty": result.ProbePenalty} + return sjson.SetBytes(body, prefix+"billing", metadata) +} + +func (w *probePenaltyResponse) finish(result *service.ForwardResult) error { + body, err := w.body() + if err != nil { + return err + } + if result != nil && result.ProbePenalty != nil { + if w.jsonMode { + body, err = rewriteProbeUsage(body, result) + } else { + blocks := bytes.Split(bytes.ReplaceAll(body, []byte("\r\n"), []byte("\n")), []byte("\n\n")) + last := -1 + for i, block := range blocks { + payload := probeEventData(block) + if gjson.GetBytes(payload, "type").String() == "message_delta" || gjson.GetBytes(payload, "usage").IsObject() || gjson.GetBytes(payload, "response.usage").IsObject() { + last = i + } + } + for i, block := range blocks { + if i != last { + continue + } + payload := probeEventData(block) + var rewritten []byte + rewritten, err = rewriteProbeUsage(payload, result) + if err != nil { + break + } + var lines [][]byte + for _, line := range bytes.Split(block, []byte("\n")) { + if !bytes.HasPrefix(line, []byte("data:")) { + lines = append(lines, line) + } + } + lines = append(lines, append([]byte("data: "), rewritten...)) + blocks[i] = bytes.Join(lines, []byte("\n")) + } + body = bytes.Join(blocks, []byte("\n\n")) + } + } + if err != nil { + return err + } + if w.jsonMode { + w.header.Set("Content-Type", "application/json") + } + if !w.live { + w.commitHeaders() + w.live = true + } + _, err = w.ResponseWriter.Write(body) + w.ResponseWriter.Flush() + return err +} + +func (w *probePenaltyResponse) settlementError() { + // No terminal success after an unknown/failed settlement. Do not retry a + // model call: the durable journal may already own the monetary event. + payload, _ := json.Marshal(gin.H{"type": "error", "error": gin.H{"type": "api_error", "message": "Probe penalty settlement unavailable; do not automatically retry"}}) + if w.live { + prefix := "event: error\ndata: " + if w.protocol == "chat" { + prefix = "data: " + } + if w.protocol == "responses" { + prefix = "event: response.failed\ndata: " + payload, _ = json.Marshal(gin.H{"type": "response.failed", "response": gin.H{"status": "failed", "error": gin.H{"code": "settlement_unavailable", "message": "Probe penalty settlement unavailable; do not automatically retry"}}}) + } + _, _ = w.ResponseWriter.Write(append(append([]byte(prefix), payload...), '\n', '\n')) + } else { + w.ResponseWriter.Header().Set("Content-Type", "application/json") + w.ResponseWriter.WriteHeader(http.StatusServiceUnavailable) + _, _ = w.ResponseWriter.Write(payload) + } + w.ResponseWriter.Flush() +} diff --git a/backend/internal/handler/probe_penalty_response_test.go b/backend/internal/handler/probe_penalty_response_test.go new file mode 100644 index 000000000000..db18cf6bb919 --- /dev/null +++ b/backend/internal/handler/probe_penalty_response_test.go @@ -0,0 +1,215 @@ +//go:build unit + +package handler + +import ( + "context" + "errors" + "net/http/httptest" + "strings" + "testing" + + "github.com/Wei-Shaw/sub2api/internal/service" + "github.com/gin-gonic/gin" + "github.com/stretchr/testify/require" + "github.com/tidwall/gjson" +) + +func probeTestWriter(t *testing.T, stream bool) (*probePenaltyResponse, *httptest.ResponseRecorder) { + t.Helper() + r := httptest.NewRecorder() + c, _ := gin.CreateTestContext(r) + w, err := newProbePenaltyResponse(c.Writer, stream) + require.NoError(t, err) + t.Cleanup(w.close) + if stream { + w.Header().Set("Content-Type", "text/event-stream") + } else { + w.Header().Set("Content-Type", "application/json") + } + return w, r +} +func probeTestResult() *service.ForwardResult { + return &service.ForwardResult{Usage: service.ClaudeUsage{InputTokens: 10, OutputTokens: 13}, ProbePenalty: &service.ProbePenaltyReceipt{MinimumCharge: .001, Adjustment: .000685, ActualCost: .001, OriginalOutputTokens: 13, BillingOutputTokens: 49, OutputTokenPrice: .0000195}} +} +func TestProbePenaltyJSONPreservesObservedUsage(t *testing.T) { + w, r := probeTestWriter(t, false) + _, err := w.WriteString(`{"type":"message","content":[{"type":"text","text":"OK"}],"usage":{"input_tokens":10,"output_tokens":13}}`) + require.NoError(t, err) + require.Empty(t, r.Body.String()) + require.NoError(t, w.validate()) + require.NoError(t, w.finish(probeTestResult())) + body := r.Body.String() + require.Equal(t, int64(49), gjson.Get(body, "usage.output_tokens").Int()) + require.Equal(t, int64(13), gjson.Get(body, "upstream_usage.output_tokens").Int()) + require.Equal(t, "OK", gjson.Get(body, "content.0.text").String()) + require.Equal(t, .001, gjson.Get(body, "billing.probe_penalty.actual_cost").Float()) +} +func TestProbePenaltySSEStreamsTextAndHoldsTerminalUsage(t *testing.T) { + w, r := probeTestWriter(t, true) + start := "event: message_start\ndata: {\"type\":\"message_start\",\"message\":{\"usage\":{\"input_tokens\":10,\"output_tokens\":1}}}\n\n" + text := "event: content_block_delta\ndata: {\"type\":\"content_block_delta\",\"delta\":{\"text\":\"OK\"}}\n\n" + tail := "event: message_delta\ndata: {\"type\":\"message_delta\",\"delta\":{\"stop_reason\":\"end_turn\"},\"usage\":{\"output_tokens\":13}}\n\nevent: message_stop\ndata: {\"type\":\"message_stop\"}\n\n" + for _, b := range []byte(start + text + tail) { + _, err := w.Write([]byte{b}) + require.NoError(t, err) + w.Flush() + } + require.Contains(t, r.Body.String(), "OK") + require.NotContains(t, r.Body.String(), "message_stop") + require.NotContains(t, r.Body.String(), "end_turn") + require.NoError(t, w.validate()) + require.NoError(t, w.finish(probeTestResult())) + require.Equal(t, 1, strings.Count(r.Body.String(), `"type":"message_stop"`)) + require.Contains(t, r.Body.String(), `"output_tokens":49`) + require.Contains(t, r.Body.String(), `"upstream_usage":{"output_tokens":13}`) +} +func TestProbePenaltyRejectsTruncatedAndFailedSettlement(t *testing.T) { + w, r := probeTestWriter(t, true) + _, err := w.WriteString("event: message_delta\ndata: {\"type\":\"message_delta\",\"usage\":{\"output_tokens\":13}}\n\n") + require.NoError(t, err) + require.Error(t, w.validate()) + w.settlementError() + require.NotContains(t, r.Body.String(), "message_delta") + require.Equal(t, 503, r.Code) +} +func TestProbePenaltyDisabledAdjustmentLeavesBodyUnchanged(t *testing.T) { + w, r := probeTestWriter(t, false) + body := `{"type":"message","usage":{"input_tokens":10,"output_tokens":10000}}` + _, err := w.WriteString(body) + require.NoError(t, err) + require.NoError(t, w.finish(&service.ForwardResult{})) + require.Equal(t, body, r.Body.String()) +} + +type probeHandlerBilling struct{ httpDeliveryBilling } + +func (r *probeHandlerBilling) ApplyStagedUsageBilling(ctx context.Context, key service.UsageBillingEventKey) (*service.UsageBillingRecovery, error) { + recovered, err := r.httpDeliveryBilling.ApplyStagedUsageBilling(ctx, key) + if recovered != nil { + recovered.Settled = true + } + return recovered, err +} +func TestProbePenaltyActualGatewayProtocols(t *testing.T) { + for _, endpoint := range []string{"messages", "chat/completions", "responses"} { + for _, fail := range []bool{false, true} { + t.Run(endpoint+map[bool]string{false: "/settled", true: "/settlement-failed"}[fail], func(t *testing.T) { + repo := &probeHandlerBilling{} + if fail { + repo.failure = errors.New("injected settlement error") + } + extra := map[string]any{service.AccountProbePenaltyExtraKey: map[string]any{"enabled": true, "minimum_charge": .001}} + run := runCompatStreamUsageHandlerWithDelivery(t, endpoint, compatStreamUsagePartialStream+compatStreamUsageCompletion, true, repo, "", extra) + require.Equal(t, 1, run.upstream.calls) + require.NotNil(t, repo.event, "actual handler must synchronously stage the charge") + require.Equal(t, .001, repo.event.Command.BalanceCost) + require.Equal(t, 7, repo.event.Usage.OutputTokens) + require.Equal(t, 12, repo.event.Usage.InputTokens) + body := run.rec.Body.String() + require.Contains(t, body, "partial") + if fail { + require.NotContains(t, body, `"usage_kind":"billing_equivalent"`) + require.Contains(t, body, "do not automatically retry") + } else { + require.Contains(t, body, `"usage_kind":"billing_equivalent"`) + require.Contains(t, body, `"actual_cost":0.001`) + require.True(t, repo.applied) + } + }) + } + } +} + +func TestProbePenaltyDownstreamSub2APIChargesEquivalentUsage(t *testing.T) { + extra := map[string]any{service.AccountProbePenaltyExtraKey: map[string]any{"enabled": true, "minimum_charge": .001}} + supplier := &probeHandlerBilling{} + upstream := runCompatStreamUsageHandlerWithDelivery(t, "messages", compatStreamUsagePartialStream+compatStreamUsageCompletion, true, supplier, "", extra) + require.NotNil(t, supplier.event) + require.Contains(t, upstream.rec.Body.String(), `"usage_kind":"billing_equivalent"`) + for _, endpoint := range []string{"messages", "chat/completions", "responses"} { + t.Run(endpoint, func(t *testing.T) { + // A second real Sub2API handler consumes the supplier's standard usage + // with no penalty configuration. No custom receipt parser is required. + downstream := runCompatStreamUsageHandlerWithDelivery(t, endpoint, upstream.rec.Body.String(), true, nil, "") + downstream.billingRepo.mu.Lock() + defer downstream.billingRepo.mu.Unlock() + require.Len(t, downstream.billingRepo.commands, 1) + charge := downstream.billingRepo.commands[0].BalanceCost + require.GreaterOrEqual(t, charge, .001) + require.Less(t, charge, .001+supplier.event.Usage.CustomerCostDetails.ProbePenalty.OutputTokenPrice) + require.Greater(t, downstream.billingRepo.commands[0].OutputTokens, 7) + require.Equal(t, 7, supplier.event.Usage.OutputTokens, "supplier retains real model consumption") + }) + } +} + +func TestProbePenaltyProtocolUsageKeepsCacheDetails(t *testing.T) { + for _, body := range []string{ + `{"object":"chat.completion","usage":{"prompt_tokens":120,"completion_tokens":13,"total_tokens":133,"prompt_tokens_details":{"cached_tokens":100}}}`, + `{"type":"response.incomplete","response":{"object":"response","usage":{"input_tokens":120,"output_tokens":13,"total_tokens":133,"input_tokens_details":{"cached_tokens":100}}}}`, + } { + out, err := rewriteProbeUsage([]byte(body), probeTestResult()) + require.NoError(t, err) + require.Contains(t, string(out), `"cached_tokens":100`) + require.Contains(t, string(out), `"total_tokens":169`) + require.Contains(t, string(out), `"upstream_usage"`) + } +} + +func TestProbePenaltyStreamingRequestJSONFallback(t *testing.T) { + w, r := probeTestWriter(t, true) + _, err := w.WriteString(`{"type":"message","usage":{"input_tokens":10,"output_tokens":13}}`) + require.NoError(t, err) + require.NoError(t, w.validate()) + require.Empty(t, r.Body.String()) + require.NoError(t, w.finish(probeTestResult())) + require.Equal(t, "application/json", r.Header().Get("Content-Type")) + require.Equal(t, int64(49), gjson.Get(r.Body.String(), "usage.output_tokens").Int()) +} + +func TestProbePenaltySparseTerminalUsageAcrossGateways(t *testing.T) { + for _, usage := range []string{`{"output_tokens":0}`, `{"cache_read_input_tokens":2}`, `null`, ``} { + for _, endpoint := range []string{"messages", "chat/completions", "responses"} { + t.Run(endpoint+"/"+usage, func(t *testing.T) { + suffix := `{"type":"message_delta","delta":{"stop_reason":"end_turn"}` + if usage != "" { + suffix += `,"usage":` + usage + } + suffix += `}` + stream := compatStreamUsagePartialStream + "event: message_delta\ndata: {\"type\":\"message_delta\",\"usage\":{\"output_tokens\":13}}\n\n" + "event: message_delta\ndata: " + suffix + "\n\nevent: message_stop\ndata: {\"type\":\"message_stop\"}\n\n" + repo := &probeHandlerBilling{} + run := runCompatStreamUsageHandlerWithDelivery(t, endpoint, stream, true, repo, "", map[string]any{service.AccountProbePenaltyExtraKey: map[string]any{"enabled": true, "minimum_charge": .001}}) + require.NotNil(t, repo.event) + require.Equal(t, 13, repo.event.Usage.OutputTokens) + require.Equal(t, .001, repo.event.Command.BalanceCost) + expected := repo.event.Usage.CustomerCostDetails.ProbePenalty.BillingOutputTokens + found := false + for _, block := range strings.Split(run.rec.Body.String(), "\n\n") { + payload := probeEventData([]byte(block)) + prefix := "" + if gjson.GetBytes(payload, "type").String() == "response.completed" { + prefix = "response." + } + if !gjson.GetBytes(payload, prefix+"billing.probe_penalty").Exists() { + continue + } + output := gjson.GetBytes(payload, prefix+"usage.output_tokens") + if !output.Exists() { + output = gjson.GetBytes(payload, prefix+"usage.completion_tokens") + } + require.Equal(t, int64(expected), output.Int()) + found = true + } + require.True(t, found, "the last sparse delta must contain canonical cumulative billing usage") + }) + } + } +} + +func TestProbePenaltyRequiresTerminalUsageCarrier(t *testing.T) { + w, _ := probeTestWriter(t, true) + _, err := w.WriteString("event: message_start\ndata: {\"type\":\"message_start\",\"message\":{\"usage\":{\"input_tokens\":10}}}\n\nevent: message_stop\ndata: {\"type\":\"message_stop\"}\n\n") + require.NoError(t, err) + require.Error(t, w.validate(), "a malformed stream cannot settle without a terminal frame to carry the equivalent usage") +} diff --git a/backend/internal/repository/account_repo.go b/backend/internal/repository/account_repo.go index 9a0e57c7a4d5..fa4f0c03c365 100644 --- a/backend/internal/repository/account_repo.go +++ b/backend/internal/repository/account_repo.go @@ -942,7 +942,7 @@ func lockAndMergeAccountProbeExtra( // Omitted cost means an unrelated edit. Keep the value under the row lock, // including a probe update committed after the edit form was loaded. - for _, key := range []string{service.AccountCostMultiplierExtraKey, service.AccountCostAutoSyncExtraKey} { + for _, key := range []string{service.AccountCostMultiplierExtraKey, service.AccountCostAutoSyncExtraKey, service.AccountProbePenaltyExtraKey} { if _, provided := extra[key]; !provided { if value, exists := currentExtra[key]; exists { if extra == nil { diff --git a/backend/internal/repository/free_fast_customer_cost_integration_test.go b/backend/internal/repository/free_fast_customer_cost_integration_test.go index aecc9b21f3f4..62864122f3e0 100644 --- a/backend/internal/repository/free_fast_customer_cost_integration_test.go +++ b/backend/internal/repository/free_fast_customer_cost_integration_test.go @@ -183,3 +183,26 @@ func TestFreeUltrafastCustomerCostDurableReplay(t *testing.T) { require.Equal(t, "99.99900400", balance) require.Equal(t, "0.00099600", quota) } + +func TestAccountProbePenaltyDurableReplay(t *testing.T) { + ctx := context.Background() + repo, cmd, usage, _ := durableBillingFixture(t) + cmd.BalanceCost, cmd.APIKeyQuotaCost = .001, .001 + usage.InputTokens, usage.OutputTokens = 10, 13 + usage.InputCost, usage.OutputCost, usage.TotalCost, usage.ActualCost = .00003, .000195, .000225, .001 + usage.CustomerCostDetails = &service.CustomerCostDetails{Version: 4, ProbePenalty: &service.ProbePenaltyReceipt{MinimumCharge: .001, Adjustment: .0007525, ActualCost: .001, OriginalOutputTokens: 13, BillingOutputTokens: 59, OutputTokenPrice: .0000165}} + require.NoError(t, repo.StageUsageBilling(ctx, &cmd, &usage)) + key := service.UsageBillingEventKey{RequestID: cmd.RequestID, APIKeyID: cmd.APIKeyID} + for i := 0; i < 2; i++ { + recovered, err := repo.ApplyStagedUsageBilling(ctx, key) + require.NoError(t, err) + require.True(t, recovered.Settled) + require.Equal(t, .001, recovered.Event.Usage.CustomerCostDetails.ProbePenalty.ActualCost) + require.Equal(t, 13, recovered.Event.Usage.OutputTokens) + } + 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.99900000", balance) + require.Equal(t, "0.00100000", quota) +} diff --git a/backend/internal/repository/scheduler_cache.go b/backend/internal/repository/scheduler_cache.go index 4f9995feb1e4..38be882abc5c 100644 --- a/backend/internal/repository/scheduler_cache.go +++ b/backend/internal/repository/scheduler_cache.go @@ -1662,6 +1662,7 @@ func filterSchedulerExtra(extra map[string]any) map[string]any { // Priority scoring runs on candidate metadata before full hydration. // Dropping saved procurement cost silently substitutes the 0.1 default. service.AccountCostMultiplierExtraKey, + service.AccountProbePenaltyExtraKey, // Anthropic shared-window and Fable-only threshold checks run on this // projection. UpdateExtra refreshes both payloads without a bucket rebuild. "session_window_utilization", diff --git a/backend/internal/repository/scheduler_cache_cost_multiplier_unit_test.go b/backend/internal/repository/scheduler_cache_cost_multiplier_unit_test.go index f18dae8b4e84..c6467fd7d875 100644 --- a/backend/internal/repository/scheduler_cache_cost_multiplier_unit_test.go +++ b/backend/internal/repository/scheduler_cache_cost_multiplier_unit_test.go @@ -58,3 +58,31 @@ func TestSchedulerCachePreservesCostMultiplier(t *testing.T) { }) } } + +func TestSchedulerCachePreservesProbePenalty(t *testing.T) { + ctx := context.Background() + cache := newSchedulerCacheUnit(t) + account := service.Account{ID: 9201, Platform: service.PlatformAnthropic, Type: service.AccountTypeAPIKey, Status: service.StatusActive, Schedulable: true, Concurrency: 1, Extra: map[string]any{service.AccountProbePenaltyExtraKey: map[string]any{"enabled": true, "minimum_charge": .001}}} + bucket := service.SchedulerBucket{GroupID: 18, Platform: service.PlatformAnthropic, Mode: service.SchedulerModeSingle} + token, err := cache.CaptureBucketWriteToken(ctx, bucket) + require.NoError(t, err) + require.NoError(t, cache.SetSnapshot(ctx, bucket, token, []service.Account{account})) + for _, enabled := range []bool{true, false, true} { + account.Extra[service.AccountProbePenaltyExtraKey] = map[string]any{"enabled": enabled, "minimum_charge": .001} + require.True(t, shouldEnqueueSchedulerOutboxForExtraUpdates(account.Extra)) + require.NoError(t, cache.SetAccount(ctx, &account)) + candidates, hit, err := cache.GetSnapshot(ctx, bucket) + require.NoError(t, err) + require.True(t, hit) + require.Len(t, candidates, 1) + full, err := cache.GetAccount(ctx, account.ID) + require.NoError(t, err) + for _, cached := range []*service.Account{candidates[0], full} { + if enabled { + require.Equal(t, .001, cached.ProbePenaltyMinimum()) + } else { + require.Zero(t, cached.ProbePenaltyMinimum()) + } + } + } +} diff --git a/backend/internal/repository/upstream_billing_probe_persistence_integration_test.go b/backend/internal/repository/upstream_billing_probe_persistence_integration_test.go index 37886ed91ff9..33dd2ad17dbc 100644 --- a/backend/internal/repository/upstream_billing_probe_persistence_integration_test.go +++ b/backend/internal/repository/upstream_billing_probe_persistence_integration_test.go @@ -713,3 +713,29 @@ func TestProbePreservesManualCostWhenAutoSyncDisabledDuringProbe(t *testing.T) { require.NoError(t, err) require.Equal(t, 1.0, synced.CostMultiplier()) } + +func TestAccountProbePenaltyOmittedEditPreservesCommittedSetting(t *testing.T) { + ctx := context.Background() + tx := testEntTx(t) + repo := newAccountRepositoryWithSQL(tx.Client(), tx, nil) + account := mustCreateAccount(t, tx.Client(), &service.Account{Name: "probe-penalty-omit", Platform: service.PlatformAnthropic, Type: service.AccountTypeAPIKey, Extra: map[string]any{service.AccountProbePenaltyExtraKey: map[string]any{"enabled": true, "minimum_charge": .001}}}) + stale, err := repo.GetByID(ctx, account.ID) + require.NoError(t, err) + require.NoError(t, repo.UpdateExtra(ctx, account.ID, map[string]any{service.AccountProbePenaltyExtraKey: map[string]any{"enabled": false, "minimum_charge": .002}})) + delete(stale.Extra, service.AccountProbePenaltyExtraKey) + stale.Name = "unrelated rename" + require.NoError(t, repo.Update(ctx, stale)) + saved, err := repo.GetByID(ctx, account.ID) + require.NoError(t, err) + require.Equal(t, map[string]any{"enabled": false, "minimum_charge": .002}, saved.Extra[service.AccountProbePenaltyExtraKey]) + stale.Extra[service.AccountProbePenaltyExtraKey] = map[string]any{"enabled": true, "minimum_charge": .003} + require.NoError(t, repo.Update(ctx, stale)) + saved, err = repo.GetByID(ctx, account.ID) + require.NoError(t, err) + require.Equal(t, .003, saved.ProbePenaltyMinimum()) + stale.Extra[service.AccountProbePenaltyExtraKey] = nil + require.NoError(t, repo.Update(ctx, stale)) + saved, err = repo.GetByID(ctx, account.ID) + require.NoError(t, err) + require.Zero(t, saved.ProbePenaltyMinimum()) +} diff --git a/backend/internal/service/account_probe_penalty.go b/backend/internal/service/account_probe_penalty.go new file mode 100644 index 000000000000..b14ad9116f8d --- /dev/null +++ b/backend/internal/service/account_probe_penalty.go @@ -0,0 +1,83 @@ +package service + +import ( + "context" + "fmt" + "math" + + infraerrors "github.com/Wei-Shaw/sub2api/internal/pkg/errors" +) + +const AccountProbePenaltyExtraKey = "probe_penalty" + +func (s *GatewayService) ProbePenaltySettlementEnabled() bool { + return s != nil && (s.cfg == nil || s.cfg.RunMode != "simple") && s.DurableUsageBillingEnabled() +} + +// Probe penalties are an explicit customer charge, never procurement cost. +// The nested object is replaced atomically by all account editing APIs. +func ValidateAccountProbePenaltyExtra(extra map[string]any) error { + raw := extra[AccountProbePenaltyExtraKey] + if raw == nil { + return nil + } + value, ok := raw.(map[string]any) + if !ok { + return infraerrors.BadRequest("INVALID_PROBE_PENALTY", "probe_penalty must contain enabled and minimum_charge") + } + enabled, boolean := value["enabled"].(bool) + minimum, number := accountCostMultiplierNumber(value["minimum_charge"]) + if !boolean || !number || minimum > 1000 || (enabled && minimum <= 0) || QuantizeUsageBillingAmount(minimum) != minimum { + return infraerrors.BadRequest("INVALID_PROBE_PENALTY", "probe_penalty requires a boolean enabled and a finite minimum_charge between 0 and 1000 with at most eight decimal places; enabled requires a positive charge") + } + return nil +} + +func (a *Account) ProbePenaltyMinimum() float64 { + if a == nil || a.Platform != PlatformAnthropic { + return 0 + } + value, ok := a.Extra[AccountProbePenaltyExtraKey].(map[string]any) + if !ok || value["enabled"] != true || ValidateAccountProbePenaltyExtra(a.Extra) != nil { + return 0 + } + minimum, _ := accountCostMultiplierNumber(value["minimum_charge"]) + return minimum +} + +// A request-time receipt, also persisted in customer_cost_details. Output tokens +// in the protocol become billing equivalents; UsageLog keeps observed tokens. +type ProbePenaltyReceipt struct { + MinimumCharge float64 `json:"minimum_charge"` + Adjustment float64 `json:"adjustment"` + ActualCost float64 `json:"actual_cost"` + OriginalOutputTokens int `json:"original_output_tokens"` + BillingOutputTokens int `json:"billing_output_tokens"` + OutputTokenPrice float64 `json:"output_token_price"` +} + +func calculateProbePenalty(cost *CostBreakdown, minimum, outputPrice float64, outputTokens int) (*ProbePenaltyReceipt, error) { + if cost == nil || minimum <= 0 || QuantizeUsageBillingAmount(cost.ActualCost) >= minimum { + return nil, nil + } + if cost.BillingMode != "" && cost.BillingMode != string(BillingModeToken) { + return nil, fmt.Errorf("probe penalty requires token billing") + } + if outputTokens < 0 || outputPrice <= 0 || math.IsNaN(outputPrice) || math.IsInf(outputPrice, 0) || cost.ActualCost < 0 || math.IsNaN(cost.ActualCost) || math.IsInf(cost.ActualCost, 0) { + return nil, fmt.Errorf("probe penalty has no finite positive output token price") + } + adjustment := QuantizeUsageBillingAmount(minimum - QuantizeUsageBillingAmount(cost.ActualCost)) + extra := math.Ceil((minimum - cost.ActualCost) / outputPrice) + if extra > 1e9 || float64(outputTokens)+extra > 1e9 { + return nil, fmt.Errorf("probe penalty exceeds billing token limit") + } + return &ProbePenaltyReceipt{MinimumCharge: minimum, Adjustment: adjustment, ActualCost: minimum, + OriginalOutputTokens: outputTokens, BillingOutputTokens: outputTokens + int(extra), OutputTokenPrice: outputPrice}, nil +} + +// The handler must publish the canonical committed receipt, including replay. +type probePenaltyResultKey struct{} + +func WithProbePenaltyResult(ctx context.Context, result *ForwardResult) context.Context { + return context.WithValue(ctx, probePenaltyResultKey{}, result) +} diff --git a/backend/internal/service/account_probe_penalty_test.go b/backend/internal/service/account_probe_penalty_test.go new file mode 100644 index 000000000000..a38c407a467a --- /dev/null +++ b/backend/internal/service/account_probe_penalty_test.go @@ -0,0 +1,104 @@ +//go:build unit + +package service + +import ( + "context" + "math" + "testing" + + "github.com/stretchr/testify/require" +) + +func TestAccountProbePenaltyValidation(t *testing.T) { + for _, minimum := range []any{nil, "0.001", -1., math.NaN(), math.Inf(1), 1001., .000000001, 0.} { + require.Error(t, ValidateAccountProbePenaltyExtra(map[string]any{AccountProbePenaltyExtraKey: map[string]any{"enabled": true, "minimum_charge": minimum}})) + } + for _, enabled := range []bool{true, false} { + a := &Account{Platform: PlatformAnthropic, Extra: map[string]any{AccountProbePenaltyExtraKey: map[string]any{"enabled": enabled, "minimum_charge": .001}}} + require.NoError(t, ValidateAccountProbePenaltyExtra(a.Extra)) + if enabled { + require.Equal(t, .001, a.ProbePenaltyMinimum()) + } else { + require.Zero(t, a.ProbePenaltyMinimum()) + } + } + require.Zero(t, (*Account)(nil).ProbePenaltyMinimum()) + require.NoError(t, ValidateAccountProbePenaltyExtra(nil)) + require.Error(t, ValidateAccountProbePenaltyExtra(map[string]any{AccountProbePenaltyExtraKey: true})) +} + +func TestAccountProbePenaltyEquivalentUsage(t *testing.T) { + for _, actual := range []float64{.000312, .000315, .000630, .001, .308745} { + cost := &CostBreakdown{ActualCost: actual, TotalCost: actual / 1.3, BillingMode: "token"} + p, err := calculateProbePenalty(cost, .001, .0000195, 13) + require.NoError(t, err) + require.Equal(t, actual, cost.ActualCost, "quoting cannot mutate cost") + if actual >= .001 { + require.Nil(t, p) + continue + } + require.Equal(t, .001, p.ActualCost) + equivalent := actual + float64(p.BillingOutputTokens-p.OriginalOutputTokens)*p.OutputTokenPrice + require.GreaterOrEqual(t, equivalent, .001) + require.Less(t, equivalent, .001+p.OutputTokenPrice) + } + _, err := calculateProbePenalty(&CostBreakdown{}, .001, 0, 0) + require.Error(t, err, "cannot invent token prices for a free/unknown model") +} + +func TestAccountProbePenaltyCanonicalBilling(t *testing.T) { + for _, eligible := range []bool{true, false} { + usageRepo := &openAIRecordUsageLogRepoStub{} + billingRepo := &openAIRecordUsageBillingRepoStub{result: &UsageBillingApplyResult{Applied: true}} + svc := newGatewayRecordUsageServiceWithBillingRepoForTest(usageRepo, billingRepo, &openAIRecordUsageUserRepoStub{}, &openAIRecordUsageSubRepoStub{}) + result := &ForwardResult{RequestID: "probe-test", Model: "claude-sonnet-4", Usage: ClaudeUsage{InputTokens: 10, OutputTokens: 13}, ProbePenaltyEligible: eligible} + account := &Account{ID: 701, Platform: PlatformAnthropic, Type: AccountTypeAPIKey, Extra: map[string]any{AccountProbePenaltyExtraKey: map[string]any{"enabled": true, "minimum_charge": .001}, "quota_limit": 100.}} + err := svc.RecordUsage(context.Background(), &RecordUsageInput{Result: result, APIKey: &APIKey{ID: 501, Quota: 100}, User: &User{ID: 601}, Account: account, APIKeyService: &openAIRecordUsageAPIKeyQuotaStub{}}) + require.NoError(t, err) + require.Equal(t, 13, usageRepo.lastLog.OutputTokens) + require.Equal(t, usageRepo.lastLog.ActualCost, billingRepo.lastCmd.BalanceCost) + require.Equal(t, usageRepo.lastLog.TotalCost, billingRepo.lastCmd.AccountQuotaCost) + if eligible { + require.Equal(t, .001, billingRepo.lastCmd.BalanceCost) + require.Equal(t, .001, billingRepo.lastCmd.APIKeyQuotaCost) + require.NotNil(t, usageRepo.lastLog.CustomerCostDetails.ProbePenalty) + require.Greater(t, result.ProbePenalty.BillingOutputTokens, 13) + } else { + require.Less(t, billingRepo.lastCmd.BalanceCost, .001) + require.Nil(t, result.ProbePenalty) + } + } +} + +func TestAccountProbePenaltySubscriptionAfterDiscount(t *testing.T) { + usageRepo := &openAIRecordUsageLogRepoStub{} + billingRepo := &openAIRecordUsageBillingRepoStub{result: &UsageBillingApplyResult{Applied: true}} + svc := newGatewayRecordUsageServiceWithBillingRepoForTest(usageRepo, billingRepo, &openAIRecordUsageUserRepoStub{}, &openAIRecordUsageSubRepoStub{}) + gid := int64(9) + rate := .5 + result := &ForwardResult{RequestID: "subscription-probe", Model: "claude-sonnet-4", Usage: ClaudeUsage{InputTokens: 10, OutputTokens: 13}, ProbePenaltyEligible: true} + err := svc.RecordUsage(context.Background(), &RecordUsageInput{Result: result, APIKey: &APIKey{ID: 501, GroupID: &gid, Group: &Group{ID: gid, RateMultiplier: .01, SubscriptionType: SubscriptionTypeSubscription}}, User: &User{ID: 601}, Subscription: &UserSubscription{ID: 17}, Account: &Account{ID: 701, Platform: PlatformAnthropic, GroupRateMultiplier: &rate, Extra: map[string]any{AccountProbePenaltyExtraKey: map[string]any{"enabled": true, "minimum_charge": .001}}}}) + require.NoError(t, err) + require.Equal(t, .001, billingRepo.lastCmd.SubscriptionCost) + require.Zero(t, billingRepo.lastCmd.BalanceCost) + require.Equal(t, .001, usageRepo.lastLog.ActualCost) +} + +type probeReceiptReplayRepo struct{ imageReceiptRepo } + +func (*probeReceiptReplayRepo) StageUsageBilling(context.Context, *UsageBillingCommand, *UsageLog) error { + return nil +} +func TestAccountProbePenaltyReceiptUsesCanonicalReplay(t *testing.T) { + canonical := &ProbePenaltyReceipt{MinimumCharge: .002, ActualCost: .002, Adjustment: .0015, OriginalOutputTokens: 13, BillingOutputTokens: 90, OutputTokenPrice: .00002} + repo := &probeReceiptReplayRepo{imageReceiptRepo{recovery: &UsageBillingRecovery{Settled: true, Event: UsageBillingEvent{Usage: UsageLog{OutputTokens: 13, InputTokens: 10, CustomerCostDetails: &CustomerCostDetails{Version: 4, ProbePenalty: canonical}}}}}} + current := &ForwardResult{Usage: ClaudeUsage{OutputTokens: 1}, ProbePenalty: &ProbePenaltyReceipt{ActualCost: .001, BillingOutputTokens: 50}} + _, err := applyDurableUsageBilling(WithProbePenaltyResult(context.Background(), current), repo, &UsageBillingCommand{RequestID: "replay", APIKeyID: 1}, &UsageLog{}, &postUsageBillingParams{}, &billingDeps{}) + require.NoError(t, err) + require.Equal(t, canonical, current.ProbePenalty) + require.Equal(t, 13, current.Usage.OutputTokens) + repo.recovery.Settled = false + _, err = applyDurableUsageBilling(WithProbePenaltyResult(context.Background(), current), repo, &UsageBillingCommand{RequestID: "unknown", APIKeyID: 1}, &UsageLog{}, &postUsageBillingParams{}, &billingDeps{}) + require.ErrorIs(t, err, ErrUsageBillingOutcomeUnknown) +} diff --git a/backend/internal/service/admin_account.go b/backend/internal/service/admin_account.go index 52c123df7950..bff7d6214021 100644 --- a/backend/internal/service/admin_account.go +++ b/backend/internal/service/admin_account.go @@ -432,6 +432,9 @@ func normalizeOpenAILongContextBillingUpdateExtra(account *Account, input *Updat // Grok media eligibility helpers live in account_grok_media_eligibility.go. func buildAccountForCreate(input *CreateAccountInput, accountExtra map[string]any) (*Account, error) { + if err := ValidateAccountProbePenaltyExtra(accountExtra); err != nil { + return nil, err + } if err := ValidateOpenAIRequestTimezoneExtra(input.Platform, accountExtra); err != nil { return nil, err } @@ -521,6 +524,9 @@ func (s *adminServiceImpl) CreateAccount(ctx context.Context, input *CreateAccou if err := ValidateAccountCostMultiplierExtra(input.Extra); err != nil { return nil, err } + if err := ValidateAccountProbePenaltyExtra(input.Extra); err != nil { + return nil, err + } if err := s.ApplyOAuthAutoConfig(ctx, input); err != nil { return nil, err } @@ -664,6 +670,9 @@ func (s *adminServiceImpl) UpdateAccount(ctx context.Context, id int64, input *U if err := ValidateAccountCostMultiplierExtra(input.Extra); err != nil { return nil, err } + if err := ValidateAccountProbePenaltyExtra(input.Extra); err != nil { + return nil, err + } if err := ValidateGroupAllowedModels(input.GroupAllowedModels); err != nil { return nil, err } @@ -1091,6 +1100,9 @@ func (s *adminServiceImpl) UpdateAccountExtra(ctx context.Context, id int64, upd if err := ValidateAccountCostMultiplierExtra(updates); err != nil { return err } + if err := ValidateAccountProbePenaltyExtra(updates); err != nil { + return err + } if hasExcelBPSProxyUpdates(updates) { account, err := s.accountRepo.GetByID(ctx, id) if err != nil { @@ -1153,6 +1165,9 @@ func (s *adminServiceImpl) BulkUpdateAccounts(ctx context.Context, input *BulkUp if err := ValidateAccountCostMultiplierExtra(input.Extra); err != nil { return nil, err } + if err := ValidateAccountProbePenaltyExtra(input.Extra); err != nil { + return nil, err + } // Managed probe/session state may only enter through dedicated typed endpoints. input.Extra = MergeOpenAICodexTicketExtra(input.Extra, nil) input.Extra = sanitizedCodexFingerprintExtraUpdates(input.Extra) diff --git a/backend/internal/service/customer_cost_details.go b/backend/internal/service/customer_cost_details.go index eb85e8d0c941..5bcc6ae5ae21 100644 --- a/backend/internal/service/customer_cost_details.go +++ b/backend/internal/service/customer_cost_details.go @@ -9,6 +9,7 @@ import ( // are Standard components before the customer rate; upstream UsageLog monetary // fields and the billing command remain authoritative and unchanged. type CustomerCostDetails struct { + ProbePenalty *ProbePenaltyReceipt `json:"probe_penalty,omitempty"` ImageMinimumCharge float64 `json:"image_minimum_charge,omitempty"` ImageMinimumChargeAdjustment float64 `json:"image_minimum_charge_adjustment,omitempty"` CacheCostDetails []CustomerCacheCostDetail `json:"cache_cost_details,omitempty"` diff --git a/backend/internal/service/gateway_service.go b/backend/internal/service/gateway_service.go index 7ded1b5ce034..efc744db477b 100644 --- a/backend/internal/service/gateway_service.go +++ b/backend/internal/service/gateway_service.go @@ -693,7 +693,10 @@ type AudioUsage struct { } type ForwardResult struct { - RequestID string + // Only a successfully completed Claude response can receive the opt-in floor. + ProbePenaltyEligible bool + ProbePenalty *ProbePenaltyReceipt + RequestID string // UpstreamHeaders 是直接上游的响应头,用于按账户配置解析上游请求标识。 UpstreamHeaders http.Header Usage ClaudeUsage diff --git a/backend/internal/service/gateway_usage_billing.go b/backend/internal/service/gateway_usage_billing.go index 46390dac24cc..40c403511825 100644 --- a/backend/internal/service/gateway_usage_billing.go +++ b/backend/internal/service/gateway_usage_billing.go @@ -929,14 +929,37 @@ func (s *GatewayService) recordUsageCore(ctx context.Context, input *recordUsage responseCost := s.calculateRecordUsageCost(ctx, result, apiKey, responseModel, multiplier, imageMultiplier, pricingAt) baselineChannelPriced := s.resolveChannelPricing(ctx, billingModel, apiKey) != nil if responseModelBillingAdoptable(cost, responseCost, baselineChannelPriced, responseChannelPriced) { - // billingModel 到此为止只是定价查表的入参,后续流程只消费 cost, - // 因此这里不改写它,改由日志记录实际生效的计费基准。 + // Keep the adopted model for the zero-output marginal price used by probe penalties. logResponseModelBillingApplied("service.gateway", account, result.RequestID, billingModel, responseModel, cost, responseCost) cost = responseCost + billingModel = responseModel } } } + // Freeze the penalty before building the deduplicated ledger command. Raw + // token components and account procurement costs remain unchanged. + if result.ProbePenaltyEligible && account.ProbePenaltyMinimum() > 0 { + outputPrice := 0.0 + if cost != nil && result.Usage.OutputTokens > 0 { + outputPrice = cost.OutputCost / float64(result.Usage.OutputTokens) * multiplier * costModelBillingMultiplier(cost) + } else if cost != nil { + one := *result + one.Usage.OutputTokens = 1 + if quote := s.calculateRecordUsageCost(ctx, &one, apiKey, billingModel, multiplier, imageMultiplier, pricingAt); quote != nil { + outputPrice = quote.OutputCost * multiplier * costModelBillingMultiplier(quote) + } + } + penalty, err := calculateProbePenalty(cost, account.ProbePenaltyMinimum(), outputPrice, result.Usage.OutputTokens) + if err != nil { + return err + } + result.ProbePenalty = penalty + if penalty != nil { + cost.ActualCost = penalty.ActualCost + } + } + // 判断计费方式:订阅模式 vs 余额模式 isSubscriptionBilling := subscription != nil && apiKey.Group != nil && apiKey.Group.IsSubscriptionType() billingType := BillingTypeBalance @@ -949,6 +972,11 @@ func (s *GatewayService) recordUsageCore(ctx context.Context, input *recordUsage usageLog := s.buildRecordUsageLog(ctx, input, result, apiKey, user, account, subscription, requestedModel, multiplier, imageMultiplier, accountRateMultiplier, billingType, cacheTTLOverridden, cost) usageLog.RateMultiplier *= costModelBillingMultiplier(cost) + if result.ProbePenalty != nil { + usageLog.CustomerCostDetails = &CustomerCostDetails{Version: 4, ProbePenalty: result.ProbePenalty, + InputCost: cost.InputCost, OutputCost: cost.OutputCost, CacheCreationCost: cost.CacheCreationCost, + CacheReadCost: cost.CacheReadCost, TotalCost: cost.TotalCost, ActualCost: cost.ActualCost, Multiplier: usageLog.RateMultiplier} + } // 计算账号统计定价费用(使用最终上游模型匹配自定义规则)。纯存储费不是一次模型请求, // 账号统计成本回落 total_cost(官方存储价)。 diff --git a/backend/internal/service/usage_billing_delivery.go b/backend/internal/service/usage_billing_delivery.go index b0c54b3853c2..1bb0d75be714 100644 --- a/backend/internal/service/usage_billing_delivery.go +++ b/backend/internal/service/usage_billing_delivery.go @@ -116,6 +116,20 @@ func applyDurableUsageBilling(ctx context.Context, repo DurableUsageBillingRepos if err != nil { return false, err } + if target, ok := ctx.Value(probePenaltyResultKey{}).(*ForwardResult); ok && target != nil { + if recovered == nil || !recovered.Settled { + return false, ErrUsageBillingOutcomeUnknown + } + canonical := recovered.Event.Usage + target.ProbePenalty = nil + if canonical.CustomerCostDetails != nil { + target.ProbePenalty = canonical.CustomerCostDetails.ProbePenalty + } + target.Usage.InputTokens = canonical.InputTokens + target.Usage.OutputTokens = canonical.OutputTokens + target.Usage.CacheReadInputTokens = canonical.CacheReadTokens + target.Usage.CacheCreationInputTokens = canonical.CacheCreationTokens + } auth, _ := p.APIKeyService.(APIKeyAuthCacheInvalidator) if err := invalidateDurableUsageBilling(ctx, recovered, deps.billingCacheService, auth); err != nil { // The committed canonical usage is already authoritative. Cache work diff --git a/docs/features/account-probe-penalty.md b/docs/features/account-probe-penalty.md new file mode 100644 index 000000000000..689813a6914c --- /dev/null +++ b/docs/features/account-probe-penalty.md @@ -0,0 +1,24 @@ +# Claude 账号探针惩罚 + +入口:账号管理 → 编辑一个 Claude(Anthropic)账号 → 探针惩罚。默认关闭,勾选后填写请求最低扣费(站内美元账面额度),例如 `0.001`。配置保存在该账号 `extra.probe_penalty`,不改变分组价卡。 + +```json +{"probe_penalty":{"enabled":true,"minimum_charge":0.001}} +``` + +适用于通过 `/v1/messages`、`/v1/chat/completions`、`/v1/responses` 完成的 Claude 按 Token 请求,支持 JSON 与 SSE;普通短请求也适用,不分析请求正文是否“有意义”。结算在所有售价倍率之后取原价与最低金额的最大值,失败或流中断的请求保持既有部分用量计费。后台原始 Token 和采购成本不增加,客户余额、订阅额度、Key 限额与用量账单共用补差后的结算金额,费用详情显示补差。 + +配置随调度快照同步到本站 gateway,结算复用持久化账单与请求去重。启用账号要求标准运行模式及持久化结算仓库。升级所有接流量节点后再启用;旧二进制不识别该设置。没有数据库迁移,关闭开关即可停止新请求补差,历史账单不回写。 + +## 外部网关 + +低于最低金额的请求在标准 `usage.output_tokens`(Chat 为 `usage.completion_tokens`) 返回计费等效 Token,原始响应用量放在 `upstream_usage`,`billing` 中标记 `usage_kind=billing_equivalent` 和补差回执。等效输出量按本站这次请求实际输出 Token 单价向上取整。本站账单仍记录实际观测的 Token;等效量不是模型生成长度。 + +New API、Sub2API 等按标准 usage 计费的下游可读取增加后的输出量。同样的输入/缓存/输出价卡和倍率下,与本站金额的差额小于一个输出 Token 单价。不同下游定价、重新估算 Token、忽略最终 usage 或按次收费都无法由本站强制统一;需要精确金额时,下游应适配 `billing.probe_penalty.actual_cost`,不要把此金额与等效 Token 重复累加。本功能不承诺未测试的第三方版本兼容。 + +SSE 正文实时转发,末尾 usage 和成功结束事件在本站持久化结算完成后发送;结算结果未知时返回错误,不自动重新请求模型。响应没有完整 usage、定价不能换算为正的输出 Token 单价或等效输出超过 10 亿 Token 时不能生成等效回执,不声称结算成功。非流式响应使用受限临时文件暂存(最大 64 MiB),流式仅暂存末尾事件(最大 1 MiB)。 + +管理员新功能提示 ID:`account-claude-probe-penalty-initial-announcement`。仅账号编辑设置显示;点击关闭后在当前浏览器当前管理员的本地存储中保留。 + + +源码对照:New API `8542c9d6490b4330fe18160930f81ae7428bc777` 的 [Claude 适配器](https://github.com/QuantumNous/new-api/blob/8542c9d6490b4330fe18160930f81ae7428bc777/relay/channel/claude/relay-claude.go) 按最终 `message_delta` 的累计用量覆盖,并在 JSON 路径使用 `usage.output_tokens`;这是源码证据,不代表所有部署版本已运行验证。`TestProbePenaltyDownstreamSub2APIChargesEquivalentUsage` 用两个实际 Sub2API handler 串接,核对本站补差后,下一级三个入口读取标准 usage 并按同价卡计费。 diff --git a/frontend/src/components/account/EditAccountModal.vue b/frontend/src/components/account/EditAccountModal.vue index 78e6b27a81f4..50f80a415ff2 100644 --- a/frontend/src/components/account/EditAccountModal.vue +++ b/frontend/src/components/account/EditAccountModal.vue @@ -2191,6 +2191,7 @@{{ t('admin.accounts.groupBillingRateMultiplierHint') }}
+{{ t('admin.accounts.probePenalty.hint') }}
+ +{{ t('admin.accounts.probePenalty.downstream') }}
+