tiered_settle_test.go 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401
  1. package service
  2. import (
  3. "testing"
  4. "github.com/QuantumNous/new-api/pkg/billingexpr"
  5. relaycommon "github.com/QuantumNous/new-api/relay/common"
  6. )
  7. // Claude Sonnet-style tiered expression: standard vs long-context
  8. const sonnetTieredExpr = `p <= 200000 ? tier("standard", p * 1.5 + c * 7.5) : tier("long_context", p * 3 + c * 11.25)`
  9. // Simple flat expression
  10. const flatExpr = `tier("default", p * 2 + c * 10)`
  11. // Expression with cache tokens
  12. const cacheExpr = `tier("default", p * 2 + c * 10 + cr * 0.2 + cc * 2.5 + cc1h * 4)`
  13. // Expression with request probes
  14. const probeExpr = `param("service_tier") == "fast" ? tier("fast", p * 4 + c * 20) : tier("normal", p * 2 + c * 10)`
  15. func makeSnapshot(expr string, groupRatio float64, estPrompt, estCompletion int) *billingexpr.BillingSnapshot {
  16. return &billingexpr.BillingSnapshot{
  17. BillingMode: "tiered_expr",
  18. ExprString: expr,
  19. ExprHash: billingexpr.ExprHashString(expr),
  20. GroupRatio: groupRatio,
  21. EstimatedPromptTokens: estPrompt,
  22. EstimatedCompletionTokens: estCompletion,
  23. }
  24. }
  25. func makeRelayInfo(expr string, groupRatio float64, estPrompt, estCompletion int) *relaycommon.RelayInfo {
  26. snap := makeSnapshot(expr, groupRatio, estPrompt, estCompletion)
  27. cost, trace, _ := billingexpr.RunExpr(expr, billingexpr.TokenParams{P: float64(estPrompt), C: float64(estCompletion)})
  28. snap.EstimatedQuotaBeforeGroup = cost
  29. snap.EstimatedQuotaAfterGroup = billingexpr.QuotaRound(cost * groupRatio)
  30. snap.EstimatedTier = trace.MatchedTier
  31. return &relaycommon.RelayInfo{
  32. TieredBillingSnapshot: snap,
  33. FinalPreConsumedQuota: snap.EstimatedQuotaAfterGroup,
  34. }
  35. }
  36. // ---------------------------------------------------------------------------
  37. // Existing tests (preserved)
  38. // ---------------------------------------------------------------------------
  39. func TestTryTieredSettleUsesFrozenRequestInput(t *testing.T) {
  40. exprStr := `param("service_tier") == "fast" ? tier("fast", p * 2) : tier("normal", p)`
  41. relayInfo := &relaycommon.RelayInfo{
  42. TieredBillingSnapshot: &billingexpr.BillingSnapshot{
  43. BillingMode: "tiered_expr",
  44. ExprString: exprStr,
  45. ExprHash: billingexpr.ExprHashString(exprStr),
  46. GroupRatio: 1.0,
  47. EstimatedPromptTokens: 100,
  48. EstimatedCompletionTokens: 0,
  49. EstimatedQuotaAfterGroup: 100,
  50. },
  51. BillingRequestInput: &billingexpr.RequestInput{
  52. Body: []byte(`{"service_tier":"fast"}`),
  53. },
  54. }
  55. ok, quota, result := TryTieredSettle(relayInfo, billingexpr.TokenParams{P: 100})
  56. if !ok {
  57. t.Fatal("expected tiered settle to apply")
  58. }
  59. if quota != 200 {
  60. t.Fatalf("quota = %d, want 200", quota)
  61. }
  62. if result == nil || result.MatchedTier != "fast" {
  63. t.Fatalf("matched tier = %v, want fast", result)
  64. }
  65. }
  66. func TestTryTieredSettleFallsBackToFrozenPreConsumeOnExprError(t *testing.T) {
  67. relayInfo := &relaycommon.RelayInfo{
  68. FinalPreConsumedQuota: 321,
  69. TieredBillingSnapshot: &billingexpr.BillingSnapshot{
  70. BillingMode: "tiered_expr",
  71. ExprString: `invalid +-+ expr`,
  72. ExprHash: billingexpr.ExprHashString(`invalid +-+ expr`),
  73. GroupRatio: 1.0,
  74. EstimatedQuotaAfterGroup: 123,
  75. },
  76. }
  77. ok, quota, result := TryTieredSettle(relayInfo, billingexpr.TokenParams{P: 100})
  78. if !ok {
  79. t.Fatal("expected tiered settle to apply")
  80. }
  81. if quota != 321 {
  82. t.Fatalf("quota = %d, want 321", quota)
  83. }
  84. if result != nil {
  85. t.Fatalf("result = %#v, want nil", result)
  86. }
  87. }
  88. // ---------------------------------------------------------------------------
  89. // Pre-consume vs Post-consume consistency
  90. // ---------------------------------------------------------------------------
  91. func TestTryTieredSettle_PreConsumeMatchesPostConsume(t *testing.T) {
  92. info := makeRelayInfo(flatExpr, 1.0, 1000, 500)
  93. params := billingexpr.TokenParams{P: 1000, C: 500}
  94. ok, quota, _ := TryTieredSettle(info, params)
  95. if !ok {
  96. t.Fatal("expected tiered settle")
  97. }
  98. // p*2 + c*10 = 2000 + 5000 = 7000
  99. if quota != 7000 {
  100. t.Fatalf("quota = %d, want 7000", quota)
  101. }
  102. if quota != info.FinalPreConsumedQuota {
  103. t.Fatalf("pre-consume %d != post-consume %d", info.FinalPreConsumedQuota, quota)
  104. }
  105. }
  106. func TestTryTieredSettle_PostConsumeOverPreConsume(t *testing.T) {
  107. info := makeRelayInfo(flatExpr, 1.0, 1000, 500)
  108. preConsumed := info.FinalPreConsumedQuota // 7000
  109. // Actual usage is higher than estimated
  110. params := billingexpr.TokenParams{P: 2000, C: 1000}
  111. ok, quota, _ := TryTieredSettle(info, params)
  112. if !ok {
  113. t.Fatal("expected tiered settle")
  114. }
  115. // p*2 + c*10 = 4000 + 10000 = 14000
  116. if quota != 14000 {
  117. t.Fatalf("quota = %d, want 14000", quota)
  118. }
  119. if quota <= preConsumed {
  120. t.Fatalf("expected supplement: actual %d should > pre-consumed %d", quota, preConsumed)
  121. }
  122. }
  123. func TestTryTieredSettle_PostConsumeUnderPreConsume(t *testing.T) {
  124. info := makeRelayInfo(flatExpr, 1.0, 1000, 500)
  125. preConsumed := info.FinalPreConsumedQuota // 7000
  126. // Actual usage is lower than estimated
  127. params := billingexpr.TokenParams{P: 100, C: 50}
  128. ok, quota, _ := TryTieredSettle(info, params)
  129. if !ok {
  130. t.Fatal("expected tiered settle")
  131. }
  132. // p*2 + c*10 = 200 + 500 = 700
  133. if quota != 700 {
  134. t.Fatalf("quota = %d, want 700", quota)
  135. }
  136. if quota >= preConsumed {
  137. t.Fatalf("expected refund: actual %d should < pre-consumed %d", quota, preConsumed)
  138. }
  139. }
  140. // ---------------------------------------------------------------------------
  141. // Tiered boundary conditions
  142. // ---------------------------------------------------------------------------
  143. func TestTryTieredSettle_ExactBoundary(t *testing.T) {
  144. info := makeRelayInfo(sonnetTieredExpr, 1.0, 200000, 1000)
  145. // p == 200000 => standard tier (p <= 200000)
  146. ok, quota, result := TryTieredSettle(info, billingexpr.TokenParams{P: 200000, C: 1000})
  147. if !ok {
  148. t.Fatal("expected tiered settle")
  149. }
  150. // standard: p*1.5 + c*7.5 = 300000 + 7500 = 307500
  151. if quota != 307500 {
  152. t.Fatalf("quota = %d, want 307500", quota)
  153. }
  154. if result.MatchedTier != "standard" {
  155. t.Fatalf("tier = %s, want standard", result.MatchedTier)
  156. }
  157. }
  158. func TestTryTieredSettle_BoundaryPlusOne(t *testing.T) {
  159. info := makeRelayInfo(sonnetTieredExpr, 1.0, 200000, 1000)
  160. // p == 200001 => crosses to long_context tier
  161. ok, quota, result := TryTieredSettle(info, billingexpr.TokenParams{P: 200001, C: 1000})
  162. if !ok {
  163. t.Fatal("expected tiered settle")
  164. }
  165. // long_context: p*3 + c*11.25 = 600003 + 11250 = 611253
  166. if quota != 611253 {
  167. t.Fatalf("quota = %d, want 611253", quota)
  168. }
  169. if result.MatchedTier != "long_context" {
  170. t.Fatalf("tier = %s, want long_context", result.MatchedTier)
  171. }
  172. if !result.CrossedTier {
  173. t.Fatal("expected CrossedTier = true")
  174. }
  175. }
  176. func TestTryTieredSettle_ZeroTokens(t *testing.T) {
  177. info := makeRelayInfo(flatExpr, 1.0, 0, 0)
  178. ok, quota, result := TryTieredSettle(info, billingexpr.TokenParams{P: 0, C: 0})
  179. if !ok {
  180. t.Fatal("expected tiered settle")
  181. }
  182. if quota != 0 {
  183. t.Fatalf("quota = %d, want 0", quota)
  184. }
  185. if result == nil {
  186. t.Fatal("result should not be nil")
  187. }
  188. }
  189. func TestTryTieredSettle_HugeTokens(t *testing.T) {
  190. info := makeRelayInfo(flatExpr, 1.0, 10000000, 5000000)
  191. ok, quota, _ := TryTieredSettle(info, billingexpr.TokenParams{P: 10000000, C: 5000000})
  192. if !ok {
  193. t.Fatal("expected tiered settle")
  194. }
  195. // p*2 + c*10 = 20000000 + 50000000 = 70000000
  196. if quota != 70000000 {
  197. t.Fatalf("quota = %d, want 70000000", quota)
  198. }
  199. }
  200. func TestTryTieredSettle_CacheTokensAffectSettlement(t *testing.T) {
  201. info := makeRelayInfo(cacheExpr, 1.0, 1000, 500)
  202. // Without cache tokens
  203. ok1, quota1, _ := TryTieredSettle(info, billingexpr.TokenParams{P: 1000, C: 500})
  204. if !ok1 {
  205. t.Fatal("expected tiered settle")
  206. }
  207. // p*2 + c*10 + cr*0.2 + cc*2.5 + cc1h*4 = 2000 + 5000 + 0 + 0 + 0 = 7000
  208. // With cache tokens
  209. ok2, quota2, _ := TryTieredSettle(info, billingexpr.TokenParams{P: 1000, C: 500, CR: 10000, CC: 5000, CC1h: 2000})
  210. if !ok2 {
  211. t.Fatal("expected tiered settle")
  212. }
  213. // 2000 + 5000 + 10000*0.2 + 5000*2.5 + 2000*4 = 2000 + 5000 + 2000 + 12500 + 8000 = 29500
  214. if quota2 <= quota1 {
  215. t.Fatalf("cache tokens should increase quota: without=%d, with=%d", quota1, quota2)
  216. }
  217. if quota1 != 7000 {
  218. t.Fatalf("no-cache quota = %d, want 7000", quota1)
  219. }
  220. if quota2 != 29500 {
  221. t.Fatalf("cache quota = %d, want 29500", quota2)
  222. }
  223. }
  224. // ---------------------------------------------------------------------------
  225. // Request probe tests
  226. // ---------------------------------------------------------------------------
  227. func TestTryTieredSettle_RequestProbeInfluencesBilling(t *testing.T) {
  228. info := makeRelayInfo(probeExpr, 1.0, 1000, 500)
  229. info.BillingRequestInput = &billingexpr.RequestInput{
  230. Body: []byte(`{"service_tier":"fast"}`),
  231. }
  232. ok, quota, result := TryTieredSettle(info, billingexpr.TokenParams{P: 1000, C: 500})
  233. if !ok {
  234. t.Fatal("expected tiered settle")
  235. }
  236. // fast: p*4 + c*20 = 4000 + 10000 = 14000
  237. if quota != 14000 {
  238. t.Fatalf("quota = %d, want 14000", quota)
  239. }
  240. if result.MatchedTier != "fast" {
  241. t.Fatalf("tier = %s, want fast", result.MatchedTier)
  242. }
  243. }
  244. func TestTryTieredSettle_NoRequestInput_FallsBackToDefault(t *testing.T) {
  245. info := makeRelayInfo(probeExpr, 1.0, 1000, 500)
  246. // No BillingRequestInput set — param("service_tier") returns nil, not "fast"
  247. ok, quota, result := TryTieredSettle(info, billingexpr.TokenParams{P: 1000, C: 500})
  248. if !ok {
  249. t.Fatal("expected tiered settle")
  250. }
  251. // normal: p*2 + c*10 = 2000 + 5000 = 7000
  252. if quota != 7000 {
  253. t.Fatalf("quota = %d, want 7000", quota)
  254. }
  255. if result.MatchedTier != "normal" {
  256. t.Fatalf("tier = %s, want normal", result.MatchedTier)
  257. }
  258. }
  259. // ---------------------------------------------------------------------------
  260. // Group ratio tests
  261. // ---------------------------------------------------------------------------
  262. func TestTryTieredSettle_GroupRatioScaling(t *testing.T) {
  263. info := makeRelayInfo(flatExpr, 1.5, 1000, 500)
  264. ok, quota, _ := TryTieredSettle(info, billingexpr.TokenParams{P: 1000, C: 500})
  265. if !ok {
  266. t.Fatal("expected tiered settle")
  267. }
  268. // cost = 7000, after group = round(7000 * 1.5) = 10500
  269. if quota != 10500 {
  270. t.Fatalf("quota = %d, want 10500", quota)
  271. }
  272. }
  273. func TestTryTieredSettle_GroupRatioZero(t *testing.T) {
  274. info := makeRelayInfo(flatExpr, 0, 1000, 500)
  275. ok, quota, _ := TryTieredSettle(info, billingexpr.TokenParams{P: 1000, C: 500})
  276. if !ok {
  277. t.Fatal("expected tiered settle")
  278. }
  279. if quota != 0 {
  280. t.Fatalf("quota = %d, want 0 (group ratio = 0)", quota)
  281. }
  282. }
  283. // ---------------------------------------------------------------------------
  284. // Ratio mode (negative tests) — TryTieredSettle must return false
  285. // ---------------------------------------------------------------------------
  286. func TestTryTieredSettle_RatioMode_NilSnapshot(t *testing.T) {
  287. info := &relaycommon.RelayInfo{
  288. TieredBillingSnapshot: nil,
  289. }
  290. ok, _, _ := TryTieredSettle(info, billingexpr.TokenParams{P: 1000, C: 500})
  291. if ok {
  292. t.Fatal("expected TryTieredSettle to return false when snapshot is nil")
  293. }
  294. }
  295. func TestTryTieredSettle_RatioMode_WrongBillingMode(t *testing.T) {
  296. info := &relaycommon.RelayInfo{
  297. TieredBillingSnapshot: &billingexpr.BillingSnapshot{
  298. BillingMode: "ratio",
  299. ExprString: flatExpr,
  300. ExprHash: billingexpr.ExprHashString(flatExpr),
  301. GroupRatio: 1.0,
  302. },
  303. }
  304. ok, _, _ := TryTieredSettle(info, billingexpr.TokenParams{P: 1000, C: 500})
  305. if ok {
  306. t.Fatal("expected TryTieredSettle to return false for ratio billing mode")
  307. }
  308. }
  309. func TestTryTieredSettle_RatioMode_EmptyBillingMode(t *testing.T) {
  310. info := &relaycommon.RelayInfo{
  311. TieredBillingSnapshot: &billingexpr.BillingSnapshot{
  312. BillingMode: "",
  313. ExprString: flatExpr,
  314. ExprHash: billingexpr.ExprHashString(flatExpr),
  315. GroupRatio: 1.0,
  316. },
  317. }
  318. ok, _, _ := TryTieredSettle(info, billingexpr.TokenParams{P: 1000, C: 500})
  319. if ok {
  320. t.Fatal("expected TryTieredSettle to return false for empty billing mode")
  321. }
  322. }
  323. // ---------------------------------------------------------------------------
  324. // Fallback tests
  325. // ---------------------------------------------------------------------------
  326. func TestTryTieredSettle_ErrorFallbackToEstimatedQuotaAfterGroup(t *testing.T) {
  327. info := &relaycommon.RelayInfo{
  328. FinalPreConsumedQuota: 0,
  329. TieredBillingSnapshot: &billingexpr.BillingSnapshot{
  330. BillingMode: "tiered_expr",
  331. ExprString: `invalid expr!!!`,
  332. ExprHash: billingexpr.ExprHashString(`invalid expr!!!`),
  333. GroupRatio: 1.0,
  334. EstimatedQuotaAfterGroup: 999,
  335. },
  336. }
  337. ok, quota, result := TryTieredSettle(info, billingexpr.TokenParams{P: 100})
  338. if !ok {
  339. t.Fatal("expected tiered settle to apply")
  340. }
  341. // FinalPreConsumedQuota is 0, should fall back to EstimatedQuotaAfterGroup
  342. if quota != 999 {
  343. t.Fatalf("quota = %d, want 999", quota)
  344. }
  345. if result != nil {
  346. t.Fatal("result should be nil on error fallback")
  347. }
  348. }