diff --git a/backend/internal/pkg/apicompat/anthropic_cache_creation_usage_test.go b/backend/internal/pkg/apicompat/anthropic_cache_creation_usage_test.go new file mode 100644 index 0000000000..d3d0aef8b7 --- /dev/null +++ b/backend/internal/pkg/apicompat/anthropic_cache_creation_usage_test.go @@ -0,0 +1,323 @@ +package apicompat + +import ( + "encoding/json" + "strings" + "testing" + + "github.com/stretchr/testify/require" +) + +func TestChatCacheWritePresenceAcrossAnthropicConverters(t *testing.T) { + for _, test := range []struct { + name string + details string + creation int + }{ + {"missing write falls back", `"cache_creation_tokens":4`, 4}, + {"zero write is authoritative", `"cache_write_tokens":0,"cache_creation_tokens":4`, 0}, + {"null write is authoritative", `"cache_write_tokens":null,"cache_creation_tokens":4`, 0}, + {"negative write clamps", `"cache_write_tokens":-2,"cache_creation_tokens":4`, 0}, + {"positive write wins", `"cache_write_tokens":2,"cache_creation_tokens":4`, 2}, + } { + t.Run(test.name, func(t *testing.T) { + var response ChatCompletionsResponse + payload := `{"id":"chat_cache","choices":[{"message":{"role":"assistant","content":"ok"},"finish_reason":"stop"}],"usage":{"prompt_tokens":10,"completion_tokens":2,"prompt_tokens_details":{"cached_tokens":3,` + test.details + `}}}` + require.NoError(t, json.Unmarshal([]byte(payload), &response)) + encoded, err := json.Marshal(response) + require.NoError(t, err) + require.NoError(t, json.Unmarshal(encoded, &response)) + if strings.Contains(test.details, `"cache_write_tokens":0`) { + require.Contains(t, string(encoded), `"cache_write_tokens":0`) + } + assertUsage := func(usage AnthropicUsage) { + require.Equal(t, 7-test.creation, usage.InputTokens) + require.Equal(t, 2, usage.OutputTokens) + require.Equal(t, 3, usage.CacheReadInputTokens) + require.Equal(t, test.creation, usage.CacheCreationInputTokens) + require.True(t, usage.CacheCreationInputTokensPresent) + require.True(t, usage.CacheReadInputTokensPresent) + require.Nil(t, usage.CacheCreation) + } + assertUsage(ChatCompletionsResponseToAnthropic(&response, "claude-sonnet-4").Usage) + converted := ChatCompletionsResponseToResponses(&response, "claude-sonnet-4", nil, nil, false, nil) + encoded, err = json.Marshal(converted) + require.NoError(t, err) + var decoded ResponsesResponse + require.NoError(t, json.Unmarshal(encoded, &decoded)) + assertUsage(ResponsesToAnthropic(&decoded, "claude-sonnet-4").Usage) + for _, adapter := range []bool{false, true} { + state := NewChatCompletionsToAnthropicStreamState("claude-sonnet-4") + var events []AnthropicStreamEvent + chunk := &ChatCompletionsChunk{ID: "chat_cache", Usage: response.Usage} + if adapter { + responsesState := NewChatCompletionsToResponsesStreamState("claude-sonnet-4") + anthropicState := NewResponsesEventToAnthropicState() + responseEvents := ChatCompletionsChunkToResponsesEvents(chunk, responsesState) + responseEvents = append(responseEvents, FinalizeChatCompletionsResponsesStream(responsesState)...) + for _, event := range responseEvents { + events = append(events, ResponsesEventToAnthropicEvents(&event, anthropicState)...) + } + events = append(events, FinalizeResponsesAnthropicStream(anthropicState)...) + } else { + events = ChatCompletionsChunkToAnthropicEvents(chunk, state) + events = append(events, FinalizeChatCompletionsAnthropicStream(state)...) + } + deltas := 0 + for _, event := range events { + if event.Type == "message_delta" { + require.NotNil(t, event.Usage) + assertUsage(*event.Usage) + deltas++ + } + } + require.Equal(t, 1, deltas) + } + }) + } +} + +func TestAnthropicCacheCreationAggregatePresence(t *testing.T) { + for _, test := range []struct { + name string + snapshot string + want int + 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}}`, 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}, + } { + t.Run(test.name, func(t *testing.T) { + var usage AnthropicUsage + require.NoError(t, json.Unmarshal([]byte(test.snapshot), &usage)) + require.Equal(t, test.present, usage.HasCacheCreationInputTokens()) + response := AnthropicToResponsesResponse(&AnthropicResponse{Usage: usage}) + require.Equal(t, test.want, response.Usage.CacheCreationInputTokens) + require.Equal(t, test.want, response.Usage.InputTokens) + state := NewAnthropicEventToResponsesState() + AnthropicEventToResponsesEvents(&AnthropicStreamEvent{ + Type: "message_start", Message: &AnthropicResponse{ID: "msg_cache", Usage: usage}, + }, state) + for range 2 { + var delta AnthropicUsage + require.NoError(t, json.Unmarshal([]byte(`{"cache_creation":{"ephemeral_1h_input_tokens":200}}`), &delta)) + AnthropicEventToResponsesEvents(&AnthropicStreamEvent{Type: "message_delta", Usage: &delta}, state) + require.Equal(t, test.want, state.CacheCreationInputTokens) + } + events := AnthropicEventToResponsesEvents(&AnthropicStreamEvent{Type: "message_stop"}, state) + require.NotEmpty(t, events) + completed := events[len(events)-1].Response + require.NotNil(t, completed) + require.Equal(t, test.want, completed.Usage.CacheCreationInputTokens) + }) + } +} + +func TestAnthropicUsageJSONRoundtrip(t *testing.T) { + for _, test := range []struct { + name string + payload string + present bool + value int + }{ + {"absent", `{"cache_creation":{"ephemeral_1h_input_tokens":30}}`, false, 0}, + {"null", `{"cache_creation_input_tokens":null,"cache_creation":{"ephemeral_1h_input_tokens":30}}`, false, 0}, + {"zero", `{"cache_creation_input_tokens":0,"cache_creation":{"ephemeral_1h_input_tokens":30}}`, true, 0}, + {"positive", `{"cache_creation_input_tokens":20,"cache_creation":{"ephemeral_1h_input_tokens":30}}`, true, 20}, + } { + t.Run(test.name, func(t *testing.T) { + var usage AnthropicUsage + require.NoError(t, json.Unmarshal([]byte(test.payload), &usage)) + for range 2 { + encoded, err := json.Marshal(usage) + require.NoError(t, err) + var fields map[string]json.RawMessage + require.NoError(t, json.Unmarshal(encoded, &fields)) + _, present := fields["cache_creation_input_tokens"] + require.Equal(t, test.present, present) + var roundtrip AnthropicUsage + require.NoError(t, json.Unmarshal(encoded, &roundtrip)) + require.Equal(t, test.present, roundtrip.HasCacheCreationInputTokens()) + require.Equal(t, test.value, roundtrip.CacheCreationInputTokens) + require.Equal(t, usage.CacheCreation, roundtrip.CacheCreation) + usage = roundtrip + } + }) + } +} + +func TestAnthropicUsageSyntheticJSONRoundtrip(t *testing.T) { + for _, test := range []struct { + name string + usage AnthropicUsage + present bool + }{ + {"missing", AnthropicUsage{}, false}, + {"inferred nonzero", AnthropicUsage{CacheCreationInputTokens: 25}, true}, + {"explicit zero", AnthropicUsage{CacheCreationInputTokensPresent: true}, true}, + } { + t.Run(test.name, func(t *testing.T) { + test.usage.InputTokens = 10 + test.usage.OutputTokens = 7 + test.usage.CacheReadInputTokens = 3 + encoded, err := json.Marshal(test.usage) + require.NoError(t, err) + var roundtrip AnthropicUsage + require.NoError(t, json.Unmarshal(encoded, &roundtrip)) + require.Equal(t, test.present, roundtrip.HasCacheCreationInputTokens()) + require.Equal(t, test.usage.CacheCreationInputTokens, roundtrip.CacheCreationInputTokens) + require.Equal(t, 10, roundtrip.InputTokens) + require.Equal(t, 7, roundtrip.OutputTokens) + require.Equal(t, 3, roundtrip.CacheReadInputTokens) + }) + } +} + +func TestAnthropicUsageAdapterZeroContracts(t *testing.T) { + for _, test := range []struct { + name string + usage AnthropicUsage + present bool + }{ + {"missing Responses usage", anthropicUsageFromResponsesUsage(nil), true}, + {"explicit Responses totals", anthropicUsageFromResponsesUsage(&ResponsesUsage{}), true}, + {"missing Chat usage", chatUsageToAnthropicUsage(nil), true}, + {"explicit Chat totals", chatUsageToAnthropicUsage(&ChatUsage{}), true}, + } { + t.Run(test.name, func(t *testing.T) { + encoded, err := json.Marshal(test.usage) + require.NoError(t, err) + var decoded AnthropicUsage + require.NoError(t, json.Unmarshal(encoded, &decoded)) + require.Equal(t, test.present, decoded.HasCacheCreationInputTokens()) + require.Zero(t, decoded.CacheCreationInputTokens) + }) + } + responsesState := NewResponsesEventToAnthropicState() + startEvents := resToAnthHandleCreated(&ResponsesStreamEvent{}, responsesState) + chatState := NewChatCompletionsToAnthropicStreamState("claude-sonnet-4") + startEvents = append(startEvents, ensureCCAnthropicMessageStart(chatState)...) + for _, event := range startEvents { + encoded, err := json.Marshal(event) + require.NoError(t, err) + var decoded AnthropicStreamEvent + require.NoError(t, json.Unmarshal(encoded, &decoded)) + require.NotNil(t, decoded.Message) + require.True(t, decoded.Message.Usage.HasCacheCreationInputTokens()) + require.True(t, decoded.Message.Usage.CacheReadInputTokensPresent) + } + terminalEvents := FinalizeResponsesAnthropicStream(responsesState) + terminalEvents = append(terminalEvents, FinalizeChatCompletionsAnthropicStream(chatState)...) + usageEvents := 0 + for _, event := range terminalEvents { + if event.Usage == nil { + continue + } + encoded, err := json.Marshal(event) + require.NoError(t, err) + var decoded AnthropicStreamEvent + require.NoError(t, json.Unmarshal(encoded, &decoded)) + require.NotNil(t, decoded.Usage) + require.True(t, decoded.Usage.HasCacheCreationInputTokens()) + require.Zero(t, decoded.Usage.CacheCreationInputTokens) + usageEvents++ + } + require.Equal(t, 2, usageEvents) +} + +func TestAnthropicCacheCreationPartialSnapshots(t *testing.T) { + state := NewAnthropicEventToResponsesState() + for index, snapshot := range []string{ + `{"cache_creation":{"ephemeral_5m_input_tokens":20}}`, + `{"cache_creation":{"ephemeral_1h_input_tokens":30}}`, + `{"cache_creation_input_tokens":null,"cache_creation":{"ephemeral_5m_input_tokens":null,"ephemeral_1h_input_tokens":null}}`, + `{"cache_creation":{"ephemeral_1h_input_tokens":30}}`, + `{"cache_creation_input_tokens":40}`, + `{"output_tokens":1}`, + `{"cache_creation_input_tokens":0}`, + `{"cache_creation":{"ephemeral_1h_input_tokens":200}}`, + `{"cache_creation_input_tokens":null,"cache_creation":{"ephemeral_1h_input_tokens":null}}`, + `{"cache_creation_input_tokens":100}`, + } { + var usage AnthropicUsage + require.NoError(t, json.Unmarshal([]byte(snapshot), &usage)) + state.mergeCacheCreationUsage(usage) + 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_cache_read_usage_test.go b/backend/internal/pkg/apicompat/anthropic_cache_read_usage_test.go new file mode 100644 index 0000000000..b4a27a8983 --- /dev/null +++ b/backend/internal/pkg/apicompat/anthropic_cache_read_usage_test.go @@ -0,0 +1,42 @@ +//go:build unit + +package apicompat + +import ( + "encoding/json" + "testing" + + "github.com/stretchr/testify/require" +) + +func TestAnthropicUsageCacheReadPresenceRoundtrip(t *testing.T) { + for _, test := range []struct { + name string + payload string + present bool + value int + }{ + {"missing", `{}`, false, 0}, + {"null", `{"cache_read_input_tokens":null,"cached_tokens":null,"prompt_tokens_details":{"cached_tokens":null}}`, false, 0}, + {"zero", `{"cache_read_input_tokens":0,"cached_tokens":0,"prompt_tokens_details":{"cached_tokens":0}}`, true, 0}, + {"positive", `{"cache_read_input_tokens":20,"cached_tokens":20,"prompt_tokens_details":{"cached_tokens":20}}`, true, 20}, + } { + t.Run(test.name, func(t *testing.T) { + var usage AnthropicUsage + require.NoError(t, json.Unmarshal([]byte(test.payload), &usage)) + for range 2 { + require.Equal(t, test.present, usage.CacheReadInputTokensPresent) + require.Equal(t, test.present, usage.CachedTokensPresent) + require.Equal(t, test.value, usage.CacheReadInputTokens) + require.Equal(t, test.value, usage.CachedTokens) + if usage.PromptTokensDetails != nil { + require.Equal(t, test.present, usage.PromptTokensDetails.CachedTokensPresent) + require.Equal(t, test.value, usage.PromptTokensDetails.CachedTokens) + } + encoded, err := json.Marshal(usage) + require.NoError(t, err) + require.NoError(t, json.Unmarshal(encoded, &usage)) + } + }) + } +} diff --git a/backend/internal/pkg/apicompat/anthropic_to_responses_response.go b/backend/internal/pkg/apicompat/anthropic_to_responses_response.go index 558763af6a..61c7cbf241 100644 --- a/backend/internal/pkg/apicompat/anthropic_to_responses_response.go +++ b/backend/internal/pkg/apicompat/anthropic_to_responses_response.go @@ -29,6 +29,23 @@ func encodeAnthropicThinking(block AnthropicContentBlock) string { return anthropicThinkingEnvelopePrefix + base64.RawStdEncoding.EncodeToString(payload) } +func anthropicCacheCreationInputTokens(usage AnthropicUsage) int { + if usage.CacheCreationInputTokens > 0 { + return max(usage.CacheCreationInputTokens, 0) + } + if usage.CacheCreation != nil && (usage.CacheCreation.Ephemeral5mInputTokens != nil || usage.CacheCreation.Ephemeral1hInputTokens != nil) { + cacheCreationTokens := 0 + if usage.CacheCreation.Ephemeral5mInputTokens != nil { + cacheCreationTokens += max(*usage.CacheCreation.Ephemeral5mInputTokens, 0) + } + if usage.CacheCreation.Ephemeral1hInputTokens != nil { + cacheCreationTokens += max(*usage.CacheCreation.Ephemeral1hInputTokens, 0) + } + return cacheCreationTokens + } + return max(usage.CacheCreationInputTokens, 0) +} + // AnthropicToResponsesResponse converts an Anthropic Messages response into a // Responses API response. This is the reverse of ResponsesToAnthropic and // enables Anthropic upstream responses to be returned in OpenAI Responses format. @@ -130,14 +147,15 @@ func AnthropicToResponsesResponse(resp *AnthropicResponse) *ResponsesResponse { // Anthropic's input_tokens excludes cache_read/cache_creation, while OpenAI // Responses' input_tokens is the total including cached tokens. Add them back // when converting so downstream consumers see OpenAI semantics. + cacheCreationTokens := anthropicCacheCreationInputTokens(resp.Usage) totalInputTokens := resp.Usage.InputTokens + resp.Usage.CacheReadInputTokens + - resp.Usage.CacheCreationInputTokens + cacheCreationTokens out.Usage = &ResponsesUsage{ InputTokens: totalInputTokens, OutputTokens: resp.Usage.OutputTokens, TotalTokens: totalInputTokens + resp.Usage.OutputTokens, - CacheCreationInputTokens: resp.Usage.CacheCreationInputTokens, + CacheCreationInputTokens: cacheCreationTokens, } if resp.Usage.CacheReadInputTokens > 0 { out.Usage.InputTokensDetails = &ResponsesInputTokensDetails{ @@ -222,6 +240,10 @@ type AnthropicEventToResponsesState struct { OutputTokens int CacheReadInputTokens int CacheCreationInputTokens int + CacheCreation AnthropicCacheCreation + + cacheCreationInputTokensPresent bool + cacheCreationInputTokensFromDetails bool StopReason string } @@ -233,6 +255,28 @@ func NewAnthropicEventToResponsesState() *AnthropicEventToResponsesState { } } +func (state *AnthropicEventToResponsesState) mergeCacheCreationUsage(usage AnthropicUsage) { + 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 { + tokens := max(*usage.CacheCreation.Ephemeral5mInputTokens, 0) + state.CacheCreation.Ephemeral5mInputTokens = &tokens + } + if usage.CacheCreation.Ephemeral1hInputTokens != nil { + tokens := max(*usage.CacheCreation.Ephemeral1hInputTokens, 0) + state.CacheCreation.Ephemeral1hInputTokens = &tokens + } + } + 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 + } +} + // AnthropicEventToResponsesEvents converts a single Anthropic SSE event into // zero or more Responses SSE events, updating state as it goes. func AnthropicEventToResponsesEvents( @@ -299,9 +343,7 @@ func anthToResHandleMessageStart(evt *AnthropicStreamEvent, state *AnthropicEven if evt.Message.Usage.CacheReadInputTokens > 0 { state.CacheReadInputTokens = evt.Message.Usage.CacheReadInputTokens } - if evt.Message.Usage.CacheCreationInputTokens > 0 { - state.CacheCreationInputTokens = evt.Message.Usage.CacheCreationInputTokens - } + state.mergeCacheCreationUsage(evt.Message.Usage) } if state.CreatedSent { @@ -560,16 +602,16 @@ 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 } if evt.Usage.CacheReadInputTokens > 0 { state.CacheReadInputTokens = evt.Usage.CacheReadInputTokens } - if evt.Usage.CacheCreationInputTokens > 0 { - state.CacheCreationInputTokens = evt.Usage.CacheCreationInputTokens - } + state.mergeCacheCreationUsage(*evt.Usage) } if evt.Delta != nil && evt.Delta.StopReason != "" { state.StopReason = evt.Delta.StopReason diff --git a/backend/internal/pkg/apicompat/chatcompletions_anthropic_bridge.go b/backend/internal/pkg/apicompat/chatcompletions_anthropic_bridge.go index 29b5bbbe17..67efd883f4 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,21 +518,13 @@ 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 - cacheCreationTokens := 0 + cacheCreationTokens := usage.PromptTokensDetails.cacheCreationInputTokens() if usage.PromptTokensDetails != nil { cachedTokens = usage.PromptTokensDetails.CachedTokens - // cache_write_tokens and cache_creation_tokens are alternate spellings of - // the same quantity, not additive; the double-conversion path - // (ChatUsageToResponsesUsage) prefers write and falls back to creation. - if usage.PromptTokensDetails.CacheWriteTokens > 0 { - cacheCreationTokens = usage.PromptTokensDetails.CacheWriteTokens - } else { - cacheCreationTokens = usage.PromptTokensDetails.CacheCreationTokens - } } inputTokens := usage.PromptTokens - cachedTokens - cacheCreationTokens @@ -540,10 +533,12 @@ func chatUsageToAnthropicUsage(usage *ChatUsage) AnthropicUsage { } return AnthropicUsage{ - InputTokens: inputTokens, - OutputTokens: usage.CompletionTokens, - CacheReadInputTokens: cachedTokens, - CacheCreationInputTokens: cacheCreationTokens, + InputTokens: inputTokens, + OutputTokens: usage.CompletionTokens, + CacheReadInputTokens: cachedTokens, + CacheCreationInputTokens: cacheCreationTokens, + CacheCreationInputTokensPresent: true, + CacheReadInputTokensPresent: true, } } @@ -714,10 +709,12 @@ func FinalizeChatCompletionsAnthropicStream(state *ChatCompletionsToAnthropicStr StopReason: stopReason, }, Usage: &AnthropicUsage{ - InputTokens: state.InputTokens, - OutputTokens: state.OutputTokens, - CacheReadInputTokens: state.CacheReadInputTokens, - CacheCreationInputTokens: state.CacheCreationInputTokens, + InputTokens: state.InputTokens, + OutputTokens: state.OutputTokens, + CacheReadInputTokens: state.CacheReadInputTokens, + CacheCreationInputTokens: state.CacheCreationInputTokens, + CacheCreationInputTokensPresent: true, + CacheReadInputTokensPresent: true, }, }, AnthropicStreamEvent{Type: "message_stop"}, @@ -741,7 +738,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/chatcompletions_responses_bridge.go b/backend/internal/pkg/apicompat/chatcompletions_responses_bridge.go index ac7472e778..efea050bd2 100644 --- a/backend/internal/pkg/apicompat/chatcompletions_responses_bridge.go +++ b/backend/internal/pkg/apicompat/chatcompletions_responses_bridge.go @@ -1537,9 +1537,10 @@ func ChatUsageToResponsesUsage(usage *ChatUsage) *ResponsesUsage { return nil } out := &ResponsesUsage{ - InputTokens: usage.PromptTokens, - OutputTokens: usage.CompletionTokens, - TotalTokens: usage.TotalTokens, + InputTokens: usage.PromptTokens, + OutputTokens: usage.CompletionTokens, + TotalTokens: usage.TotalTokens, + CacheCreationInputTokens: usage.PromptTokensDetails.cacheCreationInputTokens(), } if out.TotalTokens == 0 { out.TotalTokens = out.InputTokens + out.OutputTokens @@ -1551,10 +1552,9 @@ func ChatUsageToResponsesUsage(usage *ChatUsage) *ResponsesUsage { CacheCreationTokens: usage.PromptTokensDetails.CacheCreationTokens, CacheWriteTokens: usage.PromptTokensDetails.CacheWriteTokens, } - if usage.PromptTokensDetails.CacheWriteTokens > 0 { - out.CacheCreationInputTokens = usage.PromptTokensDetails.CacheWriteTokens - } else { - out.CacheCreationInputTokens = usage.PromptTokensDetails.CacheCreationTokens + if out.CacheCreationInputTokens == 0 { + out.InputTokensDetails.CacheCreationTokens = 0 + out.InputTokensDetails.CacheWriteTokens = 0 } } return out diff --git a/backend/internal/pkg/apicompat/responses_anthropic_cache_creation_test.go b/backend/internal/pkg/apicompat/responses_anthropic_cache_creation_test.go index aa5ecbe5ba..d18f457833 100644 --- a/backend/internal/pkg/apicompat/responses_anthropic_cache_creation_test.go +++ b/backend/internal/pkg/apicompat/responses_anthropic_cache_creation_test.go @@ -1,6 +1,7 @@ package apicompat import ( + "encoding/json" "testing" "github.com/stretchr/testify/assert" @@ -97,3 +98,101 @@ func TestAnthropicToResponsesResponse_CacheCreation(t *testing.T) { assert.Equal(t, 20, out.Usage.InputTokens, "total = input(10) + cache_read(4) + cache_creation(6)") assert.Equal(t, 6, out.Usage.CacheCreationInputTokens, "cache creation must round-trip") } + +func TestAnthropicUsageDecodesCacheCreationBreakdown(t *testing.T) { + var usage AnthropicUsage + require.NoError(t, json.Unmarshal([]byte(`{"input_tokens":10,"cache_creation":{"ephemeral_5m_input_tokens":0,"ephemeral_1h_input_tokens":7}}`), &usage)) + require.NotNil(t, usage.CacheCreation) + require.NotNil(t, usage.CacheCreation.Ephemeral5mInputTokens) + require.NotNil(t, usage.CacheCreation.Ephemeral1hInputTokens) + assert.Equal(t, 0, *usage.CacheCreation.Ephemeral5mInputTokens) + assert.Equal(t, 7, *usage.CacheCreation.Ephemeral1hInputTokens) +} + +func TestAnthropicToResponsesResponse_UsesCacheCreationBreakdown(t *testing.T) { + fiveMinutes := 2 + oneHour := 3 + resp := AnthropicResponse{Usage: AnthropicUsage{ + InputTokens: 10, + CacheCreation: &AnthropicCacheCreation{ + Ephemeral5mInputTokens: &fiveMinutes, + Ephemeral1hInputTokens: &oneHour, + }, + }} + + out := AnthropicToResponsesResponse(&resp) + require.NotNil(t, out.Usage) + assert.Equal(t, 15, out.Usage.InputTokens) + assert.Equal(t, 5, out.Usage.CacheCreationInputTokens) +} + +func TestAnthropicEventToResponsesEvents_MergesCacheCreationBreakdown(t *testing.T) { + tests := []struct { + name string + delta string + want5m int + want1h int + wantTotal int + }{ + {"explicit_1h_zero", `{"cache_creation":{"ephemeral_1h_input_tokens":0}}`, 2, 0, 2}, + {"explicit_5m_zero", `{"cache_creation":{"ephemeral_5m_input_tokens":0}}`, 0, 3, 3}, + {"omitted_details", `{}`, 2, 3, 5}, + {"empty_details", `{"cache_creation":{}}`, 2, 3, 5}, + {"legacy_aggregate_after_details", `{"cache_creation_input_tokens":99}`, 2, 3, 99}, + {"explicit_both_zero", `{"cache_creation_input_tokens":99,"cache_creation":{"ephemeral_5m_input_tokens":0,"ephemeral_1h_input_tokens":0}}`, 0, 0, 99}, + } + for _, test := range tests { + t.Run(test.name, func(t *testing.T) { + var startUsage, deltaUsage AnthropicUsage + require.NoError(t, json.Unmarshal([]byte(`{"input_tokens":10,"cache_read_input_tokens":4,"cache_creation":{"ephemeral_5m_input_tokens":2,"ephemeral_1h_input_tokens":3}}`), &startUsage)) + require.NoError(t, json.Unmarshal([]byte(test.delta), &deltaUsage)) + state := NewAnthropicEventToResponsesState() + AnthropicEventToResponsesEvents(&AnthropicStreamEvent{ + Type: "message_start", + Message: &AnthropicResponse{ID: "msg_test", Usage: startUsage}, + }, state) + assert.Equal(t, 5, state.CacheCreationInputTokens) + AnthropicEventToResponsesEvents(&AnthropicStreamEvent{Type: "message_delta", Usage: &deltaUsage}, state) + require.NotNil(t, state.CacheCreation.Ephemeral5mInputTokens) + require.NotNil(t, state.CacheCreation.Ephemeral1hInputTokens) + assert.Equal(t, test.want5m, *state.CacheCreation.Ephemeral5mInputTokens) + assert.Equal(t, test.want1h, *state.CacheCreation.Ephemeral1hInputTokens) + assert.Equal(t, test.wantTotal, state.CacheCreationInputTokens) + AnthropicEventToResponsesEvents(&AnthropicStreamEvent{ + Type: "message_delta", Usage: &AnthropicUsage{OutputTokens: 7}, + }, state) + + events := AnthropicEventToResponsesEvents(&AnthropicStreamEvent{Type: "message_stop"}, state) + require.Len(t, events, 1) + require.Equal(t, "response.completed", events[0].Type) + require.NotNil(t, events[0].Response) + usage := events[0].Response.Usage + require.NotNil(t, usage) + assert.Equal(t, test.wantTotal, usage.CacheCreationInputTokens) + assert.Equal(t, 14+test.wantTotal, usage.InputTokens) + assert.Equal(t, 7, usage.OutputTokens) + assert.Equal(t, 21+test.wantTotal, usage.TotalTokens) + }) + } +} + +func TestAnthropicEventToResponsesEvents_CacheCreationLegacyFallback(t *testing.T) { + state := NewAnthropicEventToResponsesState() + AnthropicEventToResponsesEvents(&AnthropicStreamEvent{ + Type: "message_start", + Message: &AnthropicResponse{Usage: AnthropicUsage{InputTokens: 10, CacheCreationInputTokens: 5}}, + }, state) + AnthropicEventToResponsesEvents(&AnthropicStreamEvent{ + Type: "message_delta", Usage: &AnthropicUsage{CacheCreationInputTokens: 6, CacheCreation: &AnthropicCacheCreation{}}, + }, state) + AnthropicEventToResponsesEvents(&AnthropicStreamEvent{Type: "message_delta", Usage: &AnthropicUsage{OutputTokens: 7}}, state) + assert.Nil(t, state.CacheCreation.Ephemeral5mInputTokens) + assert.Nil(t, state.CacheCreation.Ephemeral1hInputTokens) + + events := AnthropicEventToResponsesEvents(&AnthropicStreamEvent{Type: "message_stop"}, state) + require.Len(t, events, 1) + require.NotNil(t, events[0].Response) + require.NotNil(t, events[0].Response.Usage) + assert.Equal(t, 6, events[0].Response.Usage.CacheCreationInputTokens) + assert.Equal(t, 16, events[0].Response.Usage.InputTokens) +} diff --git a/backend/internal/pkg/apicompat/responses_to_anthropic.go b/backend/internal/pkg/apicompat/responses_to_anthropic.go index 1d5654b7c4..3ad307f921 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 @@ -92,7 +93,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 @@ -106,10 +107,12 @@ func anthropicUsageFromResponsesUsage(usage *ResponsesUsage) AnthropicUsage { } return AnthropicUsage{ - InputTokens: inputTokens, - OutputTokens: usage.OutputTokens, - CacheReadInputTokens: cachedTokens, - CacheCreationInputTokens: usage.CacheCreationInputTokens, + InputTokens: inputTokens, + OutputTokens: usage.OutputTokens, + CacheReadInputTokens: cachedTokens, + CacheCreationInputTokens: usage.CacheCreationInputTokens, + CacheCreationInputTokensPresent: true, + CacheReadInputTokensPresent: true, } } @@ -287,10 +290,12 @@ func FinalizeResponsesAnthropicStream(state *ResponsesEventToAnthropicState) []A StopReason: stopReason, }, Usage: &AnthropicUsage{ - InputTokens: state.InputTokens, - OutputTokens: state.OutputTokens, - CacheReadInputTokens: state.CacheReadInputTokens, - CacheCreationInputTokens: state.CacheCreationInputTokens, + InputTokens: state.InputTokens, + OutputTokens: state.OutputTokens, + CacheReadInputTokens: state.CacheReadInputTokens, + CacheCreationInputTokens: state.CacheCreationInputTokens, + CacheCreationInputTokensPresent: true, + CacheReadInputTokensPresent: true, }, }, AnthropicStreamEvent{Type: "message_stop"}, @@ -338,8 +343,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, }, }, }} @@ -776,10 +783,12 @@ func resToAnthHandleCompleted(evt *ResponsesStreamEvent, state *ResponsesEventTo StopReason: stopReason, }, Usage: &AnthropicUsage{ - InputTokens: state.InputTokens, - OutputTokens: state.OutputTokens, - CacheReadInputTokens: state.CacheReadInputTokens, - CacheCreationInputTokens: state.CacheCreationInputTokens, + InputTokens: state.InputTokens, + OutputTokens: state.OutputTokens, + CacheReadInputTokens: state.CacheReadInputTokens, + CacheCreationInputTokens: state.CacheCreationInputTokens, + CacheCreationInputTokensPresent: true, + CacheReadInputTokensPresent: true, }, }, AnthropicStreamEvent{Type: "message_stop"}, diff --git a/backend/internal/pkg/apicompat/types.go b/backend/internal/pkg/apicompat/types.go index 130f0ff63b..dd9a2a413d 100644 --- a/backend/internal/pkg/apicompat/types.go +++ b/backend/internal/pkg/apicompat/types.go @@ -163,15 +163,50 @@ func AnthropicStopReasonString(p *string) string { // AnthropicPromptTokensDetails holds OpenAI-compatible prompt token details // occasionally included by Anthropic-compatible providers. type AnthropicPromptTokensDetails struct { - CachedTokens int `json:"cached_tokens,omitempty"` + CachedTokens int `json:"cached_tokens,omitempty"` + CachedTokensPresent bool `json:"-"` +} + +func (details *AnthropicPromptTokensDetails) UnmarshalJSON(data []byte) error { + var decoded struct { + CachedTokens *int `json:"cached_tokens"` + } + if err := json.Unmarshal(data, &decoded); err != nil { + return err + } + *details = AnthropicPromptTokensDetails{} + if decoded.CachedTokens != nil { + details.CachedTokens = *decoded.CachedTokens + details.CachedTokensPresent = true + } + return nil +} + +func (details AnthropicPromptTokensDetails) MarshalJSON() ([]byte, error) { + var cachedTokens *int + if details.CachedTokensPresent || details.CachedTokens != 0 { + cachedTokens = &details.CachedTokens + } + return json.Marshal(struct { + CachedTokens *int `json:"cached_tokens,omitempty"` + }{CachedTokens: cachedTokens}) +} + +// AnthropicCacheCreation holds Anthropic's cache creation TTL breakdown. +// Pointers preserve the distinction between an omitted field and an explicit +// zero in streaming usage events. +type AnthropicCacheCreation struct { + Ephemeral5mInputTokens *int `json:"ephemeral_5m_input_tokens,omitempty"` + Ephemeral1hInputTokens *int `json:"ephemeral_1h_input_tokens,omitempty"` } // AnthropicUsage holds token counts in Anthropic format. type AnthropicUsage struct { - InputTokens int `json:"input_tokens"` - OutputTokens int `json:"output_tokens"` - CacheCreationInputTokens int `json:"cache_creation_input_tokens"` - CacheReadInputTokens int `json:"cache_read_input_tokens"` + InputTokens int `json:"input_tokens"` + OutputTokens int `json:"output_tokens"` + CacheCreationInputTokens int `json:"cache_creation_input_tokens"` + CacheReadInputTokens int `json:"cache_read_input_tokens"` + CacheCreation *AnthropicCacheCreation `json:"cache_creation,omitempty"` // Anthropic-compatible providers can also expose their native OpenAI-style // total/cache fields. Preserve them so callers can normalize provider totals // into Anthropic's mutually-exclusive billing buckets. @@ -180,6 +215,64 @@ type AnthropicUsage struct { PromptTokensDetails *AnthropicPromptTokensDetails `json:"prompt_tokens_details,omitempty"` PromptCacheHitTokens *int `json:"prompt_cache_hit_tokens,omitempty"` PromptCacheMissTokens *int `json:"prompt_cache_miss_tokens,omitempty"` + + // Presence distinguishes explicit zero from missing/null; TTL details remain raw. + CacheCreationInputTokensPresent bool `json:"-"` + CacheReadInputTokensPresent bool `json:"-"` + CachedTokensPresent bool `json:"-"` +} + +func (usage *AnthropicUsage) UnmarshalJSON(data []byte) error { + type usageAlias AnthropicUsage + var decoded struct { + usageAlias + CacheCreationInputTokens *int `json:"cache_creation_input_tokens"` + CacheReadInputTokens *int `json:"cache_read_input_tokens"` + CachedTokens *int `json:"cached_tokens"` + } + if err := json.Unmarshal(data, &decoded); err != nil { + return err + } + *usage = AnthropicUsage(decoded.usageAlias) + if decoded.CacheCreationInputTokens != nil { + usage.CacheCreationInputTokens = *decoded.CacheCreationInputTokens + usage.CacheCreationInputTokensPresent = true + } + if decoded.CacheReadInputTokens != nil { + usage.CacheReadInputTokens = *decoded.CacheReadInputTokens + usage.CacheReadInputTokensPresent = true + } + if decoded.CachedTokens != nil { + usage.CachedTokens = *decoded.CachedTokens + usage.CachedTokensPresent = true + } + return nil +} + +func (usage AnthropicUsage) HasCacheCreationInputTokens() bool { + return usage.CacheCreationInputTokensPresent || usage.CacheCreationInputTokens != 0 +} + +// MarshalJSON preserves aggregate presence and raw TTL details without deriving totals. +func (usage AnthropicUsage) MarshalJSON() ([]byte, error) { + type usageAlias AnthropicUsage + var aggregate *int + if usage.HasCacheCreationInputTokens() { + aggregate = &usage.CacheCreationInputTokens + } + var cacheReadTokens, cachedTokens *int + if usage.CacheReadInputTokensPresent || usage.CacheReadInputTokens != 0 { + cacheReadTokens = &usage.CacheReadInputTokens + } + if usage.CachedTokensPresent || usage.CachedTokens != 0 { + cachedTokens = &usage.CachedTokens + } + return json.Marshal(struct { + usageAlias + CacheCreationInputTokens *int `json:"cache_creation_input_tokens,omitempty"` + CacheReadInputTokens *int `json:"cache_read_input_tokens,omitempty"` + CachedTokens *int `json:"cached_tokens,omitempty"` + }{usageAlias: usageAlias(usage), CacheCreationInputTokens: aggregate, CacheReadInputTokens: cacheReadTokens, CachedTokens: cachedTokens}) } // --------------------------------------------------------------------------- @@ -802,6 +895,48 @@ type ChatTokenDetails struct { ReasoningTokens int `json:"reasoning_tokens,omitempty"` AcceptedPredictionTokens int `json:"accepted_prediction_tokens,omitempty"` RejectedPredictionTokens int `json:"rejected_prediction_tokens,omitempty"` + cacheWriteTokensPresent bool +} + +func (details *ChatTokenDetails) UnmarshalJSON(data []byte) error { + type detailsAlias ChatTokenDetails + var decoded struct { + detailsAlias + CacheWriteTokens json.RawMessage `json:"cache_write_tokens"` + } + if err := json.Unmarshal(data, &decoded); err != nil { + return err + } + *details = ChatTokenDetails(decoded.detailsAlias) + if len(decoded.CacheWriteTokens) != 0 { + if err := json.Unmarshal(decoded.CacheWriteTokens, &details.CacheWriteTokens); err != nil { + return err + } + details.cacheWriteTokensPresent = true + } + return nil +} + +func (details ChatTokenDetails) MarshalJSON() ([]byte, error) { + type detailsAlias ChatTokenDetails + var cacheWriteTokens *int + if details.cacheWriteTokensPresent || details.CacheWriteTokens != 0 { + cacheWriteTokens = &details.CacheWriteTokens + } + return json.Marshal(struct { + detailsAlias + CacheWriteTokens *int `json:"cache_write_tokens,omitempty"` + }{detailsAlias: detailsAlias(details), CacheWriteTokens: cacheWriteTokens}) +} + +func (details *ChatTokenDetails) cacheCreationInputTokens() int { + if details == nil { + return 0 + } + if details.cacheWriteTokensPresent || details.CacheWriteTokens > 0 { + return max(details.CacheWriteTokens, 0) + } + return max(details.CacheCreationTokens, 0) } // ChatCompletionsChunk is a single streaming chunk from POST /v1/chat/completions. diff --git a/backend/internal/service/account_stats_pricing.go b/backend/internal/service/account_stats_pricing.go index 4bb1d7f5d4..54e75f5a20 100644 --- a/backend/internal/service/account_stats_pricing.go +++ b/backend/internal/service/account_stats_pricing.go @@ -250,7 +250,7 @@ func calculateTokenStatsCost(pricing *ChannelModelPricing, tokens UsageTokens) * } cacheCreationCost := float64(tokens.CacheCreationTokens) * deref(p.CacheWritePrice) if p.CacheWrite1hPrice != nil { - cache5m, cache1h := normalizeCacheCreationBreakdown(tokens) + cache5m, cache1h := allocateCacheCreationBillingTokens(tokens) if cache5m > 0 || cache1h > 0 { cacheCreationCost = float64(cache5m)*deref(p.CacheWritePrice) + float64(cache1h)*deref(p.CacheWrite1hPrice) diff --git a/backend/internal/service/account_stats_pricing_test.go b/backend/internal/service/account_stats_pricing_test.go index 1c21d32ae2..34dbaa9224 100644 --- a/backend/internal/service/account_stats_pricing_test.go +++ b/backend/internal/service/account_stats_pricing_test.go @@ -246,6 +246,72 @@ func TestCalculateStatsCost_TokenBilling_WithCacheTTLPrices(t *testing.T) { require.InDelta(t, 0.84, *result, 1e-12) } +func TestTryCustomRules_CacheTTLAllocation(t *testing.T) { + tests := []struct { + name string + aggregate int + cache5m int + cache1h int + wantCost float64 + }{ + {name: "pure 5m remainder", aggregate: 200, cache5m: 60, wantCost: 0.6}, + {name: "pure 1h remainder", aggregate: 200, cache1h: 60, wantCost: 0.72}, + {name: "mixed remainder", aggregate: 200, cache5m: 40, cache1h: 60, wantCost: 0.72}, + {name: "no details", aggregate: 200, wantCost: 0.6}, + {name: "complete pure 5m", aggregate: 200, cache5m: 200, wantCost: 0.6}, + {name: "complete pure 1h", aggregate: 200, cache1h: 200, wantCost: 1.0}, + {name: "zero aggregate retains details", cache5m: 40, cache1h: 60, wantCost: 0.42}, + {name: "zero tokens"}, + {name: "ratio cap", aggregate: 120, cache5m: 80, cache1h: 160, wantCost: 0.52}, + } + for _, interval := range []bool{false, true} { + path := "flat" + if interval { + path = "interval" + } + t.Run(path, func(t *testing.T) { + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + pricing := ChannelModelPricing{ + Models: []string{"claude-test"}, + BillingMode: BillingModeToken, + CacheWritePrice: testPtrFloat64(0.003), + CacheWrite1hPrice: testPtrFloat64(0.005), + } + wantCost := tt.wantCost + if interval { + pricing.Intervals = []PricingInterval{{ + MinTokens: 0, + CacheWritePrice: testPtrFloat64(0.006), + CacheWrite1hPrice: testPtrFloat64(0.010), + }} + wantCost *= 2 + } + channel := &Channel{ + AccountStatsPricingRules: []AccountStatsPricingRule{{ + AccountIDs: []int64{1}, + Pricing: []ChannelModelPricing{pricing}, + }}, + } + tokens := UsageTokens{ + InputTokens: 1, + CacheCreationTokens: tt.aggregate, + CacheCreation5mTokens: tt.cache5m, + CacheCreation1hTokens: tt.cache1h, + } + result := tryCustomRules(channel, 1, 0, "anthropic", "claude-test", tokens, 1) + if wantCost == 0 { + require.Nil(t, result) + return + } + require.NotNil(t, result) + require.InDelta(t, wantCost, *result, 1e-12) + }) + } + }) + } +} + func TestCalculateStatsCost_TokenBilling_WithImageOutput(t *testing.T) { pricing := &ChannelModelPricing{ BillingMode: BillingModeToken, diff --git a/backend/internal/service/anthropic_chat_stream_usage_test.go b/backend/internal/service/anthropic_chat_stream_usage_test.go index 2397a5802d..6a68a9d106 100644 --- a/backend/internal/service/anthropic_chat_stream_usage_test.go +++ b/backend/internal/service/anthropic_chat_stream_usage_test.go @@ -27,6 +27,9 @@ func TestAnthropicChatStreamAuthoritativeUsage(t *testing.T) { prompt, billableInput, totalInput, output, cached, created int }{ {"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, 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}, {"repeated_authoritative_cache_bucket", `,"usage":{"input_tokens":1200,"prompt_tokens":1200}`, `,"usage":{"output_tokens":30,"prompt_tokens":1200,"cache_read_input_tokens":800}`, `,"usage":{"output_tokens":30,"prompt_tokens":1200,"cache_read_input_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 new file mode 100644 index 0000000000..f307738c2d --- /dev/null +++ b/backend/internal/service/anthropic_prompt_total_test.go @@ -0,0 +1,353 @@ +//go:build unit + +package service + +import ( + "context" + "encoding/json" + "io" + "net/http" + "net/http/httptest" + "strings" + "testing" + "time" + + "github.com/Wei-Shaw/sub2api/internal/config" + "github.com/Wei-Shaw/sub2api/internal/pkg/apicompat" + "github.com/gin-gonic/gin" + "github.com/stretchr/testify/require" + "github.com/tidwall/gjson" +) + +func TestAnthropicPromptTotalSnapshots(t *testing.T) { + for _, test := range []struct { + name string + start string + deltas []string + inputs []int + }{ + {"prompt total", `"prompt_tokens":100`, []string{`{"cache_creation":{"ephemeral_1h_input_tokens":30}}`, `{"cache_creation":{"ephemeral_1h_input_tokens":30}}`, `{"cache_creation":{"ephemeral_5m_input_tokens":0}}`, `{"cache_read_input_tokens":10}`, `{"prompt_tokens":120}`, `{"output_tokens":2}`}, []int{50, 50, 70, 60, 80, 80}}, + {"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 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"} { + t.Run(test.name+"/"+parser, func(t *testing.T) { + usage := &ClaudeUsage{} + merge := func(snapshot string, start bool) { + if parser == "typed" { + var source apicompat.AnthropicUsage + require.NoError(t, json.Unmarshal([]byte(snapshot), &source)) + mergeAnthropicUsage(usage, source) + return + } + data := `{"type":"message_delta","usage":` + snapshot + `}` + if start { + data = `{"type":"message_start","message":{"usage":` + snapshot + `}}` + } + if parser == "raw" { + parseSSEUsagePassthrough(data, usage) + } else { + (&GatewayService{}).parseSSEUsage(data, usage) + } + } + merge(`{`+test.start+`,"cache_creation":{"ephemeral_5m_input_tokens":20}}`, true) + require.Equal(t, 80, usage.InputTokens) + for index, delta := range test.deltas { + merge(delta, false) + require.Equal(t, test.inputs[index], usage.InputTokens, "delta %d", index) + } + }) + } + } +} + +func TestAnthropicPromptTotalCacheReadPresence(t *testing.T) { + for _, test := range []struct { + name string + delta string + read int + }{ + {"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}, + {"zero falls back", `{"cache_read_input_tokens":0,"cached_tokens":13,"prompt_tokens_details":{"cached_tokens":14},"prompt_cache_hit_tokens":15}`, 13}, + {"alias zero falls back", `{"cached_tokens":0,"prompt_tokens_details":{"cached_tokens":14},"prompt_cache_hit_tokens":15}`, 14}, + {"details zero falls back", `{"prompt_tokens_details":{"cached_tokens":0},"prompt_cache_hit_tokens":15}`, 15}, + } { + for _, parser := range []string{"typed", "raw", "generic"} { + t.Run(test.name+"/"+parser, func(t *testing.T) { + usage := &ClaudeUsage{} + merge := func(snapshot string, start bool) { + if parser == "typed" { + var source apicompat.AnthropicUsage + require.NoError(t, json.Unmarshal([]byte(snapshot), &source)) + mergeAnthropicUsage(usage, source) + return + } + data := `{"type":"message_delta","usage":` + snapshot + `}` + if start { + data = `{"type":"message_start","message":{"usage":` + snapshot + `}}` + } + if parser == "raw" { + parseSSEUsagePassthrough(data, usage) + } else { + (&GatewayService{}).parseSSEUsage(data, usage) + } + } + merge(`{"prompt_tokens":100,"cache_read_input_tokens":20,"cache_creation_input_tokens":10}`, true) + require.Equal(t, 70, usage.InputTokens) + merge(test.delta, false) + require.Equal(t, test.read, usage.CacheReadInputTokens) + require.Equal(t, 90-test.read, usage.InputTokens) + merge(`{"output_tokens":3}`, false) + require.Equal(t, test.read, usage.CacheReadInputTokens) + require.Equal(t, 90-test.read, usage.InputTokens) + }) + } + } +} + +func TestAnthropicPromptTotalCacheReadZeroForwardBoundary(t *testing.T) { + gin.SetMode(gin.TestMode) + for _, field := range []string{"cache_read_input_tokens", "cached_tokens"} { + for _, route := range []string{"typed", "raw", "generic"} { + 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" + 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" + } + response := &http.Response{StatusCode: http.StatusOK, Header: http.Header{"Content-Type": []string{"text/event-stream"}}, Body: io.NopCloser(strings.NewReader(payload))} + recorder := httptest.NewRecorder() + ctx, _ := gin.CreateTestContext(recorder) + ctx.Request = httptest.NewRequest(http.MethodPost, "/v1/messages", nil) + service := &GatewayService{cfg: &config.Config{}, rateLimitService: &RateLimitService{}} + var usage *ClaudeUsage + var err error + if route == "typed" { + var result *ForwardResult + result, err = service.handleResponsesStreamingResponse(response, ctx, "claude-sonnet-4", "claude-sonnet-4", nil, time.Now(), apicompat.ResponsesClientToolMapping{}) + require.NotNil(t, result) + usage = &result.Usage + } else { + var result *streamingResult + if route == "raw" { + result, err = service.handleStreamingResponseAnthropicAPIKeyPassthrough(context.Background(), response, ctx, &Account{ID: 701}, time.Now(), "claude-sonnet-4") + } else { + result, err = service.handleStreamingResponse(context.Background(), response, ctx, &Account{ID: 701}, time.Now(), "claude-sonnet-4", "claude-sonnet-4", false) + } + require.NotNil(t, result) + usage = result.usage + } + if terminal == "eof" && route != "typed" { + require.ErrorContains(t, err, "missing terminal event") + } else { + require.NoError(t, err) + } + require.NotNil(t, usage) + require.Equal(t, 70, usage.InputTokens) + require.Equal(t, 20, usage.CacheReadInputTokens) + require.Equal(t, 10, usage.CacheCreationInputTokens) + require.Equal(t, 2, usage.OutputTokens) + }) + } + } + } +} + +func TestAnthropicCacheReadZeroPreservesIndependentInput(t *testing.T) { + for _, field := range []string{"cache_read_input_tokens", "cached_tokens"} { + for _, parser := range []string{"typed", "generic", "raw"} { + t.Run(field+"/"+parser, func(t *testing.T) { + usage := &ClaudeUsage{} + for index, snapshot := range []string{ + `{"input_tokens":80,"cache_read_input_tokens":20,"cache_creation_input_tokens":10}`, + `{"` + field + `":0}`, + } { + if parser == "typed" { + var source apicompat.AnthropicUsage + require.NoError(t, json.Unmarshal([]byte(snapshot), &source)) + mergeAnthropicUsage(usage, source) + } else if parser == "raw" { + if index == 0 { + parseSSEUsagePassthrough(`{"type":"message_start","message":{"usage":`+snapshot+`}}`, usage) + } else { + parseSSEUsagePassthrough(`{"type":"message_delta","usage":`+snapshot+`}`, usage) + } + } else if index == 0 { + (&GatewayService{}).parseSSEUsage(`{"type":"message_start","message":{"usage":`+snapshot+`}}`, usage) + } else { + (&GatewayService{}).parseSSEUsage(`{"type":"message_delta","usage":`+snapshot+`}`, usage) + } + require.Equal(t, 80, usage.InputTokens) + } + require.Equal(t, 20, usage.CacheReadInputTokens) + require.Equal(t, 10, usage.CacheCreationInputTokens) + }) + } + } +} + +func TestAnthropicPromptTotalForwardBoundary(t *testing.T) { + gin.SetMode(gin.TestMode) + for _, source := range []string{"prompt total", "independent input"} { + for _, route := range []string{"messages", "passthrough", "native messages", "responses", "buffered responses", "chat", "buffered chat", "native responses", "buffered native responses", "native chat", "buffered native chat"} { + for _, terminal := range []string{"stop", "eof"} { + t.Run(source+"/"+route+"/"+terminal, func(t *testing.T) { + inputField, wantInput := `"input_tokens":80`, 80 + if source == "prompt total" { + inputField, wantInput = `"input_tokens":100,"prompt_tokens":100`, 50 + } + payload := "event: message_start\ndata: " + `{"type":"message_start","message":{"id":"msg_total","type":"message","role":"assistant","model":"claude-sonnet-4","content":[],"usage":{` + inputField + `,"cache_creation":{"ephemeral_5m_input_tokens":20}}}}` + "\n\n" + for range 2 { + payload += "event: message_delta\ndata: " + `{"type":"message_delta","usage":{"cache_creation":{"ephemeral_1h_input_tokens":30}}}` + "\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" + } + response := &http.Response{StatusCode: http.StatusOK, Header: http.Header{"Content-Type": []string{"text/event-stream"}}, Body: io.NopCloser(strings.NewReader(payload))} + recorder := httptest.NewRecorder() + ctx, _ := gin.CreateTestContext(recorder) + ctx.Request = httptest.NewRequest(http.MethodPost, "/v1/messages", nil) + service := &GatewayService{cfg: &config.Config{}, rateLimitService: &RateLimitService{}} + native := &OpenAIGatewayService{cfg: &config.Config{}} + var result *ForwardResult + var nativeResult *OpenAIForwardResult + var err error + switch route { + case "messages", "passthrough": + var streamed *streamingResult + if route == "messages" { + streamed, err = service.handleStreamingResponse(context.Background(), response, ctx, &Account{ID: 701}, time.Now(), "claude-sonnet-4", "claude-sonnet-4", false) + } else { + streamed, err = service.handleStreamingResponseAnthropicAPIKeyPassthrough(context.Background(), response, ctx, &Account{ID: 701}, time.Now(), "claude-sonnet-4") + } + require.NotNil(t, streamed) + result = &ForwardResult{Usage: *streamed.usage} + case "native messages": + nativeResult, err = native.handleNativeAnthropicStreamingResponse(context.Background(), response, ctx, &Account{ID: 701}, "claude-sonnet-4", "claude-sonnet-4", "claude-sonnet-4", nil, time.Now()) + case "responses": + result, err = service.handleResponsesStreamingResponse(response, ctx, "claude-sonnet-4", "claude-sonnet-4", nil, time.Now(), apicompat.ResponsesClientToolMapping{}) + case "buffered responses": + result, err = service.handleResponsesBufferedStreamingResponse(response, ctx, "claude-sonnet-4", "claude-sonnet-4", nil, time.Now(), apicompat.ResponsesClientToolMapping{}) + case "chat": + result, err = service.handleCCStreamingFromAnthropic(response, ctx, "claude-sonnet-4", "claude-sonnet-4", nil, time.Now()) + case "buffered chat": + result, err = service.handleCCBufferedFromAnthropic(response, ctx, "claude-sonnet-4", "claude-sonnet-4", nil, time.Now()) + case "native responses": + nativeResult, err = native.handleResponsesStreamingFromNativeAnthropic(response, ctx, "claude-sonnet-4", "claude-sonnet-4", "claude-sonnet-4", nil, time.Now(), apicompat.ResponsesClientToolMapping{}) + case "buffered native responses": + nativeResult, err = native.handleResponsesBufferedFromNativeAnthropic(response, ctx, "claude-sonnet-4", "claude-sonnet-4", "claude-sonnet-4", nil, time.Now(), apicompat.ResponsesClientToolMapping{}) + case "native chat": + nativeResult, err = native.handleCCStreamingFromNativeAnthropic(response, ctx, "claude-sonnet-4", "claude-sonnet-4", "claude-sonnet-4", nil, time.Now()) + case "buffered native chat": + nativeResult, err = native.handleCCBufferedFromNativeAnthropic(response, ctx, "claude-sonnet-4", "claude-sonnet-4", "claude-sonnet-4", nil, time.Now()) + } + if terminal == "eof" && (route == "messages" || route == "passthrough" || route == "native messages") { + require.ErrorContains(t, err, "missing terminal event") + } else { + require.NoError(t, err) + } + if nativeResult != nil { + require.Equal(t, wantInput+50, nativeResult.Usage.InputTokens) + billingResult := *nativeResult + billingResult.Model, billingResult.BillingModel, billingResult.UpstreamModel = "k3", "kimi-k3", "k3" + assertNativeCacheRecordUsage(t, &billingResult, nativeAnthropicTestAccount(), wantInput, 0.16) + result = &ForwardResult{Usage: ClaudeUsage{InputTokens: nativeResult.Usage.InputTokens - nativeResult.Usage.CacheCreationInputTokens, OutputTokens: nativeResult.Usage.OutputTokens, CacheCreationInputTokens: nativeResult.Usage.CacheCreationInputTokens, CacheCreation5mTokens: nativeResult.Usage.CacheCreation5mTokens, CacheCreation1hTokens: nativeResult.Usage.CacheCreation1hTokens}} + } + require.NotNil(t, result) + require.Equal(t, wantInput, result.Usage.InputTokens) + require.Equal(t, 2, result.Usage.OutputTokens) + require.Equal(t, 50, result.Usage.CacheCreationInputTokens) + require.Equal(t, 20, result.Usage.CacheCreation5mTokens) + require.Equal(t, 30, result.Usage.CacheCreation1hTokens) + result.Model = "claude-sonnet-4" + assertAnthropicCacheCreationResultCosts(t, result, 0.16) + if strings.Contains(route, "messages") || route == "passthrough" { + return + } + var clientUsage gjson.Result + if strings.HasPrefix(route, "buffered") { + clientUsage = gjson.GetBytes(recorder.Body.Bytes(), "usage") + } else { + count := 0 + for _, line := range strings.Split(recorder.Body.String(), "\n") { + if !strings.HasPrefix(line, "data: ") { + continue + } + data := strings.TrimPrefix(line, "data: ") + if gjson.Get(data, "type").String() == "response.completed" { + clientUsage = gjson.Get(data, "response.usage") + count++ + } else if gjson.Get(data, "usage").Exists() { + clientUsage = gjson.Get(data, "usage") + count++ + } + } + require.Equal(t, 1, count) + } + require.True(t, clientUsage.Exists()) + inputPath, creationPath := "input_tokens", "cache_creation_input_tokens" + if strings.HasSuffix(route, "chat") { + inputPath, creationPath = "prompt_tokens", "prompt_tokens_details.cache_creation_tokens" + } + require.EqualValues(t, wantInput+50, clientUsage.Get(inputPath).Int()) + require.EqualValues(t, 50, clientUsage.Get(creationPath).Int()) + }) + } + } + } +} + +func TestAnthropicPromptTotalBufferedMessages(t *testing.T) { + gin.SetMode(gin.TestMode) + for _, source := range []string{"prompt total", "independent input"} { + for _, route := range []string{"messages", "passthrough", "native messages"} { + t.Run(source+"/"+route, func(t *testing.T) { + inputField, wantInput := `"input_tokens":80`, 80 + if source == "prompt total" { + inputField, wantInput = `"input_tokens":100,"prompt_tokens":100`, 50 + } + body := `{"id":"msg_total","type":"message","model":"claude-sonnet-4","role":"assistant","content":[],"usage":{` + inputField + `,"output_tokens":2,"cache_creation":{"ephemeral_5m_input_tokens":20,"ephemeral_1h_input_tokens":30}}}` + response := &http.Response{StatusCode: http.StatusOK, Header: http.Header{"Content-Type": []string{"application/json"}}, Body: io.NopCloser(strings.NewReader(body))} + recorder := httptest.NewRecorder() + ctx, _ := gin.CreateTestContext(recorder) + ctx.Request = httptest.NewRequest(http.MethodPost, "/v1/messages", nil) + service := &GatewayService{cfg: &config.Config{}, rateLimitService: &RateLimitService{}} + account := &Account{ID: 701} + var usage *ClaudeUsage + var err error + switch route { + case "messages": + usage, err = service.handleNonStreamingResponse(context.Background(), response, ctx, account, "claude-sonnet-4", "claude-sonnet-4") + case "passthrough": + usage, err = service.handleNonStreamingResponseAnthropicAPIKeyPassthrough(context.Background(), response, ctx, account) + case "native messages": + var result *OpenAIForwardResult + result, err = (&OpenAIGatewayService{cfg: &config.Config{}}).handleNativeAnthropicBufferedResponse(context.Background(), response, ctx, account, "claude-sonnet-4", "claude-sonnet-4", "claude-sonnet-4", nil, time.Now()) + require.NoError(t, err) + require.Equal(t, wantInput+50, result.Usage.InputTokens) + result.Model, result.BillingModel, result.UpstreamModel = "k3", "kimi-k3", "k3" + assertNativeCacheRecordUsage(t, result, nativeAnthropicTestAccount(), wantInput, 0.16) + usage = parseClaudeUsageFromResponseBody([]byte(body)) + } + require.NoError(t, err) + require.Equal(t, wantInput, usage.InputTokens) + assertAnthropicCacheCreationResultCosts(t, &ForwardResult{Model: "claude-sonnet-4", Usage: *usage}, 0.16) + require.JSONEq(t, body, recorder.Body.String()) + }) + } + } +} diff --git a/backend/internal/service/antigravity_gateway_service_test.go b/backend/internal/service/antigravity_gateway_service_test.go index 92735948aa..c589eed3f9 100644 --- a/backend/internal/service/antigravity_gateway_service_test.go +++ b/backend/internal/service/antigravity_gateway_service_test.go @@ -1781,14 +1781,14 @@ func TestExtractSSEUsage(t *testing.T) { { name: "top-level usage with all fields", line: `data: {"usage":{"input_tokens":10,"output_tokens":20,"cache_read_input_tokens":5,"cache_creation_input_tokens":3}}`, - expected: ClaudeUsage{InputTokens: 10, OutputTokens: 20, CacheReadInputTokens: 5, CacheCreationInputTokens: 3}, + expected: ClaudeUsage{InputTokens: 10, OutputTokens: 20, CacheReadInputTokens: 5, CacheCreationInputTokens: 3, cacheCreationInputTokensPresent: true}, }, { // Anthropic message_start 把 usage 嵌套在 message.usage 下, // 必须从这里提取输入侧字段(含 cache_read/cache_creation_input_tokens)。 name: "message_start nested usage with input/cache tokens", line: `data: {"type":"message_start","message":{"id":"msg_01","usage":{"input_tokens":35576,"cache_creation_input_tokens":0,"cache_read_input_tokens":12000,"output_tokens":1}}}`, - expected: ClaudeUsage{InputTokens: 35576, OutputTokens: 1, CacheReadInputTokens: 12000}, + expected: ClaudeUsage{InputTokens: 35576, OutputTokens: 1, CacheReadInputTokens: 12000, cacheCreationInputTokensPresent: true}, }, { // message_start.message.usage.cache_creation 内的 5m/1h 明细也要解析。 diff --git a/backend/internal/service/antigravity_gateway_upstream.go b/backend/internal/service/antigravity_gateway_upstream.go index 20018202b7..1b46af06e3 100644 --- a/backend/internal/service/antigravity_gateway_upstream.go +++ b/backend/internal/service/antigravity_gateway_upstream.go @@ -150,12 +150,7 @@ func (s *AntigravityGatewayService) ForwardUpstream(ctx context.Context, c *gin. FirstTokenMs: firstTokenMs, ClientDisconnect: clientDisconnect, UpstreamHeaders: resp.Header, - Usage: ClaudeUsage{ - InputTokens: usage.InputTokens, - OutputTokens: usage.OutputTokens, - CacheReadInputTokens: usage.CacheReadInputTokens, - CacheCreationInputTokens: usage.CacheCreationInputTokens, - }, + Usage: *usage, }, nil } @@ -343,8 +338,9 @@ 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 } // 解析嵌套的 cache_creation 对象中的 5m/1h 明细 if cc, ok := u["cache_creation"].(map[string]any); ok { @@ -376,6 +372,7 @@ func (s *AntigravityGatewayService) extractClaudeUsage(body []byte) *ClaudeUsage } if v, ok := u["cache_creation_input_tokens"].(float64); ok { usage.CacheCreationInputTokens = int(v) + usage.cacheCreationInputTokensPresent = true } // 解析嵌套的 cache_creation 对象中的 5m/1h 明细 if cc, ok := u["cache_creation"].(map[string]any); ok { diff --git a/backend/internal/service/billing_service.go b/backend/internal/service/billing_service.go index 4b0e06c6bb..5790683718 100644 --- a/backend/internal/service/billing_service.go +++ b/backend/internal/service/billing_service.go @@ -1967,17 +1967,21 @@ func (s *BillingService) computeCacheCreationCost(pricing *ModelPricing, tokens return cost * multiplier } if pricing.SupportsCacheBreakdown && (pricing.CacheCreation5mPrice > 0 || pricing.CacheCreation1hPrice > 0) { - cacheCreation5mTokens, cacheCreation1hTokens := normalizeCacheCreationBreakdown(tokens) - if cacheCreation5mTokens == 0 && cacheCreation1hTokens == 0 && tokens.CacheCreationTokens > 0 { - // API 未返回 ephemeral 明细,回退到全部按 5m 单价计费 - return float64(tokens.CacheCreationTokens) * pricing.CacheCreation5mPrice * multiplier - } + cacheCreation5mTokens, cacheCreation1hTokens := allocateCacheCreationBillingTokens(tokens) return float64(cacheCreation5mTokens)*pricing.CacheCreation5mPrice*multiplier + float64(cacheCreation1hTokens)*pricing.CacheCreation1hPrice*multiplier } return float64(tokens.CacheCreationTokens) * price * multiplier } +func allocateCacheCreationBillingTokens(tokens UsageTokens) (int, int) { + cacheCreation5mTokens, cacheCreation1hTokens := normalizeCacheCreationBreakdown(tokens) + if tokens.CacheCreationTokens > 0 { + cacheCreation5mTokens += tokens.CacheCreationTokens - cacheCreation5mTokens - cacheCreation1hTokens + } + return cacheCreation5mTokens, cacheCreation1hTokens +} + // OpenAI's two write buckets are disjoint and exhaustive. Do not add the // aggregate again or reuse the Anthropic 5m/1h buckets. Invalid or unknown // breakdowns fall back to the aggregate's existing price. diff --git a/backend/internal/service/billing_service_test.go b/backend/internal/service/billing_service_test.go index b9c3d8f164..fa9f855b4c 100644 --- a/backend/internal/service/billing_service_test.go +++ b/backend/internal/service/billing_service_test.go @@ -1622,6 +1622,35 @@ func TestNormalizeCacheCreationBreakdown_BillingSafetyInvariant(t *testing.T) { } } +func TestComputeCacheCreationCost_MissingDetailUses5mFallback(t *testing.T) { + svc := &BillingService{} + pricing := &ModelPricing{SupportsCacheBreakdown: true, CacheCreation5mPrice: 0.002, CacheCreation1hPrice: 0.004} + for _, test := range []struct { + name string + tokens UsageTokens + wantCost float64 + }{ + {"5m start then aggregate only delta", UsageTokens{CacheCreationTokens: 11000, CacheCreation5mTokens: 3000}, 22}, + {"1h detail does not imply 1h remainder", UsageTokens{CacheCreationTokens: 11000, CacheCreation1hTokens: 3000}, 28}, + {"mixed detail does not imply proportional remainder", UsageTokens{CacheCreationTokens: 11000, CacheCreation5mTokens: 1000, CacheCreation1hTokens: 2000}, 26}, + {"zero details", UsageTokens{CacheCreationTokens: 11000}, 22}, + {"negative detail", UsageTokens{CacheCreationTokens: 11000, CacheCreation5mTokens: -1, CacheCreation1hTokens: 3000}, 28}, + {"ratio cap retained", UsageTokens{CacheCreationTokens: 100, CacheCreation5mTokens: 50, CacheCreation1hTokens: 200}, 0.36}, + {"synthetic already normalized detail only", UsageTokens{CacheCreation5mTokens: 20, CacheCreation1hTokens: 30}, 0.16}, + } { + t.Run(test.name, func(t *testing.T) { + before := test.tokens + for _, multiplier := range []float64{1, 2} { + require.InDelta(t, test.wantCost*multiplier, svc.computeCacheCreationCost(pricing, test.tokens, 0, multiplier), 1e-12) + } + require.Equal(t, before, test.tokens) + standard := *pricing + standard.SupportsCacheBreakdown = false + require.InDelta(t, float64(test.tokens.CacheCreationTokens)*0.003, svc.computeCacheCreationCost(&standard, test.tokens, 0.003, 1), 1e-12) + }) + } +} + func TestComputeCacheCreationCost_PreservesZeroDetailFallback(t *testing.T) { svc := &BillingService{} pricing := &ModelPricing{ diff --git a/backend/internal/service/gateway_anthropic_apikey_passthrough_test.go b/backend/internal/service/gateway_anthropic_apikey_passthrough_test.go index 8b7c2d4a09..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_creation_input_tokens":0,"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) @@ -1341,6 +1341,75 @@ func TestGatewayService_ParseSSEUsagePassthrough_FallbackFromUsageNode(t *testin require.Equal(t, 3, usage.CacheCreationInputTokens) } +func TestGatewayService_ParseSSEUsagePassthrough_OtherEventCacheCreation(t *testing.T) { + tests := []struct { + name string + start string + snapshots []string + wantAggregate int + }{ + { + name: "omitted aggregate merges partial TTL snapshots", + snapshots: []string{`{"cache_creation":{"ephemeral_5m_input_tokens":2}}`, `{"cache_creation":{"ephemeral_5m_input_tokens":null,"ephemeral_1h_input_tokens":1}}`}, + wantAggregate: 3, + }, + { + name: "null aggregate falls back to TTL", + snapshots: []string{`{"cache_creation_input_tokens":null,"cache_creation":{"ephemeral_5m_input_tokens":2,"ephemeral_1h_input_tokens":1}}`}, + 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}}`}, + wantAggregate: 3, + }, + { + name: "previous explicit aggregate survives null", + start: `{"cache_creation_input_tokens":9}`, + snapshots: []string{`{"cache_creation_input_tokens":null,"cache_creation":{"ephemeral_5m_input_tokens":2,"ephemeral_1h_input_tokens":1}}`}, + 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}}`}, + wantAggregate: 3, + }, + { + 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 { + for _, location := range []string{"usage", "message.usage", "null usage with message.usage"} { + t.Run(test.name+"/"+location, func(t *testing.T) { + usage := &ClaudeUsage{} + if test.start != "" { + parseSSEUsagePassthrough(`{"type":"message_start","message":{"usage":`+test.start+`}}`, usage) + } + for _, snapshot := range test.snapshots { + data := `{"type":"content_block_delta","usage":` + snapshot + `}` + switch location { + case "message.usage": + data = `{"type":"content_block_delta","message":{"usage":` + snapshot + `}}` + case "null usage with message.usage": + data = `{"type":"content_block_delta","usage":null,"message":{"usage":` + snapshot + `}}` + } + parseSSEUsagePassthrough(data, usage) + previous := *usage + parseSSEUsagePassthrough(data, usage) + require.Equal(t, previous, *usage, "repeated cumulative snapshots must be idempotent") + } + require.Equal(t, test.wantAggregate, usage.CacheCreationInputTokens) + require.Equal(t, 2, usage.CacheCreation5mTokens) + require.Equal(t, 1, usage.CacheCreation1hTokens) + }) + } + } +} + func TestParseClaudeUsageFromResponseBody(t *testing.T) { t.Run("empty or missing usage", func(t *testing.T) { got := parseClaudeUsageFromResponseBody(nil) @@ -1353,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_creation_input_tokens":0,"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 a781b69913..5bf8fbb495 100644 --- a/backend/internal/service/gateway_anthropic_passthrough.go +++ b/backend/internal/service/gateway_anthropic_passthrough.go @@ -651,16 +651,8 @@ func parseSSEUsagePassthrough(data string, usage *ClaudeUsage) { msgUsage := parsed.Get("message.usage") if msgUsage.Exists() { usage.InputTokens = int(msgUsage.Get("input_tokens").Int()) - usage.CacheCreationInputTokens = int(msgUsage.Get("cache_creation_input_tokens").Int()) - usage.CacheReadInputTokens = int(msgUsage.Get("cache_read_input_tokens").Int()) - // 保持与通用解析一致:message_start 允许覆盖 5m/1h 明细(包括 0)。 - cc5m := msgUsage.Get("cache_creation.ephemeral_5m_input_tokens") - cc1h := msgUsage.Get("cache_creation.ephemeral_1h_input_tokens") - if cc5m.Exists() || cc1h.Exists() { - usage.CacheCreation5mTokens = int(cc5m.Int()) - usage.CacheCreation1hTokens = int(cc1h.Int()) - } + mergeRawAnthropicCacheCreationUsage(msgUsage, usage) } case "message_delta": deltaUsage := parsed.Get("usage") @@ -671,43 +663,14 @@ func parseSSEUsagePassthrough(data string, usage *ClaudeUsage) { if v := deltaUsage.Get("output_tokens").Int(); v > 0 { usage.OutputTokens = int(v) } - if v := deltaUsage.Get("cache_creation_input_tokens").Int(); v > 0 { - usage.CacheCreationInputTokens = int(v) - } - if v := deltaUsage.Get("cache_read_input_tokens").Int(); v > 0 { - usage.CacheReadInputTokens = int(v) - } - - cc5m := deltaUsage.Get("cache_creation.ephemeral_5m_input_tokens") - cc1h := deltaUsage.Get("cache_creation.ephemeral_1h_input_tokens") - if cc5m.Exists() { - usage.CacheCreation5mTokens = int(cc5m.Int()) - } - if cc1h.Exists() { - usage.CacheCreation1hTokens = int(cc1h.Int()) - } + mergeRawAnthropicCacheCreationUsage(deltaUsage, usage) } - } - - if usage.CacheReadInputTokens == 0 { - if cached := parsed.Get("message.usage.cached_tokens").Int(); cached > 0 { - usage.CacheReadInputTokens = int(cached) - } - if cached := parsed.Get("usage.cached_tokens").Int(); usage.CacheReadInputTokens == 0 && cached > 0 { - usage.CacheReadInputTokens = int(cached) - } - } - if usage.CacheCreationInputTokens == 0 { - cc5m := parsed.Get("message.usage.cache_creation.ephemeral_5m_input_tokens").Int() - cc1h := parsed.Get("message.usage.cache_creation.ephemeral_1h_input_tokens").Int() - if cc5m == 0 && cc1h == 0 { - cc5m = parsed.Get("usage.cache_creation.ephemeral_5m_input_tokens").Int() - cc1h = parsed.Get("usage.cache_creation.ephemeral_1h_input_tokens").Int() - } - total := cc5m + cc1h - if total > 0 { - usage.CacheCreationInputTokens = int(total) + default: + usageNode := parsed.Get("usage") + if !usageNode.Exists() || usageNode.Type == gjson.Null { + usageNode = parsed.Get("message.usage") } + mergeRawAnthropicCacheCreationUsage(usageNode, usage) } // Kimi's Anthropic-compatible stream uses input_tokens with two meanings: @@ -719,6 +682,17 @@ func parseSSEUsagePassthrough(data string, usage *ClaudeUsage) { if parsed.Get("type").String() == "message_start" { usageNode = parsed.Get("message.usage") } + if !usageNode.Exists() || usageNode.Type == gjson.Null { + usageNode = parsed.Get("message.usage") + } + 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 { + if tokens := int(value.Int()); tokens > 0 { + usage.CacheReadInputTokens = tokens + break + } + } + } normalizeAnthropicCompatiblePromptUsage(usageNode, usage) } @@ -733,47 +707,30 @@ func normalizeAnthropicCompatiblePromptUsage(usageNode gjson.Result, usage *Clau promptCacheHitTokens := usageNode.Get("prompt_cache_hit_tokens") promptCacheMissTokens := usageNode.Get("prompt_cache_miss_tokens") if (!promptTokens.Exists() || promptTokens.Int() <= 0) && - !promptCacheHitTokens.Exists() && !promptCacheMissTokens.Exists() { + !promptCacheHitTokens.Exists() && !promptCacheMissTokens.Exists() && !usage.promptTotalPresent { return false } cacheReadTokens := usage.CacheReadInputTokens - if v := usageNode.Get("cache_read_input_tokens"); v.Exists() { - cacheReadTokens = int(v.Int()) - } - if cacheReadTokens == 0 { - if v := usageNode.Get("cached_tokens"); v.Exists() { - cacheReadTokens = int(v.Int()) - } - } - if cacheReadTokens == 0 { - if v := usageNode.Get("prompt_tokens_details.cached_tokens"); v.Exists() { - cacheReadTokens = int(v.Int()) - } - } - if cacheReadTokens == 0 && promptCacheHitTokens.Exists() { - cacheReadTokens = max(int(promptCacheHitTokens.Int()), 0) - } - - cacheCreationTokens := usage.CacheCreationInputTokens - if v := usageNode.Get("cache_creation_input_tokens"); v.Exists() { - cacheCreationTokens = int(v.Int()) - } - if cacheCreationTokens == 0 { - cc5m := usageNode.Get("cache_creation.ephemeral_5m_input_tokens").Int() - cc1h := usageNode.Get("cache_creation.ephemeral_1h_input_tokens").Int() - if cc5m > 0 || cc1h > 0 { - cacheCreationTokens = int(cc5m + cc1h) + 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 { + cacheReadTokens = max(int(value.Int()), 0) + if cacheReadTokens > 0 { + break + } } } - if promptCacheMissTokens.Exists() { - usage.InputTokens = max(int(promptCacheMissTokens.Int()), 0) - } else { - usage.InputTokens = max(int(promptTokens.Int())-cacheReadTokens-cacheCreationTokens, 0) + mergeRawAnthropicCacheCreationUsage(usageNode, usage) + if cacheReadTokens > 0 || usage.CacheReadInputTokens <= 0 { + usage.CacheReadInputTokens = cacheReadTokens } - usage.CacheReadInputTokens = cacheReadTokens - usage.CacheCreationInputTokens = cacheCreationTokens + var cacheMissTokens *int + if promptCacheMissTokens.Exists() && promptCacheMissTokens.Type != gjson.Null { + value := int(promptCacheMissTokens.Int()) + cacheMissTokens = &value + } + normalizeAnthropicPromptTotal(usage, int(promptTokens.Int()), cacheMissTokens) return true } @@ -791,18 +748,9 @@ func parseClaudeUsageFromResponseBody(body []byte) *ClaudeUsage { usage.InputTokens = int(usageNode.Get("input_tokens").Int()) usage.OutputTokens = int(usageNode.Get("output_tokens").Int()) - usage.CacheCreationInputTokens = int(usageNode.Get("cache_creation_input_tokens").Int()) usage.CacheReadInputTokens = int(usageNode.Get("cache_read_input_tokens").Int()) - cc5m := usageNode.Get("cache_creation.ephemeral_5m_input_tokens").Int() - cc1h := usageNode.Get("cache_creation.ephemeral_1h_input_tokens").Int() - if cc5m > 0 || cc1h > 0 { - usage.CacheCreation5mTokens = int(cc5m) - usage.CacheCreation1hTokens = int(cc1h) - } - if usage.CacheCreationInputTokens == 0 && (cc5m > 0 || cc1h > 0) { - usage.CacheCreationInputTokens = int(cc5m + cc1h) - } + mergeRawAnthropicCacheCreationUsage(usageNode, usage) if usage.CacheReadInputTokens == 0 { if cached := usageNode.Get("cached_tokens").Int(); cached > 0 { usage.CacheReadInputTokens = int(cached) 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..00c35508fc --- /dev/null +++ b/backend/internal/service/gateway_cache_compatibility_boundary_test.go @@ -0,0 +1,274 @@ +//go:build unit + +package service + +import ( + "errors" + "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}, + {"zero write overrides creation alias", `,"usage":{"prompt_tokens":10,"prompt_tokens_details":{"cached_tokens":3,"cache_write_tokens":0,"cache_creation_tokens":4}}`, `,"usage":{"input_tokens":10,"input_tokens_details":{"cached_tokens":3,"cache_write_tokens":0,"cache_creation_tokens":4}}`, 0, 3}, + {"null Chat write overrides creation alias", `,"usage":{"prompt_tokens":10,"prompt_tokens_details":{"cached_tokens":3,"cache_write_tokens":null,"cache_creation_tokens":4}}`, `,"usage":{"input_tokens":10,"input_tokens_details":{"cached_tokens":3,"cache_write_tokens":0,"cache_creation_tokens":4}}`, 0, 3}, + {"negative write overrides creation alias", `,"usage":{"prompt_tokens":10,"prompt_tokens_details":{"cached_tokens":3,"cache_write_tokens":-2,"cache_creation_tokens":4}}`, `,"usage":{"input_tokens":10,"input_tokens_details":{"cached_tokens":3,"cache_write_tokens":-2,"cache_creation_tokens":4}}`, 0, 3}, + {"positive write overrides creation alias", `,"usage":{"prompt_tokens":10,"prompt_tokens_details":{"cached_tokens":3,"cache_write_tokens":2,"cache_creation_tokens":4}}`, `,"usage":{"input_tokens":10,"input_tokens_details":{"cached_tokens":3,"cache_write_tokens":2,"cache_creation_tokens":4}}`, 2, 3}, + } { + for _, route := range []string{"chat buffered", "chat terminal", "chat eof", "responses buffered", "responses terminal", "responses eof before output", "responses eof after output"} { + responsesEOF := strings.HasPrefix(route, "responses eof") + beforeOutput := route == "responses eof before output" + if responsesEOF && 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 beforeOutput { + payload = "" + } else if responsesEOF { + payload += `data: {"type":"response.output_text.delta","output_index":0,"content_index":0,"delta":"partial"}` + "\n\n" + } else { + 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 result *OpenAIForwardResult + var err error + switch route { + case "chat buffered": + result, err = service.bufferChatCompletionsAsAnthropic(ctx, response, "gpt-5.4", "gpt-5.4", "gpt-5.4", nil, nil, time.Now()) + case "chat terminal", "chat eof": + result, err = service.streamChatCompletionsAsAnthropic(ctx, response, "gpt-5.4", "gpt-5.4", "gpt-5.4", nil, nil, time.Now()) + case "responses buffered": + result, err = service.handleAnthropicBufferedStreamingResponse(response, ctx, rawChatCompletionsTestAccount(), "gpt-5.4", "gpt-5.4", "gpt-5.4", time.Now()) + default: + result, err = service.handleAnthropicStreamingResponse(response, ctx, rawChatCompletionsTestAccount(), "gpt-5.4", "gpt-5.4", "gpt-5.4", time.Now()) + } + var failoverErr *UpstreamFailoverError + if beforeOutput { + require.ErrorAs(t, err, &failoverErr) + require.Equal(t, http.StatusBadGateway, failoverErr.StatusCode) + require.Empty(t, recorder.Body.String()) + require.False(t, ctx.Writer.Written()) + } else if responsesEOF { + require.ErrorContains(t, err, "missing terminal event") + require.False(t, errors.As(err, &failoverErr)) + require.True(t, ctx.Writer.Written()) + } else { + require.NoError(t, err) + } + require.NotNil(t, result) + require.EqualValues(t, test.creation, result.Usage.CacheCreationInputTokens) + require.EqualValues(t, test.read, result.Usage.CacheReadInputTokens) + require.EqualValues(t, test.creation, result.Usage.billingUsageTokens().CacheCreationTokens) + if responsesEOF { + require.Zero(t, result.Usage.InputTokens) + require.Zero(t, result.Usage.OutputTokens) + } + require.Equal(t, http.StatusOK, recorder.Code) + assertUsage := func(usage gjson.Result, creation, read int64) { + require.False(t, usage.Get("cache_creation").Exists()) + 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, contentDeltas := 0, 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 "content_block_delta": + if responsesEOF { + require.Equal(t, "partial", event.Get("delta.text").String()) + } + contentDeltas++ + 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++ + } + } + if beforeOutput { + require.Zero(t, starts) + require.Zero(t, contentDeltas) + } else { + require.Equal(t, 1, starts) + if responsesEOF { + require.Equal(t, 1, contentDeltas) + } + } + if responsesEOF { + require.Zero(t, deltas) + require.Zero(t, stops) + } else { + require.Equal(t, 1, deltas) + require.Equal(t, 1, stops) + } + }) + } + } +} + +func TestResponsesTerminalUsageMatchesAnthropicOutput(t *testing.T) { + gin.SetMode(gin.TestMode) + for _, stream := range []bool{false, true} { + name := "buffered" + if stream { + name = "streaming" + } + t.Run(name, func(t *testing.T) { + payload := "data: {\"type\":\"response.created\",\"response\":{\"id\":\"resp_cache\",\"model\":\"gpt-5.4\"}}\n\n" + + `data: {"type":"response.completed","usage":{"input_tokens":20,"output_tokens":4,"cache_creation_input_tokens":4,"input_tokens_details":{"cached_tokens":5}},"response":{"id":"resp_cache","status":"completed","output":[],"usage":{"input_tokens":10,"output_tokens":2,"cache_creation_input_tokens":1,"input_tokens_details":{"cached_tokens":2}}}}` + "\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 result *OpenAIForwardResult + var err error + if stream { + result, err = service.handleAnthropicStreamingResponse(response, ctx, rawChatCompletionsTestAccount(), "gpt-5.4", "gpt-5.4", "gpt-5.4", time.Now()) + } else { + result, err = service.handleAnthropicBufferedStreamingResponse(response, ctx, rawChatCompletionsTestAccount(), "gpt-5.4", "gpt-5.4", "gpt-5.4", time.Now()) + } + require.NoError(t, err) + require.NotNil(t, result) + require.Equal(t, 10, result.Usage.InputTokens) + require.Equal(t, 2, result.Usage.OutputTokens) + require.Equal(t, 1, result.Usage.CacheCreationInputTokens) + require.Equal(t, 2, result.Usage.CacheReadInputTokens) + tokens := result.Usage.billingUsageTokens() + require.Equal(t, 7, tokens.InputTokens) + require.Equal(t, 1, tokens.CacheCreationTokens) + outputUsage := gjson.Get(recorder.Body.String(), "usage") + if stream { + for _, line := range strings.Split(recorder.Body.String(), "\n") { + if strings.HasPrefix(line, "data: ") { + event := gjson.Parse(strings.TrimPrefix(line, "data: ")) + if event.Get("type").String() == "message_delta" { + outputUsage = event.Get("usage") + } + } + } + } + require.True(t, outputUsage.Exists()) + require.EqualValues(t, tokens.InputTokens, outputUsage.Get("input_tokens").Int()) + require.EqualValues(t, tokens.OutputTokens, outputUsage.Get("output_tokens").Int()) + require.EqualValues(t, tokens.CacheCreationTokens, outputUsage.Get("cache_creation_input_tokens").Int()) + require.EqualValues(t, tokens.CacheReadTokens, outputUsage.Get("cache_read_input_tokens").Int()) + require.False(t, outputUsage.Get("cache_creation").Exists()) + }) + } +} + +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 new file mode 100644 index 0000000000..03a8871b64 --- /dev/null +++ b/backend/internal/service/gateway_cache_creation_usage_test.go @@ -0,0 +1,708 @@ +//go:build unit + +package service + +import ( + "context" + "encoding/json" + "fmt" + "io" + "net/http" + "net/http/httptest" + "strconv" + "strings" + "testing" + "time" + + "github.com/Wei-Shaw/sub2api/internal/config" + "github.com/Wei-Shaw/sub2api/internal/pkg/apicompat" + "github.com/gin-gonic/gin" + "github.com/stretchr/testify/require" + "github.com/tidwall/gjson" +) + +func TestAnthropicCacheCreationSnapshots(t *testing.T) { + tests := []struct { + name string + snapshots []string + wantTotals []int + want5m int + want1h int + billed5m int + billed1h int + }{ + { + name: "aggregate 100 with 1h 200", + snapshots: []string{`{"cache_creation_input_tokens":100,"cache_creation":{"ephemeral_1h_input_tokens":200}}`, `{"cache_creation_input_tokens":100,"cache_creation":{"ephemeral_1h_input_tokens":200}}`}, + wantTotals: []int{100, 100}, want1h: 200, billed1h: 100, + }, + { + name: "contradictory explicit aggregate", + snapshots: []string{`{"cache_creation_input_tokens":100,"cache_creation":{"ephemeral_5m_input_tokens":50,"ephemeral_1h_input_tokens":200}}`, `{"cache_creation":{"ephemeral_1h_input_tokens":300}}`}, + wantTotals: []int{100, 100}, want5m: 50, want1h: 300, billed5m: 14, billed1h: 86, + }, + { + name: "partial TTL snapshots derive missing aggregate", + snapshots: []string{`{"cache_creation":{"ephemeral_5m_input_tokens":20}}`, `{"cache_creation":{"ephemeral_1h_input_tokens":30}}`, `{"cache_creation":{"ephemeral_5m_input_tokens":0}}`}, + wantTotals: []int{20, 50, 30}, want1h: 30, billed1h: 30, + }, + { + name: "aggregate only delta replaces derived total", + snapshots: []string{`{"cache_creation":{"ephemeral_5m_input_tokens":20,"ephemeral_1h_input_tokens":30}}`, `{"cache_creation_input_tokens":40}`, `{"output_tokens":7}`, `{"cache_creation":{"ephemeral_1h_input_tokens":200}}`}, + wantTotals: []int{50, 40, 40, 40}, want5m: 20, want1h: 200, billed5m: 4, billed1h: 36, + }, + { + 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{200, 250}, want5m: 50, want1h: 200, billed5m: 50, billed1h: 200, + }, + { + 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, 100, 100}, want1h: 200, billed1h: 100, + }, + { + name: "repeated cumulative snapshots do not double count", + snapshots: []string{`{"cache_creation":{"ephemeral_5m_input_tokens":20,"ephemeral_1h_input_tokens":30}}`, `{"cache_creation":{"ephemeral_5m_input_tokens":20,"ephemeral_1h_input_tokens":30}}`, `{"cache_creation":{"ephemeral_1h_input_tokens":30}}`}, + wantTotals: []int{50, 50, 50}, want5m: 20, want1h: 30, billed5m: 20, billed1h: 30, + }, + { + name: "null aggregate derives merged partial TTL", + snapshots: []string{`{"cache_creation_input_tokens":null,"cache_creation":{"ephemeral_5m_input_tokens":20}}`, `{"cache_creation_input_tokens":null,"cache_creation":{"ephemeral_5m_input_tokens":null,"ephemeral_1h_input_tokens":30}}`, `{"cache_creation":{"ephemeral_5m_input_tokens":null,"ephemeral_1h_input_tokens":null}}`}, + wantTotals: []int{20, 50, 50}, want5m: 20, want1h: 30, billed5m: 20, billed1h: 30, + }, + { + name: "null aggregate does not clear explicit aggregate", + snapshots: []string{`{"cache_creation_input_tokens":100,"cache_creation":{"ephemeral_1h_input_tokens":200}}`, `{"cache_creation_input_tokens":null,"cache_creation":{"ephemeral_1h_input_tokens":null}}`}, + wantTotals: []int{100, 100}, want1h: 200, billed1h: 100, + }, + { + 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{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, 50, 70, 35}, want5m: 20, want1h: 50, billed5m: 10, billed1h: 25, + }, + { + name: "all null is absent before partial TTL", + snapshots: []string{`{"cache_creation_input_tokens":null,"cache_creation":{"ephemeral_5m_input_tokens":null,"ephemeral_1h_input_tokens":null}}`, `{"cache_creation":{"ephemeral_5m_input_tokens":20}}`, `{"cache_creation":{"ephemeral_1h_input_tokens":30}}`}, + wantTotals: []int{0, 20, 50}, want5m: 20, want1h: 30, billed5m: 20, billed1h: 30, + }, + } + for _, test := range tests { + for _, parser := range []string{"shared merge", "raw passthrough", "generic SSE"} { + t.Run(test.name+"/"+parser, func(t *testing.T) { + usage := &ClaudeUsage{} + for index, snapshot := range test.snapshots { + if parser == "shared merge" { + var source apicompat.AnthropicUsage + require.NoError(t, json.Unmarshal([]byte(snapshot), &source)) + mergeAnthropicUsage(usage, source) + } else if parser == "generic SSE" { + if index == 0 { + (&GatewayService{}).parseSSEUsage(`{"type":"message_start","message":{"usage":`+snapshot+`}}`, usage) + } else { + (&GatewayService{}).parseSSEUsage(`{"type":"message_delta","usage":`+snapshot+`}`, usage) + } + } else if index == 0 { + parseSSEUsagePassthrough(`{"type":"message_start","message":{"usage":`+snapshot+`}}`, usage) + } else { + parseSSEUsagePassthrough(`{"type":"message_delta","usage":`+snapshot+`}`, usage) + } + require.Equal(t, test.wantTotals[index], usage.CacheCreationInputTokens) + } + require.Equal(t, test.want5m, usage.CacheCreation5mTokens) + require.Equal(t, test.want1h, usage.CacheCreation1hTokens) + cache5m, cache1h := normalizeCacheCreationBreakdown(usage.billingUsageTokens()) + require.Equal(t, test.billed5m, cache5m) + require.Equal(t, test.billed1h, cache1h) + assertAnthropicCacheCreationRecordCosts(t, *usage, float64(test.billed5m)*0.002+float64(test.billed1h)*0.004) + }) + } + } +} + +func TestAnthropicCacheCreationMissingDetailForwardBillingBoundary(t *testing.T) { + gin.SetMode(gin.TestMode) + for _, test := range []struct { + name string + start string + delta string + aggregate int + ttl5m int + ttl1h int + cacheCost float64 + }{ + {"5m start aggregate grows", `"cache_creation_input_tokens":3000,"cache_creation":{"ephemeral_5m_input_tokens":3000}`, `{"cache_creation_input_tokens":11000}`, 11000, 3000, 0, 22}, + {"1h start remainder defaults to 5m", `"cache_creation_input_tokens":3000,"cache_creation":{"ephemeral_1h_input_tokens":3000}`, `{"cache_creation_input_tokens":11000}`, 11000, 0, 3000, 28}, + {"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 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"} { + for _, terminal := range []string{"stop", "eof"} { + t.Run(test.name+"/"+route+"/"+terminal, func(t *testing.T) { + payload := "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\":2," + test.start + "}}}\n\n" + for range 2 { + payload += "event: message_delta\ndata: {\"type\":\"message_delta\",\"usage\":" + test.delta + "}\n\n" + } + payload += "event: message_delta\ndata: {\"type\":\"message_delta\",\"delta\":{\"stop_reason\":\"end_turn\"},\"usage\":{\"cache_creation_input_tokens\":null,\"cache_creation\":{\"ephemeral_5m_input_tokens\":null,\"ephemeral_1h_input_tokens\":null},\"output_tokens\":2}}\n\n" + if terminal == "stop" { + for range 2 { + payload += "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(payload))} + service := &GatewayService{cfg: &config.Config{}, rateLimitService: &RateLimitService{}} + var result *ForwardResult + var err error + switch route { + case "standard", "passthrough": + var streamed *streamingResult + if route == "standard" { + streamed, err = service.handleStreamingResponse(context.Background(), response, ctx, &Account{ID: 701}, time.Now(), "claude-sonnet-4", "claude-sonnet-4", false) + } else { + streamed, err = service.handleStreamingResponseAnthropicAPIKeyPassthrough(context.Background(), response, ctx, &Account{ID: 701}, time.Now(), "claude-sonnet-4") + require.Equal(t, payload, recorder.Body.String()) + } + require.NotNil(t, streamed) + result = &ForwardResult{RequestID: "cache_creation", Model: "claude-sonnet-4", Usage: *streamed.usage, Duration: time.Second} + case "responses": + result, err = service.handleResponsesStreamingResponse(response, ctx, "claude-sonnet-4", "claude-sonnet-4", nil, time.Now(), apicompat.ResponsesClientToolMapping{}) + case "buffered responses": + result, err = service.handleResponsesBufferedStreamingResponse(response, ctx, "claude-sonnet-4", "claude-sonnet-4", nil, time.Now(), apicompat.ResponsesClientToolMapping{}) + case "chat": + result, err = service.handleCCStreamingFromAnthropic(response, ctx, "claude-sonnet-4", "claude-sonnet-4", nil, time.Now()) + case "buffered chat": + result, err = service.handleCCBufferedFromAnthropic(response, ctx, "claude-sonnet-4", "claude-sonnet-4", nil, time.Now()) + } + if terminal == "eof" && (route == "standard" || route == "passthrough") { + require.ErrorContains(t, err, "missing terminal event") + } else { + require.NoError(t, err) + } + 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) + require.Equal(t, test.ttl5m, result.Usage.CacheCreation5mTokens) + require.Equal(t, test.ttl1h, result.Usage.CacheCreation1hTokens) + if route != "standard" && route != "passthrough" { + var usage gjson.Result + if strings.HasPrefix(route, "buffered") { + usage = gjson.Get(recorder.Body.String(), "usage") + } else { + count := 0 + for _, line := range strings.Split(recorder.Body.String(), "\n") { + if !strings.HasPrefix(line, "data: ") { + continue + } + data := strings.TrimPrefix(line, "data: ") + if route == "responses" && gjson.Get(data, "type").String() == "response.completed" { + usage = gjson.Get(data, "response.usage") + count++ + } else if route == "chat" && gjson.Get(data, "usage").Exists() { + usage = gjson.Get(data, "usage") + count++ + } + } + require.Equal(t, 1, count) + } + require.True(t, usage.Exists()) + if strings.HasSuffix(route, "chat") { + 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+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()) + } + } + assertAnthropicCacheCreationResultCosts(t, result, test.cacheCost) + }) + } + } + } +} + +func assertAnthropicCacheCreationRecordCosts(t *testing.T, usage ClaudeUsage, wantCacheCost float64) { + t.Helper() + usage.InputTokens = 10 + usage.OutputTokens = 2 + assertAnthropicCacheCreationResultCosts(t, &ForwardResult{RequestID: "cache_creation", Model: "claude-sonnet-4", Usage: usage, Duration: time.Second}, wantCacheCost) +} + +func assertAnthropicCacheCreationResultCosts(t *testing.T, result *ForwardResult, wantCacheCost float64) { + t.Helper() + assertAnthropicCacheCreationOverrideCosts(t, result, wantCacheCost, &Account{ID: 701, Platform: PlatformAnthropic}, nil, false) +} + +func assertAnthropicCacheCreationOverrideCosts(t *testing.T, result *ForwardResult, wantCacheCost float64, account *Account, settings *SettingService, wantOverridden bool) { + t.Helper() + for _, customStats := range []bool{false, true} { + usageRepo := &openAIRecordUsageLogRepoStub{inserted: true} + billingRepo := &openAIRecordUsageBillingRepoStub{} + svc := newGatewayRecordUsageServiceWithBillingRepoForTest(usageRepo, billingRepo, &openAIRecordUsageUserRepoStub{}, &openAIRecordUsageSubRepoStub{}) + svc.settingService = settings + svc.billingService = newTestBillingServiceWithPrices(map[string]*ModelPricing{ + "claude-sonnet-4": { + InputPricePerToken: 0.001, OutputPricePerToken: 0.002, + CacheCreationPricePerToken: 0.002, SupportsCacheBreakdown: true, + CacheCreation5mPrice: 0.002, CacheCreation1hPrice: 0.004, + }, + }) + channel := &Channel{ID: 1, Status: StatusActive} + statsMultiplier := 1.0 + if customStats { + statsMultiplier = 10 + channel.AccountStatsPricingRules = []AccountStatsPricingRule{{ + AccountIDs: []int64{701}, + Pricing: []ChannelModelPricing{{ + Platform: PlatformAnthropic, Models: []string{"claude-sonnet-4"}, BillingMode: BillingModeToken, + InputPrice: float64Ptr(0.01), OutputPrice: float64Ptr(0.02), + CacheWritePrice: float64Ptr(0.02), CacheWrite1hPrice: float64Ptr(0.04), + }}, + }} + } + svc.channelService = newTestChannelServiceForStats(t, channel, 10, PlatformAnthropic) + svc.resolver = NewModelPricingResolver(svc.channelService, svc.billingService) + groupID := int64(10) + require.NoError(t, svc.RecordUsage(context.Background(), &RecordUsageInput{ + Result: result, + APIKey: &APIKey{ID: 501, GroupID: &groupID, Group: &Group{ID: groupID, Platform: PlatformAnthropic, RateMultiplier: 0.5}}, + User: &User{ID: 601}, Account: account, + })) + require.NotNil(t, usageRepo.lastLog) + require.Equal(t, wantOverridden, usageRepo.lastLog.CacheTTLOverridden) + require.Equal(t, result.Usage.CacheCreationInputTokens, usageRepo.lastLog.CacheCreationTokens) + require.Equal(t, result.Usage.CacheCreation5mTokens, usageRepo.lastLog.CacheCreation5mTokens) + require.Equal(t, result.Usage.CacheCreation1hTokens, usageRepo.lastLog.CacheCreation1hTokens) + require.InDelta(t, wantCacheCost, usageRepo.lastLog.CacheCreationCost, 1e-12) + wantTotalCost := float64(result.Usage.InputTokens)*0.001 + float64(result.Usage.OutputTokens)*0.002 + wantCacheCost + require.Equal(t, result.Usage.InputTokens, usageRepo.lastLog.InputTokens) + require.InDelta(t, wantTotalCost, usageRepo.lastLog.TotalCost, 1e-12) + require.InDelta(t, wantTotalCost*0.5, usageRepo.lastLog.ActualCost, 1e-12) + require.Equal(t, 1, billingRepo.calls) + require.InDelta(t, wantTotalCost*0.5, billingRepo.lastCmd.BalanceCost, 1e-12) + require.NotNil(t, usageRepo.lastLog.AccountStatsCost) + require.InDelta(t, wantTotalCost*statsMultiplier, *usageRepo.lastLog.AccountStatsCost, 1e-12) + } +} + +func TestHandleNonStreamingResponse_CacheCreationRecordUsageBoundary(t *testing.T) { + assertAnthropicCacheCreationForwardBoundary(t, false) +} + +func TestAntigravityForwardUpstream_CacheCreationRecordUsageBoundary(t *testing.T) { + assertAnthropicCacheCreationForwardBoundary(t, true) +} + +func assertAnthropicCacheCreationForwardBoundary(t *testing.T, antigravity bool) { + t.Helper() + gin.SetMode(gin.TestMode) + for _, test := range []struct { + name string + cache string + aggregate int + present bool + cache5m int + cache1h int + cacheCost float64 + }{ + {"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}, + {"explicit zero TTL falls back to aggregate", `"cache_creation_input_tokens":200,"cache_creation":{"ephemeral_5m_input_tokens":0,"ephemeral_1h_input_tokens":0}`, 200, true, 0, 0, 0.4}, + {"missing TTL falls back to aggregate", `"cache_creation_input_tokens":200`, 200, true, 0, 0, 0.4}, + {"null TTL falls back to aggregate", `"cache_creation_input_tokens":200,"cache_creation":{"ephemeral_5m_input_tokens":null,"ephemeral_1h_input_tokens":null}`, 200, true, 0, 0, 0.4}, + {"explicit zero TTL without aggregate", `"cache_creation":{"ephemeral_5m_input_tokens":0,"ephemeral_1h_input_tokens":0}`, 0, false, 0, 0, 0}, + } { + for _, stream := range []bool{false, true} { + if !antigravity && stream { + continue + } + mode := "nonstream" + if stream { + mode = "stream" + } + t.Run(test.name+"/"+mode, func(t *testing.T) { + usageJSON := `{"input_tokens":10,"output_tokens":2,"cache_read_input_tokens":0,` + test.cache + `}` + body := `{"id":"msg_cache","type":"message","model":"claude-sonnet-4","usage":` + usageJSON + `}` + contentType := "application/json" + if stream { + contentType = "text/event-stream" + body = "event: message_start\ndata: {\"type\":\"message_start\",\"message\":{\"usage\":" + usageJSON + "}}\n\nevent: 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{contentType}}, Body: io.NopCloser(strings.NewReader(body))} + var result *ForwardResult + if antigravity { + service := &AntigravityGatewayService{httpUpstream: &httpUpstreamStub{resp: response}, settingService: &SettingService{}} + requestBody := `{"model":"claude-sonnet-4","messages":[],"stream":` + strconv.FormatBool(stream) + `}` + var err error + result, err = service.ForwardUpstream(context.Background(), ctx, &Account{ID: 701, Credentials: map[string]any{"base_url": "https://upstream.example", "api_key": "test-key"}}, []byte(requestBody)) + require.NoError(t, err) + require.Equal(t, stream, result.Stream) + } else { + service := &GatewayService{cfg: &config.Config{}, rateLimitService: &RateLimitService{}} + usage, err := service.handleNonStreamingResponse(context.Background(), response, ctx, &Account{ID: 701}, "claude-sonnet-4", "claude-sonnet-4") + require.NoError(t, err) + result = &ForwardResult{Model: "claude-sonnet-4", Usage: *usage} + } + require.Equal(t, http.StatusOK, recorder.Code) + require.Equal(t, body, recorder.Body.String()) + wantAggregate := test.aggregate + 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) + require.Equal(t, test.cache5m, result.Usage.CacheCreation5mTokens) + require.Equal(t, test.cache1h, result.Usage.CacheCreation1hTokens) + assertAnthropicCacheCreationResultCosts(t, result, test.cacheCost) + }) + } + } +} + +func TestAnthropicCacheCreationMarshaledSSEBoundary(t *testing.T) { + gin.SetMode(gin.TestMode) + for _, test := range []struct { + name string + aggregate int + present bool + wantAggregate int + wantCacheCost float64 + }{ + {"missing", 0, false, 50, 0.16}, + {"explicit zero", 0, true, 50, 0.16}, + {"synthetic nonzero", 40, false, 40, 0.128}, + } { + for _, terminal := range []string{"message_stop", "eof"} { + t.Run(test.name+"/"+terminal, func(t *testing.T) { + cache5m, cache1h := 20, 30 + events := []apicompat.AnthropicStreamEvent{ + {Type: "message_start", Message: &apicompat.AnthropicResponse{ID: "msg_cache", Type: "message", Role: "assistant", Model: "claude-sonnet-4", Usage: apicompat.AnthropicUsage{ + InputTokens: 10, CacheCreationInputTokens: test.aggregate, CacheCreationInputTokensPresent: test.present, + CacheCreation: &apicompat.AnthropicCacheCreation{Ephemeral5mInputTokens: &cache5m}, + }}}, + {Type: "message_delta", Usage: &apicompat.AnthropicUsage{OutputTokens: 2, CacheCreation: &apicompat.AnthropicCacheCreation{Ephemeral1hInputTokens: &cache1h}}}, + {Type: "message_delta", Delta: &apicompat.AnthropicDelta{StopReason: "end_turn"}, Usage: &apicompat.AnthropicUsage{OutputTokens: 2}}, + } + if terminal == "message_stop" { + events = append(events, apicompat.AnthropicStreamEvent{Type: "message_stop"}) + } + var stream strings.Builder + for _, event := range events { + encoded, err := apicompat.ResponsesAnthropicEventToSSE(event) + require.NoError(t, err) + stream.WriteString(encoded) + } + recorder := httptest.NewRecorder() + ctx, _ := gin.CreateTestContext(recorder) + response := &http.Response{Body: io.NopCloser(strings.NewReader(stream.String()))} + result, err := (&GatewayService{}).handleResponsesStreamingResponse(response, ctx, "claude-sonnet-4", "claude-sonnet-4", nil, time.Now(), apicompat.ResponsesClientToolMapping{}) + require.NoError(t, err) + require.Equal(t, test.wantAggregate, result.Usage.CacheCreationInputTokens) + var completed apicompat.ResponsesStreamEvent + for _, line := range strings.Split(recorder.Body.String(), "\n") { + if strings.HasPrefix(line, "data: ") { + var event apicompat.ResponsesStreamEvent + require.NoError(t, json.Unmarshal([]byte(strings.TrimPrefix(line, "data: ")), &event)) + if event.Type == "response.completed" { + completed = event + } + } + } + require.NotNil(t, completed.Response) + require.NotNil(t, completed.Response.Usage) + require.Equal(t, 10+test.wantAggregate, completed.Response.Usage.InputTokens) + require.Equal(t, test.wantAggregate, completed.Response.Usage.CacheCreationInputTokens) + assertAnthropicCacheCreationRecordCosts(t, result.Usage, test.wantCacheCost) + }) + } + } +} + +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.Equal(t, 200, usage.CacheCreationInputTokens) + require.Equal(t, 200, usage.CacheCreation1hTokens) + assertAnthropicCacheCreationRecordCosts(t, *usage, 0.8) + if prompt != "" { + 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.Equal(t, 100, usage.CacheCreationInputTokens) +} + +func TestAnthropicCacheCreationNullBodyParity(t *testing.T) { + for _, test := range []struct { + name string + payload string + want int + present bool + wantCost float64 + }{ + {"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}}`, 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}, + } { + t.Run(test.name, func(t *testing.T) { + var source apicompat.AnthropicUsage + require.NoError(t, json.Unmarshal([]byte(test.payload), &source)) + typed := &ClaudeUsage{} + mergeAnthropicUsage(typed, source) + raw := parseClaudeUsageFromResponseBody([]byte(`{"usage":` + test.payload + `}`)) + generic := &ClaudeUsage{} + (&GatewayService{}).parseSSEUsage(`{"type":"message_start","message":{"usage":`+test.payload+`}}`, generic) + require.Equal(t, typed, raw) + require.Equal(t, typed, generic) + require.Equal(t, test.want, raw.CacheCreationInputTokens) + require.Equal(t, test.present, raw.cacheCreationInputTokensPresent) + assertAnthropicCacheCreationRecordCosts(t, *raw, test.wantCost) + }) + } +} + +func TestAntigravityCacheCreationUsage(t *testing.T) { + for _, test := range []struct { + name string + payload string + aggregate int + 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.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}, + {"all null", `{"cache_creation_input_tokens":null,"cache_creation":{"ephemeral_5m_input_tokens":null,"ephemeral_1h_input_tokens":null}}`, 0, false, 0}, + } { + for _, parser := range []string{"body", "stream"} { + t.Run(test.name+"/"+parser, func(t *testing.T) { + service := &AntigravityGatewayService{} + usage := &ClaudeUsage{} + if parser == "body" { + usage = service.extractClaudeUsage([]byte(`{"usage":` + test.payload + `}`)) + } else { + service.extractSSEUsage(`data: {"type":"message_start","message":{"usage":`+test.payload+`}}`, usage) + } + require.Equal(t, test.aggregate, usage.CacheCreationInputTokens) + require.Equal(t, test.present, usage.cacheCreationInputTokensPresent) + require.Equal(t, int(gjson.Get(test.payload, "cache_creation.ephemeral_5m_input_tokens").Int()), usage.CacheCreation5mTokens) + require.Equal(t, int(gjson.Get(test.payload, "cache_creation.ephemeral_1h_input_tokens").Int()), usage.CacheCreation1hTokens) + assertAnthropicCacheCreationRecordCosts(t, *usage, test.wantCost) + }) + } + } +} + +func TestAntigravityCacheCreationLateDeltas(t *testing.T) { + for _, test := range []struct { + name string + aggregate string + wantTotal int + present bool + wantCost float64 + }{ + {"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}, + } { + t.Run(test.name, func(t *testing.T) { + service := &AntigravityGatewayService{} + usage := &ClaudeUsage{} + service.extractSSEUsage(`data: {"type":"message_start","message":{"usage":{`+test.aggregate+`"cache_creation":{"ephemeral_1h_input_tokens":200}}}}`, usage) + for _, delta := range []string{ + `{"cache_creation":{"ephemeral_5m_input_tokens":50}}`, + `{"cache_creation_input_tokens":null,"cache_creation":{"ephemeral_5m_input_tokens":null,"ephemeral_1h_input_tokens":300}}`, + `{"cache_creation_input_tokens":null,"cache_creation":{"ephemeral_5m_input_tokens":null,"ephemeral_1h_input_tokens":null}}`, + } { + service.extractSSEUsage(`data: {"type":"message_delta","usage":`+delta+`}`, usage) + require.Equal(t, test.wantTotal, usage.CacheCreationInputTokens) + require.Equal(t, test.present, usage.cacheCreationInputTokensPresent) + } + require.Equal(t, 50, usage.CacheCreation5mTokens) + require.Equal(t, 300, usage.CacheCreation1hTokens) + assertAnthropicCacheCreationRecordCosts(t, *usage, test.wantCost) + }) + } + + 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":{"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.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.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 { + name string + start string + delta string + wantAggregate int + }{ + {"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"} { + 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.NotNil(t, result) + 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.NotNil(t, result) + 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.NotNil(t, result) + 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.NotNil(t, result) + aggregate = result.Usage.CacheCreationInputTokens + } + require.Equal(t, test.wantAggregate, aggregate) + // Incomplete streams retain collected usage but must not report success. + if terminal == "eof" { + require.EqualError(t, err, "stream usage incomplete: missing terminal event") + require.Equal(t, http.StatusBadGateway, recorder.Code) + errorField := "code" + if strings.HasSuffix(adapter, "chat") { + errorField = "type" + } + require.JSONEq(t, fmt.Sprintf(`{"error":{%q:"server_error","message":"upstream stream ended without a terminal event"}}`, errorField), recorder.Body.String()) + return + } + require.NoError(t, err) + 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 new file mode 100644 index 0000000000..07e29bab44 --- /dev/null +++ b/backend/internal/service/gateway_cache_ttl_override_test.go @@ -0,0 +1,396 @@ +//go:build unit + +package service + +import ( + "context" + "encoding/json" + "io" + "net/http" + "net/http/httptest" + "strconv" + "strings" + "testing" + "time" + + "github.com/Wei-Shaw/sub2api/internal/config" + "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) { + for _, test := range []struct { + name string + usage ClaudeUsage + total int + changed bool + }{ + {"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}, 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}, + {"aggregate only", ClaudeUsage{CacheCreationInputTokens: 11000}, 11000, true}, + {"empty", ClaudeUsage{}, 0, false}, + } { + for _, target := range []string{"5m", "1h"} { + t.Run(test.name+"/"+target, func(t *testing.T) { + usage := test.usage + require.Equal(t, test.changed, applyCacheTTLOverride(&usage, target)) + want5m, want1h := 0, test.total + if target == "5m" { + want5m, want1h = test.total, 0 + } + require.Equal(t, want5m, usage.CacheCreation5mTokens) + require.Equal(t, want1h, usage.CacheCreation1hTokens) + require.Equal(t, test.usage.CacheCreationInputTokens, usage.CacheCreationInputTokens) + require.Equal(t, test.usage.cacheCreationInputTokensPresent, usage.cacheCreationInputTokensPresent) + snapshot := usage + require.False(t, applyCacheTTLOverride(&usage, target)) + require.Equal(t, snapshot, usage) + }) + } + } +} + +type cacheTTLOverrideBoundaryCase struct { + name string + snapshots []string + aggregate int + present bool + ttl5m int + ttl1h int + rawCost float64 +} + +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}`}, 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}}`}, 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}, + } +} + +func cacheTTLOverrideBoundaryAccount(t *testing.T, mode string) (*Account, *SettingService, string) { + t.Helper() + resetGatewayForwardingSettingsCacheForTest(t) + account := &Account{ID: 701, Platform: PlatformAnthropic, Type: AccountTypeOAuth} + var settings *SettingService + target := "" + if strings.Contains(mode, "global") { + settings = NewSettingService(&gatewayTTLSettingRepo{data: map[string]string{ + SettingKeyEnableAnthropicCacheTTL1hInjection: "true", + }}, &config.Config{}) + target = "5m" + } + if strings.HasPrefix(mode, "account") { + target = strings.Split(mode, "/")[1] + account.Extra = map[string]any{"cache_ttl_override_enabled": true, "cache_ttl_override_target": target} + } + return account, settings, target +} + +func cacheTTLOverrideBoundaryResponse(test cacheTTLOverrideBoundaryCase, stream bool, cacheRead int) string { + base := `"input_tokens":10,"output_tokens":2,"cache_read_input_tokens":` + strconv.Itoa(cacheRead) + if !stream { + cache := `"cache_creation":{"ephemeral_5m_input_tokens":` + strconv.Itoa(test.ttl5m) + `,"ephemeral_1h_input_tokens":` + strconv.Itoa(test.ttl1h) + `}` + if test.present { + 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 + `}}` + } + payload := "event: message_start\ndata: {\"type\":\"message_start\",\"message\":{\"id\":\"msg_cache\",\"type\":\"message\",\"role\":\"assistant\",\"model\":\"k3\",\"content\":[],\"usage\":{" + base + "," + strings.TrimPrefix(test.snapshots[0], "{") + "}}\n\n" + for _, snapshot := range test.snapshots { + for range 2 { + payload += "event: message_delta\ndata: {\"type\":\"message_delta\",\"usage\":" + snapshot + "}\n\n" + } + } + payload += "event: message_delta\ndata: {\"type\":\"message_delta\",\"delta\":{\"stop_reason\":\"end_turn\"},\"usage\":{\"output_tokens\":2}}\n\nevent: message_stop\ndata: {\"type\":\"message_stop\"}\n\n" + return payload +} + +func TestCacheTTLOverrideForwardBillingBoundary(t *testing.T) { + gin.SetMode(gin.TestMode) + for _, test := range cacheTTLOverrideBoundaryCases() { + for _, route := range []string{"nonstream", "standard", "passthrough", "responses", "buffered responses", "chat", "buffered chat"} { + for _, mode := range []string{"raw", "account/5m", "account/1h", "global", "account/1h/global"} { + t.Run(test.name+"/"+route+"/"+mode, func(t *testing.T) { + account, settings, target := cacheTTLOverrideBoundaryAccount(t, mode) + payload := cacheTTLOverrideBoundaryResponse(test, route != "nonstream", 0) + contentType := "text/event-stream" + if route == "nonstream" { + contentType = "application/json" + } + 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 result *ForwardResult + var err error + switch route { + case "nonstream": + var usage *ClaudeUsage + usage, err = service.handleNonStreamingResponse(context.Background(), response, ctx, account, "k3", "k3") + require.NotNil(t, usage) + result = &ForwardResult{Usage: *usage} + case "standard", "passthrough": + var streamed *streamingResult + if route == "standard" { + streamed, err = service.handleStreamingResponse(context.Background(), response, ctx, account, time.Now(), "k3", "k3", false) + } else { + streamed, err = service.handleStreamingResponseAnthropicAPIKeyPassthrough(context.Background(), response, ctx, account, time.Now(), "k3") + } + require.NotNil(t, streamed) + result = &ForwardResult{Usage: *streamed.usage} + case "responses": + result, err = service.handleResponsesStreamingResponse(response, ctx, "k3", "k3", nil, time.Now(), apicompat.ResponsesClientToolMapping{}) + case "buffered responses": + result, err = service.handleResponsesBufferedStreamingResponse(response, ctx, "k3", "k3", nil, time.Now(), apicompat.ResponsesClientToolMapping{}) + case "chat": + result, err = service.handleCCStreamingFromAnthropic(response, ctx, "k3", "k3", nil, time.Now()) + case "buffered chat": + result, err = service.handleCCBufferedFromAnthropic(response, ctx, "k3", "k3", nil, time.Now()) + } + require.NoError(t, err) + require.NotNil(t, result) + require.Equal(t, http.StatusOK, recorder.Code) + require.Equal(t, test.aggregate, result.Usage.CacheCreationInputTokens) + require.Equal(t, test.present, result.Usage.cacheCreationInputTokensPresent) + if target == "" || route == "passthrough" { + if route == "nonstream" || route == "standard" || route == "passthrough" { + require.Equal(t, payload, recorder.Body.String()) + } + } + if target == "" || (route != "standard" && route != "nonstream") { + require.Equal(t, test.ttl5m, result.Usage.CacheCreation5mTokens) + require.Equal(t, test.ttl1h, result.Usage.CacheCreation1hTokens) + } + want5m, want1h, wantCost := test.ttl5m, test.ttl1h, test.rawCost + if target == "5m" { + want5m, want1h, wantCost = test.aggregate, 0, float64(test.aggregate)*0.002 + } else if target == "1h" { + want5m, want1h, wantCost = 0, test.aggregate, float64(test.aggregate)*0.004 + } + 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) + } + result.Model = "claude-sonnet-4" + result.UpstreamModel = "claude-sonnet-4" + assertAnthropicCacheCreationOverrideCosts(t, result, wantCost, account, settings, target != "" && test.aggregate > 0) + require.Equal(t, test.aggregate, result.Usage.CacheCreationInputTokens) + require.Equal(t, want5m, result.Usage.CacheCreation5mTokens) + require.Equal(t, want1h, result.Usage.CacheCreation1hTokens) + }) + } + } + } +} + +func TestNativeCacheTTLOverridePreservesRawBillingBoundary(t *testing.T) { + gin.SetMode(gin.TestMode) + for _, test := range cacheTTLOverrideBoundaryCases() { + for _, route := range []string{"messages", "chat", "responses"} { + for _, stream := range []bool{false, true} { + for _, mode := range []string{"raw", "account/5m", "account/1h", "global", "account/1h/global"} { + t.Run(test.name+"/"+route+"/stream="+strconv.FormatBool(stream)+"/"+mode, func(t *testing.T) { + overrideAccount, settings, _ := cacheTTLOverrideBoundaryAccount(t, mode) + account := nativeAnthropicTestAccount() + account.Extra = overrideAccount.Extra + payload := cacheTTLOverrideBoundaryResponse(test, stream || route != "messages", 7) + contentType := "text/event-stream" + if route == "messages" && !stream { + contentType = "application/json" + } + upstream := &httpUpstreamRecorder{resp: &http.Response{StatusCode: http.StatusOK, Header: http.Header{"Content-Type": []string{contentType}}, Body: io.NopCloser(strings.NewReader(payload))}} + service := &OpenAIGatewayService{cfg: rawChatCompletionsTestConfig(), httpUpstream: upstream, settingService: settings} + body := []byte(`{"model":"k3","max_tokens":32,"messages":[{"role":"user","content":"hi"}],"stream":` + strconv.FormatBool(stream) + `}`) + path := "/v1/messages" + if route == "chat" { + path = "/v1/chat/completions" + } else if route == "responses" { + path = "/v1/responses" + body = []byte(`{"model":"k3","input":"hi","stream":` + strconv.FormatBool(stream) + `}`) + } + recorder := httptest.NewRecorder() + ctx, _ := gin.CreateTestContext(recorder) + ctx.Request = httptest.NewRequest(http.MethodPost, path, strings.NewReader(string(body))) + var result *OpenAIForwardResult + var err error + switch route { + case "messages": + result, err = service.ForwardAsAnthropic(context.Background(), ctx, account, body, "", "") + case "chat": + result, err = service.ForwardAsChatCompletions(context.Background(), ctx, account, body, "", "") + case "responses": + result, err = service.Forward(context.Background(), ctx, account, body) + } + require.NoError(t, err) + require.NotNil(t, result) + require.Equal(t, http.StatusOK, recorder.Code) + require.Equal(t, 17+test.aggregate, result.Usage.InputTokens) + require.Equal(t, test.aggregate, result.Usage.CacheCreationInputTokens) + require.Equal(t, test.present, result.Usage.cacheCreationInputTokensPresent) + require.Equal(t, test.ttl5m, result.Usage.CacheCreation5mTokens) + require.Equal(t, test.ttl1h, result.Usage.CacheCreation1hTokens) + if route == "messages" { + require.Equal(t, payload, recorder.Body.String()) + } else { + assertNativeCacheCompatibleUsage(t, recorder.Body.String(), route, stream, 10, test.aggregate) + } + assertNativeCacheRecordUsageWithSettings(t, result, account, 10, test.rawCost, settings) + }) + } + } + } + } +} + +func TestRewriteCacheCreationJSONAuthoritativeTotal(t *testing.T) { + for _, test := range cacheTTLOverrideBoundaryCases() { + for _, target := range []string{"5m", "1h"} { + t.Run(test.name+"/"+target, func(t *testing.T) { + var response struct { + Usage map[string]any `json:"usage"` + } + require.NoError(t, json.Unmarshal([]byte(cacheTTLOverrideBoundaryResponse(test, false, 0)), &response)) + aggregate, present := response.Usage["cache_creation_input_tokens"] + 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"]) + require.False(t, rewriteCacheCreationJSON(response.Usage, target)) + afterAggregate, afterPresent := response.Usage["cache_creation_input_tokens"] + require.Equal(t, aggregate, afterAggregate) + require.Equal(t, present, afterPresent) + }) + } + } +} + +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_chat_completions.go b/backend/internal/service/gateway_forward_as_chat_completions.go index 565ec4a069..fb5f932a7e 100644 --- a/backend/internal/service/gateway_forward_as_chat_completions.go +++ b/backend/internal/service/gateway_forward_as_chat_completions.go @@ -357,14 +357,7 @@ func (s *GatewayService) handleCCBufferedFromAnthropic( } // Update usage from accumulated delta - if usage.InputTokens > 0 || usage.OutputTokens > 0 { - finalResp.Usage = apicompat.AnthropicUsage{ - InputTokens: usage.InputTokens, - OutputTokens: usage.OutputTokens, - CacheCreationInputTokens: usage.CacheCreationInputTokens, - CacheReadInputTokens: usage.CacheReadInputTokens, - } - } + normalizeAnthropicEventUsageForResponses(&apicompat.AnthropicStreamEvent{Message: finalResp}, usage) // Chain: Anthropic → Responses → Chat Completions responsesResp := apicompat.AnthropicToResponsesResponse(finalResp) diff --git a/backend/internal/service/gateway_forward_as_chat_completions_test.go b/backend/internal/service/gateway_forward_as_chat_completions_test.go index 163b204490..efec974391 100644 --- a/backend/internal/service/gateway_forward_as_chat_completions_test.go +++ b/backend/internal/service/gateway_forward_as_chat_completions_test.go @@ -114,7 +114,7 @@ func TestHandleCCBufferedFromAnthropic_PreservesMessageStartCacheUsageAndReasoni Header: http.Header{"x-request-id": []string{"rid_cc_buffered"}}, Body: io.NopCloser(strings.NewReader(strings.Join([]string{ `event: message_start`, - `data: {"type":"message_start","message":{"id":"msg_1","type":"message","role":"assistant","content":[],"model":"claude-sonnet-4.5","stop_reason":"","usage":{"input_tokens":12,"cache_read_input_tokens":9,"cache_creation_input_tokens":3}}}`, + `data: {"type":"message_start","message":{"id":"msg_1","type":"message","role":"assistant","content":[],"model":"claude-sonnet-4.5","stop_reason":"","usage":{"input_tokens":12,"cache_read_input_tokens":9,"cache_creation_input_tokens":5,"cache_creation":{"ephemeral_5m_input_tokens":2,"ephemeral_1h_input_tokens":3}}}}`, ``, `event: content_block_start`, `data: {"type":"content_block_start","index":0,"content_block":{"type":"text","text":"hello"}}`, @@ -132,7 +132,9 @@ func TestHandleCCBufferedFromAnthropic_PreservesMessageStartCacheUsageAndReasoni require.Equal(t, 12, result.Usage.InputTokens) require.Equal(t, 7, result.Usage.OutputTokens) require.Equal(t, 9, result.Usage.CacheReadInputTokens) - require.Equal(t, 3, result.Usage.CacheCreationInputTokens) + require.Equal(t, 5, result.Usage.CacheCreationInputTokens) + require.Equal(t, 2, result.Usage.CacheCreation5mTokens) + require.Equal(t, 3, result.Usage.CacheCreation1hTokens) require.NotNil(t, result.ReasoningEffort) require.Equal(t, "high", *result.ReasoningEffort) } diff --git a/backend/internal/service/gateway_forward_as_responses.go b/backend/internal/service/gateway_forward_as_responses.go index 93c3f62239..faa1bd7e0c 100644 --- a/backend/internal/service/gateway_forward_as_responses.go +++ b/backend/internal/service/gateway_forward_as_responses.go @@ -308,30 +308,27 @@ func mergeAnthropicUsage(dst *ClaudeUsage, src apicompat.AnthropicUsage) { return } - cacheReadTokens := src.CacheReadInputTokens - if cacheReadTokens == 0 && src.CachedTokens > 0 { - cacheReadTokens = src.CachedTokens + cacheReadTokens := max(src.CacheReadInputTokens, 0) + hasCacheReadTokens := src.CacheReadInputTokensPresent || src.CacheReadInputTokens != 0 + if cacheReadTokens == 0 && (src.CachedTokensPresent || src.CachedTokens != 0) { + cacheReadTokens = max(src.CachedTokens, 0) + hasCacheReadTokens = true } - if cacheReadTokens == 0 && src.PromptTokensDetails != nil && src.PromptTokensDetails.CachedTokens > 0 { - cacheReadTokens = src.PromptTokensDetails.CachedTokens + if cacheReadTokens == 0 && src.PromptTokensDetails != nil && (src.PromptTokensDetails.CachedTokensPresent || src.PromptTokensDetails.CachedTokens != 0) { + cacheReadTokens = max(src.PromptTokensDetails.CachedTokens, 0) + hasCacheReadTokens = true } if cacheReadTokens == 0 && src.PromptCacheHitTokens != nil { cacheReadTokens = max(*src.PromptCacheHitTokens, 0) + hasCacheReadTokens = true } + mergeAnthropicCacheCreationUsage(dst, src) // Some Anthropic-compatible providers retain OpenAI-style prompt/cache // fields. Prefer those authoritative totals or hit/miss buckets over the // overloaded input_tokens field. This covers Kimi's changing stream // semantics as well as GLM/DeepSeek cache aliases. - if src.PromptTokens > 0 || src.PromptCacheHitTokens != nil || src.PromptCacheMissTokens != nil { - if src.PromptCacheMissTokens != nil { - dst.InputTokens = max(*src.PromptCacheMissTokens, 0) - } else { - dst.InputTokens = max(src.PromptTokens-cacheReadTokens-src.CacheCreationInputTokens, 0) - } - dst.CacheReadInputTokens = cacheReadTokens - dst.CacheCreationInputTokens = src.CacheCreationInputTokens - } else { + if src.PromptTokens <= 0 && src.PromptCacheHitTokens == nil && src.PromptCacheMissTokens == nil && !dst.promptTotalPresent { // Without an authoritative prompt total or miss bucket, input_tokens is // provider-specific: it may already be the uncached bucket, or it may be // a total from an earlier event. Do not infer a subtraction merely because @@ -340,18 +337,69 @@ func mergeAnthropicUsage(dst *ClaudeUsage, src apicompat.AnthropicUsage) { if src.InputTokens > 0 { dst.InputTokens = src.InputTokens } - if cacheReadTokens > 0 { - dst.CacheReadInputTokens = cacheReadTokens - } - if src.CacheCreationInputTokens > 0 { - dst.CacheCreationInputTokens = src.CacheCreationInputTokens - } } + if hasCacheReadTokens && (cacheReadTokens > 0 || dst.CacheReadInputTokens <= 0) { + dst.CacheReadInputTokens = cacheReadTokens + } + normalizeAnthropicPromptTotal(dst, src.PromptTokens, src.PromptCacheMissTokens) if src.OutputTokens > 0 { dst.OutputTokens = src.OutputTokens } } +func normalizeAnthropicPromptTotal(usage *ClaudeUsage, promptTokens int, promptCacheMissTokens *int) { + if promptCacheMissTokens != nil { + usage.promptTotalPresent = false + usage.InputTokens = max(*promptCacheMissTokens, 0) + return + } + if promptTokens > 0 { + usage.promptTotalTokens = promptTokens + usage.promptTotalPresent = true + } + if usage.promptTotalPresent { + usage.InputTokens = max(usage.promptTotalTokens-usage.CacheReadInputTokens-usage.CacheCreationInputTokens, 0) + } +} + +func mergeAnthropicCacheCreationUsage(dst *ClaudeUsage, src apicompat.AnthropicUsage) { + 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 { + dst.CacheCreation5mTokens = max(*src.CacheCreation.Ephemeral5mInputTokens, 0) + } + if src.CacheCreation.Ephemeral1hInputTokens != nil { + dst.CacheCreation1hTokens = max(*src.CacheCreation.Ephemeral1hInputTokens, 0) + } + 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 + } + } +} + +func mergeRawAnthropicCacheCreationUsage(node gjson.Result, dst *ClaudeUsage) { + aggregate := node.Get("cache_creation_input_tokens") + usage := apicompat.AnthropicUsage{ + CacheCreationInputTokens: int(aggregate.Int()), + CacheCreationInputTokensPresent: aggregate.Exists() && aggregate.Type != gjson.Null, + CacheCreation: &apicompat.AnthropicCacheCreation{}, + } + if tokens := node.Get("cache_creation.ephemeral_5m_input_tokens"); tokens.Exists() && tokens.Type != gjson.Null { + value := int(tokens.Int()) + usage.CacheCreation.Ephemeral5mInputTokens = &value + } + if tokens := node.Get("cache_creation.ephemeral_1h_input_tokens"); tokens.Exists() && tokens.Type != gjson.Null { + value := int(tokens.Int()) + usage.CacheCreation.Ephemeral1hInputTokens = &value + } + mergeAnthropicCacheCreationUsage(dst, usage) +} + func syncAnthropicResponsesUsage(state *apicompat.AnthropicEventToResponsesState, usage ClaudeUsage) { state.InputTokens = usage.InputTokens state.OutputTokens = usage.OutputTokens @@ -368,6 +416,8 @@ func normalizeAnthropicEventUsageForResponses(event *apicompat.AnthropicStreamEv dst.OutputTokens = usage.OutputTokens dst.CacheReadInputTokens = usage.CacheReadInputTokens dst.CacheCreationInputTokens = usage.CacheCreationInputTokens + dst.CacheCreationInputTokensPresent = true + dst.CacheCreation = nil } normalize(event.Usage) if event.Message != nil { @@ -513,14 +563,7 @@ func (s *GatewayService) handleResponsesBufferedStreamingResponse( } // Update usage from accumulated delta - if usage.InputTokens > 0 || usage.OutputTokens > 0 { - finalResp.Usage = apicompat.AnthropicUsage{ - InputTokens: usage.InputTokens, - OutputTokens: usage.OutputTokens, - CacheCreationInputTokens: usage.CacheCreationInputTokens, - CacheReadInputTokens: usage.CacheReadInputTokens, - } - } + normalizeAnthropicEventUsageForResponses(&apicompat.AnthropicStreamEvent{Message: finalResp}, usage) // Convert to Responses format if isClaude55SignedThinkingModel(mappedModel) { diff --git a/backend/internal/service/gateway_forward_as_responses_test.go b/backend/internal/service/gateway_forward_as_responses_test.go index 9e00b8007a..c35bf0b749 100644 --- a/backend/internal/service/gateway_forward_as_responses_test.go +++ b/backend/internal/service/gateway_forward_as_responses_test.go @@ -252,7 +252,7 @@ func TestHandleResponsesBufferedStreamingResponse_PreservesMessageStartCacheUsag Header: http.Header{"x-request-id": []string{"rid_buffered"}}, Body: io.NopCloser(strings.NewReader(strings.Join([]string{ `event: message_start`, - `data: {"type":"message_start","message":{"id":"msg_1","type":"message","role":"assistant","content":[],"model":"claude-sonnet-4.5","stop_reason":"","usage":{"input_tokens":12,"cache_read_input_tokens":9,"cache_creation_input_tokens":3}}}`, + `data: {"type":"message_start","message":{"id":"msg_1","type":"message","role":"assistant","content":[],"model":"claude-sonnet-4.5","stop_reason":"","usage":{"input_tokens":12,"cache_read_input_tokens":9,"cache_creation_input_tokens":5,"cache_creation":{"ephemeral_5m_input_tokens":2,"ephemeral_1h_input_tokens":3}}}}`, ``, `event: content_block_start`, `data: {"type":"content_block_start","index":0,"content_block":{"type":"text","text":"hello"}}`, @@ -270,7 +270,9 @@ func TestHandleResponsesBufferedStreamingResponse_PreservesMessageStartCacheUsag require.Equal(t, 12, result.Usage.InputTokens) require.Equal(t, 7, result.Usage.OutputTokens) require.Equal(t, 9, result.Usage.CacheReadInputTokens) - require.Equal(t, 3, result.Usage.CacheCreationInputTokens) + require.Equal(t, 5, result.Usage.CacheCreationInputTokens) + require.Equal(t, 2, result.Usage.CacheCreation5mTokens) + require.Equal(t, 3, result.Usage.CacheCreation1hTokens) require.Contains(t, rec.Body.String(), `"cached_tokens":9`) } @@ -367,6 +369,36 @@ func TestHandleResponsesStreamingResponse_NormalizesTerminalUsage(t *testing.T) wantOutput: 30, wantCacheCreation: 800, }, + { + name: "explicit aggregate caps contradictory TTL breakdown", + startUsage: `"input_tokens":10,"cache_creation_input_tokens":100,"cache_creation":{"ephemeral_1h_input_tokens":200}`, + deltaUsage: `"output_tokens":7,"cache_creation":{"ephemeral_1h_input_tokens":200}`, + wantInput: 10, wantOutput: 7, wantCacheCreation: 100, + }, + { + 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, wantCacheCreation: 200, + }, + { + name: "null aggregate and TTL preserve partial snapshots", + startUsage: `"input_tokens":10,"cache_creation_input_tokens":null,"cache_creation":{"ephemeral_5m_input_tokens":20,"ephemeral_1h_input_tokens":null}`, + deltaUsage: `"output_tokens":7,"cache_creation_input_tokens":null,"cache_creation":{"ephemeral_5m_input_tokens":null,"ephemeral_1h_input_tokens":30}`, + wantInput: 10, wantOutput: 7, wantCacheCreation: 50, + }, + { + 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, 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, + }, } for _, tt := range tests { diff --git a/backend/internal/service/gateway_service.go b/backend/internal/service/gateway_service.go index 285632a572..7ed33d1470 100644 --- a/backend/internal/service/gateway_service.go +++ b/backend/internal/service/gateway_service.go @@ -663,6 +663,11 @@ type ClaudeUsage struct { CacheCreation5mTokens int // 5分钟缓存创建token(来自嵌套 cache_creation 对象) CacheCreation1hTokens int // 1小时缓存创建token(来自嵌套 cache_creation 对象) ImageOutputTokens int `json:"image_output_tokens,omitempty"` + + 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 4e1dcf9c2e..ae1d2f2dca 100644 --- a/backend/internal/service/gateway_upstream_response.go +++ b/backend/internal/service/gateway_upstream_response.go @@ -1261,6 +1261,8 @@ func (s *GatewayService) parseSSEUsage(data string, usage *ClaudeUsage) { } type sseUsagePatch struct { + promptTokens int + promptCacheMissTokens *int inputTokens int hasInputTokens bool outputTokens int @@ -1289,19 +1291,20 @@ func (s *GatewayService) extractSSEUsagePatch(event map[string]any) *sseUsagePat return nil } - patch := &sseUsagePatch{} + patch := extractAnthropicPromptPatch(usageObj) patch.hasInputTokens = true if v, ok := parseSSEUsageInt(usageObj["input_tokens"]); ok { patch.inputTokens = v } - patch.hasCacheCreationInput = true if v, ok := parseSSEUsageInt(usageObj["cache_creation_input_tokens"]); ok { patch.cacheCreationInputTokens = v + patch.hasCacheCreationInput = true } - patch.hasCacheReadInput = true if v, ok := parseSSEUsageInt(usageObj["cache_read_input_tokens"]); ok { - patch.cacheReadInputTokens = v + patch.cacheReadInputTokens = max(v, 0) + patch.hasCacheReadInput = true } + applyAnthropicCacheReadAliases(patch, usageObj) if cc, ok := usageObj["cache_creation"].(map[string]any); ok { if v, exists := parseSSEUsageInt(cc["ephemeral_5m_input_tokens"]); exists { patch.cacheCreation5mTokens = v @@ -1320,7 +1323,7 @@ func (s *GatewayService) extractSSEUsagePatch(event map[string]any) *sseUsagePat return nil } - patch := &sseUsagePatch{} + patch := extractAnthropicPromptPatch(usageObj) if v, ok := parseSSEUsageInt(usageObj["input_tokens"]); ok && v > 0 { patch.inputTokens = v patch.hasInputTokens = true @@ -1329,14 +1332,15 @@ func (s *GatewayService) extractSSEUsagePatch(event map[string]any) *sseUsagePat patch.outputTokens = v patch.hasOutputTokens = true } - if v, ok := parseSSEUsageInt(usageObj["cache_creation_input_tokens"]); ok && v > 0 { + if v, ok := parseSSEUsageInt(usageObj["cache_creation_input_tokens"]); ok && v >= 0 { patch.cacheCreationInputTokens = v patch.hasCacheCreationInput = true } - if v, ok := parseSSEUsageInt(usageObj["cache_read_input_tokens"]); ok && v > 0 { - patch.cacheReadInputTokens = v + if v, ok := parseSSEUsageInt(usageObj["cache_read_input_tokens"]); ok { + patch.cacheReadInputTokens = max(v, 0) patch.hasCacheReadInput = true } + applyAnthropicCacheReadAliases(patch, usageObj) if cc, ok := usageObj["cache_creation"].(map[string]any); ok { if v, exists := parseSSEUsageInt(cc["ephemeral_5m_input_tokens"]); exists { patch.cacheCreation5mTokens = v @@ -1353,6 +1357,28 @@ func (s *GatewayService) extractSSEUsagePatch(event map[string]any) *sseUsagePat return nil } +func extractAnthropicPromptPatch(usageObj map[string]any) *sseUsagePatch { + patch := &sseUsagePatch{} + patch.promptTokens, _ = parseSSEUsageInt(usageObj["prompt_tokens"]) + if value, ok := parseSSEUsageInt(usageObj["prompt_cache_miss_tokens"]); ok { + patch.promptCacheMissTokens = &value + } + return patch +} + +func applyAnthropicCacheReadAliases(patch *sseUsagePatch, usageObj map[string]any) { + details, _ := usageObj["prompt_tokens_details"].(map[string]any) + for _, alias := range []any{usageObj["cached_tokens"], details["cached_tokens"], usageObj["prompt_cache_hit_tokens"]} { + if patch.cacheReadInputTokens != 0 { + break + } + if value, ok := parseSSEUsageInt(alias); ok { + patch.cacheReadInputTokens = max(value, 0) + patch.hasCacheReadInput = true + } + } +} + func mergeSSEUsagePatch(usage *ClaudeUsage, patch *sseUsagePatch) { if usage == nil || patch == nil { return @@ -1361,10 +1387,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 { @@ -1376,6 +1404,11 @@ func mergeSSEUsagePatch(usage *ClaudeUsage, patch *sseUsagePatch) { if patch.hasCacheCreation1h { usage.CacheCreation1hTokens = patch.cacheCreation1hTokens } + 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) } func parseSSEUsageInt(value any) (int, bool) { @@ -1408,24 +1441,19 @@ func parseSSEUsageInt(value any) (int, bool) { // applyCacheTTLOverride 将所有 cache creation tokens 归入指定的 TTL 类型。 // target 为 "5m" 或 "1h"。返回 true 表示发生了变更。 func applyCacheTTLOverride(usage *ClaudeUsage, target string) bool { - // Fallback: 如果只有聚合字段但无 5m/1h 明细,将聚合字段归入 5m 默认类别 - if usage.CacheCreation5mTokens == 0 && usage.CacheCreation1hTokens == 0 && usage.CacheCreationInputTokens > 0 { - usage.CacheCreation5mTokens = usage.CacheCreationInputTokens - } - - total := usage.CacheCreation5mTokens + usage.CacheCreation1hTokens + total := max(usage.CacheCreationInputTokens, 0) if total == 0 { - return false + total = max(usage.CacheCreation5mTokens, 0) + max(usage.CacheCreation1hTokens, 0) } switch target { case "1h": - if usage.CacheCreation1hTokens == total { + if usage.CacheCreation1hTokens == total && usage.CacheCreation5mTokens == 0 { return false // 已经全是 1h } usage.CacheCreation1hTokens = total usage.CacheCreation5mTokens = 0 default: // "5m" - if usage.CacheCreation5mTokens == total { + if usage.CacheCreation5mTokens == total && usage.CacheCreation1hTokens == 0 { return false // 已经全是 5m } usage.CacheCreation5mTokens = total @@ -1437,30 +1465,24 @@ func applyCacheTTLOverride(usage *ClaudeUsage, target string) bool { // rewriteCacheCreationJSON 在 JSON usage 对象中重写 cache_creation 嵌套对象的 TTL 分类。 // usageObj 是 usage JSON 对象(map[string]any)。 func rewriteCacheCreationJSON(usageObj map[string]any, target string) bool { - ccObj, ok := usageObj["cache_creation"].(map[string]any) - if !ok { + 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"]) - total := v5m + v1h - if total == 0 { + aggregate, present := parseSSEUsageInt(usageObj["cache_creation_input_tokens"]) + usage := ClaudeUsage{ + CacheCreationInputTokens: aggregate, + cacheCreationInputTokensPresent: present, + CacheCreation5mTokens: v5m, + CacheCreation1hTokens: v1h, + } + if !applyCacheTTLOverride(&usage, target) { return false } - switch target { - case "1h": - if v1h == total { - return false - } - ccObj["ephemeral_1h_input_tokens"] = float64(total) - ccObj["ephemeral_5m_input_tokens"] = float64(0) - default: // "5m" - if v5m == total { - return false - } - ccObj["ephemeral_5m_input_tokens"] = float64(total) - ccObj["ephemeral_1h_input_tokens"] = float64(0) - } + ccObj["ephemeral_5m_input_tokens"] = float64(usage.CacheCreation5mTokens) + ccObj["ephemeral_1h_input_tokens"] = float64(usage.CacheCreation1hTokens) return true } @@ -1502,13 +1524,8 @@ func (s *GatewayService) handleNonStreamingResponse(ctx context.Context, resp *h return nil, fmt.Errorf("parse response: %w", err) } - // 解析嵌套的 cache_creation 对象中的 5m/1h 明细 - cc5m := gjson.GetBytes(body, "usage.cache_creation.ephemeral_5m_input_tokens") - cc1h := gjson.GetBytes(body, "usage.cache_creation.ephemeral_1h_input_tokens") - if cc5m.Exists() || cc1h.Exists() { - response.Usage.CacheCreation5mTokens = int(cc5m.Int()) - response.Usage.CacheCreation1hTokens = int(cc1h.Int()) - } + mergeRawAnthropicCacheCreationUsage(gjson.GetBytes(body, "usage"), &response.Usage) + normalizeAnthropicCompatiblePromptUsage(gjson.GetBytes(body, "usage"), &response.Usage) // 兼容 Kimi cached_tokens → cache_read_input_tokens if response.Usage.CacheReadInputTokens == 0 { @@ -1524,7 +1541,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 6010eb893e..6bf853f48c 100644 --- a/backend/internal/service/gateway_usage_billing.go +++ b/backend/internal/service/gateway_usage_billing.go @@ -852,13 +852,7 @@ func (s *GatewayService) recordUsageCore(ctx context.Context, input *recordUsage account.ID, *apiKey.GroupID, result.UpstreamModel, result.Model, // Anthropic's input_tokens excludes cache_read and cache_creation (billed separately); // OpenAI gateway uses actualInputTokens which also excludes cache_read for the same reason. - UsageTokens{ - InputTokens: result.Usage.InputTokens, - OutputTokens: result.Usage.OutputTokens, - CacheCreationTokens: result.Usage.CacheCreationInputTokens, - CacheReadTokens: result.Usage.CacheReadInputTokens, - ImageOutputTokens: result.Usage.ImageOutputTokens, - }, + result.Usage.billingUsageTokens(), cost.TotalCost-cacheStorageCost, pricingAt, accountStatsLongContextPricingEnabled(nil), result.upstreamPriceFactor(), ) @@ -1274,6 +1268,23 @@ func (s *GatewayService) calculateImageCost( return s.billingService.CalculateImageCost(billingModel, sizeTier, result.ImageCount, groupConfig, multiplier) } +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: creationTokens, + CacheReadTokens: usage.CacheReadInputTokens, + CacheCreation5mTokens: usage.CacheCreation5mTokens, + CacheCreation1hTokens: usage.CacheCreation1hTokens, + ImageOutputTokens: usage.ImageOutputTokens, + } + return tokens +} + // calculateTokenCost 计算 Token 计费:路径选择(分组/渠道定价 → 内置定价) // 统一交给 BillingService.CalculateTokenCostForRequest,与模型广场的阶梯表查询同源。 func (s *GatewayService) calculateTokenCost( @@ -1284,15 +1295,7 @@ func (s *GatewayService) calculateTokenCost( multiplier float64, pricingAt time.Time, ) *CostBreakdown { - tokens := UsageTokens{ - InputTokens: result.Usage.InputTokens, - OutputTokens: result.Usage.OutputTokens, - CacheCreationTokens: result.Usage.CacheCreationInputTokens, - CacheReadTokens: result.Usage.CacheReadInputTokens, - CacheCreation5mTokens: result.Usage.CacheCreation5mTokens, - CacheCreation1hTokens: result.Usage.CacheCreation1hTokens, - ImageOutputTokens: result.Usage.ImageOutputTokens, - } + tokens := result.Usage.billingUsageTokens() var resolved *ResolvedPricing if s.resolver != nil && apiKey.Group != nil { diff --git a/backend/internal/service/kimi_anthropic_usage_test.go b/backend/internal/service/kimi_anthropic_usage_test.go index 458ba9fb39..fcd5a816f1 100644 --- a/backend/internal/service/kimi_anthropic_usage_test.go +++ b/backend/internal/service/kimi_anthropic_usage_test.go @@ -246,3 +246,19 @@ func TestCNProviderAnthropicUsageBillsUncachedInput(t *testing.T) { }) } } + +func TestMergeAnthropicUsagePreservesCacheCreationBreakdownPresence(t *testing.T) { + var first apicompat.AnthropicUsage + require.NoError(t, json.Unmarshal([]byte(`{"input_tokens":10,"cache_creation":{"ephemeral_5m_input_tokens":2,"ephemeral_1h_input_tokens":3}}`), &first)) + var later apicompat.AnthropicUsage + require.NoError(t, json.Unmarshal([]byte(`{"output_tokens":7,"cache_creation":{"ephemeral_1h_input_tokens":0}}`), &later)) + + usage := &ClaudeUsage{} + mergeAnthropicUsage(usage, first) + mergeAnthropicUsage(usage, later) + + require.Equal(t, 2, usage.CacheCreation5mTokens) + require.Equal(t, 0, usage.CacheCreation1hTokens) + require.Equal(t, 2, usage.CacheCreationInputTokens) + require.Equal(t, 7, usage.OutputTokens) +} diff --git a/backend/internal/service/openai_cache_write_ttl_test.go b/backend/internal/service/openai_cache_write_ttl_test.go index 060693cd2d..508122f7a7 100644 --- a/backend/internal/service/openai_cache_write_ttl_test.go +++ b/backend/internal/service/openai_cache_write_ttl_test.go @@ -104,6 +104,72 @@ func TestOpenAICacheWriteTTLRecordUsage(t *testing.T) { } } +func TestCacheWriteTTLProjectionAndPricingCoexist(t *testing.T) { + for _, test := range []struct { + name string + usage OpenAIUsage + tokens UsageTokens + cost float64 + statsCost float64 + }{ + { + name: "OpenAI 30m and 12h", + usage: OpenAIUsage{CacheCreationInputTokens: 50, CacheCreation30mInputTokens: 20, CacheCreation12hInputTokens: 30}, + tokens: UsageTokens{CacheCreationTokens: 50, CacheCreation30mTokens: 20, CacheCreation12hTokens: 30}, + cost: 270, + statsCost: 250, + }, + { + name: "Anthropic partial details with 5m remainder", + usage: OpenAIUsage{CacheCreationInputTokens: 100, CacheCreation5mTokens: 20, CacheCreation1hTokens: 30, cacheCreationInputTokensPresent: true}, + tokens: UsageTokens{CacheCreationTokens: 100, CacheCreation5mTokens: 20, CacheCreation1hTokens: 30}, + cost: 260, + statsCost: 260, + }, + { + name: "Anthropic explicit zero falls back to details", + usage: OpenAIUsage{CacheCreation5mTokens: 20, CacheCreation1hTokens: 30, cacheCreationInputTokensPresent: true}, + tokens: UsageTokens{CacheCreationTokens: 50, CacheCreation5mTokens: 20, CacheCreation1hTokens: 30}, + cost: 160, + statsCost: 160, + }, + { + name: "Anthropic contradictory details capped at aggregate", + usage: OpenAIUsage{CacheCreationInputTokens: 100, CacheCreation5mTokens: 50, CacheCreation1hTokens: 200, cacheCreationInputTokensPresent: true}, + tokens: UsageTokens{CacheCreationTokens: 100, CacheCreation5mTokens: 50, CacheCreation1hTokens: 200}, + cost: 360, + statsCost: 360, + }, + } { + t.Run(test.name, func(t *testing.T) { + test.usage.InputTokens = 200 + test.usage.CacheReadInputTokens = 10 + test.usage.OutputTokens = 2 + test.tokens.InputTokens = 190 - test.tokens.CacheCreationTokens + test.tokens.CacheReadTokens = 10 + test.tokens.OutputTokens = 2 + tokens := test.usage.billingUsageTokens() + require.Equal(t, test.tokens, tokens) + + pricing := &ModelPricing{ + SupportsCacheBreakdown: true, + CacheCreation5mPrice: 2, + CacheCreation1hPrice: 4, + CacheCreation12hPricePerToken: float64Ptr(7), + } + service := &BillingService{} + require.Equal(t, test.cost*2, service.computeCacheCreationCost(pricing, tokens, 3, 2)) + statsCost := calculateTokenStatsCost(&ChannelModelPricing{ + CacheWritePrice: float64Ptr(2), + CacheWrite1hPrice: float64Ptr(4), + CacheWrite12hPrice: float64Ptr(7), + }, tokens) + require.NotNil(t, statsCost) + require.Equal(t, test.statsCost, *statsCost) + }) + } +} + func TestOpenAICacheWriteTTLInvalidDetailsKeepAggregate(t *testing.T) { for _, details := range []string{ `null`, `{}`, `{"ttl_12h_tokens":10}`, diff --git a/backend/internal/service/openai_gateway_chat_completions_anthropic_native.go b/backend/internal/service/openai_gateway_chat_completions_anthropic_native.go index 7c06556352..7d44ac42ea 100644 --- a/backend/internal/service/openai_gateway_chat_completions_anthropic_native.go +++ b/backend/internal/service/openai_gateway_chat_completions_anthropic_native.go @@ -280,14 +280,7 @@ func (s *OpenAIGatewayService) handleCCBufferedFromNativeAnthropic( return nil, fmt.Errorf("upstream stream ended without response") } - if usage.InputTokens > 0 || usage.OutputTokens > 0 { - finalResp.Usage = apicompat.AnthropicUsage{ - InputTokens: usage.InputTokens, - OutputTokens: usage.OutputTokens, - CacheCreationInputTokens: usage.CacheCreationInputTokens, - CacheReadInputTokens: usage.CacheReadInputTokens, - } - } + normalizeAnthropicEventUsageForResponses(&apicompat.AnthropicStreamEvent{Message: finalResp}, usage) responsesResp := apicompat.AnthropicToResponsesResponse(finalResp) ccResp := apicompat.ResponsesToChatCompletions(responsesResp, originalModel) diff --git a/backend/internal/service/openai_gateway_messages.go b/backend/internal/service/openai_gateway_messages.go index 14aaee67a2..3c11290f86 100644 --- a/backend/internal/service/openai_gateway_messages.go +++ b/backend/internal/service/openai_gateway_messages.go @@ -1135,6 +1135,9 @@ func (s *OpenAIGatewayService) handleAnthropicStreamingResponse( isTerminalEvent := isOpenAICompatResponsesTerminalEvent(eventType) || isBareErrorEvent if isTerminalEvent { terminalEventType = eventType + if event.Usage != nil { + usage = copyOpenAIUsageFromResponsesUsage(event.Usage) + } if event.Response != nil { if id := strings.TrimSpace(event.Response.ID); id != "" { responseID = id @@ -1143,9 +1146,6 @@ func (s *OpenAIGatewayService) handleAnthropicStreamingResponse( usage = copyOpenAIUsageFromResponsesUsage(event.Response.Usage) } } - if event.Usage != nil { - usage = copyOpenAIUsageFromResponsesUsage(event.Usage) - } // cyber_policy 致命不可重试:标记供 handler 事后记录;以 Anthropic SSE error 事件 // 回写让客户端感知并停止重试(F4),丢弃后续转换输出。 if eventType == "response.failed" || isBareErrorEvent { diff --git a/backend/internal/service/openai_gateway_messages_anthropic_native.go b/backend/internal/service/openai_gateway_messages_anthropic_native.go index 0570abcbda..971aa7f5d0 100644 --- a/backend/internal/service/openai_gateway_messages_anthropic_native.go +++ b/backend/internal/service/openai_gateway_messages_anthropic_native.go @@ -590,9 +590,12 @@ func claudeUsageToOpenAIUsage(u *ClaudeUsage) OpenAIUsage { return OpenAIUsage{} } return OpenAIUsage{ - InputTokens: u.InputTokens + u.CacheCreationInputTokens + u.CacheReadInputTokens, - OutputTokens: u.OutputTokens, - CacheCreationInputTokens: u.CacheCreationInputTokens, - CacheReadInputTokens: u.CacheReadInputTokens, + InputTokens: u.InputTokens + u.CacheCreationInputTokens + u.CacheReadInputTokens, + OutputTokens: u.OutputTokens, + CacheCreationInputTokens: u.CacheCreationInputTokens, + CacheCreation5mTokens: u.CacheCreation5mTokens, + CacheCreation1hTokens: u.CacheCreation1hTokens, + CacheReadInputTokens: u.CacheReadInputTokens, + cacheCreationInputTokensPresent: u.cacheCreationInputTokensPresent, } } diff --git a/backend/internal/service/openai_gateway_native_cache_creation_test.go b/backend/internal/service/openai_gateway_native_cache_creation_test.go new file mode 100644 index 0000000000..63bfcf6c00 --- /dev/null +++ b/backend/internal/service/openai_gateway_native_cache_creation_test.go @@ -0,0 +1,226 @@ +//go:build unit + +package service + +import ( + "context" + "fmt" + "io" + "net/http" + "net/http/httptest" + "strings" + "testing" + + "github.com/gin-gonic/gin" + "github.com/stretchr/testify/require" + "github.com/tidwall/gjson" +) + +func TestNativeAnthropicCacheCreationRouteBillingBoundary(t *testing.T) { + gin.SetMode(gin.TestMode) + for _, test := range []struct { + name string + snapshots []string + aggregate int + ttl5m int + ttl1h int + billed5m int + billed1h int + uncached int + }{ + {"legacy aggregate only", []string{`{"cache_creation_input_tokens":50}`}, 50, 0, 0, 50, 0, 10}, + {"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}}`}, 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}, + {"zero start aggregate grows", []string{`{"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, 11000, 0, 10}, + {"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_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}}`}, 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"} { + for _, stream := range []bool{false, true} { + for _, terminal := range []string{"stop", "eof"} { + if route == "messages" && !stream && (terminal == "eof" || len(test.snapshots) != 1) { + continue + } + t.Run(fmt.Sprintf("%s/%s/stream=%t/%s", test.name, route, stream, terminal), func(t *testing.T) { + startUsage := `{"input_tokens":10,"output_tokens":2,"cache_read_input_tokens":7}` + if test.snapshots[0] != `{}` { + startUsage = strings.TrimSuffix(startUsage, "}") + "," + strings.TrimPrefix(test.snapshots[0], "{") + } + message := `{"id":"msg_cache","type":"message","role":"assistant","model":"k3","content":[],"usage":` + startUsage + `}` + payload := "event: message_start\ndata: {\"type\":\"message_start\",\"message\":" + message + "}\n\n" + for _, snapshot := range test.snapshots { + for range 2 { + payload += "event: message_delta\ndata: {\"type\":\"message_delta\",\"usage\":" + snapshot + "}\n\n" + } + } + payload += "event: message_delta\ndata: {\"type\":\"message_delta\",\"delta\":{\"stop_reason\":\"end_turn\"},\"usage\":{\"output_tokens\":2}}\n\n" + if terminal == "stop" { + for range 2 { + payload += "event: message_stop\ndata: {\"type\":\"message_stop\"}\n\n" + } + } + contentType := "text/event-stream" + if route == "messages" && !stream { + payload, contentType = message, "application/json" + } + upstream := &httpUpstreamRecorder{resp: &http.Response{ + StatusCode: http.StatusOK, + Header: http.Header{"Content-Type": []string{contentType}, "X-Request-Id": []string{"native-cache"}}, + Body: io.NopCloser(strings.NewReader(payload)), + }} + svc := &OpenAIGatewayService{cfg: rawChatCompletionsTestConfig(), httpUpstream: upstream} + body := []byte(fmt.Sprintf(`{"model":"k3","max_tokens":32,"messages":[{"role":"user","content":"hi"}],"stream":%t}`, stream)) + path := "/v1/messages" + if route == "responses" { + path = "/v1/responses" + body = []byte(fmt.Sprintf(`{"model":"k3","input":"hi","stream":%t}`, stream)) + } else if route == "chat" { + path = "/v1/chat/completions" + } + recorder := httptest.NewRecorder() + ctx, _ := gin.CreateTestContext(recorder) + ctx.Request = httptest.NewRequest(http.MethodPost, path, strings.NewReader(string(body))) + account := nativeAnthropicTestAccount() + var result *OpenAIForwardResult + var err error + switch route { + case "messages": + result, err = svc.ForwardAsAnthropic(context.Background(), ctx, account, body, "", "") + case "chat": + result, err = svc.ForwardAsChatCompletions(context.Background(), ctx, account, body, "", "") + case "responses": + result, err = svc.Forward(context.Background(), ctx, account, body) + } + if route == "messages" && stream && terminal == "eof" { + require.ErrorContains(t, err, "missing terminal event") + } else { + require.NoError(t, err) + } + require.NotNil(t, result) + require.Len(t, upstream.requests, 1) + require.True(t, strings.HasSuffix(upstream.lastReq.URL.Path, "/v1/messages")) + require.Equal(t, stream || route != "messages", gjson.GetBytes(upstream.lastBody, "stream").Bool()) + require.Equal(t, "/v1/messages", result.UpstreamEndpoint) + require.Equal(t, stream, result.Stream) + require.Equal(t, uncachedInput+7+test.aggregate, result.Usage.InputTokens) + require.Equal(t, 2, result.Usage.OutputTokens) + require.Equal(t, 7, result.Usage.CacheReadInputTokens) + require.Equal(t, test.aggregate, result.Usage.CacheCreationInputTokens) + require.Equal(t, test.ttl5m, result.Usage.CacheCreation5mTokens) + require.Equal(t, test.ttl1h, result.Usage.CacheCreation1hTokens) + require.Equal(t, http.StatusOK, recorder.Code) + if route == "messages" { + require.Equal(t, payload, recorder.Body.String()) + } else { + assertNativeCacheCompatibleUsage(t, recorder.Body.String(), route, stream, uncachedInput, test.aggregate) + } + cacheCost := float64(test.billed5m)*0.002 + float64(test.billed1h)*0.004 + assertNativeCacheRecordUsage(t, result, account, uncachedInput, cacheCost) + }) + } + } + } + } +} + +func assertNativeCacheCompatibleUsage(t *testing.T, body, route string, stream bool, uncachedInput, aggregate int) { + t.Helper() + var usage gjson.Result + if !stream { + usage = gjson.Get(body, "usage") + } else { + count := 0 + for _, line := range strings.Split(body, "\n") { + if !strings.HasPrefix(line, "data: ") { + continue + } + data := strings.TrimPrefix(line, "data: ") + if route == "responses" && gjson.Get(data, "type").String() == "response.completed" { + usage = gjson.Get(data, "response.usage") + count++ + } else if route == "chat" && gjson.Get(data, "usage").Exists() { + usage = gjson.Get(data, "usage") + count++ + } + } + require.Equal(t, 1, count) + if route == "chat" { + require.Equal(t, 1, strings.Count(body, "data: [DONE]")) + } + } + require.True(t, usage.Exists()) + if route == "responses" { + require.EqualValues(t, uncachedInput+7+aggregate, usage.Get("input_tokens").Int()) + require.EqualValues(t, 2, usage.Get("output_tokens").Int()) + require.EqualValues(t, 7, usage.Get("input_tokens_details.cached_tokens").Int()) + require.EqualValues(t, aggregate, usage.Get("cache_creation_input_tokens").Int()) + } else { + require.EqualValues(t, uncachedInput+7+aggregate, usage.Get("prompt_tokens").Int()) + require.EqualValues(t, 2, usage.Get("completion_tokens").Int()) + require.EqualValues(t, 7, usage.Get("prompt_tokens_details.cached_tokens").Int()) + require.EqualValues(t, aggregate, usage.Get("prompt_tokens_details.cache_creation_tokens").Int()) + } + require.EqualValues(t, uncachedInput+9+aggregate, usage.Get("total_tokens").Int()) +} + +func assertNativeCacheRecordUsage(t *testing.T, result *OpenAIForwardResult, account *Account, uncachedInput int, cacheCost float64) { + t.Helper() + assertNativeCacheRecordUsageWithSettings(t, result, account, uncachedInput, cacheCost, nil) +} + +func assertNativeCacheRecordUsageWithSettings(t *testing.T, result *OpenAIForwardResult, account *Account, uncachedInput int, cacheCost float64, settings *SettingService) { + t.Helper() + usageRepo := &openAIRecordUsageLogRepoStub{inserted: true} + billingRepo := &openAIRecordUsageBillingRepoStub{} + svc := newOpenAIRecordUsageServiceWithBillingRepoForTest(usageRepo, billingRepo, &openAIRecordUsageUserRepoStub{}, &openAIRecordUsageSubRepoStub{}, nil) + svc.settingService = settings + svc.billingService = newTestBillingServiceWithPrices(map[string]*ModelPricing{ + "kimi-k3": { + InputPricePerToken: 0.001, OutputPricePerToken: 0.002, CacheReadPricePerToken: 0.0001, + CacheCreationPricePerToken: 0.002, SupportsCacheBreakdown: true, + CacheCreation5mPrice: 0.002, CacheCreation1hPrice: 0.004, + }, + }) + channel := &Channel{ID: 1, Status: StatusActive, AccountStatsPricingRules: []AccountStatsPricingRule{{ + AccountIDs: []int64{account.ID}, + Pricing: []ChannelModelPricing{{ + Platform: account.Platform, Models: []string{"k3"}, BillingMode: BillingModeToken, + InputPrice: float64Ptr(0.01), OutputPrice: float64Ptr(0.02), CacheReadPrice: float64Ptr(0.001), + CacheWritePrice: float64Ptr(0.02), CacheWrite1hPrice: float64Ptr(0.04), + }}, + }}} + svc.channelService = newTestChannelServiceForStats(t, channel, 10, account.Platform) + svc.resolver = NewModelPricingResolver(svc.channelService, svc.billingService) + groupID := int64(10) + require.NoError(t, svc.RecordUsage(context.Background(), &OpenAIRecordUsageInput{ + Result: result, Account: account, User: &User{ID: 601}, + APIKey: &APIKey{ID: 501, GroupID: &groupID, Group: &Group{ID: groupID, Platform: account.Platform, RateMultiplier: 0.5}}, + })) + require.Equal(t, 1, usageRepo.calls) + require.False(t, usageRepo.lastLog.CacheTTLOverridden) + require.Equal(t, 1, billingRepo.calls) + require.Equal(t, uncachedInput, usageRepo.lastLog.InputTokens) + require.Equal(t, result.Usage.CacheCreationInputTokens, usageRepo.lastLog.CacheCreationTokens) + require.Equal(t, result.Usage.CacheCreation5mTokens, usageRepo.lastLog.CacheCreation5mTokens) + require.Equal(t, result.Usage.CacheCreation1hTokens, usageRepo.lastLog.CacheCreation1hTokens) + require.InDelta(t, cacheCost, usageRepo.lastLog.CacheCreationCost, 1e-12) + totalCost := float64(uncachedInput)*0.001 + float64(result.Usage.OutputTokens)*0.002 + float64(result.Usage.CacheReadInputTokens)*0.0001 + cacheCost + require.InDelta(t, totalCost, usageRepo.lastLog.TotalCost, 1e-12) + require.InDelta(t, totalCost*0.5, usageRepo.lastLog.ActualCost, 1e-12) + require.InDelta(t, totalCost*0.5, billingRepo.lastCmd.BalanceCost, 1e-12) + require.NotNil(t, usageRepo.lastLog.AccountStatsCost) + require.InDelta(t, totalCost*10, *usageRepo.lastLog.AccountStatsCost, 1e-12) +} diff --git a/backend/internal/service/openai_gateway_responses_anthropic_native.go b/backend/internal/service/openai_gateway_responses_anthropic_native.go index 3f36d0d30b..bb4a31fed6 100644 --- a/backend/internal/service/openai_gateway_responses_anthropic_native.go +++ b/backend/internal/service/openai_gateway_responses_anthropic_native.go @@ -282,14 +282,7 @@ func (s *OpenAIGatewayService) handleResponsesBufferedFromNativeAnthropic( return nil, fmt.Errorf("upstream stream ended without response") } - if usage.InputTokens > 0 || usage.OutputTokens > 0 { - finalResp.Usage = apicompat.AnthropicUsage{ - InputTokens: usage.InputTokens, - OutputTokens: usage.OutputTokens, - CacheCreationInputTokens: usage.CacheCreationInputTokens, - CacheReadInputTokens: usage.CacheReadInputTokens, - } - } + normalizeAnthropicEventUsageForResponses(&apicompat.AnthropicStreamEvent{Message: finalResp}, usage) if isClaude55SignedThinkingModel(upstreamModel) { finalResp.Model = upstreamModel diff --git a/backend/internal/service/openai_gateway_service.go b/backend/internal/service/openai_gateway_service.go index dc015f9609..4884ed802d 100644 --- a/backend/internal/service/openai_gateway_service.go +++ b/backend/internal/service/openai_gateway_service.go @@ -227,10 +227,14 @@ type OpenAIUsage struct { ImageCacheReadTokens int `json:"image_cache_read_tokens,omitempty"` OutputTokens int `json:"output_tokens"` CacheCreationInputTokens int `json:"cache_creation_input_tokens,omitempty"` + CacheCreation5mTokens int `json:"cache_creation_5m_tokens,omitempty"` + CacheCreation1hTokens int `json:"cache_creation_1h_tokens,omitempty"` CacheCreation30mInputTokens int `json:"cache_creation_30m_input_tokens,omitempty"` CacheCreation12hInputTokens int `json:"cache_creation_12h_input_tokens,omitempty"` CacheReadInputTokens int `json:"cache_read_input_tokens,omitempty"` ImageOutputTokens int `json:"image_output_tokens,omitempty"` + + cacheCreationInputTokensPresent bool } // OpenAIForwardResult represents the result of forwarding diff --git a/backend/internal/service/openai_gateway_usage.go b/backend/internal/service/openai_gateway_usage.go index 4adbc2b1c6..5626bd841a 100644 --- a/backend/internal/service/openai_gateway_usage.go +++ b/backend/internal/service/openai_gateway_usage.go @@ -151,6 +151,27 @@ 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-creationTokens, 0), + ImageInputTokens: max(usage.ImageInputTokens-usage.ImageCacheReadTokens, 0), + ImageCacheReadTokens: usage.ImageCacheReadTokens, + OutputTokens: usage.OutputTokens, + CacheCreationTokens: creationTokens, + CacheCreation5mTokens: usage.CacheCreation5mTokens, + CacheCreation1hTokens: usage.CacheCreation1hTokens, + CacheCreation30mTokens: usage.CacheCreation30mInputTokens, + CacheCreation12hTokens: usage.CacheCreation12hInputTokens, + CacheReadTokens: usage.CacheReadInputTokens, + ImageOutputTokens: usage.ImageOutputTokens, + } + return tokens +} + // RecordUsage records usage and deducts balance func (s *OpenAIGatewayService) RecordUsage(ctx context.Context, input *OpenAIRecordUsageInput) error { if input == nil { @@ -179,23 +200,8 @@ func (s *OpenAIGatewayService) RecordUsage(ctx context.Context, input *OpenAIRec // OpenAI input_tokens 是总输入,包含缓存读取和缓存写入明细。 // 将三类 token 拆成互斥桶,避免缓存写入同时按普通输入和 cache_write 重复计费。 - actualInputTokens := result.Usage.InputTokens - result.Usage.CacheReadInputTokens - result.Usage.CacheCreationInputTokens - if actualInputTokens < 0 { - actualInputTokens = 0 - } - - // Calculate cost - tokens := UsageTokens{ - InputTokens: actualInputTokens, - ImageInputTokens: max(result.Usage.ImageInputTokens-result.Usage.ImageCacheReadTokens, 0), - ImageCacheReadTokens: result.Usage.ImageCacheReadTokens, - OutputTokens: result.Usage.OutputTokens, - CacheCreationTokens: result.Usage.CacheCreationInputTokens, - CacheCreation30mTokens: result.Usage.CacheCreation30mInputTokens, - CacheCreation12hTokens: result.Usage.CacheCreation12hInputTokens, - CacheReadTokens: result.Usage.CacheReadInputTokens, - ImageOutputTokens: result.Usage.ImageOutputTokens, - } + tokens := result.Usage.billingUsageTokens() + actualInputTokens := tokens.InputTokens // Get rate multiplier multiplier := 1.0 @@ -402,6 +408,8 @@ func (s *OpenAIGatewayService) RecordUsage(ctx context.Context, input *OpenAIRec InputTokens: actualInputTokens, OutputTokens: result.Usage.OutputTokens, CacheCreationTokens: result.Usage.CacheCreationInputTokens, + CacheCreation5mTokens: result.Usage.CacheCreation5mTokens, + CacheCreation1hTokens: result.Usage.CacheCreation1hTokens, CacheCreation30mTokens: result.Usage.CacheCreation30mInputTokens, CacheCreation12hTokens: result.Usage.CacheCreation12hInputTokens, CacheReadTokens: result.Usage.CacheReadInputTokens,