From 7c517a1a86349b25f9ca6f4307929a3159f9f4cd Mon Sep 17 00:00:00 2001 From: Yunfei He Date: Mon, 30 Nov 2026 10:12:45 +0000 Subject: [PATCH] fix(platform): price Opus input the same in scan limits and estimates --- .../administration/security-audits.md | 4 +- packages/platform/src/security-models.ts | 9 +- .../test/unit/security-models.test.ts | 9 +- .../meta/design-docs/0095-security-audits.md | 14 +-- .../packages/api/src/security/model-proxy.ts | 6 +- .../test/integration/security-spend.test.ts | 92 ++++++++++++++++++- .../api/test/unit/security-budget.test.ts | 2 +- .../test/unit/security-model-proxy.test.ts | 3 +- 8 files changed, 120 insertions(+), 19 deletions(-) diff --git a/docs/guide/platform/administration/security-audits.md b/docs/guide/platform/administration/security-audits.md index 74eba69bb..926524417 100644 --- a/docs/guide/platform/administration/security-audits.md +++ b/docs/guide/platform/administration/security-audits.md @@ -181,11 +181,11 @@ Both caps are off by default. The platform pays for scans separately from a plan Every scan has a spend limit, including when monthly caps are off. To start a scan, Void reserves that amount against the monthly caps that apply. Commands that start scans show it as the estimated cost. -Before each model call, Void estimates what the call costs. If that is more than what is left of the limit, Void refuses the call. The scan ends as incomplete (spend limit reached) and keeps the findings it has confirmed. A call can cost more than its estimate, so a scan can go a little over its limit. +Before each model call, Void estimates what the call costs. If that is more than what is left of the limit, Void refuses the call. The scan ends as incomplete (spend limit reached) and keeps the findings it has confirmed. A call can cost more than its estimate, so a scan can go over its limit. Spending counts cached input at the model's cached price. Only DeepSeek and GLM have one. For the other models, cached input counts at full price. -By default, the limit is the model's list price for the smaller of the input-token limit and 1.2 million tokens, plus the output-token limit. With the default token settings this is $0.504 for DeepSeek, $2.208 for GLM and $7.20 for Opus. The input-token limit counts cached input in full and defaults to 10 million. To set one limit for every model, from $0.01 to $12: +By default, the limit is the model's list price for the smaller of the input-token limit and 1.2 million tokens, plus the output-token limit. For Anthropic models, the limit prices input at 1.25 times the list price, the rate for a 5-minute cache write. With the default token settings this is $0.504 for DeepSeek, $2.208 for GLM and $8.40 for Opus. The input-token limit counts cached input in full and defaults to 10 million. To set one limit for every model, from $0.01 to $12: ```sh void platform security limits --scan-usd 2.50 diff --git a/packages/platform/src/security-models.ts b/packages/platform/src/security-models.ts index 44333d1fe..76ca2eb26 100644 --- a/packages/platform/src/security-models.ts +++ b/packages/platform/src/security-models.ts @@ -220,6 +220,12 @@ export function securityModelCostUsd( return nano === null ? null : nano / 1_000_000_000; } +/** Anthropic's 5-minute cache writes cost 1.25 times the input price. */ +export function securityEstimateInputTokens(id: SecurityModelId, tokens: number): number { + assertTokenCount(tokens, 'tokens'); + return getSecurityModel(id).host === 'anthropic' ? tokens + Math.ceil(tokens / 4) : tokens; +} + /** The amount reserved at scan start in USD, or `null` for an unpriced model. */ export function securityScanReserveUsd( id: SecurityModelId, @@ -232,9 +238,10 @@ export function securityScanReserveUsd( maxOutputTokens: SECURITY_RESERVE_OUTPUT_TOKENS, }, ): number | null { + const inputTokens = Math.min(limits.maxInputTokens, SECURITY_RESERVE_INPUT_TOKENS); const defaultUsd = securityModelCostUsd( id, - Math.min(limits.maxInputTokens, SECURITY_RESERVE_INPUT_TOKENS), + securityEstimateInputTokens(id, inputTokens), limits.maxOutputTokens, ); return defaultUsd === null ? null : (limits.maxScanUsd ?? defaultUsd); diff --git a/packages/platform/test/unit/security-models.test.ts b/packages/platform/test/unit/security-models.test.ts index edbd17a7e..ce169e55a 100644 --- a/packages/platform/test/unit/security-models.test.ts +++ b/packages/platform/test/unit/security-models.test.ts @@ -1,16 +1,19 @@ import { expect, it } from 'vite-plus/test'; import { + securityEstimateInputTokens, securityModelCostNanoUsd, securityModelCostUsd, securityScanReserveUsd, } from '../../src/security-models.ts'; -// I7: a scan reserves its worst case at list price; calls add up in whole nano-dollars. -it('reserves the worst case of a scan and prices calls without drift', () => { +// I7: a scan reserves its estimated cost. Calls add up in whole nano-dollars. +it('estimates the scan reserve and prices calls without drift', () => { expect(securityScanReserveUsd('@cf/zai-org/glm-5.3')).toBe(2.208); expect(securityScanReserveUsd('anthropic/claude-sonnet-5.5')).toBeNull(); const limits = { maxInputTokens: 100_000, maxOutputTokens: 10_000 }; - expect(securityScanReserveUsd('anthropic/claude-opus-5.5', limits)).toBe(0.6); + expect(securityScanReserveUsd('anthropic/claude-opus-5.5', limits)).toBe(0.7); + expect(securityEstimateInputTokens('anthropic/claude-opus-5.5', 25)).toBe(32); + expect(() => securityEstimateInputTokens('anthropic/claude-opus-5.5', 0.5)).toThrow(); let total = 0; for (let call = 0; call < 1000; call += 1) { total += securityModelCostNanoUsd('@cf/zai-org/glm-5.3', 1234, 56)!; diff --git a/platform/meta/design-docs/0095-security-audits.md b/platform/meta/design-docs/0095-security-audits.md index ea55d5735..caa026024 100644 --- a/platform/meta/design-docs/0095-security-audits.md +++ b/platform/meta/design-docs/0095-security-audits.md @@ -298,14 +298,16 @@ Migration `0065_security_audits.sql`, 11 tables in `security/schema.ts`: and scan call caps, token caps, provider-run tools refused (`tool_not_allowed`). - `limits.maxScanUsd` sets the reserve for every scan, including when monthly caps are off. A `null` or missing value uses list price for `min(maxInputTokens, 1_200_000)` and - `maxOutputTokens`. The default raw input cap is 10M. Upgrades keep saved token caps - but lower the automatic reserve for saved caps above 1.2M. + `maxOutputTokens`, at 1.25× the input price for Messages. The default raw input cap is + 10M. Upgrades keep saved token caps. Compared with list price for the whole saved cap, the + automatic reserve for Chat Completions and Responses is lower for caps above 1.2M. For + Messages, it is higher for caps below 1.5M, the same at 1.5M and lower for caps above 1.5M. - Each call holds its estimate on the scan row if it fits the remaining reserve. The estimate prices `ceil(forwarded UTF-8 bytes / 2.5)` input tokens and the call's output allowance at - list price. Both month rows price one input token per forwarded byte and the same output - allowance. Both prices use twice the input price for Messages calls. A call whose estimate - does not fit the scan row the proxy read is refused before it takes a session call or a - `@cf` rate token; the hold checks again on the fresh row. + list price, at 1.25× the input price for Messages. Both month rows price one input token + per forwarded byte and the same output allowance, at 2× the input price for Messages. A call + whose estimate does not fit the scan row the proxy read is refused before it takes a session + call or a `@cf` rate token; the hold checks again on the fresh row. - Settlement replaces each hold with the metered cost, including any cache discounts. Actual costs can take the scan over its limit. A possibly billed call whose usage isn't recorded, including a stream cut off after its usage arrived, adds fallback token counts. diff --git a/platform/packages/api/src/security/model-proxy.ts b/platform/packages/api/src/security/model-proxy.ts index 9a47ff1fe..52a2d9604 100644 --- a/platform/packages/api/src/security/model-proxy.ts +++ b/platform/packages/api/src/security/model-proxy.ts @@ -16,6 +16,7 @@ import { isSecurityModelId, isSecurityModelPriced, SECURITY_PROVIDER_NOTICE_VERSION, + securityEstimateInputTokens, securityModelCostNanoUsd, } from '@void/platform/security-models'; import type { @@ -1074,9 +1075,8 @@ export async function handleSecurityModelRequest( // An Anthropic input token written to the 1 h cache costs 2× input. const inputMultiplier = route === 'messages' ? 2 : 1; const worstNano = securityModelCostNanoUsd(model, worstInput * inputMultiplier, callOutput) ?? 0; - const estimateInput = Math.ceil((worstInput * 2) / 5); - const estimateNano = - securityModelCostNanoUsd(model, estimateInput * inputMultiplier, callOutput) ?? 0; + const estimateInput = securityEstimateInputTokens(model, Math.ceil((worstInput * 2) / 5)); + const estimateNano = securityModelCostNanoUsd(model, estimateInput, callOutput) ?? 0; // A call the scan's spend limit cannot fit is refused before it takes a session call or // a `@cf` rate token. The hold checks again on the fresh row. if (scan.meteredNano + estimateNano > scan.reservedNano) { diff --git a/platform/packages/api/test/integration/security-spend.test.ts b/platform/packages/api/test/integration/security-spend.test.ts index 1a16d1975..1fcf296f9 100644 --- a/platform/packages/api/test/integration/security-spend.test.ts +++ b/platform/packages/api/test/integration/security-spend.test.ts @@ -1,4 +1,7 @@ -import { securityModelCostNanoUsd } from '@void/platform/security-models'; +import { + SECURITY_PROVIDER_NOTICE_VERSION, + securityModelCostNanoUsd, +} from '@void/platform/security-models'; import { defaultSecurityPolicy } from '@void/platform/security-policy'; import type { SecurityPolicy } from '@void/platform/security-policy'; import { and, eq } from 'drizzle-orm'; @@ -22,6 +25,7 @@ import { } from '../../src/security/model-proxy.ts'; import type { SecurityModelProxyDeps } from '../../src/security/model-proxy.ts'; import { changeSecurityPolicy, readSecurityPolicyLenient } from '../../src/security/policy.ts'; +import { passingEntitlement } from '../helpers/security-policy.ts'; import { clearTables, createTestDeployment, @@ -31,10 +35,11 @@ import { teardownEnv, } from './helpers.ts'; import type { TestEnv } from './helpers.ts'; -import { saveSecurityPolicy } from './security-fixtures.ts'; +import { liveProject, saveSecurityPolicy } from './security-fixtures.ts'; const CF = '@cf/zai-org/glm-5.3'; const DEEPSEEK = '@cf/deepseek-ai/deepseek-v4.1-flash-1017'; +const OPUS = 'anthropic/claude-opus-5.5'; const NOV = '2026-11-01'; const NOW = Date.parse('2026-11-18T12:00:00.000Z'); const LEASE = '2026-11-18T13:00:00.000Z'; @@ -321,6 +326,89 @@ describe('model proxy on real SQL', () => { }); } + async function opusCall(tokensIn: number) { + const { owner, project: app, deployment } = await liveProject(env, `opus-${tokensIn}`); + const scanId = `ss_opus_${tokensIn}`; + const { limits } = await savePolicy({ entitlement: passingEntitlement() }); + await env.db.insert(projectSecuritySettings).values({ + project_id: app.id, + provider_notice_version: SECURITY_PROVIDER_NOTICE_VERSION, + provider_notice_at: new Date(NOW).toISOString(), + provider_notice_by_user_id: owner.id, + }); + const reserveNano = securityScanReserveNano(OPUS, limits)!; + await scan(app.id, deployment.id, scanId, { + engine: 'agent_sdk', + model_used: OPUS, + tokens_in: tokensIn, + metered_nano_usd: securityModelCostNanoUsd(OPUS, (tokensIn * 5) / 4, 0)!, + reserved_nano_usd: reserveNano, + }); + + const fetch = vi.fn(async () => + Response.json({ content: [], usage: { input_tokens: 1, output_tokens: 1 } }), + ); + const hold = vi.fn((input) => + holdSecurityModelCall(env.db, input), + ); + const recordFailure = vi.fn(async () => {}); + const request = new Request('http://model.void.internal/v1/messages', { + method: 'POST', + body: JSON.stringify({ + model: OPUS, + messages: [{ role: 'user', content: 'x'.repeat(1_600_000) }], + max_tokens: 128_000, + }), + }); + const response = await handleSecurityModelRequest( + deps({ fetch, hold, recordFailure }), + scanId, + 1, + request, + ); + await response.text(); + const held = hold.mock.calls[0]?.[0]; + const forwarded = fetch.mock.calls[0]?.[1]?.body; + return { + status: response.status, + reason: recordFailure.mock.calls[0]?.[2].reason ?? null, + stop: response.headers.get(SECURITY_STOP_HEADER), + holds: hold.mock.calls.length, + providerCalls: fetch.mock.calls.length, + forwardedBytes: + typeof forwarded === 'string' ? new TextEncoder().encode(forwarded).length : null, + reserveNano, + estimateNano: held?.estimateNano ?? null, + worstNano: held?.worstNano ?? null, + }; + } + + test('allows a fresh Opus scan to send a 1.6 MB call with default limits', async () => { + expect(await opusCall(0)).toMatchObject({ + status: 200, + reason: null, + stop: null, + holds: 1, + providerCalls: 1, + forwardedBytes: 1_600_089, + reserveNano: 8_400_000_000, + estimateNano: 5_600_180_000, + worstNano: 15_200_712_000, + }); + }); + + test('allows an Opus call that exactly fits the default limit, and refuses one over it', async () => { + // The call's 640,036 estimated input tokens bring the first total to exactly 1.2M. + expect(await opusCall(559_964)).toMatchObject({ status: 200, holds: 1, providerCalls: 1 }); + expect(await opusCall(559_968)).toMatchObject({ + status: 429, + reason: 'spend', + stop: 'tokens', + holds: 0, + providerCalls: 0, + }); + }); + test('meters tokens × list price, and a project cap stops the next call that could cross it', async () => { const p = await project('spend-meter'); await scan(p.id, p.deploymentId, 'ss_1', { reserved_nano_usd: 2 * USD }); diff --git a/platform/packages/api/test/unit/security-budget.test.ts b/platform/packages/api/test/unit/security-budget.test.ts index 8ee37a3c0..1ed61659c 100644 --- a/platform/packages/api/test/unit/security-budget.test.ts +++ b/platform/packages/api/test/unit/security-budget.test.ts @@ -58,7 +58,7 @@ it('computes the automatic and explicit scan reserves', () => { } expect(securityScanReserveNano(deepseek, limits)).toBe(504_000_000); expect(securityScanReserveNano('@cf/zai-org/glm-5.3', limits)).toBe(2_208_000_000); - expect(securityScanReserveNano('anthropic/claude-opus-5.5', limits)).toBe(7_200_000_000); + expect(securityScanReserveNano('anthropic/claude-opus-5.5', limits)).toBe(8_400_000_000); expect(securityScanReserveNano('@cf/zai-org/glm-5.3', { ...limits, maxScanUsd: 2.58 })).toBe( 2_580_000_000, ); diff --git a/platform/packages/api/test/unit/security-model-proxy.test.ts b/platform/packages/api/test/unit/security-model-proxy.test.ts index 56eef7c7e..e67533432 100644 --- a/platform/packages/api/test/unit/security-model-proxy.test.ts +++ b/platform/packages/api/test/unit/security-model-proxy.test.ts @@ -384,8 +384,9 @@ describe('third-party calls through AI Gateway REST (I3)', () => { }); expect(body).toEqual({ model: 'claude-opus-5.5', max_tokens: 4096, messages: [] }); const bytes = new TextEncoder().encode(JSON.stringify(body)).byteLength; + const estimatedInput = Math.ceil((bytes * 2) / 5); expect(h.holds[0]).toMatchObject({ - estimateNano: securityModelCostNanoUsd(OPUS, Math.ceil((bytes * 2) / 5) * 2, 4096), + estimateNano: securityModelCostNanoUsd(OPUS, Math.ceil(estimatedInput * 1.25), 4096), worstNano: securityModelCostNanoUsd(OPUS, bytes * 2, 4096), });