From cf1ae262d62e6bff4d6a41f7072b822215899726 Mon Sep 17 00:00:00 2001 From: Lukasz Raczylo Date: Thu, 26 Nov 2026 01:55:17 +0000 Subject: [PATCH] refactor(pricing): share one prompt token split --- limits.go | 2 +- prompt_cache_stats.go | 25 +------------------------ prompt_cache_stats_test.go | 17 +++++++++++++++++ 3 files changed, 19 insertions(+), 25 deletions(-) diff --git a/limits.go b/limits.go index dda44c9..ef11446 100644 --- a/limits.go +++ b/limits.go @@ -2080,7 +2080,7 @@ func (l *limiter) accountWith(scopes []limitScope, u usage, costMicros int64, x var pcRead, pcWrite, pcSave int64 if !x.responseCacheHit { - pcRead, pcWrite, _ = promptCacheSplit(u) + pcRead, pcWrite, _ = splitPromptTokens(u) pcSave = x.promptCacheSaved if pcSave < 0 || pcSave > maxCostMicrosPerRequest { pcSave = 0 diff --git a/prompt_cache_stats.go b/prompt_cache_stats.go index ab41f3a..e29ac99 100644 --- a/prompt_cache_stats.go +++ b/prompt_cache_stats.go @@ -51,35 +51,12 @@ func (s *promptCacheStats) snapshot() map[promptCacheKey]int64 { return out } -// promptCacheSplit clamps like computeCostMicros: cached in [0,prompt], write in [0,prompt-cached]. -func promptCacheSplit(u usage) (int64, int64, int64) { - cached := u.cached - if cached < 0 { - cached = 0 - } - if cached > u.prompt { - cached = u.prompt - } - write := u.cacheWrite - if write < 0 { - write = 0 - } - if write > u.prompt-cached { - write = u.prompt - cached - } - rest := u.prompt - cached - write - if rest < 0 { - rest = 0 - } - return cached, write, rest -} - // recordPromptCache counts one real upstream response; never call it for a response-cache hit. func (g *Gateway) recordPromptCache(provider, model string, u usage) { if !metricsEnabled(g.cfg) { return } - cached, write, rest := promptCacheSplit(u) + cached, write, rest := splitPromptTokens(u) g.promptCacheStats.add(promptCacheKey{provider, model, promptCacheKindRead}, cached) g.promptCacheStats.add(promptCacheKey{provider, model, promptCacheKindWrite}, write) g.promptCacheStats.add(promptCacheKey{provider, model, promptCacheKindUncached}, rest) diff --git a/prompt_cache_stats_test.go b/prompt_cache_stats_test.go index 2191352..162935f 100644 --- a/prompt_cache_stats_test.go +++ b/prompt_cache_stats_test.go @@ -192,3 +192,20 @@ func TestAdminUsageModelsDetailBudgetUnchanged(t *testing.T) { require.NotNil(t, got.Models[0].PromptCacheReadTokens) assert.EqualValues(t, 7, *got.Models[0].PromptCacheReadTokens) } + +func TestSplitPromptTokensNegativePrompt(t *testing.T) { + t.Parallel() + u := usage{prompt: -5, cached: 3, cacheWrite: 2} + cached, write, rest := splitPromptTokens(u) + assert.Zero(t, cached) + assert.Zero(t, write) + assert.Zero(t, rest) + + cfg := newAdminTestConfig() + cfg.Metrics = &MetricsConfig{Enabled: true} + _, gw := newAdminGatewayHandle(t, cfg) + gw.recordPromptCache("p", "m", u) + for k, v := range gw.promptCacheStats.snapshot() { + assert.Zero(t, v, "%v", k) + } +}