From 71532bf91cfe79f65f1943bdb32e896cd087238b Mon Sep 17 00:00:00 2001 From: wucm667 Date: Thu, 5 Nov 2026 09:24:56 +0800 Subject: [PATCH] fix(usage): preserve compatible cache snapshot semantics --- .../anthropic_cache_creation_usage_test.go | 84 ++++++- .../anthropic_to_responses_response.go | 17 +- .../chatcompletions_anthropic_bridge.go | 7 +- .../pkg/apicompat/responses_to_anthropic.go | 12 +- .../anthropic_chat_stream_usage_test.go | 2 +- .../service/anthropic_prompt_total_test.go | 20 +- .../service/antigravity_gateway_upstream.go | 2 +- ...teway_anthropic_apikey_passthrough_test.go | 23 +- .../service/gateway_anthropic_passthrough.go | 8 +- ...teway_cache_compatibility_boundary_test.go | 180 +++++++++++++++ .../gateway_cache_creation_usage_test.go | 213 ++++++++++++------ .../gateway_cache_ttl_override_test.go | 128 ++++++++++- .../service/gateway_forward_as_responses.go | 9 +- .../gateway_forward_as_responses_test.go | 12 +- backend/internal/service/gateway_service.go | 7 +- .../service/gateway_upstream_response.go | 19 +- .../internal/service/gateway_usage_billing.go | 12 +- ...enai_gateway_native_cache_creation_test.go | 7 +- .../internal/service/openai_gateway_usage.go | 12 +- 19 files changed, 625 insertions(+), 149 deletions(-) create mode 100644 backend/internal/service/gateway_cache_compatibility_boundary_test.go diff --git a/backend/internal/pkg/apicompat/anthropic_cache_creation_usage_test.go b/backend/internal/pkg/apicompat/anthropic_cache_creation_usage_test.go index 4d1a341d8b..a3cf369317 100644 --- a/backend/internal/pkg/apicompat/anthropic_cache_creation_usage_test.go +++ b/backend/internal/pkg/apicompat/anthropic_cache_creation_usage_test.go @@ -15,7 +15,7 @@ func TestAnthropicCacheCreationAggregatePresence(t *testing.T) { present bool }{ {"contradictory aggregate", `{"cache_creation_input_tokens":100,"cache_creation":{"ephemeral_1h_input_tokens":200}}`, 100, true}, - {"explicit zero", `{"cache_creation_input_tokens":0,"cache_creation":{"ephemeral_1h_input_tokens":200}}`, 0, true}, + {"explicit zero", `{"cache_creation_input_tokens":0,"cache_creation":{"ephemeral_1h_input_tokens":200}}`, 200, true}, {"missing aggregate", `{"cache_creation":{"ephemeral_1h_input_tokens":200}}`, 200, false}, {"null aggregate", `{"cache_creation_input_tokens":null,"cache_creation":{"ephemeral_1h_input_tokens":200}}`, 200, false}, {"null TTL", `{"cache_creation":{"ephemeral_5m_input_tokens":null,"ephemeral_1h_input_tokens":200}}`, 200, false}, @@ -112,9 +112,9 @@ func TestAnthropicUsageAdapterZeroContracts(t *testing.T) { usage AnthropicUsage present bool }{ - {"missing Responses usage", anthropicUsageFromResponsesUsage(nil), false}, + {"missing Responses usage", anthropicUsageFromResponsesUsage(nil), true}, {"explicit Responses totals", anthropicUsageFromResponsesUsage(&ResponsesUsage{}), true}, - {"missing Chat usage", chatUsageToAnthropicUsage(nil), false}, + {"missing Chat usage", chatUsageToAnthropicUsage(nil), true}, {"explicit Chat totals", chatUsageToAnthropicUsage(&ChatUsage{}), true}, } { t.Run(test.name, func(t *testing.T) { @@ -136,7 +136,8 @@ func TestAnthropicUsageAdapterZeroContracts(t *testing.T) { var decoded AnthropicStreamEvent require.NoError(t, json.Unmarshal(encoded, &decoded)) require.NotNil(t, decoded.Message) - require.False(t, decoded.Message.Usage.HasCacheCreationInputTokens()) + require.True(t, decoded.Message.Usage.HasCacheCreationInputTokens()) + require.True(t, decoded.Message.Usage.CacheReadInputTokensPresent) } terminalEvents := FinalizeResponsesAnthropicStream(responsesState) terminalEvents = append(terminalEvents, FinalizeChatCompletionsAnthropicStream(chatState)...) @@ -174,6 +175,79 @@ func TestAnthropicCacheCreationPartialSnapshots(t *testing.T) { var usage AnthropicUsage require.NoError(t, json.Unmarshal([]byte(snapshot), &usage)) state.mergeCacheCreationUsage(usage) - require.Equal(t, []int{20, 50, 50, 50, 40, 40, 0, 0, 0, 100}[index], state.CacheCreationInputTokens) + require.Equal(t, []int{20, 50, 50, 50, 40, 40, 40, 40, 40, 100}[index], state.CacheCreationInputTokens) + } +} + +func TestAnthropicConvertersRawCacheUsageLifecycle(t *testing.T) { + for _, test := range []struct { + name string + aggregate int + want []int + }{ + {"zero aggregate derives partial TTL", 0, []int{20, 50, 50, 50, 30}}, + {"positive aggregate survives placeholders", 40, []int{40, 40, 40, 40, 40}}, + } { + for _, terminal := range []string{"message_stop", "eof"} { + t.Run(test.name+"/"+terminal, func(t *testing.T) { + state := NewAnthropicEventToResponsesState() + chatState := NewResponsesEventToChatState() + chatState.IncludeUsage = true + var completed *ResponsesResponse + var chatUsage *ChatUsage + consume := func(events []ResponsesStreamEvent) { + for _, event := range events { + if event.Type == "response.completed" { + completed = event.Response + } + for _, chunk := range ResponsesEventToChatChunks(&event, chatState) { + if chunk.Usage != nil { + chatUsage = chunk.Usage + } + } + } + } + start := AnthropicStreamEvent{Type: "message_start", Message: &AnthropicResponse{ + ID: "msg_cache", Model: "claude-sonnet-4", Usage: AnthropicUsage{ + InputTokens: 10, CacheReadInputTokens: 9, + CacheCreationInputTokens: test.aggregate, CacheCreationInputTokensPresent: true, + }, + }} + consume(AnthropicEventToResponsesEvents(&start, state)) + for index, snapshot := range []string{ + `{"output_tokens":7,"cache_creation_input_tokens":0,"cache_creation":{"ephemeral_5m_input_tokens":20}}`, + `{"cache_creation_input_tokens":0,"cache_creation":{"ephemeral_1h_input_tokens":30}}`, + `{"input_tokens":0,"output_tokens":0,"cache_read_input_tokens":0,"cache_creation_input_tokens":0}`, + `{"input_tokens":0,"output_tokens":0,"cache_read_input_tokens":0,"cache_creation_input_tokens":0}`, + `{"cache_creation":{"ephemeral_5m_input_tokens":0}}`, + } { + var event AnthropicStreamEvent + require.NoError(t, json.Unmarshal([]byte(`{"type":"message_delta","usage":`+snapshot+`}`), &event)) + consume(AnthropicEventToResponsesEvents(&event, state)) + require.Equal(t, test.want[index], state.CacheCreationInputTokens, "snapshot %d", index) + require.Equal(t, 7, state.OutputTokens, "snapshot %d", index) + } + if terminal == "message_stop" { + consume(AnthropicEventToResponsesEvents(&AnthropicStreamEvent{Type: "message_stop"}, state)) + } else { + consume(FinalizeAnthropicResponsesStream(state)) + } + want := test.want[len(test.want)-1] + require.NotNil(t, completed) + require.NotNil(t, completed.Usage) + require.Equal(t, want, completed.Usage.CacheCreationInputTokens) + require.Equal(t, 19+want, completed.Usage.InputTokens) + require.Equal(t, 7, completed.Usage.OutputTokens) + require.Equal(t, 26+want, completed.Usage.TotalTokens) + require.NotNil(t, chatUsage) + require.Equal(t, 19+want, chatUsage.PromptTokens) + require.Equal(t, 7, chatUsage.CompletionTokens) + require.NotNil(t, chatUsage.PromptTokensDetails) + require.Equal(t, want, chatUsage.PromptTokensDetails.CacheCreationTokens) + require.Equal(t, 9, chatUsage.PromptTokensDetails.CachedTokens) + require.Empty(t, FinalizeAnthropicResponsesStream(state)) + require.Empty(t, FinalizeResponsesChatStream(chatState)) + }) + } } } diff --git a/backend/internal/pkg/apicompat/anthropic_to_responses_response.go b/backend/internal/pkg/apicompat/anthropic_to_responses_response.go index a9a818267d..809344daa5 100644 --- a/backend/internal/pkg/apicompat/anthropic_to_responses_response.go +++ b/backend/internal/pkg/apicompat/anthropic_to_responses_response.go @@ -30,7 +30,7 @@ func encodeAnthropicThinking(block AnthropicContentBlock) string { } func anthropicCacheCreationInputTokens(usage AnthropicUsage) int { - if usage.HasCacheCreationInputTokens() { + if usage.CacheCreationInputTokens > 0 { return max(usage.CacheCreationInputTokens, 0) } if usage.CacheCreation != nil && (usage.CacheCreation.Ephemeral5mInputTokens != nil || usage.CacheCreation.Ephemeral1hInputTokens != nil) { @@ -43,7 +43,7 @@ func anthropicCacheCreationInputTokens(usage AnthropicUsage) int { } return cacheCreationTokens } - return usage.CacheCreationInputTokens + return max(usage.CacheCreationInputTokens, 0) } // AnthropicToResponsesResponse converts an Anthropic Messages response into a @@ -238,7 +238,8 @@ type AnthropicEventToResponsesState struct { CacheCreationInputTokens int CacheCreation AnthropicCacheCreation - cacheCreationInputTokensPresent bool + cacheCreationInputTokensPresent bool + cacheCreationInputTokensFromDetails bool StopReason string } @@ -251,9 +252,10 @@ func NewAnthropicEventToResponsesState() *AnthropicEventToResponsesState { } func (state *AnthropicEventToResponsesState) mergeCacheCreationUsage(usage AnthropicUsage) { - if usage.HasCacheCreationInputTokens() { + if usage.HasCacheCreationInputTokens() && (usage.CacheCreationInputTokens > 0 || state.CacheCreationInputTokens <= 0) { state.CacheCreationInputTokens = max(usage.CacheCreationInputTokens, 0) state.cacheCreationInputTokensPresent = true + state.cacheCreationInputTokensFromDetails = false } if usage.CacheCreation != nil { if usage.CacheCreation.Ephemeral5mInputTokens != nil { @@ -265,8 +267,9 @@ func (state *AnthropicEventToResponsesState) mergeCacheCreationUsage(usage Anthr state.CacheCreation.Ephemeral1hInputTokens = &tokens } } - if !state.cacheCreationInputTokensPresent && (state.CacheCreation.Ephemeral5mInputTokens != nil || state.CacheCreation.Ephemeral1hInputTokens != nil) { + if (!state.cacheCreationInputTokensPresent || state.cacheCreationInputTokensFromDetails || state.CacheCreationInputTokens <= 0) && (state.CacheCreation.Ephemeral5mInputTokens != nil || state.CacheCreation.Ephemeral1hInputTokens != nil) { state.CacheCreationInputTokens = anthropicCacheCreationInputTokens(AnthropicUsage{CacheCreation: &state.CacheCreation}) + state.cacheCreationInputTokensFromDetails = true } } @@ -590,7 +593,9 @@ func anthToResHandleContentBlockStop(evt *AnthropicStreamEvent, state *Anthropic func anthToResHandleMessageDelta(evt *AnthropicStreamEvent, state *AnthropicEventToResponsesState) []ResponsesStreamEvent { if evt.Usage != nil { - state.OutputTokens = evt.Usage.OutputTokens + if evt.Usage.OutputTokens > 0 { + state.OutputTokens = evt.Usage.OutputTokens + } if evt.Usage.InputTokens > 0 { state.InputTokens = evt.Usage.InputTokens } diff --git a/backend/internal/pkg/apicompat/chatcompletions_anthropic_bridge.go b/backend/internal/pkg/apicompat/chatcompletions_anthropic_bridge.go index 004888b51f..893e6a29da 100644 --- a/backend/internal/pkg/apicompat/chatcompletions_anthropic_bridge.go +++ b/backend/internal/pkg/apicompat/chatcompletions_anthropic_bridge.go @@ -411,6 +411,7 @@ func ChatCompletionsResponseToAnthropic(resp *ChatCompletionsResponse, model str Type: "message", Role: "assistant", Model: model, + Usage: chatUsageToAnthropicUsage(nil), } if resp != nil { @@ -517,7 +518,7 @@ func chatFinishReasonToAnthropicStopReason(reason string, blocks []AnthropicCont // usage shape. Mirrors ChatUsageToResponsesUsage + anthropicUsageFromResponsesUsage. func chatUsageToAnthropicUsage(usage *ChatUsage) AnthropicUsage { if usage == nil { - return AnthropicUsage{} + return AnthropicUsage{CacheCreationInputTokensPresent: true, CacheReadInputTokensPresent: true} } cachedTokens := 0 @@ -545,6 +546,7 @@ func chatUsageToAnthropicUsage(usage *ChatUsage) AnthropicUsage { CacheReadInputTokens: cachedTokens, CacheCreationInputTokens: cacheCreationTokens, CacheCreationInputTokensPresent: true, + CacheReadInputTokensPresent: true, } } @@ -720,6 +722,7 @@ func FinalizeChatCompletionsAnthropicStream(state *ChatCompletionsToAnthropicStr CacheReadInputTokens: state.CacheReadInputTokens, CacheCreationInputTokens: state.CacheCreationInputTokens, CacheCreationInputTokensPresent: true, + CacheReadInputTokensPresent: true, }, }, AnthropicStreamEvent{Type: "message_stop"}, @@ -743,7 +746,7 @@ func ensureCCAnthropicMessageStart(state *ChatCompletionsToAnthropicStreamState) Content: []AnthropicContentBlock{}, Model: state.Model, StopReason: nil, // JSON null; never "" - Usage: AnthropicUsage{InputTokens: 0, OutputTokens: 0}, + Usage: chatUsageToAnthropicUsage(nil), }, }} } diff --git a/backend/internal/pkg/apicompat/responses_to_anthropic.go b/backend/internal/pkg/apicompat/responses_to_anthropic.go index 2b514b1391..11fc9b3b02 100644 --- a/backend/internal/pkg/apicompat/responses_to_anthropic.go +++ b/backend/internal/pkg/apicompat/responses_to_anthropic.go @@ -20,6 +20,7 @@ func ResponsesToAnthropic(resp *ResponsesResponse, model string) *AnthropicRespo Type: "message", Role: "assistant", Model: model, + Usage: anthropicUsageFromResponsesUsage(nil), } var blocks []AnthropicContentBlock @@ -97,7 +98,7 @@ func ResponsesToAnthropic(resp *ResponsesResponse, model string) *AnthropicRespo func anthropicUsageFromResponsesUsage(usage *ResponsesUsage) AnthropicUsage { if usage == nil { - return AnthropicUsage{} + return AnthropicUsage{CacheCreationInputTokensPresent: true, CacheReadInputTokensPresent: true} } cachedTokens := 0 @@ -116,6 +117,7 @@ func anthropicUsageFromResponsesUsage(usage *ResponsesUsage) AnthropicUsage { CacheReadInputTokens: cachedTokens, CacheCreationInputTokens: usage.CacheCreationInputTokens, CacheCreationInputTokensPresent: true, + CacheReadInputTokensPresent: true, } } @@ -291,6 +293,7 @@ func FinalizeResponsesAnthropicStream(state *ResponsesEventToAnthropicState) []A CacheReadInputTokens: state.CacheReadInputTokens, CacheCreationInputTokens: state.CacheCreationInputTokens, CacheCreationInputTokensPresent: true, + CacheReadInputTokensPresent: true, }, }, AnthropicStreamEvent{Type: "message_stop"}, @@ -338,8 +341,10 @@ func resToAnthHandleCreated(evt *ResponsesStreamEvent, state *ResponsesEventToAn Model: state.Model, StopReason: nil, Usage: AnthropicUsage{ - InputTokens: 0, - OutputTokens: 0, + InputTokens: 0, + OutputTokens: 0, + CacheCreationInputTokensPresent: true, + CacheReadInputTokensPresent: true, }, }, }} @@ -775,6 +780,7 @@ func resToAnthHandleCompleted(evt *ResponsesStreamEvent, state *ResponsesEventTo CacheReadInputTokens: state.CacheReadInputTokens, CacheCreationInputTokens: state.CacheCreationInputTokens, CacheCreationInputTokensPresent: true, + CacheReadInputTokensPresent: true, }, }, AnthropicStreamEvent{Type: "message_stop"}, diff --git a/backend/internal/service/anthropic_chat_stream_usage_test.go b/backend/internal/service/anthropic_chat_stream_usage_test.go index 77e51a8836..6a68a9d106 100644 --- a/backend/internal/service/anthropic_chat_stream_usage_test.go +++ b/backend/internal/service/anthropic_chat_stream_usage_test.go @@ -28,7 +28,7 @@ func TestAnthropicChatStreamAuthoritativeUsage(t *testing.T) { }{ {"cache", `,"usage":{"input_tokens":308,"cache_read_input_tokens":241,"cache_creation_input_tokens":17}`, `,"usage":{"output_tokens":49}`, "", true, 566, 308, 566, 49, 241, 17}, {"contradictory_cache_creation", `,"usage":{"input_tokens":10,"cache_creation_input_tokens":100,"cache_creation":{"ephemeral_1h_input_tokens":200}}`, `,"usage":{"output_tokens":7,"cache_creation":{"ephemeral_1h_input_tokens":200}}`, `,"usage":{"output_tokens":7,"cache_creation":{"ephemeral_1h_input_tokens":200}}`, true, 110, 10, 110, 7, 0, 100}, - {"zero_cache_creation", `,"usage":{"input_tokens":10,"cache_creation_input_tokens":0,"cache_creation":{"ephemeral_1h_input_tokens":200}}`, `,"usage":{"output_tokens":7,"cache_creation":{"ephemeral_1h_input_tokens":200}}`, "", true, 10, 10, 10, 7, 0, 0}, + {"zero_cache_creation", `,"usage":{"input_tokens":10,"cache_creation_input_tokens":0,"cache_creation":{"ephemeral_1h_input_tokens":200}}`, `,"usage":{"output_tokens":7,"cache_creation":{"ephemeral_1h_input_tokens":200}}`, "", true, 210, 10, 210, 7, 0, 200}, {"partial_cache_creation", `,"usage":{"input_tokens":10,"cache_creation":{"ephemeral_5m_input_tokens":20}}`, `,"usage":{"output_tokens":7,"cache_creation":{"ephemeral_1h_input_tokens":30}}`, `,"usage":{"output_tokens":7,"cache_creation":{"ephemeral_1h_input_tokens":30}}`, true, 60, 10, 60, 7, 0, 50}, {"deepseek_partial_cache", "", `,"usage":{"input_tokens":1200,"output_tokens":30,"prompt_cache_hit_tokens":800,"prompt_cache_miss_tokens":400}`, "", true, 1200, 400, 1200, 30, 800, 0}, {"openai_partial_cache", "", `,"usage":{"prompt_tokens":1200,"output_tokens":30,"prompt_tokens_details":{"cached_tokens":800}}`, "", true, 1200, 400, 1200, 30, 800, 0}, diff --git a/backend/internal/service/anthropic_prompt_total_test.go b/backend/internal/service/anthropic_prompt_total_test.go index ae0161982c..f307738c2d 100644 --- a/backend/internal/service/anthropic_prompt_total_test.go +++ b/backend/internal/service/anthropic_prompt_total_test.go @@ -30,7 +30,7 @@ func TestAnthropicPromptTotalSnapshots(t *testing.T) { {"independent input", `"input_tokens":80`, []string{`{"cache_creation":{"ephemeral_1h_input_tokens":30}}`, `{"cache_creation":{"ephemeral_1h_input_tokens":30}}`}, []int{80, 80}}, {"miss overrides total", `"prompt_tokens":100`, []string{`{"prompt_tokens":100,"prompt_cache_miss_tokens":40}`, `{"cache_creation":{"ephemeral_1h_input_tokens":30}}`}, []int{40, 40}}, {"late read aliases", `"prompt_tokens":100`, []string{`{"cached_tokens":10}`, `{"cached_tokens":15}`, `{"prompt_tokens_details":{"cached_tokens":20}}`, `{"prompt_cache_hit_tokens":25}`, `{"cache_creation":{"ephemeral_1h_input_tokens":30}}`}, []int{70, 65, 60, 55, 25}}, - {"aggregate clears", `"prompt_tokens":100`, []string{`{"cache_creation_input_tokens":50}`, `{"cache_creation_input_tokens":0}`, `{"cache_creation":{"ephemeral_1h_input_tokens":30}}`}, []int{50, 100, 100}}, + {"aggregate survives zero placeholder", `"prompt_tokens":100`, []string{`{"cache_creation_input_tokens":50}`, `{"cache_creation_input_tokens":0}`, `{"cache_creation":{"ephemeral_1h_input_tokens":30}}`}, []int{50, 50, 50}}, {"cache exceeds prompt", `"prompt_tokens":100`, []string{`{"cache_creation":{"ephemeral_1h_input_tokens":100}}`, `{"cache_creation":{"ephemeral_1h_input_tokens":30}}`}, []int{0, 50}}, } { for _, parser := range []string{"typed", "raw", "generic"} { @@ -70,10 +70,10 @@ func TestAnthropicPromptTotalCacheReadPresence(t *testing.T) { delta string read int }{ - {"canonical zero", `{"cache_read_input_tokens":0}`, 0}, - {"cached zero", `{"cached_tokens":0}`, 0}, - {"details zero", `{"prompt_tokens_details":{"cached_tokens":0}}`, 0}, - {"hit zero", `{"prompt_cache_hit_tokens":0}`, 0}, + {"canonical zero", `{"cache_read_input_tokens":0}`, 20}, + {"cached zero", `{"cached_tokens":0}`, 20}, + {"details zero", `{"prompt_tokens_details":{"cached_tokens":0}}`, 20}, + {"hit zero", `{"prompt_cache_hit_tokens":0}`, 20}, {"missing", `{"output_tokens":2}`, 20}, {"null", `{"cache_read_input_tokens":null,"cached_tokens":null,"prompt_tokens_details":{"cached_tokens":null},"prompt_cache_hit_tokens":null}`, 20}, {"canonical precedence", `{"cache_read_input_tokens":12,"cached_tokens":13,"prompt_tokens_details":{"cached_tokens":14},"prompt_cache_hit_tokens":15}`, 12}, @@ -121,7 +121,9 @@ func TestAnthropicPromptTotalCacheReadZeroForwardBoundary(t *testing.T) { for _, terminal := range []string{"stop", "eof"} { t.Run(field+"/"+route+"/"+terminal, func(t *testing.T) { payload := "event: message_start\ndata: " + `{"type":"message_start","message":{"id":"msg_zero","type":"message","role":"assistant","model":"claude-sonnet-4","content":[],"usage":{"input_tokens":100,"prompt_tokens":100,"cache_read_input_tokens":20,"cache_creation_input_tokens":10}}}` + "\n\n" - payload += "event: message_delta\ndata: " + `{"type":"message_delta","usage":{"` + field + `":0}}` + "\n\n" + for range 2 { + payload += "event: message_delta\ndata: " + `{"type":"message_delta","usage":{"` + field + `":0}}` + "\n\n" + } payload += "event: message_delta\ndata: " + `{"type":"message_delta","delta":{"stop_reason":"end_turn"},"usage":{"output_tokens":2}}` + "\n\n" if terminal == "stop" { payload += "event: message_stop\ndata: {\"type\":\"message_stop\"}\n\n" @@ -154,8 +156,8 @@ func TestAnthropicPromptTotalCacheReadZeroForwardBoundary(t *testing.T) { require.NoError(t, err) } require.NotNil(t, usage) - require.Equal(t, 90, usage.InputTokens) - require.Zero(t, usage.CacheReadInputTokens) + require.Equal(t, 70, usage.InputTokens) + require.Equal(t, 20, usage.CacheReadInputTokens) require.Equal(t, 10, usage.CacheCreationInputTokens) require.Equal(t, 2, usage.OutputTokens) }) @@ -190,7 +192,7 @@ func TestAnthropicCacheReadZeroPreservesIndependentInput(t *testing.T) { } require.Equal(t, 80, usage.InputTokens) } - require.Zero(t, usage.CacheReadInputTokens) + require.Equal(t, 20, usage.CacheReadInputTokens) require.Equal(t, 10, usage.CacheCreationInputTokens) }) } diff --git a/backend/internal/service/antigravity_gateway_upstream.go b/backend/internal/service/antigravity_gateway_upstream.go index 79b8f4042f..30c99ef307 100644 --- a/backend/internal/service/antigravity_gateway_upstream.go +++ b/backend/internal/service/antigravity_gateway_upstream.go @@ -330,7 +330,7 @@ func (s *AntigravityGatewayService) extractSSEUsage(line string, usage *ClaudeUs if v, ok := u["cache_read_input_tokens"].(float64); ok && int(v) > 0 { usage.CacheReadInputTokens = int(v) } - if v, ok := u["cache_creation_input_tokens"].(float64); ok && int(v) >= 0 { + if v, ok := u["cache_creation_input_tokens"].(float64); ok && (int(v) > 0 || usage.CacheCreationInputTokens <= 0) { usage.CacheCreationInputTokens = int(v) usage.cacheCreationInputTokensPresent = true } diff --git a/backend/internal/service/gateway_anthropic_apikey_passthrough_test.go b/backend/internal/service/gateway_anthropic_apikey_passthrough_test.go index 9157776810..70e4b3feab 100644 --- a/backend/internal/service/gateway_anthropic_apikey_passthrough_test.go +++ b/backend/internal/service/gateway_anthropic_apikey_passthrough_test.go @@ -1287,7 +1287,7 @@ func TestExtractAnthropicSSEDataLine(t *testing.T) { func TestGatewayService_ParseSSEUsagePassthrough_MessageStartFallbacks(t *testing.T) { usage := &ClaudeUsage{} - data := `{"type":"message_start","message":{"usage":{"input_tokens":12,"cache_read_input_tokens":0,"cached_tokens":9,"cache_creation":{"ephemeral_5m_input_tokens":3,"ephemeral_1h_input_tokens":4}}}}` + data := `{"type":"message_start","message":{"usage":{"input_tokens":12,"cache_read_input_tokens":0,"cached_tokens":9,"cache_creation_input_tokens":0,"cache_creation":{"ephemeral_5m_input_tokens":3,"ephemeral_1h_input_tokens":4}}}}` parseSSEUsagePassthrough(data, usage) @@ -1359,8 +1359,9 @@ func TestGatewayService_ParseSSEUsagePassthrough_OtherEventCacheCreation(t *test wantAggregate: 3, }, { - name: "explicit zero retains raw TTL", - snapshots: []string{`{"cache_creation_input_tokens":0,"cache_creation":{"ephemeral_5m_input_tokens":2,"ephemeral_1h_input_tokens":1}}`}, + name: "explicit zero retains raw TTL", + snapshots: []string{`{"cache_creation_input_tokens":0,"cache_creation":{"ephemeral_5m_input_tokens":2,"ephemeral_1h_input_tokens":1}}`}, + wantAggregate: 3, }, { name: "previous explicit aggregate survives null", @@ -1369,14 +1370,16 @@ func TestGatewayService_ParseSSEUsagePassthrough_OtherEventCacheCreation(t *test wantAggregate: 9, }, { - name: "previous explicit zero survives omitted aggregate", - start: `{"cache_creation_input_tokens":0}`, - snapshots: []string{`{"cache_creation":{"ephemeral_5m_input_tokens":2,"ephemeral_1h_input_tokens":1}}`}, + name: "previous explicit zero survives omitted aggregate", + start: `{"cache_creation_input_tokens":0}`, + snapshots: []string{`{"cache_creation":{"ephemeral_5m_input_tokens":2,"ephemeral_1h_input_tokens":1}}`}, + wantAggregate: 3, }, { - name: "explicit zero replaces previous aggregate", - start: `{"cache_creation_input_tokens":9}`, - snapshots: []string{`{"cache_creation_input_tokens":0,"cache_creation":{"ephemeral_5m_input_tokens":2,"ephemeral_1h_input_tokens":1}}`}, + name: "explicit zero preserves previous aggregate", + start: `{"cache_creation_input_tokens":9}`, + snapshots: []string{`{"cache_creation_input_tokens":0,"cache_creation":{"ephemeral_5m_input_tokens":2,"ephemeral_1h_input_tokens":1}}`}, + wantAggregate: 9, }, } for _, test := range tests { @@ -1419,7 +1422,7 @@ func TestParseClaudeUsageFromResponseBody(t *testing.T) { }) t.Run("parse all usage fields and fallback", func(t *testing.T) { - body := []byte(`{"usage":{"input_tokens":21,"output_tokens":34,"cache_read_input_tokens":0,"cached_tokens":13,"cache_creation":{"ephemeral_5m_input_tokens":5,"ephemeral_1h_input_tokens":8}}}`) + body := []byte(`{"usage":{"input_tokens":21,"output_tokens":34,"cache_read_input_tokens":0,"cached_tokens":13,"cache_creation_input_tokens":0,"cache_creation":{"ephemeral_5m_input_tokens":5,"ephemeral_1h_input_tokens":8}}}`) got := parseClaudeUsageFromResponseBody(body) require.Equal(t, 21, got.InputTokens) require.Equal(t, 34, got.OutputTokens) diff --git a/backend/internal/service/gateway_anthropic_passthrough.go b/backend/internal/service/gateway_anthropic_passthrough.go index baa1c5c5b0..7fc54db3a4 100644 --- a/backend/internal/service/gateway_anthropic_passthrough.go +++ b/backend/internal/service/gateway_anthropic_passthrough.go @@ -671,8 +671,8 @@ func parseSSEUsagePassthrough(data string, usage *ClaudeUsage) { } for _, path := range []string{"cache_read_input_tokens", "cached_tokens", "prompt_tokens_details.cached_tokens", "prompt_cache_hit_tokens"} { if value := usageNode.Get(path); value.Exists() && value.Type != gjson.Null { - usage.CacheReadInputTokens = max(int(value.Int()), 0) - if usage.CacheReadInputTokens > 0 { + if tokens := int(value.Int()); tokens > 0 { + usage.CacheReadInputTokens = tokens break } } @@ -706,7 +706,9 @@ func normalizeAnthropicCompatiblePromptUsage(usageNode gjson.Result, usage *Clau } mergeRawAnthropicCacheCreationUsage(usageNode, usage) - usage.CacheReadInputTokens = cacheReadTokens + if cacheReadTokens > 0 || usage.CacheReadInputTokens <= 0 { + usage.CacheReadInputTokens = cacheReadTokens + } var cacheMissTokens *int if promptCacheMissTokens.Exists() && promptCacheMissTokens.Type != gjson.Null { value := int(promptCacheMissTokens.Int()) diff --git a/backend/internal/service/gateway_cache_compatibility_boundary_test.go b/backend/internal/service/gateway_cache_compatibility_boundary_test.go new file mode 100644 index 0000000000..c351f009ad --- /dev/null +++ b/backend/internal/service/gateway_cache_compatibility_boundary_test.go @@ -0,0 +1,180 @@ +//go:build unit + +package service + +import ( + "io" + "net/http" + "net/http/httptest" + "strings" + "testing" + "time" + + "github.com/Wei-Shaw/sub2api/internal/pkg/apicompat" + "github.com/gin-gonic/gin" + "github.com/stretchr/testify/require" + "github.com/tidwall/gjson" +) + +func TestAnthropicConverterOutputCacheFields(t *testing.T) { + gin.SetMode(gin.TestMode) + for _, test := range []struct { + name string + chatUsage string + responsesUsage string + creation int64 + read int64 + }{ + {"missing usage", "", "", 0, 0}, + {"null usage", `,"usage":null`, `,"usage":null`, 0, 0}, + {"empty usage", `,"usage":{}`, `,"usage":{}`, 0, 0}, + {"read only", `,"usage":{"prompt_tokens":10,"prompt_tokens_details":{"cached_tokens":3}}`, `,"usage":{"input_tokens":10,"input_tokens_details":{"cached_tokens":3}}`, 0, 3}, + {"creation only", `,"usage":{"prompt_tokens":10,"prompt_tokens_details":{"cache_write_tokens":4}}`, `,"usage":{"input_tokens":10,"cache_creation_input_tokens":4}`, 4, 0}, + } { + for _, route := range []string{"chat buffered", "chat terminal", "chat eof", "responses buffered", "responses terminal", "responses eof"} { + if strings.HasSuffix(route, "eof") && test.name != "missing usage" { + continue + } + t.Run(test.name+"/"+route, func(t *testing.T) { + payload := `{"id":"chat_cache","choices":[{"message":{"role":"assistant","content":"ok"},"finish_reason":"stop"}]` + test.chatUsage + `}` + if strings.HasPrefix(route, "responses") { + payload = "data: {\"type\":\"response.created\",\"response\":{\"id\":\"resp_cache\",\"model\":\"gpt-5.4\"}}\n\n" + if !strings.HasSuffix(route, "eof") { + payload += `data: {"type":"response.completed","response":{"id":"resp_cache","status":"completed","output":[]` + test.responsesUsage + `}}` + "\n\n" + } + } else if !strings.HasSuffix(route, "buffered") { + payload = `data: {"id":"chat_cache","choices":[{"delta":{"role":"assistant","content":"ok"},"finish_reason":"stop"}]` + test.chatUsage + `}` + "\n\n" + if strings.HasSuffix(route, "terminal") { + payload += "data: [DONE]\n\n" + } + } + recorder := httptest.NewRecorder() + ctx, _ := gin.CreateTestContext(recorder) + ctx.Request = httptest.NewRequest(http.MethodPost, "/v1/messages", nil) + response := &http.Response{StatusCode: http.StatusOK, Header: make(http.Header), Body: io.NopCloser(strings.NewReader(payload))} + service := &OpenAIGatewayService{cfg: rawChatCompletionsTestConfig()} + var err error + switch route { + case "chat buffered": + _, err = service.bufferChatCompletionsAsAnthropic(ctx, response, "gpt-5.4", "gpt-5.4", "gpt-5.4", nil, nil, time.Now()) + case "chat terminal", "chat eof": + _, err = service.streamChatCompletionsAsAnthropic(ctx, response, "gpt-5.4", "gpt-5.4", "gpt-5.4", nil, nil, time.Now()) + case "responses buffered": + _, err = service.handleAnthropicBufferedStreamingResponse(response, ctx, rawChatCompletionsTestAccount(), "gpt-5.4", "gpt-5.4", "gpt-5.4", time.Now()) + default: + _, err = service.handleAnthropicStreamingResponse(response, ctx, rawChatCompletionsTestAccount(), "gpt-5.4", "gpt-5.4", "gpt-5.4", time.Now()) + } + if route == "responses eof" { + require.ErrorContains(t, err, "missing terminal event") + } else { + require.NoError(t, err) + } + require.Equal(t, http.StatusOK, recorder.Code) + assertUsage := func(usage gjson.Result, creation, read int64) { + for field, want := range map[string]int64{"cache_creation_input_tokens": creation, "cache_read_input_tokens": read} { + tokens := usage.Get(field) + require.True(t, tokens.Exists(), field) + require.Equal(t, gjson.Number, tokens.Type, field) + require.Equal(t, want, tokens.Int(), field) + } + } + if strings.HasSuffix(route, "buffered") { + assertUsage(gjson.Get(recorder.Body.String(), "usage"), test.creation, test.read) + return + } + starts, deltas, stops := 0, 0, 0 + for _, line := range strings.Split(recorder.Body.String(), "\n") { + if !strings.HasPrefix(line, "data: ") { + continue + } + event := gjson.Parse(strings.TrimPrefix(line, "data: ")) + switch event.Get("type").String() { + case "message_start": + assertUsage(event.Get("message.usage"), 0, 0) + starts++ + case "message_delta": + assertUsage(event.Get("usage"), test.creation, test.read) + deltas++ + case "message_stop": + stops++ + } + } + require.Equal(t, 1, starts) + if route == "responses eof" { + require.Zero(t, deltas) + require.Zero(t, stops) + } else { + require.Equal(t, 1, deltas) + require.Equal(t, 1, stops) + } + }) + } + } +} + +func TestAnthropicZeroCacheDeltaPromptReconciliation(t *testing.T) { + for _, parser := range []string{"raw", "typed", "generic", "antigravity"} { + t.Run(parser, func(t *testing.T) { + usage := &ClaudeUsage{} + for index, snapshot := range []string{ + `{"input_tokens":100,"prompt_tokens":100,"cache_read_input_tokens":30,"cache_creation_input_tokens":0,"cache_creation":{"ephemeral_5m_input_tokens":20}}`, + `{"input_tokens":0,"cache_read_input_tokens":0,"cache_creation_input_tokens":0,"cache_creation":{"ephemeral_1h_input_tokens":10}}`, + `{"input_tokens":0,"cache_read_input_tokens":0,"cache_creation_input_tokens":0,"cache_creation":{"ephemeral_1h_input_tokens":10}}`, + } { + event := `{"type":"message_delta","usage":` + snapshot + `}` + if index == 0 { + event = `{"type":"message_start","message":{"usage":` + snapshot + `}}` + } + switch parser { + case "raw": + parseSSEUsagePassthrough(event, usage) + case "typed": + var source apicompat.AnthropicUsage + require.NoError(t, source.UnmarshalJSON([]byte(snapshot))) + mergeAnthropicUsage(usage, source) + case "generic": + (&GatewayService{}).parseSSEUsage(event, usage) + case "antigravity": + (&AntigravityGatewayService{}).extractSSEUsage("data: "+event, usage) + } + creation := 20 + if index > 0 { + creation = 30 + } + require.Equal(t, 30, usage.CacheReadInputTokens) + if parser == "antigravity" { + require.Equal(t, 100, usage.InputTokens) + } else { + require.Equal(t, creation, usage.CacheCreationInputTokens) + require.Equal(t, 100-30-creation, usage.InputTokens) + } + cache5m, cache1h := normalizeCacheCreationBreakdown(usage.billingUsageTokens()) + require.Equal(t, creation, cache5m+cache1h) + } + }) + } +} + +func TestCacheCreationZeroAggregateBillingProjection(t *testing.T) { + claude := ClaudeUsage{ + InputTokens: 40, CacheReadInputTokens: 10, + CacheCreation5mTokens: 20, CacheCreation1hTokens: 30, + cacheCreationInputTokensPresent: true, + } + openAI := OpenAIUsage{ + InputTokens: 100, CacheReadInputTokens: 10, + CacheCreation5mTokens: 20, CacheCreation1hTokens: 30, + cacheCreationInputTokensPresent: true, + } + for _, tokens := range []UsageTokens{claude.billingUsageTokens(), openAI.billingUsageTokens()} { + require.Equal(t, 40, tokens.InputTokens) + require.Equal(t, 50, tokens.CacheCreationTokens) + require.Equal(t, 10, tokens.CacheReadTokens) + cache5m, cache1h := normalizeCacheCreationBreakdown(tokens) + require.Equal(t, 20, cache5m) + require.Equal(t, 30, cache1h) + require.InDelta(t, 0.1, (&BillingService{}).computeCacheCreationCost(&ModelPricing{}, tokens, 0.002, 1), 1e-12) + } + require.Zero(t, claude.CacheCreationInputTokens) + require.Zero(t, openAI.CacheCreationInputTokens) +} diff --git a/backend/internal/service/gateway_cache_creation_usage_test.go b/backend/internal/service/gateway_cache_creation_usage_test.go index fbdd618e75..b45e6fdcc0 100644 --- a/backend/internal/service/gateway_cache_creation_usage_test.go +++ b/backend/internal/service/gateway_cache_creation_usage_test.go @@ -51,14 +51,14 @@ func TestAnthropicCacheCreationSnapshots(t *testing.T) { wantTotals: []int{50, 40, 40, 40}, want5m: 20, want1h: 200, billed5m: 4, billed1h: 36, }, { - name: "explicit zero survives TTL updates", + name: "explicit zero falls back to TTL updates", snapshots: []string{`{"cache_creation_input_tokens":0,"cache_creation":{"ephemeral_1h_input_tokens":200}}`, `{"cache_creation":{"ephemeral_5m_input_tokens":50}}`}, - wantTotals: []int{0, 0}, want5m: 50, want1h: 200, + wantTotals: []int{200, 250}, want5m: 50, want1h: 200, billed5m: 50, billed1h: 200, }, { - name: "explicit zero delta clears aggregate", + name: "explicit zero delta preserves aggregate", snapshots: []string{`{"cache_creation_input_tokens":100}`, `{"cache_creation_input_tokens":0}`, `{"cache_creation":{"ephemeral_1h_input_tokens":200}}`}, - wantTotals: []int{100, 0, 0}, want1h: 200, + wantTotals: []int{100, 100, 100}, want1h: 200, billed1h: 100, }, { name: "repeated cumulative snapshots do not double count", @@ -78,12 +78,12 @@ func TestAnthropicCacheCreationSnapshots(t *testing.T) { { name: "null does not clear explicit zero", snapshots: []string{`{"cache_creation_input_tokens":0,"cache_creation":{"ephemeral_1h_input_tokens":200}}`, `{"cache_creation_input_tokens":null,"cache_creation":{"ephemeral_5m_input_tokens":20,"ephemeral_1h_input_tokens":null}}`}, - wantTotals: []int{0, 0}, want5m: 20, want1h: 200, + wantTotals: []int{200, 220}, want5m: 20, want1h: 200, billed5m: 20, billed1h: 200, }, { name: "zero to positive retains partial TTL history", snapshots: []string{`{"cache_creation":{"ephemeral_5m_input_tokens":20}}`, `{"cache_creation_input_tokens":0,"cache_creation":{"ephemeral_1h_input_tokens":30}}`, `{"cache_creation":{"ephemeral_1h_input_tokens":50}}`, `{"cache_creation_input_tokens":35}`}, - wantTotals: []int{20, 0, 0, 35}, want5m: 20, want1h: 50, billed5m: 10, billed1h: 25, + wantTotals: []int{20, 50, 70, 35}, want5m: 20, want1h: 50, billed5m: 10, billed1h: 25, }, { name: "all null is absent before partial TTL", @@ -140,7 +140,9 @@ func TestAnthropicCacheCreationMissingDetailForwardBillingBoundary(t *testing.T) {"mixed start remainder defaults to 5m", `"cache_creation_input_tokens":3000,"cache_creation":{"ephemeral_5m_input_tokens":1000,"ephemeral_1h_input_tokens":2000}`, `{"cache_creation_input_tokens":11000}`, 11000, 1000, 2000, 26}, {"zero start aggregate grows", `"cache_creation_input_tokens":0,"cache_creation":{"ephemeral_5m_input_tokens":0,"ephemeral_1h_input_tokens":0}`, `{"cache_creation_input_tokens":11000}`, 11000, 0, 0, 22}, {"unchanged aggregate", `"cache_creation_input_tokens":3000,"cache_creation":{"ephemeral_1h_input_tokens":3000}`, `{"cache_creation_input_tokens":3000}`, 3000, 0, 3000, 12}, - {"explicit zero suppresses retained detail", `"cache_creation_input_tokens":3000,"cache_creation":{"ephemeral_1h_input_tokens":3000}`, `{"cache_creation_input_tokens":0}`, 0, 0, 3000, 0}, + {"explicit zero preserves retained detail", `"cache_creation_input_tokens":3000,"cache_creation":{"ephemeral_1h_input_tokens":3000}`, `{"cache_creation_input_tokens":0}`, 3000, 0, 3000, 12}, + {"explicit zero uses partial details", `"cache_creation_input_tokens":0,"cache_creation":{"ephemeral_5m_input_tokens":50}`, `{"cache_creation_input_tokens":0,"cache_creation":{"ephemeral_1h_input_tokens":200}}`, 250, 50, 200, 0.9}, + {"zero cache placeholders preserve totals", `"cache_creation_input_tokens":100,"cache_read_input_tokens":9,"cache_creation":{"ephemeral_1h_input_tokens":200}`, `{"input_tokens":0,"cache_creation_input_tokens":0,"cache_read_input_tokens":0}`, 100, 0, 200, 0.4}, {"oversized detail ratio capped", `"cache_creation_input_tokens":100,"cache_creation":{"ephemeral_5m_input_tokens":50,"ephemeral_1h_input_tokens":200}`, `{"cache_creation_input_tokens":100}`, 100, 50, 200, 0.36}, } { for _, route := range []string{"standard", "passthrough", "responses", "buffered responses", "chat", "buffered chat"} { @@ -190,6 +192,8 @@ func TestAnthropicCacheCreationMissingDetailForwardBillingBoundary(t *testing.T) } require.NotNil(t, result) require.Equal(t, 10, result.Usage.InputTokens) + wantRead := int(gjson.Get("{"+test.start+"}", "cache_read_input_tokens").Int()) + require.Equal(t, wantRead, result.Usage.CacheReadInputTokens) require.Equal(t, 2, result.Usage.OutputTokens) require.Equal(t, test.aggregate, result.Usage.CacheCreationInputTokens) require.True(t, result.Usage.cacheCreationInputTokensPresent) @@ -218,10 +222,12 @@ func TestAnthropicCacheCreationMissingDetailForwardBillingBoundary(t *testing.T) } require.True(t, usage.Exists()) if strings.HasSuffix(route, "chat") { - require.EqualValues(t, 10+test.aggregate, usage.Get("prompt_tokens").Int()) + require.EqualValues(t, 10+test.aggregate+wantRead, usage.Get("prompt_tokens").Int()) + require.EqualValues(t, wantRead, usage.Get("prompt_tokens_details.cached_tokens").Int()) require.EqualValues(t, test.aggregate, usage.Get("prompt_tokens_details.cache_creation_tokens").Int()) } else { - require.EqualValues(t, 10+test.aggregate, usage.Get("input_tokens").Int()) + require.EqualValues(t, 10+test.aggregate+wantRead, usage.Get("input_tokens").Int()) + require.EqualValues(t, wantRead, usage.Get("input_tokens_details.cached_tokens").Int()) require.EqualValues(t, test.aggregate, usage.Get("cache_creation_input_tokens").Int()) } } @@ -316,7 +322,7 @@ func assertAnthropicCacheCreationForwardBoundary(t *testing.T, antigravity bool) cache1h int cacheCost float64 }{ - {"explicit aggregate zero", `"cache_creation_input_tokens":0,"cache_creation":{"ephemeral_5m_input_tokens":50,"ephemeral_1h_input_tokens":200}`, 0, true, 50, 200, 0}, + {"explicit aggregate zero", `"cache_creation_input_tokens":0,"cache_creation":{"ephemeral_5m_input_tokens":50,"ephemeral_1h_input_tokens":200}`, 250, true, 50, 200, 0.9}, {"missing aggregate", `"cache_creation":{"ephemeral_5m_input_tokens":50,"ephemeral_1h_input_tokens":200}`, 250, false, 50, 200, 0.9}, {"null aggregate", `"cache_creation_input_tokens":null,"cache_creation":{"ephemeral_5m_input_tokens":50,"ephemeral_1h_input_tokens":200}`, 250, false, 50, 200, 0.9}, {"positive aggregate caps TTL", `"cache_creation_input_tokens":100,"cache_creation":{"ephemeral_5m_input_tokens":50,"ephemeral_1h_input_tokens":200}`, 100, true, 50, 200, 0.36}, @@ -362,8 +368,8 @@ func assertAnthropicCacheCreationForwardBoundary(t *testing.T, antigravity bool) require.Equal(t, http.StatusOK, recorder.Code) require.Equal(t, body, recorder.Body.String()) wantAggregate := test.aggregate - if antigravity && !test.present { - wantAggregate = 0 + if antigravity { + wantAggregate = int(gjson.Get(usageJSON, "cache_creation_input_tokens").Int()) } require.Equal(t, wantAggregate, result.Usage.CacheCreationInputTokens) require.Equal(t, test.present, result.Usage.cacheCreationInputTokensPresent) @@ -385,7 +391,7 @@ func TestAnthropicCacheCreationMarshaledSSEBoundary(t *testing.T) { wantCacheCost float64 }{ {"missing", 0, false, 50, 0.16}, - {"explicit zero", 0, true, 0, 0}, + {"explicit zero", 0, true, 50, 0.16}, {"synthetic nonzero", 40, false, 40, 0.128}, } { for _, terminal := range []string{"message_stop", "eof"} { @@ -437,16 +443,18 @@ func TestAnthropicCacheCreationMarshaledSSEBoundary(t *testing.T) { func TestRawAnthropicCacheCreationExplicitZero(t *testing.T) { for _, prompt := range []string{"", `,"prompt_tokens":500`} { usage := parseClaudeUsageFromResponseBody([]byte(`{"usage":{"input_tokens":10,"cache_creation_input_tokens":0,"cache_creation":{"ephemeral_1h_input_tokens":200}` + prompt + `}}`)) - require.Zero(t, usage.CacheCreationInputTokens) + require.Equal(t, 200, usage.CacheCreationInputTokens) require.Equal(t, 200, usage.CacheCreation1hTokens) - assertAnthropicCacheCreationRecordCosts(t, *usage, 0) + assertAnthropicCacheCreationRecordCosts(t, *usage, 0.8) if prompt != "" { - require.Equal(t, 500, usage.InputTokens) + require.Equal(t, 300, usage.InputTokens) + } else { + require.Equal(t, 10, usage.InputTokens) } } usage := &ClaudeUsage{CacheCreationInputTokens: 100} (&AntigravityGatewayService{}).extractSSEUsage(`data: {"type":"message_delta","usage":{"cache_creation_input_tokens":0}}`, usage) - require.Zero(t, usage.CacheCreationInputTokens) + require.Equal(t, 100, usage.CacheCreationInputTokens) } func TestAnthropicCacheCreationNullBodyParity(t *testing.T) { @@ -459,7 +467,7 @@ func TestAnthropicCacheCreationNullBodyParity(t *testing.T) { }{ {"missing aggregate", `{"cache_creation":{"ephemeral_1h_input_tokens":200}}`, 200, false, 0.8}, {"null aggregate", `{"cache_creation_input_tokens":null,"cache_creation":{"ephemeral_1h_input_tokens":200}}`, 200, false, 0.8}, - {"zero aggregate", `{"cache_creation_input_tokens":0,"cache_creation":{"ephemeral_1h_input_tokens":200}}`, 0, true, 0}, + {"zero aggregate", `{"cache_creation_input_tokens":0,"cache_creation":{"ephemeral_1h_input_tokens":200}}`, 200, true, 0.8}, {"null TTL with positive aggregate", `{"cache_creation_input_tokens":100,"cache_creation":{"ephemeral_5m_input_tokens":null,"ephemeral_1h_input_tokens":null}}`, 100, true, 0.2}, {"all null", `{"cache_creation_input_tokens":null,"cache_creation":{"ephemeral_5m_input_tokens":null,"ephemeral_1h_input_tokens":null}}`, 0, false, 0}, } { @@ -488,7 +496,7 @@ func TestAntigravityCacheCreationUsage(t *testing.T) { present bool wantCost float64 }{ - {"explicit zero with TTL", `{"cache_creation_input_tokens":0,"cache_creation":{"ephemeral_5m_input_tokens":50,"ephemeral_1h_input_tokens":200}}`, 0, true, 0}, + {"explicit zero with TTL", `{"cache_creation_input_tokens":0,"cache_creation":{"ephemeral_5m_input_tokens":50,"ephemeral_1h_input_tokens":200}}`, 0, true, 0.9}, {"missing aggregate keeps TTL fallback", `{"cache_creation":{"ephemeral_5m_input_tokens":50,"ephemeral_1h_input_tokens":200}}`, 0, false, 0.9}, {"null aggregate keeps TTL fallback", `{"cache_creation_input_tokens":null,"cache_creation":{"ephemeral_5m_input_tokens":50,"ephemeral_1h_input_tokens":200}}`, 0, false, 0.9}, {"positive aggregate", `{"cache_creation_input_tokens":100,"cache_creation":{"ephemeral_1h_input_tokens":200}}`, 100, true, 0.4}, @@ -521,7 +529,7 @@ func TestAntigravityCacheCreationLateDeltas(t *testing.T) { present bool wantCost float64 }{ - {"explicit zero survives", `"cache_creation_input_tokens":0,`, 0, true, 0}, + {"explicit zero falls back", `"cache_creation_input_tokens":0,`, 0, true, 1.3}, {"missing aggregate keeps TTL fallback", "", 0, false, 1.3}, {"null aggregate keeps TTL fallback", `"cache_creation_input_tokens":null,`, 0, false, 1.3}, {"positive aggregate survives", `"cache_creation_input_tokens":100,`, 100, true, 0.372}, @@ -545,20 +553,79 @@ func TestAntigravityCacheCreationLateDeltas(t *testing.T) { }) } - t.Run("explicit zero delta clears aggregate with retained TTL", func(t *testing.T) { + t.Run("explicit zero delta preserves aggregate with retained TTL", func(t *testing.T) { service := &AntigravityGatewayService{} usage := &ClaudeUsage{} - service.extractSSEUsage(`data: {"type":"message_start","message":{"usage":{"cache_creation_input_tokens":100,"cache_creation":{"ephemeral_1h_input_tokens":200}}}}`, usage) - service.extractSSEUsage(`data: {"type":"message_delta","usage":{"cache_creation_input_tokens":0}}`, usage) + service.extractSSEUsage(`data: {"type":"message_start","message":{"usage":{"input_tokens":10,"cache_read_input_tokens":9,"cache_creation_input_tokens":100,"cache_creation":{"ephemeral_1h_input_tokens":200}}}}`, usage) + for range 2 { + service.extractSSEUsage(`data: {"type":"message_delta","usage":{"input_tokens":0,"cache_read_input_tokens":0,"cache_creation_input_tokens":0}}`, usage) + } service.extractSSEUsage(`data: {"type":"message_delta","usage":{"cache_creation_input_tokens":null,"cache_creation":{"ephemeral_5m_input_tokens":50}}}`, usage) - require.Zero(t, usage.CacheCreationInputTokens) + require.Equal(t, 100, usage.CacheCreationInputTokens) + require.Equal(t, 9, usage.CacheReadInputTokens) + require.Equal(t, 10, usage.InputTokens) require.True(t, usage.cacheCreationInputTokensPresent) require.Equal(t, 50, usage.CacheCreation5mTokens) require.Equal(t, 200, usage.CacheCreation1hTokens) - assertAnthropicCacheCreationRecordCosts(t, *usage, 0) + assertAnthropicCacheCreationRecordCosts(t, *usage, 0.36) }) } +func TestAntigravityRawCacheUsageStreamingLifecycle(t *testing.T) { + gin.SetMode(gin.TestMode) + for _, test := range []struct { + name string + aggregate string + wantTotal int + wantCost float64 + }{ + {"zero aggregate keeps TTL billing fallback", "0", 0, 1.3}, + {"positive aggregate survives zero placeholders", "100", 100, 0.372}, + } { + for _, terminal := range []string{"message_stop", "eof"} { + t.Run(test.name+"/"+terminal, func(t *testing.T) { + stream := "event: message_start\ndata: " + `{"type":"message_start","message":{"id":"msg_cache","type":"message","role":"assistant","model":"claude-sonnet-4","content":[],"usage":{"input_tokens":10,"output_tokens":0,"cache_read_input_tokens":9,"cache_creation_input_tokens":` + test.aggregate + `,"cache_creation":{"ephemeral_1h_input_tokens":200}}}}` + "\n\n" + for _, snapshot := range []string{ + `{"output_tokens":7,"cache_creation":{"ephemeral_5m_input_tokens":50}}`, + `{"cache_creation":{"ephemeral_1h_input_tokens":300}}`, + `{"input_tokens":0,"output_tokens":0,"cache_read_input_tokens":0,"cache_creation_input_tokens":0}`, + `{"input_tokens":0,"output_tokens":0,"cache_read_input_tokens":0,"cache_creation_input_tokens":0}`, + `{"cache_creation_input_tokens":null,"cache_creation":{"ephemeral_5m_input_tokens":null,"ephemeral_1h_input_tokens":null}}`, + } { + stream += "event: message_delta\ndata: " + `{"type":"message_delta","usage":` + snapshot + "}\n\n" + } + stream += "event: message_delta\ndata: " + `{"type":"message_delta","delta":{"stop_reason":"end_turn"},"usage":{"output_tokens":0,"cache_creation_input_tokens":0}}` + "\n\n" + if terminal == "message_stop" { + stream += "event: message_stop\ndata: {\"type\":\"message_stop\"}\n\n" + } + recorder := httptest.NewRecorder() + ctx, _ := gin.CreateTestContext(recorder) + ctx.Request = httptest.NewRequest(http.MethodPost, "/v1/messages", nil) + response := &http.Response{ + StatusCode: http.StatusOK, Header: http.Header{"Content-Type": []string{"text/event-stream"}}, + Body: io.NopCloser(strings.NewReader(stream)), + } + service := &AntigravityGatewayService{httpUpstream: &httpUpstreamStub{resp: response}, settingService: &SettingService{}} + result, err := service.ForwardUpstream(context.Background(), ctx, + &Account{ID: 701, Credentials: map[string]any{"base_url": "https://upstream.example", "api_key": "test-key"}}, + []byte(`{"model":"claude-sonnet-4","messages":[],"stream":true}`)) + require.NoError(t, err) + require.True(t, result.Stream) + require.Equal(t, http.StatusOK, recorder.Code) + require.Equal(t, stream, recorder.Body.String()) + require.Equal(t, 10, result.Usage.InputTokens) + require.Equal(t, 7, result.Usage.OutputTokens) + require.Equal(t, 9, result.Usage.CacheReadInputTokens) + require.Equal(t, test.wantTotal, result.Usage.CacheCreationInputTokens) + require.True(t, result.Usage.cacheCreationInputTokensPresent) + require.Equal(t, 50, result.Usage.CacheCreation5mTokens) + require.Equal(t, 300, result.Usage.CacheCreation1hTokens) + assertAnthropicCacheCreationResultCosts(t, result, test.wantCost) + }) + } + } +} + func TestAnthropicCacheOnlyBufferedSSEUsage(t *testing.T) { gin.SetMode(gin.TestMode) for _, test := range []struct { @@ -567,54 +634,62 @@ func TestAnthropicCacheOnlyBufferedSSEUsage(t *testing.T) { delta string wantAggregate int }{ - {"explicit zero transition", `{"cache_creation_input_tokens":100,"cache_creation":{"ephemeral_1h_input_tokens":200}}`, `{"cache_creation_input_tokens":0}`, 0}, + {"explicit zero transition", `{"cache_creation_input_tokens":100,"cache_creation":{"ephemeral_1h_input_tokens":200}}`, `{"cache_creation_input_tokens":0}`, 100}, {"derived zero transition", `{"cache_creation":{"ephemeral_5m_input_tokens":20}}`, `{"cache_creation":{"ephemeral_5m_input_tokens":0}}`, 0}, {"merged partial TTL", `{"cache_creation":{"ephemeral_5m_input_tokens":20}}`, `{"cache_creation_input_tokens":null,"cache_creation":{"ephemeral_5m_input_tokens":null,"ephemeral_1h_input_tokens":30}}`, 50}, + {"explicit zero partial TTL", `{"cache_creation_input_tokens":0,"cache_creation":{"ephemeral_5m_input_tokens":20}}`, `{"cache_creation_input_tokens":0,"cache_creation":{"ephemeral_1h_input_tokens":30}}`, 50}, } { for _, adapter := range []string{"responses", "chat", "native responses", "native chat"} { - t.Run(test.name+"/"+adapter, func(t *testing.T) { - stream := "event: message_start\ndata: {\"type\":\"message_start\",\"message\":{\"id\":\"msg_cache\",\"type\":\"message\",\"role\":\"assistant\",\"model\":\"claude-sonnet-4\",\"content\":[],\"usage\":" + test.start + "}}\n\n" + - "event: message_delta\ndata: {\"type\":\"message_delta\",\"usage\":" + test.delta + "}\n\nevent: message_stop\ndata: {\"type\":\"message_stop\"}\n\n" - recorder := httptest.NewRecorder() - ctx, _ := gin.CreateTestContext(recorder) - response := &http.Response{Body: io.NopCloser(strings.NewReader(stream))} - var aggregate int - var err error - switch adapter { - case "responses": - var result *ForwardResult - result, err = (&GatewayService{}).handleResponsesBufferedStreamingResponse(response, ctx, "claude-sonnet-4", "claude-sonnet-4", nil, time.Now(), apicompat.ResponsesClientToolMapping{}) - require.NoError(t, err) - aggregate = result.Usage.CacheCreationInputTokens - case "chat": - var result *ForwardResult - result, err = (&GatewayService{}).handleCCBufferedFromAnthropic(response, ctx, "claude-sonnet-4", "claude-sonnet-4", nil, time.Now()) - require.NoError(t, err) - aggregate = result.Usage.CacheCreationInputTokens - case "native responses": - var result *OpenAIForwardResult - result, err = (&OpenAIGatewayService{}).handleResponsesBufferedFromNativeAnthropic(response, ctx, "claude-sonnet-4", "claude-sonnet-4", "claude-sonnet-4", nil, time.Now(), apicompat.ResponsesClientToolMapping{}) - require.NoError(t, err) - aggregate = result.Usage.CacheCreationInputTokens - case "native chat": - var result *OpenAIForwardResult - result, err = (&OpenAIGatewayService{}).handleCCBufferedFromNativeAnthropic(response, ctx, "claude-sonnet-4", "claude-sonnet-4", "claude-sonnet-4", nil, time.Now()) - require.NoError(t, err) - aggregate = result.Usage.CacheCreationInputTokens - } - require.Equal(t, test.wantAggregate, aggregate) - require.Equal(t, http.StatusOK, recorder.Code) - require.True(t, json.Valid(recorder.Body.Bytes())) - inputPath := "usage.input_tokens" - cachePath := "usage.cache_creation_input_tokens" - if strings.HasSuffix(adapter, "chat") { - inputPath = "usage.prompt_tokens" - cachePath = "usage.prompt_tokens_details.cache_creation_tokens" - } - require.True(t, gjson.GetBytes(recorder.Body.Bytes(), inputPath).Exists()) - require.Equal(t, int64(test.wantAggregate), gjson.GetBytes(recorder.Body.Bytes(), inputPath).Int()) - require.Equal(t, int64(test.wantAggregate), gjson.GetBytes(recorder.Body.Bytes(), cachePath).Int()) - }) + for _, terminal := range []string{"message_stop", "eof"} { + t.Run(test.name+"/"+adapter+"/"+terminal, func(t *testing.T) { + stream := "event: message_start\ndata: {\"type\":\"message_start\",\"message\":{\"id\":\"msg_cache\",\"type\":\"message\",\"role\":\"assistant\",\"model\":\"claude-sonnet-4\",\"content\":[],\"usage\":" + test.start + "}}\n\n" + for range 2 { + stream += "event: message_delta\ndata: {\"type\":\"message_delta\",\"usage\":" + test.delta + "}\n\n" + } + if terminal == "message_stop" { + stream += "event: message_stop\ndata: {\"type\":\"message_stop\"}\n\n" + } + recorder := httptest.NewRecorder() + ctx, _ := gin.CreateTestContext(recorder) + response := &http.Response{Body: io.NopCloser(strings.NewReader(stream))} + var aggregate int + var err error + switch adapter { + case "responses": + var result *ForwardResult + result, err = (&GatewayService{}).handleResponsesBufferedStreamingResponse(response, ctx, "claude-sonnet-4", "claude-sonnet-4", nil, time.Now(), apicompat.ResponsesClientToolMapping{}) + require.NoError(t, err) + aggregate = result.Usage.CacheCreationInputTokens + case "chat": + var result *ForwardResult + result, err = (&GatewayService{}).handleCCBufferedFromAnthropic(response, ctx, "claude-sonnet-4", "claude-sonnet-4", nil, time.Now()) + require.NoError(t, err) + aggregate = result.Usage.CacheCreationInputTokens + case "native responses": + var result *OpenAIForwardResult + result, err = (&OpenAIGatewayService{}).handleResponsesBufferedFromNativeAnthropic(response, ctx, "claude-sonnet-4", "claude-sonnet-4", "claude-sonnet-4", nil, time.Now(), apicompat.ResponsesClientToolMapping{}) + require.NoError(t, err) + aggregate = result.Usage.CacheCreationInputTokens + case "native chat": + var result *OpenAIForwardResult + result, err = (&OpenAIGatewayService{}).handleCCBufferedFromNativeAnthropic(response, ctx, "claude-sonnet-4", "claude-sonnet-4", "claude-sonnet-4", nil, time.Now()) + require.NoError(t, err) + aggregate = result.Usage.CacheCreationInputTokens + } + require.Equal(t, test.wantAggregate, aggregate) + require.Equal(t, http.StatusOK, recorder.Code) + require.True(t, json.Valid(recorder.Body.Bytes())) + inputPath := "usage.input_tokens" + cachePath := "usage.cache_creation_input_tokens" + if strings.HasSuffix(adapter, "chat") { + inputPath = "usage.prompt_tokens" + cachePath = "usage.prompt_tokens_details.cache_creation_tokens" + } + require.True(t, gjson.GetBytes(recorder.Body.Bytes(), inputPath).Exists()) + require.Equal(t, int64(test.wantAggregate), gjson.GetBytes(recorder.Body.Bytes(), inputPath).Int()) + require.Equal(t, int64(test.wantAggregate), gjson.GetBytes(recorder.Body.Bytes(), cachePath).Int()) + }) + } } } } diff --git a/backend/internal/service/gateway_cache_ttl_override_test.go b/backend/internal/service/gateway_cache_ttl_override_test.go index 6b7959ce1e..07e29bab44 100644 --- a/backend/internal/service/gateway_cache_ttl_override_test.go +++ b/backend/internal/service/gateway_cache_ttl_override_test.go @@ -17,6 +17,7 @@ import ( "github.com/Wei-Shaw/sub2api/internal/pkg/apicompat" "github.com/gin-gonic/gin" "github.com/stretchr/testify/require" + "github.com/tidwall/gjson" ) func TestApplyCacheTTLOverrideAuthoritativeTotal(t *testing.T) { @@ -28,7 +29,7 @@ func TestApplyCacheTTLOverrideAuthoritativeTotal(t *testing.T) { }{ {"partial details", ClaudeUsage{CacheCreationInputTokens: 11000, CacheCreation1hTokens: 3000, cacheCreationInputTokensPresent: true}, 11000, true}, {"oversized details", ClaudeUsage{CacheCreationInputTokens: 100, CacheCreation5mTokens: 50, CacheCreation1hTokens: 200, cacheCreationInputTokensPresent: true}, 100, true}, - {"explicit zero", ClaudeUsage{CacheCreation5mTokens: 50, CacheCreation1hTokens: 200, cacheCreationInputTokensPresent: true}, 0, true}, + {"explicit zero", ClaudeUsage{CacheCreation5mTokens: 50, CacheCreation1hTokens: 200, cacheCreationInputTokensPresent: true}, 250, true}, {"synthetic positive aggregate", ClaudeUsage{CacheCreationInputTokens: 11000, CacheCreation1hTokens: 3000}, 11000, true}, {"synthetic detail only", ClaudeUsage{CacheCreation5mTokens: 50, CacheCreation1hTokens: 200}, 250, true}, {"synthetic negative detail", ClaudeUsage{CacheCreation5mTokens: -50, CacheCreation1hTokens: 200}, 200, true}, @@ -68,9 +69,9 @@ type cacheTTLOverrideBoundaryCase struct { func cacheTTLOverrideBoundaryCases() []cacheTTLOverrideBoundaryCase { return []cacheTTLOverrideBoundaryCase{ {"growing aggregate", []string{`{"cache_creation_input_tokens":3000,"cache_creation":{"ephemeral_1h_input_tokens":3000}}`, `{"cache_creation_input_tokens":11000}`}, 11000, true, 0, 3000, 28}, - {"explicit zero delta", []string{`{"cache_creation_input_tokens":3000,"cache_creation":{"ephemeral_1h_input_tokens":3000}}`, `{"cache_creation_input_tokens":0}`}, 0, true, 0, 3000, 0}, + {"explicit zero delta", []string{`{"cache_creation_input_tokens":3000,"cache_creation":{"ephemeral_1h_input_tokens":3000}}`, `{"cache_creation_input_tokens":0}`}, 3000, true, 0, 3000, 12}, {"oversized details", []string{`{"cache_creation_input_tokens":100,"cache_creation":{"ephemeral_5m_input_tokens":50,"ephemeral_1h_input_tokens":200}}`}, 100, true, 50, 200, 0.36}, - {"explicit zero snapshot", []string{`{"cache_creation_input_tokens":0,"cache_creation":{"ephemeral_5m_input_tokens":50,"ephemeral_1h_input_tokens":200}}`}, 0, true, 50, 200, 0}, + {"explicit zero snapshot", []string{`{"cache_creation_input_tokens":0,"cache_creation":{"ephemeral_5m_input_tokens":50,"ephemeral_1h_input_tokens":200}}`}, 250, true, 50, 200, 0.9}, {"detail only", []string{`{"cache_creation":{"ephemeral_5m_input_tokens":50,"ephemeral_1h_input_tokens":200}}`}, 250, false, 50, 200, 0.9}, {"null aggregate", []string{`{"cache_creation_input_tokens":null,"cache_creation":{"ephemeral_5m_input_tokens":50,"ephemeral_1h_input_tokens":200}}`}, 250, false, 50, 200, 0.9}, {"aggregate only", []string{`{"cache_creation_input_tokens":11000}`}, 11000, true, 0, 0, 22}, @@ -101,7 +102,11 @@ func cacheTTLOverrideBoundaryResponse(test cacheTTLOverrideBoundaryCase, stream if !stream { cache := `"cache_creation":{"ephemeral_5m_input_tokens":` + strconv.Itoa(test.ttl5m) + `,"ephemeral_1h_input_tokens":` + strconv.Itoa(test.ttl1h) + `}` if test.present { - cache += `,"cache_creation_input_tokens":` + strconv.Itoa(test.aggregate) + aggregate := test.aggregate + if len(test.snapshots) == 1 { + aggregate = int(gjson.Get(test.snapshots[0], "cache_creation_input_tokens").Int()) + } + cache += `,"cache_creation_input_tokens":` + strconv.Itoa(aggregate) } return `{"id":"msg_cache","type":"message","role":"assistant","model":"k3","content":[],"usage":{` + base + `,` + cache + `}}` } @@ -178,7 +183,46 @@ func TestCacheTTLOverrideForwardBillingBoundary(t *testing.T) { } else if target == "1h" { want5m, want1h, wantCost = 0, test.aggregate, float64(test.aggregate)*0.004 } - if target != "" && (route == "nonstream" || (route == "standard" && test.aggregate > 0)) { + if target != "" && route == "standard" { + var originalEvents, rewrittenEvents []string + for _, line := range strings.Split(payload, "\n") { + if strings.HasPrefix(line, "data: ") { + originalEvents = append(originalEvents, strings.TrimPrefix(line, "data: ")) + } + } + for _, line := range strings.Split(recorder.Body.String(), "\n") { + if strings.HasPrefix(line, "data: ") { + rewrittenEvents = append(rewrittenEvents, strings.TrimPrefix(line, "data: ")) + } + } + require.Len(t, rewrittenEvents, len(originalEvents)) + forward5m, forward1h := 0, 0 + for index, originalEvent := range originalEvents { + usagePath := "usage" + if gjson.Get(originalEvent, "type").String() == "message_start" { + usagePath = "message.usage" + } + originalUsage := gjson.Get(originalEvent, usagePath) + rewrittenUsage := gjson.Get(rewrittenEvents[index], usagePath) + require.Equal(t, originalUsage.Get("cache_creation").Exists(), rewrittenUsage.Get("cache_creation").Exists()) + require.Equal(t, originalUsage.Get("cache_creation_input_tokens").Raw, rewrittenUsage.Get("cache_creation_input_tokens").Raw) + if originalUsage.Get("cache_creation").IsObject() { + total := int(originalUsage.Get("cache_creation_input_tokens").Int()) + if total <= 0 { + total = int(originalUsage.Get("cache_creation.ephemeral_5m_input_tokens").Int() + originalUsage.Get("cache_creation.ephemeral_1h_input_tokens").Int()) + } + forward5m, forward1h = 0, total + if target == "5m" { + forward5m, forward1h = total, 0 + } + require.EqualValues(t, forward5m, rewrittenUsage.Get("cache_creation.ephemeral_5m_input_tokens").Int()) + require.EqualValues(t, forward1h, rewrittenUsage.Get("cache_creation.ephemeral_1h_input_tokens").Int()) + } + } + require.Equal(t, forward5m, result.Usage.CacheCreation5mTokens) + require.Equal(t, forward1h, result.Usage.CacheCreation1hTokens) + } + if target != "" && route == "nonstream" { require.Equal(t, want5m, result.Usage.CacheCreation5mTokens) require.Equal(t, want1h, result.Usage.CacheCreation1hTokens) } @@ -262,11 +306,14 @@ func TestRewriteCacheCreationJSONAuthoritativeTotal(t *testing.T) { } require.NoError(t, json.Unmarshal([]byte(cacheTTLOverrideBoundaryResponse(test, false, 0)), &response)) aggregate, present := response.Usage["cache_creation_input_tokens"] - require.True(t, rewriteCacheCreationJSON(response.Usage, target)) + originalDetails := response.Usage["cache_creation"].(map[string]any) + original5m := int(originalDetails["ephemeral_5m_input_tokens"].(float64)) + original1h := int(originalDetails["ephemeral_1h_input_tokens"].(float64)) want5m, want1h := 0, test.aggregate if target == "5m" { want5m, want1h = test.aggregate, 0 } + require.Equal(t, original5m != want5m || original1h != want1h, rewriteCacheCreationJSON(response.Usage, target)) details := response.Usage["cache_creation"].(map[string]any) require.EqualValues(t, want5m, details["ephemeral_5m_input_tokens"]) require.EqualValues(t, want1h, details["ephemeral_1h_input_tokens"]) @@ -278,3 +325,72 @@ func TestRewriteCacheCreationJSONAuthoritativeTotal(t *testing.T) { } } } + +func TestRewriteCacheCreationJSONPreservesAbsentDetails(t *testing.T) { + for _, payload := range []string{ + `{"cache_creation_input_tokens":100}`, + `{"cache_creation_input_tokens":100,"cache_creation":null}`, + `{"cache_creation_input_tokens":0}`, + } { + for _, target := range []string{"5m", "1h"} { + var usage map[string]any + require.NoError(t, json.Unmarshal([]byte(payload), &usage)) + for range 2 { + require.False(t, rewriteCacheCreationJSON(usage, target)) + encoded, err := json.Marshal(usage) + require.NoError(t, err) + require.JSONEq(t, payload, string(encoded)) + } + } + } +} + +func TestCacheTTLOverrideForwardPreservesAbsentDetails(t *testing.T) { + gin.SetMode(gin.TestMode) + for _, details := range []string{"", `,"cache_creation":null`} { + for _, stream := range []bool{false, true} { + for _, target := range []string{"5m", "1h"} { + t.Run(details+"/stream="+strconv.FormatBool(stream)+"/"+target, func(t *testing.T) { + account, settings, _ := cacheTTLOverrideBoundaryAccount(t, "account/"+target) + usage := `{"input_tokens":10,"output_tokens":2,"cache_creation_input_tokens":100` + details + `}` + payload := `{"id":"msg_cache","type":"message","role":"assistant","model":"k3","content":[],"usage":` + usage + `}` + contentType := "application/json" + if stream { + payload = "event: message_start\ndata: {\"type\":\"message_start\",\"message\":" + payload + "}\n\nevent: message_stop\ndata: {\"type\":\"message_stop\"}\n\n" + contentType = "text/event-stream" + } + recorder := httptest.NewRecorder() + ctx, _ := gin.CreateTestContext(recorder) + ctx.Request = httptest.NewRequest(http.MethodPost, "/v1/messages", nil) + response := &http.Response{StatusCode: http.StatusOK, Header: http.Header{"Content-Type": []string{contentType}}, Body: io.NopCloser(strings.NewReader(payload))} + service := &GatewayService{cfg: &config.Config{}, rateLimitService: &RateLimitService{}, settingService: settings} + var err error + if stream { + _, err = service.handleStreamingResponse(context.Background(), response, ctx, account, time.Now(), "k3", "k3", false) + } else { + _, err = service.handleNonStreamingResponse(context.Background(), response, ctx, account, "k3", "k3") + } + require.NoError(t, err) + if !stream { + require.JSONEq(t, payload, recorder.Body.String()) + return + } + starts := 0 + for _, line := range strings.Split(recorder.Body.String(), "\n") { + if !strings.HasPrefix(line, "data: ") { + continue + } + event := gjson.Parse(strings.TrimPrefix(line, "data: ")) + if event.Get("type").String() == "message_start" { + got := event.Get("message.usage.cache_creation") + require.False(t, got.IsObject()) + require.Equal(t, gjson.Get(usage, "cache_creation").Raw, got.Raw) + starts++ + } + } + require.Equal(t, 1, starts) + }) + } + } + } +} diff --git a/backend/internal/service/gateway_forward_as_responses.go b/backend/internal/service/gateway_forward_as_responses.go index cb492392c2..b2d12332d3 100644 --- a/backend/internal/service/gateway_forward_as_responses.go +++ b/backend/internal/service/gateway_forward_as_responses.go @@ -324,7 +324,7 @@ func mergeAnthropicUsage(dst *ClaudeUsage, src apicompat.AnthropicUsage) { dst.InputTokens = src.InputTokens } } - if hasCacheReadTokens { + if hasCacheReadTokens && (cacheReadTokens > 0 || dst.CacheReadInputTokens <= 0) { dst.CacheReadInputTokens = cacheReadTokens } normalizeAnthropicPromptTotal(dst, src.PromptTokens, src.PromptCacheMissTokens) @@ -349,9 +349,10 @@ func normalizeAnthropicPromptTotal(usage *ClaudeUsage, promptTokens int, promptC } func mergeAnthropicCacheCreationUsage(dst *ClaudeUsage, src apicompat.AnthropicUsage) { - if src.HasCacheCreationInputTokens() { + if src.HasCacheCreationInputTokens() && (src.CacheCreationInputTokens > 0 || dst.CacheCreationInputTokens <= 0) { dst.CacheCreationInputTokens = max(src.CacheCreationInputTokens, 0) dst.cacheCreationInputTokensPresent = true + dst.cacheCreationInputTokensFromDetails = false } if src.CacheCreation != nil { if src.CacheCreation.Ephemeral5mInputTokens != nil { @@ -360,8 +361,9 @@ func mergeAnthropicCacheCreationUsage(dst *ClaudeUsage, src apicompat.AnthropicU if src.CacheCreation.Ephemeral1hInputTokens != nil { dst.CacheCreation1hTokens = max(*src.CacheCreation.Ephemeral1hInputTokens, 0) } - if !dst.cacheCreationInputTokensPresent && (src.CacheCreation.Ephemeral5mInputTokens != nil || src.CacheCreation.Ephemeral1hInputTokens != nil) { + if (!dst.cacheCreationInputTokensPresent || dst.cacheCreationInputTokensFromDetails || dst.CacheCreationInputTokens <= 0) && (src.CacheCreation.Ephemeral5mInputTokens != nil || src.CacheCreation.Ephemeral1hInputTokens != nil) { dst.CacheCreationInputTokens = dst.CacheCreation5mTokens + dst.CacheCreation1hTokens + dst.cacheCreationInputTokensFromDetails = true } } } @@ -401,6 +403,7 @@ func normalizeAnthropicEventUsageForResponses(event *apicompat.AnthropicStreamEv dst.CacheReadInputTokens = usage.CacheReadInputTokens dst.CacheCreationInputTokens = usage.CacheCreationInputTokens dst.CacheCreationInputTokensPresent = true + dst.CacheCreation = nil } normalize(event.Usage) if event.Message != nil { diff --git a/backend/internal/service/gateway_forward_as_responses_test.go b/backend/internal/service/gateway_forward_as_responses_test.go index 13416b719a..c35bf0b749 100644 --- a/backend/internal/service/gateway_forward_as_responses_test.go +++ b/backend/internal/service/gateway_forward_as_responses_test.go @@ -376,10 +376,10 @@ func TestHandleResponsesStreamingResponse_NormalizesTerminalUsage(t *testing.T) wantInput: 10, wantOutput: 7, wantCacheCreation: 100, }, { - name: "explicit zero survives contradictory TTL breakdown", + name: "explicit zero falls back to TTL breakdown", startUsage: `"input_tokens":10,"cache_creation_input_tokens":0,"cache_creation":{"ephemeral_1h_input_tokens":200}`, deltaUsage: `"output_tokens":7,"cache_creation":{"ephemeral_1h_input_tokens":200}`, - wantInput: 10, wantOutput: 7, + wantInput: 10, wantOutput: 7, wantCacheCreation: 200, }, { name: "null aggregate and TTL preserve partial snapshots", @@ -391,7 +391,13 @@ func TestHandleResponsesStreamingResponse_NormalizesTerminalUsage(t *testing.T) name: "null does not clear explicit aggregate zero", startUsage: `"input_tokens":10,"cache_creation_input_tokens":0,"cache_creation":{"ephemeral_1h_input_tokens":200}`, deltaUsage: `"output_tokens":7,"cache_creation_input_tokens":null,"cache_creation":{"ephemeral_1h_input_tokens":null}`, - wantInput: 10, wantOutput: 7, + wantInput: 10, wantOutput: 7, wantCacheCreation: 200, + }, + { + name: "zero placeholders preserve normalized prompt total", + startUsage: `"input_tokens":100,"prompt_tokens":100,"cache_read_input_tokens":30,"cache_creation_input_tokens":0,"cache_creation":{"ephemeral_5m_input_tokens":20}`, + deltaUsage: `"input_tokens":0,"output_tokens":7,"cache_read_input_tokens":0,"cache_creation_input_tokens":0,"cache_creation":{"ephemeral_1h_input_tokens":10}`, + wantInput: 40, wantOutput: 7, wantCached: 30, wantCacheCreation: 30, }, } diff --git a/backend/internal/service/gateway_service.go b/backend/internal/service/gateway_service.go index b20b006a24..30499271dc 100644 --- a/backend/internal/service/gateway_service.go +++ b/backend/internal/service/gateway_service.go @@ -605,9 +605,10 @@ type ClaudeUsage struct { CacheCreation1hTokens int // 1小时缓存创建token(来自嵌套 cache_creation 对象) ImageOutputTokens int `json:"image_output_tokens,omitempty"` - cacheCreationInputTokensPresent bool - promptTotalTokens int - promptTotalPresent bool + cacheCreationInputTokensPresent bool + cacheCreationInputTokensFromDetails bool + promptTotalTokens int + promptTotalPresent bool } // ForwardResult 转发结果 diff --git a/backend/internal/service/gateway_upstream_response.go b/backend/internal/service/gateway_upstream_response.go index 3049f3b3d7..81b6809aea 100644 --- a/backend/internal/service/gateway_upstream_response.go +++ b/backend/internal/service/gateway_upstream_response.go @@ -1304,11 +1304,12 @@ func mergeSSEUsagePatch(usage *ClaudeUsage, patch *sseUsagePatch) { if patch.hasInputTokens { usage.InputTokens = patch.inputTokens } - if patch.hasCacheCreationInput { + if patch.hasCacheCreationInput && (patch.cacheCreationInputTokens > 0 || usage.CacheCreationInputTokens <= 0) { usage.CacheCreationInputTokens = patch.cacheCreationInputTokens usage.cacheCreationInputTokensPresent = true + usage.cacheCreationInputTokensFromDetails = false } - if patch.hasCacheReadInput { + if patch.hasCacheReadInput && (patch.cacheReadInputTokens > 0 || usage.CacheReadInputTokens <= 0) { usage.CacheReadInputTokens = patch.cacheReadInputTokens } if patch.hasOutputTokens { @@ -1320,8 +1321,9 @@ func mergeSSEUsagePatch(usage *ClaudeUsage, patch *sseUsagePatch) { if patch.hasCacheCreation1h { usage.CacheCreation1hTokens = patch.cacheCreation1hTokens } - if !usage.cacheCreationInputTokensPresent && (patch.hasCacheCreation5m || patch.hasCacheCreation1h) { + if (!usage.cacheCreationInputTokensPresent || usage.cacheCreationInputTokensFromDetails || usage.CacheCreationInputTokens <= 0) && (patch.hasCacheCreation5m || patch.hasCacheCreation1h) { usage.CacheCreationInputTokens = max(usage.CacheCreation5mTokens, 0) + max(usage.CacheCreation1hTokens, 0) + usage.cacheCreationInputTokensFromDetails = true } normalizeAnthropicPromptTotal(usage, patch.promptTokens, patch.promptCacheMissTokens) } @@ -1357,7 +1359,7 @@ func parseSSEUsageInt(value any) (int, bool) { // target 为 "5m" 或 "1h"。返回 true 表示发生了变更。 func applyCacheTTLOverride(usage *ClaudeUsage, target string) bool { total := max(usage.CacheCreationInputTokens, 0) - if !usage.cacheCreationInputTokensPresent && total == 0 { + if total == 0 { total = max(usage.CacheCreation5mTokens, 0) + max(usage.CacheCreation1hTokens, 0) } switch target { @@ -1381,6 +1383,9 @@ func applyCacheTTLOverride(usage *ClaudeUsage, target string) bool { // usageObj 是 usage JSON 对象(map[string]any)。 func rewriteCacheCreationJSON(usageObj map[string]any, target string) bool { ccObj, _ := usageObj["cache_creation"].(map[string]any) + if ccObj == nil { + return false + } v5m, _ := parseSSEUsageInt(ccObj["ephemeral_5m_input_tokens"]) v1h, _ := parseSSEUsageInt(ccObj["ephemeral_1h_input_tokens"]) aggregate, present := parseSSEUsageInt(usageObj["cache_creation_input_tokens"]) @@ -1393,10 +1398,6 @@ func rewriteCacheCreationJSON(usageObj map[string]any, target string) bool { if !applyCacheTTLOverride(&usage, target) { return false } - if ccObj == nil { - ccObj = make(map[string]any) - usageObj["cache_creation"] = ccObj - } ccObj["ephemeral_5m_input_tokens"] = float64(usage.CacheCreation5mTokens) ccObj["ephemeral_1h_input_tokens"] = float64(usage.CacheCreation1hTokens) return true @@ -1457,7 +1458,7 @@ func (s *GatewayService) handleNonStreamingResponse(ctx context.Context, resp *h // Cache TTL Override: 重写 non-streaming 响应中的 cache_creation 分类。 // 账号级设置优先;全局 1h 请求注入开启时,默认把 usage 计费归回 5m。 if overrideTarget, ok := s.resolveCacheTTLUsageOverrideTarget(ctx, account); ok { - if applyCacheTTLOverride(&response.Usage, overrideTarget) { + if changed := applyCacheTTLOverride(&response.Usage, overrideTarget); changed && gjson.GetBytes(body, "usage.cache_creation").IsObject() { // 同步更新 body JSON 中的嵌套 cache_creation 对象 if newBody, err := sjson.SetBytes(body, "usage.cache_creation.ephemeral_5m_input_tokens", response.Usage.CacheCreation5mTokens); err == nil { body = newBody diff --git a/backend/internal/service/gateway_usage_billing.go b/backend/internal/service/gateway_usage_billing.go index a280c1fcca..de31a2dac0 100644 --- a/backend/internal/service/gateway_usage_billing.go +++ b/backend/internal/service/gateway_usage_billing.go @@ -1243,22 +1243,20 @@ func (s *GatewayService) calculateImageCost( return s.billingService.CalculateImageCost(billingModel, sizeTier, result.ImageCount, groupConfig, multiplier) } -// billingUsageTokens projects explicit aggregate zero to effective zero TTL usage -// for billing and account stats, retaining raw TTL details on ClaudeUsage. func (usage ClaudeUsage) billingUsageTokens() UsageTokens { + creationTokens := usage.CacheCreationInputTokens + if creationTokens <= 0 { + creationTokens = max(usage.CacheCreation5mTokens, 0) + max(usage.CacheCreation1hTokens, 0) + } tokens := UsageTokens{ InputTokens: usage.InputTokens, OutputTokens: usage.OutputTokens, - CacheCreationTokens: usage.CacheCreationInputTokens, + CacheCreationTokens: creationTokens, CacheReadTokens: usage.CacheReadInputTokens, CacheCreation5mTokens: usage.CacheCreation5mTokens, CacheCreation1hTokens: usage.CacheCreation1hTokens, ImageOutputTokens: usage.ImageOutputTokens, } - if usage.cacheCreationInputTokensPresent && usage.CacheCreationInputTokens == 0 { - tokens.CacheCreation5mTokens = 0 - tokens.CacheCreation1hTokens = 0 - } return tokens } diff --git a/backend/internal/service/openai_gateway_native_cache_creation_test.go b/backend/internal/service/openai_gateway_native_cache_creation_test.go index 121ade7a25..63bfcf6c00 100644 --- a/backend/internal/service/openai_gateway_native_cache_creation_test.go +++ b/backend/internal/service/openai_gateway_native_cache_creation_test.go @@ -32,7 +32,7 @@ func TestNativeAnthropicCacheCreationRouteBillingBoundary(t *testing.T) { {"missing cache creation usage", []string{`{}`}, 0, 0, 0, 0, 0, 10}, {"missing aggregate", []string{`{"cache_creation":{"ephemeral_5m_input_tokens":20,"ephemeral_1h_input_tokens":30}}`}, 50, 20, 30, 20, 30, 10}, {"null aggregate", []string{`{"cache_creation_input_tokens":null,"cache_creation":{"ephemeral_5m_input_tokens":20,"ephemeral_1h_input_tokens":30}}`}, 50, 20, 30, 20, 30, 10}, - {"explicit zero", []string{`{"cache_creation_input_tokens":0,"cache_creation":{"ephemeral_5m_input_tokens":20,"ephemeral_1h_input_tokens":30}}`}, 0, 20, 30, 0, 0, 10}, + {"explicit zero", []string{`{"cache_creation_input_tokens":0,"cache_creation":{"ephemeral_5m_input_tokens":20,"ephemeral_1h_input_tokens":30}}`}, 50, 20, 30, 20, 30, 10}, {"details below aggregate", []string{`{"cache_creation_input_tokens":100,"cache_creation":{"ephemeral_5m_input_tokens":20,"ephemeral_1h_input_tokens":30}}`}, 100, 20, 30, 70, 30, 10}, {"aggregate grows without TTL", []string{`{"cache_creation_input_tokens":3000,"cache_creation":{"ephemeral_5m_input_tokens":3000}}`, `{"cache_creation_input_tokens":11000}`}, 11000, 3000, 0, 11000, 0, 10}, {"1h start unknown remainder uses 5m", []string{`{"cache_creation_input_tokens":3000,"cache_creation":{"ephemeral_1h_input_tokens":3000}}`, `{"cache_creation_input_tokens":11000}`}, 11000, 0, 3000, 8000, 3000, 10}, @@ -40,11 +40,12 @@ func TestNativeAnthropicCacheCreationRouteBillingBoundary(t *testing.T) { {"contradictory aggregate", []string{`{"cache_creation_input_tokens":100,"cache_creation":{"ephemeral_5m_input_tokens":50,"ephemeral_1h_input_tokens":200}}`}, 100, 50, 200, 20, 80, 10}, {"negative TTL", []string{`{"cache_creation":{"ephemeral_5m_input_tokens":-20,"ephemeral_1h_input_tokens":30}}`}, 30, 0, 30, 0, 30, 10}, {"partial TTL clear", []string{`{"cache_creation":{"ephemeral_5m_input_tokens":20}}`, `{"cache_creation":{"ephemeral_1h_input_tokens":30}}`, `{"cache_creation":{"ephemeral_5m_input_tokens":0}}`}, 30, 0, 30, 0, 30, 10}, - {"explicit zero delta", []string{`{"cache_creation_input_tokens":100,"cache_creation":{"ephemeral_5m_input_tokens":20,"ephemeral_1h_input_tokens":30}}`, `{"cache_creation_input_tokens":0}`, `{"cache_creation":{"ephemeral_1h_input_tokens":40}}`}, 0, 20, 40, 0, 0, 10}, + {"explicit zero delta", []string{`{"cache_creation_input_tokens":100,"cache_creation":{"ephemeral_5m_input_tokens":20,"ephemeral_1h_input_tokens":30}}`, `{"cache_creation_input_tokens":0,"cache_read_input_tokens":0,"input_tokens":0}`, `{"cache_creation":{"ephemeral_1h_input_tokens":40}}`}, 100, 20, 40, 60, 40, 10}, {"zero to positive", []string{`{"cache_creation_input_tokens":0,"cache_creation":{"ephemeral_5m_input_tokens":20,"ephemeral_1h_input_tokens":30}}`, `{"cache_creation_input_tokens":40}`}, 40, 20, 30, 16, 24, 10}, {"null preserves aggregate", []string{`{"cache_creation_input_tokens":100,"cache_creation":{"ephemeral_5m_input_tokens":20,"ephemeral_1h_input_tokens":30}}`, `{"cache_creation_input_tokens":null,"cache_creation":{"ephemeral_1h_input_tokens":40}}`}, 100, 20, 40, 60, 40, 10}, {"normalized prompt total", []string{`{"prompt_tokens":100,"cached_tokens":7,"cache_creation":{"ephemeral_5m_input_tokens":20,"ephemeral_1h_input_tokens":30}}`}, 50, 20, 30, 20, 30, 43}, - {"normalized prompt explicit zero", []string{`{"prompt_tokens":100,"cached_tokens":7,"cache_creation_input_tokens":0,"cache_creation":{"ephemeral_5m_input_tokens":20,"ephemeral_1h_input_tokens":30}}`}, 0, 20, 30, 0, 0, 93}, + {"normalized prompt explicit zero", []string{`{"prompt_tokens":100,"cached_tokens":7,"cache_creation_input_tokens":0,"cache_creation":{"ephemeral_5m_input_tokens":20,"ephemeral_1h_input_tokens":30}}`}, 50, 20, 30, 20, 30, 43}, + {"normalized prompt partial zero deltas", []string{`{"prompt_tokens":100,"cache_creation_input_tokens":0,"cache_creation":{"ephemeral_5m_input_tokens":20}}`, `{"cache_creation_input_tokens":0,"cache_read_input_tokens":0,"cache_creation":{"ephemeral_1h_input_tokens":30}}`}, 50, 20, 30, 20, 30, 43}, } { uncachedInput := test.uncached for _, route := range []string{"messages", "chat", "responses"} { diff --git a/backend/internal/service/openai_gateway_usage.go b/backend/internal/service/openai_gateway_usage.go index 21597489cb..59f0374a01 100644 --- a/backend/internal/service/openai_gateway_usage.go +++ b/backend/internal/service/openai_gateway_usage.go @@ -152,21 +152,21 @@ func groupBillsOpenAIFastAtStandard(apiKey *APIKey, account *Account, serviceTie } func (usage OpenAIUsage) billingUsageTokens() UsageTokens { + creationTokens := usage.CacheCreationInputTokens + if creationTokens <= 0 { + creationTokens = max(usage.CacheCreation5mTokens, 0) + max(usage.CacheCreation1hTokens, 0) + } tokens := UsageTokens{ - InputTokens: max(usage.InputTokens-usage.CacheReadInputTokens-usage.CacheCreationInputTokens, 0), + InputTokens: max(usage.InputTokens-usage.CacheReadInputTokens-creationTokens, 0), ImageInputTokens: max(usage.ImageInputTokens-usage.ImageCacheReadTokens, 0), ImageCacheReadTokens: usage.ImageCacheReadTokens, OutputTokens: usage.OutputTokens, - CacheCreationTokens: usage.CacheCreationInputTokens, + CacheCreationTokens: creationTokens, CacheCreation5mTokens: usage.CacheCreation5mTokens, CacheCreation1hTokens: usage.CacheCreation1hTokens, CacheReadTokens: usage.CacheReadInputTokens, ImageOutputTokens: usage.ImageOutputTokens, } - if usage.cacheCreationInputTokensPresent && usage.CacheCreationInputTokens == 0 { - tokens.CacheCreation5mTokens = 0 - tokens.CacheCreation1hTokens = 0 - } return tokens }