model_pricing_resolver_test.go 32 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908
  1. //go:build unit
  2. package service
  3. import (
  4. "context"
  5. "errors"
  6. "testing"
  7. "github.com/stretchr/testify/require"
  8. )
  9. func newTestBillingServiceForResolver() *BillingService {
  10. bs := &BillingService{
  11. fallbackPrices: make(map[string]*ModelPricing),
  12. }
  13. bs.fallbackPrices["claude-sonnet-4"] = &ModelPricing{
  14. InputPricePerToken: 3e-6,
  15. OutputPricePerToken: 15e-6,
  16. CacheCreationPricePerToken: 3.75e-6,
  17. CacheReadPricePerToken: 0.3e-6,
  18. SupportsCacheBreakdown: false,
  19. }
  20. return bs
  21. }
  22. func TestResolve_NoGroupID(t *testing.T) {
  23. bs := newTestBillingServiceForResolver()
  24. r := NewModelPricingResolver(&ChannelService{}, bs)
  25. resolved := r.Resolve(context.Background(), PricingInput{
  26. Model: "claude-sonnet-4",
  27. GroupID: nil,
  28. })
  29. require.NotNil(t, resolved)
  30. require.Equal(t, BillingModeToken, resolved.Mode)
  31. require.NotNil(t, resolved.BasePricing)
  32. require.InDelta(t, 3e-6, resolved.BasePricing.InputPricePerToken, 1e-12)
  33. // BillingService.GetModelPricing uses fallback internally, but resolveBasePricing
  34. // reports "litellm" when GetModelPricing succeeds (regardless of internal source)
  35. require.Equal(t, "litellm", resolved.Source)
  36. }
  37. func TestResolve_UnknownModel(t *testing.T) {
  38. bs := newTestBillingServiceForResolver()
  39. r := NewModelPricingResolver(&ChannelService{}, bs)
  40. resolved := r.Resolve(context.Background(), PricingInput{
  41. Model: "unknown-model-xyz",
  42. GroupID: nil,
  43. })
  44. require.NotNil(t, resolved)
  45. require.Nil(t, resolved.BasePricing)
  46. // Unknown model: GetModelPricing returns error, source is "fallback"
  47. require.Equal(t, "fallback", resolved.Source)
  48. }
  49. func TestGetIntervalPricing_NoIntervals(t *testing.T) {
  50. bs := newTestBillingServiceForResolver()
  51. r := NewModelPricingResolver(&ChannelService{}, bs)
  52. basePricing := &ModelPricing{InputPricePerToken: 5e-6}
  53. resolved := &ResolvedPricing{
  54. Mode: BillingModeToken,
  55. BasePricing: basePricing,
  56. Intervals: nil,
  57. }
  58. result := r.GetIntervalPricing(resolved, 50000)
  59. require.Equal(t, basePricing, result)
  60. }
  61. func TestGetIntervalPricing_MatchesInterval(t *testing.T) {
  62. bs := newTestBillingServiceForResolver()
  63. r := NewModelPricingResolver(&ChannelService{}, bs)
  64. resolved := &ResolvedPricing{
  65. Mode: BillingModeToken,
  66. BasePricing: &ModelPricing{InputPricePerToken: 5e-6},
  67. SupportsCacheBreakdown: true,
  68. Intervals: []PricingInterval{
  69. {MinTokens: 0, MaxTokens: testPtrInt(128000), InputPrice: testPtrFloat64(1e-6), OutputPrice: testPtrFloat64(2e-6)},
  70. {MinTokens: 128000, MaxTokens: nil, InputPrice: testPtrFloat64(3e-6), OutputPrice: testPtrFloat64(6e-6)},
  71. },
  72. }
  73. result := r.GetIntervalPricing(resolved, 50000)
  74. require.NotNil(t, result)
  75. require.InDelta(t, 1e-6, result.InputPricePerToken, 1e-12)
  76. require.InDelta(t, 2e-6, result.OutputPricePerToken, 1e-12)
  77. require.True(t, result.SupportsCacheBreakdown)
  78. result2 := r.GetIntervalPricing(resolved, 200000)
  79. require.NotNil(t, result2)
  80. require.InDelta(t, 3e-6, result2.InputPricePerToken, 1e-12)
  81. }
  82. func TestGetIntervalPricing_NoMatch_FallsBackToBase(t *testing.T) {
  83. bs := newTestBillingServiceForResolver()
  84. r := NewModelPricingResolver(&ChannelService{}, bs)
  85. basePricing := &ModelPricing{InputPricePerToken: 99e-6}
  86. resolved := &ResolvedPricing{
  87. Mode: BillingModeToken,
  88. BasePricing: basePricing,
  89. Intervals: []PricingInterval{
  90. {MinTokens: 10000, MaxTokens: testPtrInt(50000), InputPrice: testPtrFloat64(1e-6)},
  91. },
  92. }
  93. result := r.GetIntervalPricing(resolved, 5000)
  94. require.Equal(t, basePricing, result)
  95. }
  96. func TestGPT56ExplicitZeroCacheWritePriceIsPreserved(t *testing.T) {
  97. bs := &BillingService{}
  98. resolver := NewModelPricingResolver(nil, bs)
  99. zero := 0.0
  100. t.Run("flat channel price", func(t *testing.T) {
  101. resolved := &ResolvedPricing{
  102. Mode: BillingModeToken,
  103. BasePricing: &ModelPricing{
  104. InputPricePerToken: 5e-6,
  105. OutputPricePerToken: 30e-6,
  106. },
  107. }
  108. resolver.applyTokenOverrides(&ChannelModelPricing{CacheWritePrice: &zero}, resolved)
  109. require.True(t, resolved.BasePricing.CacheCreationPriceExplicit)
  110. cost, err := bs.CalculateCostUnified(CostInput{
  111. Model: "gpt-5.6-sol",
  112. Tokens: UsageTokens{CacheCreationTokens: 100},
  113. RateMultiplier: 1,
  114. Resolver: resolver,
  115. Resolved: resolved,
  116. })
  117. require.NoError(t, err)
  118. require.Zero(t, cost.CacheCreationCost)
  119. })
  120. t.Run("interval price", func(t *testing.T) {
  121. pricing := intervalToModelPricing(&PricingInterval{CacheWritePrice: &zero}, &ModelPricing{}, nil)
  122. require.True(t, pricing.CacheCreationPriceExplicit)
  123. cost, err := bs.CalculateCostUnified(CostInput{
  124. Model: "gpt-5.6-sol",
  125. Tokens: UsageTokens{CacheCreationTokens: 100},
  126. RateMultiplier: 1,
  127. Resolver: resolver,
  128. Resolved: &ResolvedPricing{
  129. Mode: BillingModeToken,
  130. BasePricing: pricing,
  131. },
  132. })
  133. require.NoError(t, err)
  134. require.Zero(t, cost.CacheCreationCost)
  135. })
  136. }
  137. func TestGetRequestTierPrice(t *testing.T) {
  138. bs := newTestBillingServiceForResolver()
  139. r := NewModelPricingResolver(&ChannelService{}, bs)
  140. resolved := &ResolvedPricing{
  141. Mode: BillingModePerRequest,
  142. RequestTiers: []PricingInterval{
  143. {TierLabel: "1K", PerRequestPrice: testPtrFloat64(0.04)},
  144. {TierLabel: "2K", PerRequestPrice: testPtrFloat64(0.08)},
  145. },
  146. }
  147. require.InDelta(t, 0.04, r.GetRequestTierPrice(resolved, "1K"), 1e-12)
  148. require.InDelta(t, 0.08, r.GetRequestTierPrice(resolved, "2K"), 1e-12)
  149. require.InDelta(t, 0.0, r.GetRequestTierPrice(resolved, "4K"), 1e-12)
  150. }
  151. func TestGetRequestTierPriceByContext(t *testing.T) {
  152. bs := newTestBillingServiceForResolver()
  153. r := NewModelPricingResolver(&ChannelService{}, bs)
  154. resolved := &ResolvedPricing{
  155. Mode: BillingModePerRequest,
  156. RequestTiers: []PricingInterval{
  157. {MinTokens: 0, MaxTokens: testPtrInt(128000), PerRequestPrice: testPtrFloat64(0.05)},
  158. {MinTokens: 128000, MaxTokens: nil, PerRequestPrice: testPtrFloat64(0.10)},
  159. },
  160. }
  161. require.InDelta(t, 0.05, r.GetRequestTierPriceByContext(resolved, 50000), 1e-12)
  162. require.InDelta(t, 0.10, r.GetRequestTierPriceByContext(resolved, 200000), 1e-12)
  163. }
  164. func TestGetRequestTierPrice_NilPerRequestPrice(t *testing.T) {
  165. bs := newTestBillingServiceForResolver()
  166. r := NewModelPricingResolver(&ChannelService{}, bs)
  167. resolved := &ResolvedPricing{
  168. Mode: BillingModePerRequest,
  169. RequestTiers: []PricingInterval{
  170. {TierLabel: "1K", PerRequestPrice: nil},
  171. },
  172. }
  173. require.InDelta(t, 0.0, r.GetRequestTierPrice(resolved, "1K"), 1e-12)
  174. }
  175. // ===========================================================================
  176. // Channel override tests — exercises applyChannelOverrides via Resolve
  177. // ===========================================================================
  178. // helper: creates a resolver wired to a ChannelService that returns the given
  179. // channel (active, groupID=100, platform=anthropic) with the specified pricing.
  180. func newResolverWithChannel(t *testing.T, pricing []ChannelModelPricing) *ModelPricingResolver {
  181. t.Helper()
  182. const groupID = 100
  183. repo := &mockChannelRepository{
  184. listAllFn: func(_ context.Context) ([]Channel, error) {
  185. return []Channel{{
  186. ID: 1,
  187. Name: "test-channel",
  188. Status: StatusActive,
  189. GroupIDs: []int64{groupID},
  190. ModelPricing: pricing,
  191. }}, nil
  192. },
  193. getGroupPlatformsFn: func(_ context.Context, _ []int64) (map[int64]string, error) {
  194. return map[int64]string{groupID: "anthropic"}, nil
  195. },
  196. }
  197. cs := NewChannelService(repo, nil, nil, nil, nil)
  198. bs := newTestBillingServiceForResolver()
  199. return NewModelPricingResolver(cs, bs)
  200. }
  201. // groupIDPtr returns a pointer to groupID 100 (the test constant).
  202. func groupIDPtr() *int64 { v := int64(100); return &v }
  203. // ---------------------------------------------------------------------------
  204. // 1. Token mode overrides
  205. // ---------------------------------------------------------------------------
  206. func TestResolve_WithChannelOverride_TokenFlat(t *testing.T) {
  207. r := newResolverWithChannel(t, []ChannelModelPricing{{
  208. Platform: "anthropic",
  209. Models: []string{"claude-sonnet-4"},
  210. BillingMode: BillingModeToken,
  211. InputPrice: testPtrFloat64(10e-6),
  212. OutputPrice: testPtrFloat64(50e-6),
  213. }})
  214. resolved := r.Resolve(context.Background(), PricingInput{
  215. Model: "claude-sonnet-4",
  216. GroupID: groupIDPtr(),
  217. })
  218. require.NotNil(t, resolved)
  219. require.Equal(t, BillingModeToken, resolved.Mode)
  220. require.Equal(t, "channel", resolved.Source)
  221. require.NotNil(t, resolved.BasePricing)
  222. require.InDelta(t, 10e-6, resolved.BasePricing.InputPricePerToken, 1e-12)
  223. require.Zero(t, resolved.BasePricing.InputPricePerTokenPriority)
  224. require.InDelta(t, 50e-6, resolved.BasePricing.OutputPricePerToken, 1e-12)
  225. require.Zero(t, resolved.BasePricing.OutputPricePerTokenPriority)
  226. }
  227. func TestResolve_WithChannelOverride_TokenPartialOverride(t *testing.T) {
  228. // Channel only sets InputPrice; OutputPrice should remain from the base (LiteLLM/fallback).
  229. r := newResolverWithChannel(t, []ChannelModelPricing{{
  230. Platform: "anthropic",
  231. Models: []string{"claude-sonnet-4"},
  232. BillingMode: BillingModeToken,
  233. InputPrice: testPtrFloat64(20e-6),
  234. // OutputPrice intentionally nil
  235. }})
  236. resolved := r.Resolve(context.Background(), PricingInput{
  237. Model: "claude-sonnet-4",
  238. GroupID: groupIDPtr(),
  239. })
  240. require.NotNil(t, resolved)
  241. require.Equal(t, "channel", resolved.Source)
  242. require.NotNil(t, resolved.BasePricing)
  243. // InputPrice overridden by channel
  244. require.InDelta(t, 20e-6, resolved.BasePricing.InputPricePerToken, 1e-12)
  245. // OutputPrice kept from base (fallback: 15e-6)
  246. require.InDelta(t, 15e-6, resolved.BasePricing.OutputPricePerToken, 1e-12)
  247. }
  248. func TestResolve_WithChannelOverride_TokenWithIntervals(t *testing.T) {
  249. r := newResolverWithChannel(t, []ChannelModelPricing{{
  250. Platform: "anthropic",
  251. Models: []string{"claude-sonnet-4"},
  252. BillingMode: BillingModeToken,
  253. Intervals: []PricingInterval{
  254. {MinTokens: 0, MaxTokens: testPtrInt(128000), InputPrice: testPtrFloat64(2e-6), OutputPrice: testPtrFloat64(8e-6)},
  255. {MinTokens: 128000, MaxTokens: nil, InputPrice: testPtrFloat64(4e-6), OutputPrice: testPtrFloat64(16e-6)},
  256. },
  257. }})
  258. resolved := r.Resolve(context.Background(), PricingInput{
  259. Model: "claude-sonnet-4",
  260. GroupID: groupIDPtr(),
  261. Group: &Group{LongContextPricingEnabled: false},
  262. })
  263. require.NotNil(t, resolved)
  264. require.Equal(t, "channel", resolved.Source)
  265. require.False(t, resolved.longContextPricingEnabled)
  266. require.Len(t, resolved.Intervals, 2)
  267. // GetIntervalPricing should use channel intervals
  268. iv := r.GetIntervalPricing(resolved, 50000)
  269. require.NotNil(t, iv)
  270. require.InDelta(t, 2e-6, iv.InputPricePerToken, 1e-12)
  271. require.InDelta(t, 8e-6, iv.OutputPricePerToken, 1e-12)
  272. iv2 := r.GetIntervalPricing(resolved, 200000)
  273. require.NotNil(t, iv2)
  274. require.InDelta(t, 4e-6, iv2.InputPricePerToken, 1e-12)
  275. require.InDelta(t, 16e-6, iv2.OutputPricePerToken, 1e-12)
  276. }
  277. func TestResolve_WithChannelOverride_TokenNilBasePricing(t *testing.T) {
  278. // Base pricing is nil (unknown model), channel has flat prices → creates new BasePricing.
  279. r := newResolverWithChannel(t, []ChannelModelPricing{{
  280. Platform: "anthropic",
  281. Models: []string{"unknown-model-xyz"},
  282. BillingMode: BillingModeToken,
  283. InputPrice: testPtrFloat64(7e-6),
  284. OutputPrice: testPtrFloat64(21e-6),
  285. }})
  286. resolved := r.Resolve(context.Background(), PricingInput{
  287. Model: "unknown-model-xyz",
  288. GroupID: groupIDPtr(),
  289. })
  290. require.NotNil(t, resolved)
  291. require.Equal(t, "channel", resolved.Source)
  292. // BasePricing was nil from resolveBasePricing but applyTokenOverrides creates a new one
  293. require.NotNil(t, resolved.BasePricing)
  294. require.InDelta(t, 7e-6, resolved.BasePricing.InputPricePerToken, 1e-12)
  295. require.InDelta(t, 21e-6, resolved.BasePricing.OutputPricePerToken, 1e-12)
  296. }
  297. // ---------------------------------------------------------------------------
  298. // 2. Per-request mode overrides
  299. // ---------------------------------------------------------------------------
  300. func TestResolve_WithChannelOverride_PerRequest(t *testing.T) {
  301. r := newResolverWithChannel(t, []ChannelModelPricing{{
  302. Platform: "anthropic",
  303. Models: []string{"claude-sonnet-4"},
  304. BillingMode: BillingModePerRequest,
  305. PerRequestPrice: testPtrFloat64(0.05),
  306. Intervals: []PricingInterval{
  307. {MinTokens: 0, MaxTokens: testPtrInt(128000), PerRequestPrice: testPtrFloat64(0.03)},
  308. {MinTokens: 128000, MaxTokens: nil, PerRequestPrice: testPtrFloat64(0.10)},
  309. },
  310. }})
  311. resolved := r.Resolve(context.Background(), PricingInput{
  312. Model: "claude-sonnet-4",
  313. GroupID: groupIDPtr(),
  314. })
  315. require.NotNil(t, resolved)
  316. require.Equal(t, BillingModePerRequest, resolved.Mode)
  317. require.Equal(t, "channel", resolved.Source)
  318. require.InDelta(t, 0.05, resolved.DefaultPerRequestPrice, 1e-12)
  319. require.Len(t, resolved.RequestTiers, 2)
  320. // Verify tier lookups
  321. require.InDelta(t, 0.03, r.GetRequestTierPriceByContext(resolved, 50000), 1e-12)
  322. require.InDelta(t, 0.10, r.GetRequestTierPriceByContext(resolved, 200000), 1e-12)
  323. }
  324. func TestResolve_WithChannelOverride_PerRequestNilPrice(t *testing.T) {
  325. // PerRequestPrice nil → DefaultPerRequestPrice stays 0.
  326. r := newResolverWithChannel(t, []ChannelModelPricing{{
  327. Platform: "anthropic",
  328. Models: []string{"claude-sonnet-4"},
  329. BillingMode: BillingModePerRequest,
  330. // PerRequestPrice intentionally nil
  331. Intervals: []PricingInterval{
  332. {MinTokens: 0, MaxTokens: testPtrInt(128000), PerRequestPrice: testPtrFloat64(0.02)},
  333. },
  334. }})
  335. resolved := r.Resolve(context.Background(), PricingInput{
  336. Model: "claude-sonnet-4",
  337. GroupID: groupIDPtr(),
  338. })
  339. require.NotNil(t, resolved)
  340. require.Equal(t, BillingModePerRequest, resolved.Mode)
  341. require.InDelta(t, 0.0, resolved.DefaultPerRequestPrice, 1e-12)
  342. require.Len(t, resolved.RequestTiers, 1)
  343. }
  344. // ---------------------------------------------------------------------------
  345. // 3. Image mode overrides
  346. // ---------------------------------------------------------------------------
  347. func TestResolve_WithChannelOverride_Image(t *testing.T) {
  348. r := newResolverWithChannel(t, []ChannelModelPricing{{
  349. Platform: "anthropic",
  350. Models: []string{"claude-sonnet-4"},
  351. BillingMode: BillingModeImage,
  352. PerRequestPrice: testPtrFloat64(0.08),
  353. Intervals: []PricingInterval{
  354. {TierLabel: "1K", PerRequestPrice: testPtrFloat64(0.04)},
  355. {TierLabel: "2K", PerRequestPrice: testPtrFloat64(0.08)},
  356. {TierLabel: "4K", PerRequestPrice: testPtrFloat64(0.16)},
  357. },
  358. }})
  359. resolved := r.Resolve(context.Background(), PricingInput{
  360. Model: "claude-sonnet-4",
  361. GroupID: groupIDPtr(),
  362. })
  363. require.NotNil(t, resolved)
  364. require.Equal(t, BillingModeImage, resolved.Mode)
  365. require.Equal(t, "channel", resolved.Source)
  366. require.InDelta(t, 0.08, resolved.DefaultPerRequestPrice, 1e-12)
  367. require.Len(t, resolved.RequestTiers, 3)
  368. }
  369. func TestResolve_WithChannelOverride_ImageTierLabels(t *testing.T) {
  370. r := newResolverWithChannel(t, []ChannelModelPricing{{
  371. Platform: "anthropic",
  372. Models: []string{"claude-sonnet-4"},
  373. BillingMode: BillingModeImage,
  374. Intervals: []PricingInterval{
  375. {TierLabel: "1K", PerRequestPrice: testPtrFloat64(0.04)},
  376. {TierLabel: "2K", PerRequestPrice: testPtrFloat64(0.08)},
  377. {TierLabel: "4K", PerRequestPrice: testPtrFloat64(0.16)},
  378. },
  379. }})
  380. resolved := r.Resolve(context.Background(), PricingInput{
  381. Model: "claude-sonnet-4",
  382. GroupID: groupIDPtr(),
  383. })
  384. require.InDelta(t, 0.04, r.GetRequestTierPrice(resolved, "1K"), 1e-12)
  385. require.InDelta(t, 0.08, r.GetRequestTierPrice(resolved, "2K"), 1e-12)
  386. require.InDelta(t, 0.16, r.GetRequestTierPrice(resolved, "4K"), 1e-12)
  387. require.InDelta(t, 0.0, r.GetRequestTierPrice(resolved, "8K"), 1e-12) // not found
  388. }
  389. // ---------------------------------------------------------------------------
  390. // 4. Source tracking & default mode
  391. // ---------------------------------------------------------------------------
  392. func TestResolve_WithChannelOverride_SourceIsChannel(t *testing.T) {
  393. r := newResolverWithChannel(t, []ChannelModelPricing{{
  394. Platform: "anthropic",
  395. Models: []string{"claude-sonnet-4"},
  396. BillingMode: BillingModeToken,
  397. InputPrice: testPtrFloat64(1e-6),
  398. }})
  399. resolved := r.Resolve(context.Background(), PricingInput{
  400. Model: "claude-sonnet-4",
  401. GroupID: groupIDPtr(),
  402. })
  403. require.Equal(t, "channel", resolved.Source)
  404. }
  405. func TestResolve_WithChannelOverride_DefaultMode(t *testing.T) {
  406. // Channel pricing with empty BillingMode → defaults to BillingModeToken.
  407. r := newResolverWithChannel(t, []ChannelModelPricing{{
  408. Platform: "anthropic",
  409. Models: []string{"claude-sonnet-4"},
  410. BillingMode: "", // intentionally empty
  411. InputPrice: testPtrFloat64(5e-6),
  412. }})
  413. resolved := r.Resolve(context.Background(), PricingInput{
  414. Model: "claude-sonnet-4",
  415. GroupID: groupIDPtr(),
  416. })
  417. require.Equal(t, "channel", resolved.Source)
  418. require.Equal(t, BillingModeToken, resolved.Mode)
  419. require.NotNil(t, resolved.BasePricing)
  420. require.InDelta(t, 5e-6, resolved.BasePricing.InputPricePerToken, 1e-12)
  421. }
  422. // ---------------------------------------------------------------------------
  423. // 5. GetIntervalPricing integration after channel override
  424. // ---------------------------------------------------------------------------
  425. func TestGetIntervalPricing_WithChannelIntervals(t *testing.T) {
  426. // Channel provides intervals that override the base pricing path.
  427. r := newResolverWithChannel(t, []ChannelModelPricing{{
  428. Platform: "anthropic",
  429. Models: []string{"claude-sonnet-4"},
  430. BillingMode: BillingModeToken,
  431. Intervals: []PricingInterval{
  432. {MinTokens: 0, MaxTokens: testPtrInt(100000), InputPrice: testPtrFloat64(1e-6), OutputPrice: testPtrFloat64(5e-6)},
  433. {MinTokens: 100000, MaxTokens: nil, InputPrice: testPtrFloat64(2e-6), OutputPrice: testPtrFloat64(10e-6)},
  434. },
  435. }})
  436. resolved := r.Resolve(context.Background(), PricingInput{
  437. Model: "claude-sonnet-4",
  438. GroupID: groupIDPtr(),
  439. })
  440. // Token count 50000 matches first interval
  441. pricing := r.GetIntervalPricing(resolved, 50000)
  442. require.NotNil(t, pricing)
  443. require.InDelta(t, 1e-6, pricing.InputPricePerToken, 1e-12)
  444. require.InDelta(t, 5e-6, pricing.OutputPricePerToken, 1e-12)
  445. // Token count 150000 matches second interval
  446. pricing2 := r.GetIntervalPricing(resolved, 150000)
  447. require.NotNil(t, pricing2)
  448. require.InDelta(t, 2e-6, pricing2.InputPricePerToken, 1e-12)
  449. require.InDelta(t, 10e-6, pricing2.OutputPricePerToken, 1e-12)
  450. }
  451. func TestGetIntervalPricing_ChannelIntervalsNoMatch(t *testing.T) {
  452. // Channel intervals don't match token count → falls back to BasePricing.
  453. r := newResolverWithChannel(t, []ChannelModelPricing{{
  454. Platform: "anthropic",
  455. Models: []string{"claude-sonnet-4"},
  456. BillingMode: BillingModeToken,
  457. InputPrice: testPtrFloat64(4e-6),
  458. Intervals: []PricingInterval{
  459. // Only covers tokens > 50000
  460. {MinTokens: 50000, MaxTokens: testPtrInt(200000), InputPrice: testPtrFloat64(9e-6)},
  461. },
  462. }})
  463. resolved := r.Resolve(context.Background(), PricingInput{
  464. Model: "claude-sonnet-4",
  465. GroupID: groupIDPtr(),
  466. })
  467. // Token count 1000 doesn't match any interval (1000 <= 50000 minTokens)
  468. pricing := r.GetIntervalPricing(resolved, 1000)
  469. // Should fall back to BasePricing after applying the channel default.
  470. require.NotNil(t, pricing)
  471. require.Equal(t, resolved.BasePricing, pricing)
  472. require.InDelta(t, 4e-6, pricing.InputPricePerToken, 1e-12)
  473. }
  474. // ===========================================================================
  475. // 6. Error path tests
  476. // ===========================================================================
  477. func TestResolve_WithChannelOverride_CacheError(t *testing.T) {
  478. // When ListAll returns an error, the ChannelService cache build fails.
  479. // Resolve should gracefully fall back to base pricing without panicking.
  480. repo := &mockChannelRepository{
  481. listAllFn: func(_ context.Context) ([]Channel, error) {
  482. return nil, errors.New("database unavailable")
  483. },
  484. }
  485. cs := NewChannelService(repo, nil, nil, nil, nil)
  486. bs := newTestBillingServiceForResolver()
  487. r := NewModelPricingResolver(cs, bs)
  488. gid := int64(100)
  489. resolved := r.Resolve(context.Background(), PricingInput{
  490. Model: "claude-sonnet-4",
  491. GroupID: &gid,
  492. })
  493. require.NotNil(t, resolved)
  494. // Should NOT panic, should NOT have source "channel"
  495. require.NotEqual(t, "channel", resolved.Source)
  496. // Base pricing should still be present (from BillingService fallback)
  497. require.NotNil(t, resolved.BasePricing)
  498. require.InDelta(t, 3e-6, resolved.BasePricing.InputPricePerToken, 1e-12)
  499. }
  500. // ===========================================================================
  501. // 7. GetRequestTierPriceByContext boundary tests
  502. // ===========================================================================
  503. func TestGetRequestTierPriceByContext_EmptyTiers(t *testing.T) {
  504. bs := newTestBillingServiceForResolver()
  505. r := NewModelPricingResolver(&ChannelService{}, bs)
  506. resolved := &ResolvedPricing{
  507. Mode: BillingModePerRequest,
  508. RequestTiers: nil, // empty
  509. }
  510. price := r.GetRequestTierPriceByContext(resolved, 50000)
  511. require.InDelta(t, 0.0, price, 1e-12)
  512. // Also test with explicit empty slice
  513. resolved2 := &ResolvedPricing{
  514. Mode: BillingModePerRequest,
  515. RequestTiers: []PricingInterval{},
  516. }
  517. price2 := r.GetRequestTierPriceByContext(resolved2, 50000)
  518. require.InDelta(t, 0.0, price2, 1e-12)
  519. }
  520. func TestGetRequestTierPriceByContext_ExactBoundary(t *testing.T) {
  521. bs := newTestBillingServiceForResolver()
  522. r := NewModelPricingResolver(&ChannelService{}, bs)
  523. resolved := &ResolvedPricing{
  524. Mode: BillingModePerRequest,
  525. RequestTiers: []PricingInterval{
  526. {MinTokens: 0, MaxTokens: testPtrInt(128000), PerRequestPrice: testPtrFloat64(0.05)},
  527. {MinTokens: 128000, MaxTokens: nil, PerRequestPrice: testPtrFloat64(0.10)},
  528. },
  529. }
  530. // totalContextTokens = 128000 exactly:
  531. // FindMatchingInterval checks: totalTokens > MinTokens && totalTokens <= MaxTokens
  532. // For first interval: 128000 > 0 (true) && 128000 <= 128000 (true) → matches first interval
  533. price := r.GetRequestTierPriceByContext(resolved, 128000)
  534. require.InDelta(t, 0.05, price, 1e-12)
  535. // totalContextTokens = 128001 should match second interval
  536. // For first interval: 128001 > 0 (true) && 128001 <= 128000 (false) → no match
  537. // For second interval: 128001 > 128000 (true) && MaxTokens == nil → matches
  538. price2 := r.GetRequestTierPriceByContext(resolved, 128001)
  539. require.InDelta(t, 0.10, price2, 1e-12)
  540. }
  541. // ===========================================================================
  542. // 8. filterValidIntervals
  543. // ===========================================================================
  544. func TestFilterValidIntervals(t *testing.T) {
  545. tests := []struct {
  546. name string
  547. intervals []PricingInterval
  548. wantLen int
  549. }{
  550. {
  551. name: "empty list",
  552. intervals: nil,
  553. wantLen: 0,
  554. },
  555. {
  556. name: "all-nil interval filtered out",
  557. intervals: []PricingInterval{
  558. {MinTokens: 0, MaxTokens: testPtrInt(128000)},
  559. },
  560. wantLen: 0,
  561. },
  562. {
  563. name: "interval with only InputPrice kept",
  564. intervals: []PricingInterval{
  565. {MinTokens: 0, MaxTokens: testPtrInt(128000), InputPrice: testPtrFloat64(1e-6)},
  566. },
  567. wantLen: 1,
  568. },
  569. {
  570. name: "interval with only OutputPrice kept",
  571. intervals: []PricingInterval{
  572. {MinTokens: 0, MaxTokens: testPtrInt(128000), OutputPrice: testPtrFloat64(2e-6)},
  573. },
  574. wantLen: 1,
  575. },
  576. {
  577. name: "interval with only CacheWritePrice kept",
  578. intervals: []PricingInterval{
  579. {MinTokens: 0, CacheWritePrice: testPtrFloat64(3e-6)},
  580. },
  581. wantLen: 1,
  582. },
  583. {
  584. name: "interval with only CacheReadPrice kept",
  585. intervals: []PricingInterval{
  586. {MinTokens: 0, CacheReadPrice: testPtrFloat64(0.5e-6)},
  587. },
  588. wantLen: 1,
  589. },
  590. {
  591. name: "interval with only PerRequestPrice kept",
  592. intervals: []PricingInterval{
  593. {TierLabel: "1K", PerRequestPrice: testPtrFloat64(0.04)},
  594. },
  595. wantLen: 1,
  596. },
  597. {
  598. name: "interval with only multiplier kept",
  599. intervals: []PricingInterval{
  600. {MinTokens: 272000, InputMultiplier: testPtrFloat64(2)},
  601. },
  602. wantLen: 1,
  603. },
  604. {
  605. name: "mixed valid and invalid",
  606. intervals: []PricingInterval{
  607. {MinTokens: 0, MaxTokens: testPtrInt(128000), InputPrice: testPtrFloat64(1e-6)},
  608. {MinTokens: 128000, MaxTokens: nil}, // all-nil → filtered out
  609. {MinTokens: 256000, OutputPrice: testPtrFloat64(5e-6)},
  610. },
  611. wantLen: 2,
  612. },
  613. }
  614. for _, tt := range tests {
  615. t.Run(tt.name, func(t *testing.T) {
  616. result := filterValidIntervals(tt.intervals)
  617. require.Len(t, result, tt.wantLen)
  618. })
  619. }
  620. }
  621. // ===========================================================================
  622. // 9. ImageOutputPriceExplicit tests
  623. // ===========================================================================
  624. func TestApplyTokenOverrides_FlatSetsImageOutputPriceExplicit(t *testing.T) {
  625. r := newResolverWithChannel(t, []ChannelModelPricing{{
  626. Platform: "anthropic",
  627. Models: []string{"claude-sonnet-4"},
  628. BillingMode: BillingModeToken,
  629. InputPrice: testPtrFloat64(3e-6),
  630. OutputPrice: testPtrFloat64(15e-6),
  631. // ImageOutputPrice intentionally nil
  632. }})
  633. resolved := r.Resolve(context.Background(), PricingInput{
  634. Model: "claude-sonnet-4",
  635. GroupID: groupIDPtr(),
  636. })
  637. require.Equal(t, PricingSourceChannel, resolved.Source)
  638. require.True(t, resolved.BasePricing.ImageOutputPriceExplicit)
  639. require.Equal(t, 0.0, resolved.BasePricing.ImageOutputPricePerToken)
  640. }
  641. func TestApplyTokenOverrides_FlatWithImageOutputPriceSetsExplicit(t *testing.T) {
  642. r := newResolverWithChannel(t, []ChannelModelPricing{{
  643. Platform: "anthropic",
  644. Models: []string{"claude-sonnet-4"},
  645. BillingMode: BillingModeToken,
  646. InputPrice: testPtrFloat64(3e-6),
  647. OutputPrice: testPtrFloat64(15e-6),
  648. ImageOutputPrice: testPtrFloat64(50e-6),
  649. }})
  650. resolved := r.Resolve(context.Background(), PricingInput{
  651. Model: "claude-sonnet-4",
  652. GroupID: groupIDPtr(),
  653. })
  654. require.True(t, resolved.BasePricing.ImageOutputPriceExplicit)
  655. require.InDelta(t, 50e-6, resolved.BasePricing.ImageOutputPricePerToken, 1e-12)
  656. }
  657. func TestApplyTokenOverrides_IntervalSetsImageOutputPriceExplicit(t *testing.T) {
  658. r := newResolverWithChannel(t, []ChannelModelPricing{{
  659. Platform: "anthropic",
  660. Models: []string{"claude-sonnet-4"},
  661. BillingMode: BillingModeToken,
  662. // No ImageOutputPrice
  663. Intervals: []PricingInterval{
  664. {MinTokens: 0, MaxTokens: testPtrInt(100000), InputPrice: testPtrFloat64(3e-6), OutputPrice: testPtrFloat64(15e-6)},
  665. },
  666. }})
  667. resolved := r.Resolve(context.Background(), PricingInput{
  668. Model: "claude-sonnet-4",
  669. GroupID: groupIDPtr(),
  670. })
  671. // BasePricing should have explicit mark (for interval fallback)
  672. require.True(t, resolved.BasePricing.ImageOutputPriceExplicit)
  673. require.Equal(t, 0.0, resolved.BasePricing.ImageOutputPricePerToken)
  674. // intervalToModelPricing should also have explicit mark
  675. pricing := r.GetIntervalPricing(resolved, 50000)
  676. require.True(t, pricing.ImageOutputPriceExplicit)
  677. require.Equal(t, 0.0, pricing.ImageOutputPricePerToken)
  678. }
  679. // ===========================================================================
  680. // 10. Regression: channel overrides must not pollute fallbackPrices
  681. // ===========================================================================
  682. // TestApplyTokenOverrides_FlatDoesNotPolluteFallbackPrices verifies that the
  683. // flat-override path in applyTokenOverrides clones the BasePricing struct
  684. // before mutation, so the shared fallbackPrices map entry is not written through.
  685. func TestApplyTokenOverrides_FlatDoesNotPolluteFallbackPrices(t *testing.T) {
  686. r := newResolverWithChannel(t, []ChannelModelPricing{{
  687. Platform: "anthropic",
  688. Models: []string{"claude-sonnet-4"},
  689. BillingMode: BillingModeToken,
  690. InputPrice: testPtrFloat64(10e-6), // base is 3e-6
  691. OutputPrice: testPtrFloat64(50e-6), // base is 15e-6
  692. }})
  693. resolved := r.Resolve(context.Background(), PricingInput{
  694. Model: "claude-sonnet-4",
  695. GroupID: groupIDPtr(),
  696. })
  697. // Resolved pricing should reflect the channel override
  698. require.NotNil(t, resolved)
  699. require.InDelta(t, 10e-6, resolved.BasePricing.InputPricePerToken, 1e-12)
  700. require.InDelta(t, 50e-6, resolved.BasePricing.OutputPricePerToken, 1e-12)
  701. // Global fallbackPrices must NOT be polluted
  702. fp := r.billingService.fallbackPrices["claude-sonnet-4"]
  703. require.InDelta(t, 3e-6, fp.InputPricePerToken, 1e-12, "fallback InputPricePerToken polluted")
  704. require.InDelta(t, 15e-6, fp.OutputPricePerToken, 1e-12, "fallback OutputPricePerToken polluted")
  705. require.False(t, fp.ImageOutputPriceExplicit, "fallback ImageOutputPriceExplicit polluted")
  706. }
  707. // TestApplyTokenOverrides_IntervalDoesNotPolluteFallbackPrices verifies that
  708. // the interval-override path also clones before mutation.
  709. func TestApplyTokenOverrides_IntervalDoesNotPolluteFallbackPrices(t *testing.T) {
  710. r := newResolverWithChannel(t, []ChannelModelPricing{{
  711. Platform: "anthropic",
  712. Models: []string{"claude-sonnet-4"},
  713. BillingMode: BillingModeToken,
  714. Intervals: []PricingInterval{
  715. {MinTokens: 0, MaxTokens: testPtrInt(100000), InputPrice: testPtrFloat64(2e-6), OutputPrice: testPtrFloat64(8e-6)},
  716. },
  717. }})
  718. resolved := r.Resolve(context.Background(), PricingInput{
  719. Model: "claude-sonnet-4",
  720. GroupID: groupIDPtr(),
  721. })
  722. require.NotNil(t, resolved)
  723. require.True(t, resolved.BasePricing.ImageOutputPriceExplicit)
  724. // Global fallbackPrices must NOT be polluted
  725. fp := r.billingService.fallbackPrices["claude-sonnet-4"]
  726. require.InDelta(t, 3e-6, fp.InputPricePerToken, 1e-12, "fallback InputPricePerToken polluted")
  727. require.InDelta(t, 15e-6, fp.OutputPricePerToken, 1e-12, "fallback OutputPricePerToken polluted")
  728. require.False(t, fp.ImageOutputPriceExplicit, "fallback ImageOutputPriceExplicit polluted")
  729. }
  730. func TestResolve_GroupPricingOverridesChannel(t *testing.T) {
  731. r := newResolverWithChannel(t, []ChannelModelPricing{{
  732. Platform: "anthropic", Models: []string{"claude-sonnet-4"}, BillingMode: BillingModeToken,
  733. InputPrice: testPtrFloat64(10e-6), OutputPrice: testPtrFloat64(20e-6),
  734. }})
  735. group := &Group{ID: 100, ModelPricing: []ChannelModelPricing{{
  736. Models: []string{"claude-sonnet-*"}, BillingMode: BillingModeToken,
  737. InputPrice: testPtrFloat64(1e-6), OutputPrice: testPtrFloat64(2e-6),
  738. }}}
  739. resolved := r.Resolve(context.Background(), PricingInput{Model: "claude-sonnet-4", GroupID: groupIDPtr(), Group: group})
  740. require.Equal(t, PricingSourceGroup, resolved.Source)
  741. require.InDelta(t, 1e-6, resolved.BasePricing.InputPricePerToken, 1e-12)
  742. require.InDelta(t, 2e-6, resolved.BasePricing.OutputPricePerToken, 1e-12)
  743. }
  744. func TestResolve_GroupLongContextUsesPresetNotCustomIntervals(t *testing.T) {
  745. bs := newTestBillingServiceForResolver()
  746. bs.fallbackPrices["claude-sonnet-4"].LongContextInputThreshold = 200000
  747. bs.fallbackPrices["claude-sonnet-4"].LongContextThresholdInclusive = true
  748. bs.fallbackPrices["claude-sonnet-4"].LongContextInputMultiplier = 2
  749. bs.fallbackPrices["claude-sonnet-4"].LongContextOutputMultiplier = 2
  750. r := NewModelPricingResolver(nil, bs)
  751. group := &Group{ID: 100, ModelPricing: []ChannelModelPricing{{
  752. Models: []string{"claude-sonnet-4"}, BillingMode: BillingModeToken,
  753. InputPrice: testPtrFloat64(1e-6), OutputPrice: testPtrFloat64(2e-6),
  754. Intervals: []PricingInterval{
  755. {MinTokens: 0, MaxTokens: testPtrInt(200000), InputPrice: testPtrFloat64(9e-6)},
  756. {MinTokens: 200000, InputPrice: testPtrFloat64(18e-6)},
  757. },
  758. }}}
  759. resolved := r.Resolve(context.Background(), PricingInput{Model: "claude-sonnet-4", Group: group})
  760. require.False(t, resolved.longContextPricingEnabled)
  761. require.Empty(t, resolved.Intervals, "group token intervals are not a user-facing long-context ladder")
  762. require.InDelta(t, 1e-6, r.GetIntervalPricing(resolved, 300000).InputPricePerToken, 1e-12)
  763. require.Equal(t, 200000, resolved.BasePricing.LongContextInputThreshold)
  764. group.LongContextPricingEnabled = true
  765. resolved = r.Resolve(context.Background(), PricingInput{Model: "claude-sonnet-4", Group: group})
  766. require.True(t, resolved.longContextPricingEnabled)
  767. require.Empty(t, resolved.Intervals)
  768. require.InDelta(t, 1e-6, r.GetIntervalPricing(resolved, 300000).InputPricePerToken, 1e-12)
  769. require.Equal(t, 200000, resolved.BasePricing.LongContextInputThreshold)
  770. require.InDelta(t, 2.0, resolved.BasePricing.LongContextInputMultiplier, 1e-12)
  771. }
  772. func TestCalculateCostUnified_UsesContinuousMediaUnits(t *testing.T) {
  773. bs := newTestBillingServiceForResolver()
  774. r := NewModelPricingResolver(nil, bs)
  775. price := 0.08
  776. group := &Group{ModelPricing: []ChannelModelPricing{{
  777. Models: []string{"grok-voice-think-fast-2.0"}, BillingMode: BillingModePerRequest,
  778. PerRequestPrice: &price,
  779. }}}
  780. cost, err := bs.CalculateCostUnified(CostInput{
  781. Ctx: context.Background(), Model: "grok-voice-think-fast-2.0", Group: group,
  782. UsageUnits: 1.5, RateMultiplier: 1, Resolver: r,
  783. })
  784. require.NoError(t, err)
  785. require.InDelta(t, 0.12, cost.TotalCost, 1e-12)
  786. }