:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
fix(llma): keep a vendor's own promotion at the served price (#93722)
Brandon0d5f5c42485d
diff --git a/nodejs/src/ingestion/pipelines/ai/costs/scripts/update-ai-costs.test.ts b/nodejs/src/ingestion/pipelines/ai/costs/scripts/update-ai-costs.test.tsindex 8f027530b5d7..876f0c097461 100644--- a/nodejs/src/ingestion/pipelines/ai/costs/scripts/update-ai-costs.test.ts+++ b/nodejs/src/ingestion/pipelines/ai/costs/scripts/update-ai-costs.test.ts@@ -2,6 +2,7 @@ import fs from 'fs'import path from 'path'import { parseJSON } from '~/common/utils/json-parse'+import { normalizeProviderKey } from '~/ingestion/pipelines/ai/costs/provider-matching'import type { ModelCost } from '~/ingestion/pipelines/ai/costs/providers/types'import {@@ -11,18 +12,23 @@ import {type DiscountReportEntry,type EndpointCandidate,FLAT_FEE_FIELDS,+ MODEL_NAMESPACE_VENDORS,OPTIONAL_PRICING_FIELDS,+ type RouteRate,type RunTotals,UNCHECKED_WARN_FRACTION,accumulateModelRow,- buildDefaultCost,buildModelCost,buildModelRow,+ buildServedCost,collectModelRows,confirmDiscountAgainstSiblings,fetchOpenRouterCosts,finalizeTotals,foldModelIntoTotals,+ hasNoRefuter,+ isFirstPartyRoute,+ isVendorPromotion,parseDiscountRate,readEndpointsFromOpenRouter,renderDiscountReport,@@ -40,10 +46,14 @@ const cost = (promptPrice: string, discount = 0, completion = promptPrice): Retureturn built}-const candidate = (key: string, promptPrice: string, discount: number): EndpointCandidate => ({+const candidate = (key: string, promptPrice: string, discount: number, vendorPromotion = false): EndpointCandidate => ({key,cost: cost(promptPrice, discount)!,discount,+ vendorPromotion,+ unrefutable: false,+ servedPrompt: undefined,+ listPrompt: undefined,})/** An endpoints-payload entry shaped the way OpenRouter serves it. */@@ -137,15 +147,167 @@ describe('withoutDiscount()', () => {})})-describe('buildDefaultCost()', () => {+describe('isFirstPartyRoute()', () => {+ it.each<{ description: string; model: string; key: string; expected: boolean }>([+ { description: 'the vendor route itself', model: 'openai/gpt-5.6-luna', key: 'openai', expected: true },+ { description: 'a vendor service tier', model: 'openai/gpt-5.6-luna', key: 'openai-flex', expected: true },+ {+ description: "the vendor's other hosting arm",+ model: 'google/gemini-3.7-flash',+ key: 'google-vertex-global',+ expected: true,+ },+ {+ description: 'a batch variant of the model',+ model: 'google/x:batch',+ key: 'google-ai-studio',+ expected: true,+ },+ { description: 'a vendor aliased to another name', model: 'qwen/qwen-plus', key: 'alibaba', expected: true },+ { description: 'a hyphenated vendor alias', model: 'x-ai/grok-5', key: 'xai-priority', expected: true },+ { description: 'a reseller', model: 'google/gemini-3.7-flash', key: 'novita-fp8', expected: false },+ { description: 'the vendor of a different model', model: 'qwen/qwen-plus', key: 'qwen', expected: false },+ { description: 'a reseller sharing the vendor prefix', model: 'openai/o5', key: 'openaint', expected: false },+ { description: 'an id with no namespace', model: 'gpt-5.6-luna', key: 'openai', expected: false },+ // Without the separator guard the whole id is read as its own vendor, and+ // this is the shape where that returns true instead of false.+ { description: 'a slug-only id that looks like a vendor', model: 'openai-x', key: 'openai', expected: false },+ ])('$description', ({ model, key, expected }) => {+ expect(isFirstPartyRoute(model, key)).toBe(expected)+ })++ it('holds the alias table already normalized on both sides', () => {+ // Neither side is normalized on lookup, so an entry that is not already+ // in key form never matches and reverts that vendor to de-discounting.+ for (const [namespace, vendor] of Object.entries(MODEL_NAMESPACE_VENDORS)) {+ expect(normalizeProviderKey(namespace)).toBe(namespace)+ expect(normalizeProviderKey(vendor)).toBe(vendor)+ }+ })++ it('maps every alias onto a vendor that hosts most of its own namespace', () => {+ // Binds the table to the price book rather than to itself. Mere presence+ // is too weak: resellers appear on other vendors' namespaces too, and+ // `qwen: 'together'` would pass that. A vendor hosts the bulk of its own+ // models (80-100% live) where a reseller reaches a third at most.+ const book: Array<{ model: string; cost: Record<string, unknown> }> = parseJSON(+ fs.readFileSync(path.join(__dirname, '../providers/llm-costs.json'), 'utf8')+ )++ let checked = 0+ for (const [namespace, vendor] of Object.entries(MODEL_NAMESPACE_VENDORS)) {+ const models = book.filter((row) => row.model.startsWith(`${namespace}/`))+ // A namespace the catalogue drops makes its entry inert, not wrong.+ if (models.length === 0) {+ continue+ }+ const hosted = models.filter((row) =>+ Object.keys(row.cost).some((key) => key === vendor || key.startsWith(`${vendor}-`))+ )+ expect(hosted.length / models.length).toBeGreaterThan(0.5)+ checked += 1+ }+ expect(checked).toBeGreaterThan(0)+ })+})++describe('isVendorPromotion()', () => {+ // Prices default well clear of any list price a case builds, so a case only+ // exercises the price refutation when it sets them.+ const route = (discount: number, firstParty: boolean, servedPrompt = 7e-7): RouteRate => ({+ discount,+ firstParty,+ servedPrompt,+ listPrompt: discount === 0 ? servedPrompt : parseFloat((servedPrompt / (1 - discount)).toPrecision(10)),+ })++ it.each<{ description: string; subject: RouteRate; routes: RouteRate[]; expected: boolean }>([+ {+ description: 'holds when only the vendor runs the rate',+ subject: route(0.5, true),+ routes: [route(0.5, true), route(0, false)],+ expected: true,+ },+ {+ description: 'fails when an unrelated host runs the same rate',+ subject: route(0.5, true),+ routes: [route(0.5, true), route(0.5, false)],+ expected: false,+ },+ {+ description: 'ignores an unrelated host on a different rate',+ subject: route(0.5, true),+ routes: [route(0.5, true), route(0.2, false)],+ expected: true,+ },+ {+ // 4e-8 / 0.2 is 2.0000000000000004e-7 in float, so this matches only+ // because both sides round first. Pins that rounding.+ description: 'refutes on a price whose division is inexact',+ subject: route(0.8, true, 4e-8),+ routes: [route(0.8, true, 4e-8), route(0, false, 2e-7)],+ expected: false,+ },+ {+ // A negative rate is a markup: the served price sits above list, and+ // dividing it out is what recovers list.+ description: 'never holds for a markup',+ subject: route(-0.2, true),+ routes: [route(-0.2, true)],+ expected: false,+ },+ {+ description: 'fails when de-discounting lands on an undiscounted price',+ // minimax-m2 live: the vendor's 0.15 divides out to exactly what two+ // undiscounted hosts charge, so the rate is a markdown off a real list.+ subject: route(0.15, true, 2.55e-7),+ routes: [route(0.15, true, 2.55e-7), route(0, false, 3e-7)],+ expected: false,+ },+ {+ description: 'ignores an undiscounted host at a different price',+ subject: route(0.15, true, 2.55e-7),+ routes: [route(0.15, true, 2.55e-7), route(0, false, 9e-7)],+ expected: true,+ },+ {+ description: 'never holds for a reseller route',+ subject: route(0.5, false),+ routes: [route(0.5, false)],+ expected: false,+ },+ {+ // Sole route on purpose: a second route would refute this on its own.+ description: 'never holds without a rate',+ subject: route(0, true),+ routes: [route(0, true)],+ expected: false,+ },+ ])('$description', ({ subject, routes, expected }) => {+ expect(isVendorPromotion(subject, routes)).toBe(expected)+ })++ it('holds on a vendor-only model, where nothing can refute it', () => {+ // gemini-3.7-flash is this shape: every route is Google's, so both+ // refutations scan an empty set. `hasNoRefuter` marks it in the report.+ const routes = [route(0.5, true), route(0.5, true, 3.5e-7)]+ expect(isVendorPromotion(routes[0], routes)).toBe(true)+ expect(hasNoRefuter(routes)).toBe(true)+ // An undiscounted route could refute on price even when it is the vendor's own.+ expect(hasNoRefuter([route(0.5, true), route(0, true)])).toBe(false)+ expect(hasNoRefuter([route(0.5, true), route(0.5, false)])).toBe(false)+ })+})++describe('buildServedCost()', () => {it('keeps the served price when the list payload carries a rate', () => {- expect(buildDefaultCost({ prompt: '0.0000005', completion: '0.000003', discount: 0.5 })!.prompt_token).toBe(+ expect(buildServedCost({ prompt: '0.0000005', completion: '0.000003', discount: 0.5 })!.prompt_token).toBe(0.0000005)})it('behaves like the plain builder when there is no rate', () => {- expect(buildDefaultCost({ prompt: '0.000001', completion: '0.000006' })).toEqual({+ expect(buildServedCost({ prompt: '0.000001', completion: '0.000006' })).toEqual({prompt_token: 0.000001,completion_token: 0.000006,})@@ -326,13 +488,13 @@ describe('buildModelRow()', () => {expect(Object.keys(built!.cost)).toStrictEqual(['default'])})- it('stores each endpoint at its de-discounted list price', () => {+ it('stores each reseller endpoint at its de-discounted list price', () => {const built = buildModelRow('openai/gpt-5.6-luna', listPricing, [- endpoint('openai', '0.0000005', 0.5),+ endpoint('novita-fp8', '0.0000005', 0.5),endpoint('azure', '0.000001'),])expect(built!.checked).toBe(true)- expect(built!.cost.openai.prompt_token).toBe(0.000001)+ expect(built!.cost['novita-fp8'].prompt_token).toBe(0.000001)expect(built!.cost.azure.prompt_token).toBe(0.000001)})@@ -346,12 +508,22 @@ describe('buildModelRow()', () => {it('reports the discounted endpoints and the confirmation verdict', () => {const built = buildModelRow('openai/gpt-5.6-luna', listPricing, [- endpoint('openai', '0.0000005', 0.5),+ endpoint('novita-fp8', '0.0000005', 0.5),endpoint('azure', '0.000001'),])expect(built!.discount).toEqual({model: 'openai/gpt-5.6-luna',- endpoints: [{ key: 'openai', discount: 0.5, confirmation: 'confirmed' as const }],+ endpoints: [+ {+ key: 'novita-fp8',+ discount: 0.5,+ confirmation: 'confirmed' as const,+ vendorPromotion: false,+ unrefutable: false,+ servedPrompt: 5e-7,+ listPrompt: 0.000001,+ },+ ],})})@@ -369,11 +541,66 @@ describe('buildModelRow()', () => {})it('reports not-checkable when no undiscounted sibling exists', () => {- // Every Qwen model: Alibaba is the only route, so nothing corroborates it.- const built = buildModelRow('qwen/qwen-plus', listPricing, [endpoint('alibaba-fp8', '0.000000169', 0.35)])+ // Reseller tag on purpose: a vendor route would keep its promotion instead.+ const built = buildModelRow('qwen/qwen-plus', listPricing, [endpoint('novita-fp8', '0.000000169', 0.35)])expect(built!.discount?.endpoints[0].confirmation).toBe('not-checkable')})+ it('leaves a vendor-run promotion at the price the vendor serves', () => {+ const built = buildModelRow('google/gemini-3.7-flash', listPricing, [+ endpoint('google-ai-studio', '0.0000005', 0.5),+ endpoint('google-vertex-global', '0.0000005', 0.5),+ ])+ expect(built!.cost['google-ai-studio'].prompt_token).toBe(0.0000005)+ expect(built!.cost['google-vertex-global'].prompt_token).toBe(0.0000005)+ expect(built!.discount?.endpoints.map((e) => [e.key, e.confirmation])).toEqual([+ ['google-ai-studio', 'not-applicable'],+ ['google-vertex-global', 'not-applicable'],+ ])+ })++ it('de-discounts a vendor route when unrelated hosts run the same rate', () => {+ // One rate across unrelated hosts is OpenRouter promoting the model, so+ // the vendor's route goes to list with the rest.+ const built = buildModelRow('z-ai/glm-5.3-flash', listPricing, [+ endpoint('z-ai-fp8', '0.000000075', 0.5),+ endpoint('novita-fp8', '0.000000075', 0.5),+ endpoint('deepinfra-fp8', '0.000000075', 0.5),+ endpoint('together', '0.00000015'),+ ])+ expect(built!.cost['z-ai-fp8'].prompt_token).toBe(1.5e-7)+ expect(built!.cost['novita-fp8'].prompt_token).toBe(1.5e-7)+ expect(built!.discount?.endpoints[0].confirmation).toBe('confirmed')+ })++ it('de-discounts a vendor route whose recovered price an undiscounted host charges', () => {+ // minimax-m2 live: 0.15 off 2.55e-7 recovers 3e-7, which two undiscounted+ // hosts charge outright, so the rate is a markdown and not MiniMax's promo.+ const built = buildModelRow('minimax/minimax-m2', listPricing, [+ endpoint('minimax-fp8', '0.000000255', 0.15),+ endpoint('novita-fp8', '0.0000003'),+ ])+ expect(built!.cost['minimax-fp8'].prompt_token).toBe(3e-7)+ expect(built!.discount?.endpoints[0].confirmation).toBe('confirmed')+ })++ it('marks a vendor-only model as having nothing that could refute it', () => {+ const built = buildModelRow('google/gemini-3.7-flash', listPricing, [+ endpoint('google-ai-studio', '0.0000005', 0.5),+ ])+ expect(built!.cost['google-ai-studio'].prompt_token).toBe(0.0000005)+ expect(built!.discount?.endpoints[0].unrefutable).toBe(true)+ })++ it('keeps a vendor promotion when a reseller runs a different rate', () => {+ const built = buildModelRow('openai/gpt-5.6-luna', listPricing, [+ endpoint('openai', '0.0000005', 0.5),+ endpoint('novita-fp8', '0.0000008', 0.2),+ ])+ expect(built!.cost.openai.prompt_token).toBe(0.0000005)+ expect(built!.cost['novita-fp8'].prompt_token).toBe(0.000001)+ })+it('warns once, naming the model, on an out-of-range rate', () => {// Parsed twice per endpoint; a second warn would be unattributable.const warn = jest.spyOn(console, 'warn').mockImplementation(() => {})@@ -420,6 +647,15 @@ describe('confirmDiscountAgainstSiblings()', () => {expect(confirmDiscountAgainstSiblings(openai, [openai, candidate('azure', '0.000001', 0)])).toBe('confirmed')})+ it('has nothing to corroborate for a route that kept its promotion', () => {+ // The matching sibling stays: without the guard it reads as corroborating+ // a division that never ran.+ const openai = candidate('openai', '0.0000005', 0.5, true)+ expect(confirmDiscountAgainstSiblings(openai, [openai, candidate('azure', '0.000001', 0)])).toBe(+ 'not-applicable'+ )+ })+it('reports unconfirmed when the recovered price matches no sibling', () => {const openai = candidate('openai', '0.0000005', 0.5)expect(confirmDiscountAgainstSiblings(openai, [openai, candidate('azure', '0.000009', 0)])).toBe('unconfirmed')@@ -439,11 +675,19 @@ describe('confirmDiscountAgainstSiblings()', () => {key: 'openai',cost: buildModelCost({ prompt: '0.0000005', completion: '0.000009', discount: 0.5 })!,discount: 0.5,+ vendorPromotion: false,+ unrefutable: false,+ servedPrompt: undefined,+ listPrompt: undefined,}const sibling: EndpointCandidate = {key: 'azure',cost: buildModelCost({ prompt: '0.000001', completion: '0.000002' })!,discount: 0,+ vendorPromotion: false,+ unrefutable: false,+ servedPrompt: undefined,+ listPrompt: undefined,}expect(confirmDiscountAgainstSiblings(discounted, [discounted, sibling])).toBe('confirmed')})@@ -486,7 +730,17 @@ describe('sanitizeReportCell()', () => {describe('renderDiscountReport()', () => {const entry = (over: Partial<DiscountReportEntry> = {}): DiscountReportEntry => ({model: 'openai/gpt-5.6-luna',- endpoints: [{ key: 'openai', discount: 0.5, confirmation: 'confirmed' as const }],+ endpoints: [+ {+ key: 'openai',+ discount: 0.5,+ confirmation: 'confirmed' as const,+ vendorPromotion: false,+ unrefutable: false,+ servedPrompt: undefined,+ listPrompt: undefined,+ },+ ],...over,})@@ -526,13 +780,39 @@ describe('renderDiscountReport()', () => {entry(),entry({model: 'aaa/unconfirmed',- endpoints: [{ key: 'openai', discount: 0.5, confirmation: 'unconfirmed' as const }],+ endpoints: [+ {+ key: 'openai',+ discount: 0.5,+ confirmation: 'unconfirmed' as const,+ vendorPromotion: false,+ unrefutable: false,+ servedPrompt: undefined,+ listPrompt: undefined,+ },+ ],}),entry({model: 'qwen/qwen-plus',endpoints: [- { key: 'alibaba-fp8', discount: 0.35, confirmation: 'not-checkable' as const },- { key: 'streamlake', discount: 0.4, confirmation: 'not-checkable' as const },+ {+ key: 'alibaba-fp8',+ discount: 0.35,+ confirmation: 'not-checkable' as const,+ vendorPromotion: false,+ unrefutable: false,+ servedPrompt: undefined,+ listPrompt: undefined,+ },+ {+ key: 'streamlake',+ discount: 0.4,+ confirmation: 'not-checkable' as const,+ vendorPromotion: false,+ unrefutable: false,+ servedPrompt: undefined,+ listPrompt: undefined,+ },],}),])@@ -541,9 +821,81 @@ describe('renderDiscountReport()', () => {expect(report).toContain('1/2 checkable')})+ it('attributes a kept promotion to the vendor, not to OpenRouter', () => {+ // Without the vendorPromotion filters the headline claims 3 endpoints on+ // 2 models and the ratio reads 1/2, crediting routes nothing corroborated.+ const report = renderDiscountReport([+ entry(),+ entry({+ model: 'google/gemini-3.7-flash',+ endpoints: [+ {+ key: 'google-ai-studio',+ discount: 0.5,+ confirmation: 'not-applicable' as const,+ vendorPromotion: true,+ unrefutable: true,+ servedPrompt: 7.5e-7,+ listPrompt: 1.5e-6,+ },+ {+ key: 'google-vertex-global',+ discount: 0.5,+ confirmation: 'not-applicable' as const,+ vendorPromotion: true,+ unrefutable: false,+ servedPrompt: undefined,+ listPrompt: undefined,+ },+ ],+ }),+ ])+ expect(report).toContain('**1 endpoint(s)**')+ expect(report).toContain('**1 model(s)**')+ expect(report).toContain('1/1 checkable')+ expect(report).toContain('**2 endpoint(s)**')+ expect(report).toContain('**1** of those had no route that could have refuted')+ expect(report).toContain('| `google-ai-studio` | 50% | served (unrefuted) | $0.75 vs $1.5 | not-applicable |')+ expect(report).toContain('| `google-vertex-global` | 50% | served | | not-applicable |')+ })++ it('reads what was stored off the flag, not off the verdict', () => {+ // The two agree in production. Held apart here so a regression back to+ // deriving `Stored` from the enum cannot pass.+ const report = renderDiscountReport([+ entry({+ endpoints: [+ {+ key: 'openai',+ discount: 0.5,+ confirmation: 'not-applicable' as const,+ vendorPromotion: false,+ unrefutable: false,+ servedPrompt: undefined,+ listPrompt: undefined,+ },+ ],+ }),+ ])+ expect(report).toContain('| 50% | list |')+ expect(report).toContain('**1 endpoint(s)**')+ })+it('puts the confirmation verdict on the row it belongs to', () => {const report = renderDiscountReport([- entry({ endpoints: [{ key: 'openai', discount: 0.5, confirmation: 'unconfirmed' as const }] }),+ entry({+ endpoints: [+ {+ key: 'openai',+ discount: 0.5,+ confirmation: 'unconfirmed' as const,+ vendorPromotion: false,+ unrefutable: false,+ servedPrompt: undefined,+ listPrompt: undefined,+ },+ ],+ }),])expect(report).toContain('| unconfirmed |')})@@ -552,8 +904,24 @@ describe('renderDiscountReport()', () => {const report = renderDiscountReport([entry({endpoints: [- { key: 'openai', discount: 0.5, confirmation: 'confirmed' as const },- { key: 'openai-flex', discount: 0.5, confirmation: 'confirmed' as const },+ {+ key: 'openai',+ discount: 0.5,+ confirmation: 'confirmed' as const,+ vendorPromotion: false,+ unrefutable: false,+ servedPrompt: undefined,+ listPrompt: undefined,+ },+ {+ key: 'openai-flex',+ discount: 0.5,+ confirmation: 'confirmed' as const,+ vendorPromotion: false,+ unrefutable: false,+ servedPrompt: undefined,+ listPrompt: undefined,+ },],}),])@@ -581,6 +949,10 @@ describe('renderDiscountReport()', () => {key: `k${e}`,discount: 0.5,confirmation: 'confirmed' as const,+ vendorPromotion: false,+ unrefutable: false,+ servedPrompt: undefined,+ listPrompt: undefined,})),}))@@ -619,7 +991,17 @@ describe('renderDiscountReport()', () => {// Sanitized separately from the model id, so it needs its own input.const report = renderDiscountReport([entry({- endpoints: [{ key: 'a|b\n| pwned | 9 | 9 |', discount: 0.5, confirmation: 'confirmed' as const }],+ endpoints: [+ {+ key: 'a|b\n| pwned | 9 | 9 |',+ discount: 0.5,+ confirmation: 'confirmed' as const,+ vendorPromotion: false,+ unrefutable: false,+ servedPrompt: undefined,+ listPrompt: undefined,+ },+ ],}),])expect(report).not.toContain('pwned | 9 | 9 |')@@ -648,7 +1030,17 @@ describe('accumulateModelRow()', () => {it('collects a discount entry when the row reports one', () => {const discount = {model: 'm',- endpoints: [{ key: 'openai', discount: 0.5, confirmation: 'confirmed' as const }],+ endpoints: [+ {+ key: 'openai',+ discount: 0.5,+ confirmation: 'confirmed' as const,+ vendorPromotion: false,+ unrefutable: false,+ servedPrompt: undefined,+ listPrompt: undefined,+ },+ ],}expect(accumulateModelRow(built({ discount }), 'm', totals()).discounts).toStrictEqual([discount])})@@ -671,7 +1063,17 @@ describe('accumulateModelRow()', () => {const base = totals()const discount: DiscountReportEntry = {model: 'a',- endpoints: [{ key: 'openai', discount: 0.5, confirmation: 'confirmed' }],+ endpoints: [+ {+ key: 'openai',+ discount: 0.5,+ confirmation: 'confirmed',+ vendorPromotion: false,+ unrefutable: false,+ servedPrompt: undefined,+ listPrompt: undefined,+ },+ ],}accumulateModelRow(built({ checked: false, discount }), 'a', base)expect(base.models).toHaveLength(0)@@ -979,7 +1381,17 @@ describe('writeOutputs()', () => {const writes = captureWrites()const promo: DiscountReportEntry = {model: 'openai/gpt-5.6-luna',- endpoints: [{ key: 'openai', discount: 0.5, confirmation: 'confirmed' }],+ endpoints: [+ {+ key: 'openai',+ discount: 0.5,+ confirmation: 'confirmed',+ vendorPromotion: false,+ unrefutable: false,+ servedPrompt: undefined,+ listPrompt: undefined,+ },+ ],}writeOutputs([{ model: 'm', cost: { default: cost('0.000001')! } }], [promo], 0)diff --git a/nodejs/src/ingestion/pipelines/ai/costs/scripts/update-ai-costs.ts b/nodejs/src/ingestion/pipelines/ai/costs/scripts/update-ai-costs.tsindex bf96bcf947ba..ec06c779864a 100644--- a/nodejs/src/ingestion/pipelines/ai/costs/scripts/update-ai-costs.ts+++ b/nodejs/src/ingestion/pipelines/ai/costs/scripts/update-ai-costs.ts@@ -100,8 +100,73 @@ export const withoutDiscount = (pricing: Record<string, unknown> | undefined): Rreturn rest}-/** `default` must stay at the served price whatever the list payload carries. */-export const buildDefaultCost = (+/** Route vendors OpenRouter names differently from the namespace it files their+ * models under; a namespace absent here matches its own name. Not+ * `PROVIDER_ALIASES`: that resolves `$ai_provider` onto one canonical key, where+ * `google` means `google-ai-studio` and would miss `google-vertex-*`. */+export const MODEL_NAMESPACE_VENDORS: Record<string, string> = {+ 'bytedance-seed': 'seed',+ mistralai: 'mistral',+ qwen: 'alibaba',+ rekaai: 'reka',+ 'x-ai': 'xai',+}++/** True when the model's own vendor operates the route. */+export const isFirstPartyRoute = (modelId: string, providerKey: string): boolean => {+ const separator = modelId.indexOf('/')+ if (separator < 0) {+ return false+ }++ const vendor = normalizeProviderKey(modelId.slice(0, separator))+ const routeVendor = MODEL_NAMESPACE_VENDORS[vendor] ?? vendor+ // Hyphen-anchored, so `google` claims `google-vertex` but `openai` cannot+ // claim a reseller that merely starts with those letters.+ return providerKey === routeVendor || providerKey.startsWith(`${routeVendor}-`)+}++export interface RouteRate {+ discount: number+ firstParty: boolean+ /** Prompt price as served, and where dividing the rate out would put it.+ * Undefined when the feed's price does not parse, which corroborates nothing. */+ servedPrompt: number | undefined+ listPrompt: number | undefined+}++/** Where dividing a rate out puts a price. Shared with `buildModelCost` so a+ * corroboration check compares against the number that actually gets stored. */+const toListPrice = (value: number, discount: number): number =>+ discount === 0 ? value : parseFloat((value / (1 - discount)).toPrecision(10))++/** True when a rate is the vendor's own promotion, which its direct callers pay+ * too, so the route keeps the served price. Two things refute it: an unrelated+ * operator on the same rate, which makes the promotion OpenRouter's; and a+ * de-discounted price landing on an undiscounted route, which proves the+ * division recovers a list price somebody still charges. */+export const isVendorPromotion = (route: RouteRate, routes: RouteRate[]): boolean => {+ if (!route.firstParty || route.discount <= 0) {+ return false+ }++ if (routes.some((other) => !other.firstParty && other.discount === route.discount)) {+ return false+ }++ return !routes.some(+ (other) => other.discount === 0 && other.servedPrompt !== undefined && other.servedPrompt === route.listPrompt+ )+}++/** True when no route could have satisfied either refutation above: none outside+ * the vendor to carry the rate, and none undiscounted to carry the price. The+ * verdict then stands on the vendor's word alone. */+export const hasNoRefuter = (routes: RouteRate[]): boolean =>+ !routes.some((route) => !route.firstParty || route.discount === 0)++/** Keeps a cost at the price OpenRouter serves, promotion included. */+export const buildServedCost = (modelPricing: Record<string, unknown> | undefined,context?: string): ModelCost | null => buildModelCost(withoutDiscount(modelPricing), context)@@ -119,18 +184,16 @@ export const buildModelCost = (pricing: Record<string, unknown> | undefined, con}const discount = parseDiscountRate(pricing, context)- const toListPrice = (value: number): number =>- discount === 0 ? value : parseFloat((value / (1 - discount)).toPrecision(10))const cost: ModelCost = {- prompt_token: toListPrice(promptToken),- completion_token: toListPrice(completionToken),+ prompt_token: toListPrice(promptToken, discount),+ completion_token: toListPrice(completionToken, discount),}for (const [targetField, sourceField] of OPTIONAL_PRICING_FIELDS) {const parsedValue = parsePricingNumber(pricing[sourceField])if (parsedValue !== undefined && parsedValue !== 0) {- cost[targetField] = FLAT_FEE_FIELDS.has(targetField) ? parsedValue : toListPrice(parsedValue)+ cost[targetField] = FLAT_FEE_FIELDS.has(targetField) ? parsedValue : toListPrice(parsedValue, discount)}}@@ -141,6 +204,13 @@ export interface EndpointCandidate {key: stringcost: ModelCostdiscount: number+ vendorPromotion: boolean+ /** True when nothing in the model could have refuted `vendorPromotion`. */+ unrefutable: boolean+ /** Served price and where dividing the rate out would put it, carried so the+ * report can show a reader the spread it asks them to check. */+ servedPrompt: number | undefined+ listPrompt: number | undefined}/*@@ -150,7 +220,7 @@ export interface EndpointCandidate {* two readers needs an `openrouter` key in `CanonicalProvider` first.*/-export type DiscountConfirmation = 'confirmed' | 'unconfirmed' | 'not-checkable'+export type DiscountConfirmation = 'confirmed' | 'unconfirmed' | 'not-checkable' | 'not-applicable'/** Corroborates one route's de-discount against an undiscounted sibling. Per* route, or a verdict rolled up across a model's routes gets displayed against@@ -160,6 +230,11 @@ export const confirmDiscountAgainstSiblings = (candidate: EndpointCandidate,candidates: EndpointCandidate[]): DiscountConfirmation => {+ // A route stored at its served price had nothing divided out to corroborate.+ if (candidate.vendorPromotion) {+ return 'not-applicable'+ }+const undiscounted = candidates.filter((other) => other.discount === 0)if (candidate.discount === 0 || undiscounted.length === 0) {return 'not-checkable'@@ -173,7 +248,17 @@ export const confirmDiscountAgainstSiblings = (export interface DiscountReportEntry {model: string- endpoints: Array<{ key: string; discount: number; confirmation: DiscountConfirmation }>+ endpoints: Array<{+ key: string+ discount: number+ confirmation: DiscountConfirmation+ /** What was stored, carried rather than read back off the verdict: the+ * report is the only audit surface for these prices. */+ vendorPromotion: boolean+ unrefutable: boolean+ servedPrompt: number | undefined+ listPrompt: number | undefined+ }>}/** Share of the catalogue that may go unchecked before the run says so loudly. */@@ -182,6 +267,16 @@ export const UNCHECKED_WARN_FRACTION = 0.1/** Table rows rendered before the remainder collapses into a count line. */export const DISCOUNT_REPORT_ROW_LIMIT = 200+/** Served price against the one dividing the rate out recovers, per million+ * tokens. Only kept routes get it: the reader has to judge those by hand. */+const renderSpread = (endpoint: DiscountReportEntry['endpoints'][number]): string => {+ if (!endpoint.vendorPromotion || endpoint.servedPrompt === undefined || endpoint.listPrompt === undefined) {+ return ''+ }+ const perMillion = (value: number): string => `$${parseFloat((value * 1e6).toPrecision(6))}`+ return `${perMillion(endpoint.servedPrompt)} vs ${perMillion(endpoint.listPrompt)}`+}+/** Confines a third-party string to inert text in one table cell. An allowlist,* because a denylist has to anticipate every markdown construct that renders. */export const sanitizeReportCell = (value: string): string =>@@ -204,10 +299,18 @@ export const renderDiscountReport = (entries: DiscountReportEntry[], uncheckedMo}const rows = [...entries].sort((a, b) => a.model.localeCompare(b.model))- const verdicts = rows.map((row) => row.endpoints.map((e) => e.confirmation))+ // Routes that kept their promotion would pad the denominator with nothing+ // reconstructed.+ const verdicts = rows.map((row) => row.endpoints.filter((e) => !e.vendorPromotion).map((e) => e.confirmation))const confirmed = verdicts.filter((v) => v.includes('confirmed')).lengthconst checkable = verdicts.filter((v) => v.some((c) => c !== 'not-checkable')).length- const endpointCount = rows.reduce((total, row) => total + row.endpoints.length, 0)++ const allEndpoints = rows.flatMap((row) => row.endpoints)+ const kept = allEndpoints.filter((e) => e.vendorPromotion)+ // The platform's own promotions: a vendor's is not OpenRouter running one.+ const endpointCount = allEndpoints.length - kept.length+ const modelCount = rows.filter((row) => row.endpoints.some((e) => !e.vendorPromotion)).length+ const unrefuted = kept.filter((e) => e.unrefutable).lengthconst flatFeeList = [...FLAT_FEE_FIELDS].sort()@@ -217,18 +320,24 @@ export const renderDiscountReport = (entries: DiscountReportEntry[], uncheckedMoconst lines = ['## Discounts','',- `OpenRouter is running a promotion on **${endpointCount} endpoint(s)** across **${rows.length} model(s)**.`,- 'Per-provider keys below are stored at list rate, with the promotion divided back',+ `OpenRouter is running a promotion on **${endpointCount} endpoint(s)** across **${modelCount} model(s)**.`,+ 'Reseller keys below are stored at list rate, with the promotion divided back','out, so a provider key keeps meaning what that provider charges a direct caller.',`Per-call fees (${flatFeeList}) carry across untouched: promotional routes in`,'the feed serve `web_search` at the same fee as their undiscounted siblings,','and every other per-call fee follows the same policy.',- 'The `default` key is left as OpenRouter serves it.',+ '',+ `The \`default\` key is left as OpenRouter serves it, and so are **${kept.length} endpoint(s)**`,+ 'marked `served` below, where the model vendor runs the route and neither an',+ 'unrelated operator on the same rate nor an undiscounted sibling price',+ `contradicts it. **${unrefuted}** of those had no route that could have refuted`,+ "either way, so they stand on the vendor's word: the spread column gives the",+ 'served and recovered prices to check against the vendor’s own pricing page.','',`Independently confirmed against an undiscounted sibling route: ${confirmed}/${checkable} checkable model(s).`,unchecked,- '| Model | Endpoint | Rate | Confirmed |',- '| --- | --- | --- | --- |',+ '| Model | Endpoint | Rate | Stored | Spread /1M | Confirmed |',+ '| --- | --- | --- | --- | --- | --- |',]// Bounded on emitted rows, not models: the widest model carries 32 endpoints,@@ -243,8 +352,9 @@ export const renderDiscountReport = (entries: DiscountReportEntry[], uncheckedMofor (const [index, endpoint] of row.endpoints.entries()) {const model = index === 0 ? sanitizeReportCell(row.model) : ''const confirmation = endpoint.confirmation+ const stored = endpoint.vendorPromotion ? (endpoint.unrefutable ? 'served (unrefuted)' : 'served') : 'list'lines.push(- `| ${model} | \`${sanitizeReportCell(endpoint.key)}\` | ${Math.round(endpoint.discount * 100)}% | ${confirmation} |`+ `| ${model} | \`${sanitizeReportCell(endpoint.key)}\` | ${Math.round(endpoint.discount * 100)}% | ${stored} | ${renderSpread(endpoint)} | ${confirmation} |`)}emitted += row.endpoints.length@@ -275,34 +385,59 @@ export const buildModelRow = (modelPricing: Record<string, unknown> | undefined,endpoints: unknown[]): BuiltModelRow | null => {- const defaultCost = buildDefaultCost(modelPricing, modelId)+ const defaultCost = buildServedCost(modelPricing, modelId)if (!defaultCost) {return null}const cost: Record<string, ModelCost> = { default: defaultCost }const candidates: EndpointCandidate[] = []- for (const raw of endpoints) {+ // Rates are read across every route before any cost is built: whether a+ // vendor's own rate is its promotion depends on who else is running it.+ const routes = endpoints.map((raw) => {const endpoint = (raw ?? {}) as { tag?: string; provider_name?: string; pricing?: Record<string, unknown> }- const context = `${modelId} (${endpoint.tag ?? '?'})`- const endpointCost = buildModelCost(endpoint.pricing, context)- if (!endpointCost) {- continue- }-const providerKey = endpointProviderKey(endpoint)// Normalized too: every key here is interpolated into canonical-providers.ts// as a string literal, so it must be [a-z0-9-] by construction.- const safeProviderKey =+ const key =providerKey && providerKey !== 'default'? providerKey: `provider-${normalizeProviderKey(endpoint.provider_name ?? 'unknown') || 'unknown'}`+ const context = `${modelId} (${endpoint.tag ?? '?'})`+ // Silent here; the builder below warns on whatever it is handed.+ const discount = parseDiscountRate(endpoint.pricing ?? {}, context, false)+ const servedPrompt = parsePricingNumber(endpoint.pricing?.prompt)+ return {+ endpoint,+ key,+ context,+ discount,+ firstParty: isFirstPartyRoute(modelId, key),+ servedPrompt,+ listPrompt: servedPrompt === undefined ? undefined : toListPrice(servedPrompt, discount),+ }+ })++ const unrefutable = hasNoRefuter(routes)++ for (const route of routes) {+ const vendorPromotion = isVendorPromotion(route, routes)+ const endpointCost = vendorPromotion+ ? buildServedCost(route.endpoint.pricing, route.context)+ : buildModelCost(route.endpoint.pricing, route.context)+ if (!endpointCost) {+ continue+ }- cost[safeProviderKey] = endpointCost+ cost[route.key] = endpointCostcandidates.push({- key: safeProviderKey,+ key: route.key,cost: endpointCost,- discount: parseDiscountRate(endpoint.pricing ?? {}, context, false),+ discount: route.discount,+ vendorPromotion,+ unrefutable,+ servedPrompt: route.servedPrompt,+ listPrompt: route.listPrompt,})}@@ -324,6 +459,10 @@ export const buildModelRow = (key: candidate.key,discount: candidate.discount,confirmation: confirmDiscountAgainstSiblings(candidate, candidates),+ vendorPromotion: candidate.vendorPromotion,+ unrefutable: candidate.unrefutable,+ servedPrompt: candidate.servedPrompt,+ listPrompt: candidate.listPrompt,})),}: undefined,