From 7f6673ead54a1949a0db990eda789f72bbfd6dae Mon Sep 17 00:00:00 2001 From: wucm667 Date: Sat, 17 Oct 2026 13:43:55 +0800 Subject: [PATCH 01/85] fix(apicompat): preserve Anthropic cache creation TTL details --- .../anthropic_to_responses_response.go | 46 +++++++-- ...responses_anthropic_cache_creation_test.go | 99 +++++++++++++++++++ backend/internal/pkg/apicompat/types.go | 17 +++- ...ateway_forward_as_chat_completions_test.go | 6 +- .../service/gateway_forward_as_responses.go | 23 ++++- .../gateway_forward_as_responses_test.go | 6 +- .../service/kimi_anthropic_usage_test.go | 16 +++ 7 files changed, 193 insertions(+), 20 deletions(-) diff --git a/backend/internal/pkg/apicompat/anthropic_to_responses_response.go b/backend/internal/pkg/apicompat/anthropic_to_responses_response.go index 2e7c85d3c9..ed24f7bbd0 100644 --- a/backend/internal/pkg/apicompat/anthropic_to_responses_response.go +++ b/backend/internal/pkg/apicompat/anthropic_to_responses_response.go @@ -29,6 +29,20 @@ func encodeAnthropicThinking(block AnthropicContentBlock) string { return anthropicThinkingEnvelopePrefix + base64.RawStdEncoding.EncodeToString(payload) } +func anthropicCacheCreationInputTokens(usage AnthropicUsage) int { + 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 usage.CacheCreationInputTokens +} + // 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 +144,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{ @@ -218,6 +233,7 @@ type AnthropicEventToResponsesState struct { OutputTokens int CacheReadInputTokens int CacheCreationInputTokens int + CacheCreation AnthropicCacheCreation StopReason string } @@ -229,6 +245,24 @@ func NewAnthropicEventToResponsesState() *AnthropicEventToResponsesState { } } +func (state *AnthropicEventToResponsesState) mergeCacheCreationUsage(usage AnthropicUsage) { + 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.CacheCreation.Ephemeral5mInputTokens != nil || state.CacheCreation.Ephemeral1hInputTokens != nil { + state.CacheCreationInputTokens = anthropicCacheCreationInputTokens(AnthropicUsage{CacheCreation: &state.CacheCreation}) + } else if usage.CacheCreationInputTokens > 0 { + state.CacheCreationInputTokens = usage.CacheCreationInputTokens + } +} + // AnthropicEventToResponsesEvents converts a single Anthropic SSE event into // zero or more Responses SSE events, updating state as it goes. func AnthropicEventToResponsesEvents( @@ -295,9 +329,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 { @@ -558,9 +590,7 @@ func anthToResHandleMessageDelta(evt *AnthropicStreamEvent, state *AnthropicEven 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/responses_anthropic_cache_creation_test.go b/backend/internal/pkg/apicompat/responses_anthropic_cache_creation_test.go index aa5ecbe5ba..46cca7fc19 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, 5}, + {"explicit_both_zero", `{"cache_creation_input_tokens":99,"cache_creation":{"ephemeral_5m_input_tokens":0,"ephemeral_1h_input_tokens":0}}`, 0, 0, 0}, + } + 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_input_tokens":99,"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, CacheCreationInputTokens: 99}, + }, 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/types.go b/backend/internal/pkg/apicompat/types.go index 956101bd73..09b9aae18e 100644 --- a/backend/internal/pkg/apicompat/types.go +++ b/backend/internal/pkg/apicompat/types.go @@ -166,12 +166,21 @@ type AnthropicPromptTokensDetails struct { CachedTokens int `json:"cached_tokens,omitempty"` } +// 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. 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 189c086192..bbd9d1c2a8 100644 --- a/backend/internal/service/gateway_forward_as_responses.go +++ b/backend/internal/service/gateway_forward_as_responses.go @@ -296,6 +296,21 @@ func mergeAnthropicUsage(dst *ClaudeUsage, src apicompat.AnthropicUsage) { if cacheReadTokens == 0 && src.PromptCacheHitTokens != nil { cacheReadTokens = max(*src.PromptCacheHitTokens, 0) } + 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 src.CacheCreation.Ephemeral5mInputTokens != nil || src.CacheCreation.Ephemeral1hInputTokens != nil { + dst.CacheCreationInputTokens = dst.CacheCreation5mTokens + dst.CacheCreation1hTokens + } + } + cacheCreationTokens := src.CacheCreationInputTokens + if src.CacheCreation != nil && (src.CacheCreation.Ephemeral5mInputTokens != nil || src.CacheCreation.Ephemeral1hInputTokens != nil) { + cacheCreationTokens = dst.CacheCreationInputTokens + } // Some Anthropic-compatible providers retain OpenAI-style prompt/cache // fields. Prefer those authoritative totals or hit/miss buckets over the @@ -305,10 +320,10 @@ func mergeAnthropicUsage(dst *ClaudeUsage, src apicompat.AnthropicUsage) { if src.PromptCacheMissTokens != nil { dst.InputTokens = max(*src.PromptCacheMissTokens, 0) } else { - dst.InputTokens = max(src.PromptTokens-cacheReadTokens-src.CacheCreationInputTokens, 0) + dst.InputTokens = max(src.PromptTokens-cacheReadTokens-cacheCreationTokens, 0) } dst.CacheReadInputTokens = cacheReadTokens - dst.CacheCreationInputTokens = src.CacheCreationInputTokens + dst.CacheCreationInputTokens = cacheCreationTokens } else { // Without an authoritative prompt total or miss bucket, input_tokens is // provider-specific: it may already be the uncached bucket, or it may be @@ -321,8 +336,8 @@ func mergeAnthropicUsage(dst *ClaudeUsage, src apicompat.AnthropicUsage) { if cacheReadTokens > 0 { dst.CacheReadInputTokens = cacheReadTokens } - if src.CacheCreationInputTokens > 0 { - dst.CacheCreationInputTokens = src.CacheCreationInputTokens + if cacheCreationTokens > 0 { + dst.CacheCreationInputTokens = cacheCreationTokens } } if src.OutputTokens > 0 { diff --git a/backend/internal/service/gateway_forward_as_responses_test.go b/backend/internal/service/gateway_forward_as_responses_test.go index 9e00b8007a..a992a118a6 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`) } 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) +} From efc58486d88a5f43078dcd16bd0b05b33c75ed3e Mon Sep 17 00:00:00 2001 From: wucm667 Date: Sat, 24 Oct 2026 12:16:53 +0800 Subject: [PATCH 02/85] fix(usage): preserve authoritative cache creation totals --- .../anthropic_cache_creation_usage_test.go | 179 +++++++ .../anthropic_to_responses_response.go | 13 +- .../chatcompletions_anthropic_bridge.go | 18 +- ...responses_anthropic_cache_creation_test.go | 8 +- .../pkg/apicompat/responses_to_anthropic.go | 27 +- backend/internal/pkg/apicompat/types.go | 37 ++ .../anthropic_chat_stream_usage_test.go | 3 + .../antigravity_gateway_service_test.go | 4 +- .../service/antigravity_gateway_upstream.go | 11 +- ...teway_anthropic_apikey_passthrough_test.go | 70 ++- .../service/gateway_anthropic_passthrough.go | 61 +-- .../gateway_cache_creation_usage_test.go | 497 ++++++++++++++++++ .../gateway_forward_as_chat_completions.go | 9 +- .../service/gateway_forward_as_responses.go | 67 ++- .../gateway_forward_as_responses_test.go | 24 + backend/internal/service/gateway_service.go | 2 + .../service/gateway_upstream_response.go | 16 +- .../internal/service/gateway_usage_billing.go | 37 +- ...teway_chat_completions_anthropic_native.go | 9 +- ...enai_gateway_responses_anthropic_native.go | 9 +- 20 files changed, 936 insertions(+), 165 deletions(-) create mode 100644 backend/internal/pkg/apicompat/anthropic_cache_creation_usage_test.go create mode 100644 backend/internal/service/gateway_cache_creation_usage_test.go diff --git a/backend/internal/pkg/apicompat/anthropic_cache_creation_usage_test.go b/backend/internal/pkg/apicompat/anthropic_cache_creation_usage_test.go new file mode 100644 index 0000000000..4d1a341d8b --- /dev/null +++ b/backend/internal/pkg/apicompat/anthropic_cache_creation_usage_test.go @@ -0,0 +1,179 @@ +package apicompat + +import ( + "encoding/json" + "testing" + + "github.com/stretchr/testify/require" +) + +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}}`, 0, 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), false}, + {"explicit Responses totals", anthropicUsageFromResponsesUsage(&ResponsesUsage{}), true}, + {"missing Chat usage", chatUsageToAnthropicUsage(nil), false}, + {"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.False(t, decoded.Message.Usage.HasCacheCreationInputTokens()) + } + 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, 0, 0, 0, 100}[index], state.CacheCreationInputTokens) + } +} diff --git a/backend/internal/pkg/apicompat/anthropic_to_responses_response.go b/backend/internal/pkg/apicompat/anthropic_to_responses_response.go index ed24f7bbd0..a9a818267d 100644 --- a/backend/internal/pkg/apicompat/anthropic_to_responses_response.go +++ b/backend/internal/pkg/apicompat/anthropic_to_responses_response.go @@ -30,6 +30,9 @@ func encodeAnthropicThinking(block AnthropicContentBlock) string { } func anthropicCacheCreationInputTokens(usage AnthropicUsage) int { + if usage.HasCacheCreationInputTokens() { + return max(usage.CacheCreationInputTokens, 0) + } if usage.CacheCreation != nil && (usage.CacheCreation.Ephemeral5mInputTokens != nil || usage.CacheCreation.Ephemeral1hInputTokens != nil) { cacheCreationTokens := 0 if usage.CacheCreation.Ephemeral5mInputTokens != nil { @@ -235,6 +238,8 @@ type AnthropicEventToResponsesState struct { CacheCreationInputTokens int CacheCreation AnthropicCacheCreation + cacheCreationInputTokensPresent bool + StopReason string } @@ -246,6 +251,10 @@ func NewAnthropicEventToResponsesState() *AnthropicEventToResponsesState { } func (state *AnthropicEventToResponsesState) mergeCacheCreationUsage(usage AnthropicUsage) { + if usage.HasCacheCreationInputTokens() { + state.CacheCreationInputTokens = max(usage.CacheCreationInputTokens, 0) + state.cacheCreationInputTokensPresent = true + } if usage.CacheCreation != nil { if usage.CacheCreation.Ephemeral5mInputTokens != nil { tokens := max(*usage.CacheCreation.Ephemeral5mInputTokens, 0) @@ -256,10 +265,8 @@ func (state *AnthropicEventToResponsesState) mergeCacheCreationUsage(usage Anthr state.CacheCreation.Ephemeral1hInputTokens = &tokens } } - if state.CacheCreation.Ephemeral5mInputTokens != nil || state.CacheCreation.Ephemeral1hInputTokens != nil { + if !state.cacheCreationInputTokensPresent && (state.CacheCreation.Ephemeral5mInputTokens != nil || state.CacheCreation.Ephemeral1hInputTokens != nil) { state.CacheCreationInputTokens = anthropicCacheCreationInputTokens(AnthropicUsage{CacheCreation: &state.CacheCreation}) - } else if usage.CacheCreationInputTokens > 0 { - state.CacheCreationInputTokens = usage.CacheCreationInputTokens } } diff --git a/backend/internal/pkg/apicompat/chatcompletions_anthropic_bridge.go b/backend/internal/pkg/apicompat/chatcompletions_anthropic_bridge.go index 20a590c1c6..004888b51f 100644 --- a/backend/internal/pkg/apicompat/chatcompletions_anthropic_bridge.go +++ b/backend/internal/pkg/apicompat/chatcompletions_anthropic_bridge.go @@ -540,10 +540,11 @@ 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, } } @@ -714,10 +715,11 @@ 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, }, }, AnthropicStreamEvent{Type: "message_stop"}, 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 46cca7fc19..d18f457833 100644 --- a/backend/internal/pkg/apicompat/responses_anthropic_cache_creation_test.go +++ b/backend/internal/pkg/apicompat/responses_anthropic_cache_creation_test.go @@ -138,13 +138,13 @@ func TestAnthropicEventToResponsesEvents_MergesCacheCreationBreakdown(t *testing {"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, 5}, - {"explicit_both_zero", `{"cache_creation_input_tokens":99,"cache_creation":{"ephemeral_5m_input_tokens":0,"ephemeral_1h_input_tokens":0}}`, 0, 0, 0}, + {"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_input_tokens":99,"cache_creation":{"ephemeral_5m_input_tokens":2,"ephemeral_1h_input_tokens":3}}`), &startUsage)) + 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{ @@ -159,7 +159,7 @@ func TestAnthropicEventToResponsesEvents_MergesCacheCreationBreakdown(t *testing assert.Equal(t, test.want1h, *state.CacheCreation.Ephemeral1hInputTokens) assert.Equal(t, test.wantTotal, state.CacheCreationInputTokens) AnthropicEventToResponsesEvents(&AnthropicStreamEvent{ - Type: "message_delta", Usage: &AnthropicUsage{OutputTokens: 7, CacheCreationInputTokens: 99}, + Type: "message_delta", Usage: &AnthropicUsage{OutputTokens: 7}, }, state) events := AnthropicEventToResponsesEvents(&AnthropicStreamEvent{Type: "message_stop"}, state) diff --git a/backend/internal/pkg/apicompat/responses_to_anthropic.go b/backend/internal/pkg/apicompat/responses_to_anthropic.go index 424affde73..2b514b1391 100644 --- a/backend/internal/pkg/apicompat/responses_to_anthropic.go +++ b/backend/internal/pkg/apicompat/responses_to_anthropic.go @@ -111,10 +111,11 @@ 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, } } @@ -285,10 +286,11 @@ 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, }, }, AnthropicStreamEvent{Type: "message_stop"}, @@ -768,10 +770,11 @@ 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, }, }, AnthropicStreamEvent{Type: "message_stop"}, diff --git a/backend/internal/pkg/apicompat/types.go b/backend/internal/pkg/apicompat/types.go index 09b9aae18e..289bf04420 100644 --- a/backend/internal/pkg/apicompat/types.go +++ b/backend/internal/pkg/apicompat/types.go @@ -189,6 +189,43 @@ 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:"-"` +} + +func (usage *AnthropicUsage) UnmarshalJSON(data []byte) error { + type usageAlias AnthropicUsage + var decoded struct { + usageAlias + CacheCreationInputTokens *int `json:"cache_creation_input_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 + } + 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 + } + return json.Marshal(struct { + usageAlias + CacheCreationInputTokens *int `json:"cache_creation_input_tokens,omitempty"` + }{usageAlias: usageAlias(usage), CacheCreationInputTokens: aggregate}) } // --------------------------------------------------------------------------- diff --git a/backend/internal/service/anthropic_chat_stream_usage_test.go b/backend/internal/service/anthropic_chat_stream_usage_test.go index 2397a5802d..77e51a8836 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, 10, 10, 10, 7, 0, 0}, + {"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/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 e6b9a73fa8..79b8f4042f 100644 --- a/backend/internal/service/antigravity_gateway_upstream.go +++ b/backend/internal/service/antigravity_gateway_upstream.go @@ -151,12 +151,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 } @@ -335,8 +330,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 = int(v) + usage.cacheCreationInputTokensPresent = true } // 解析嵌套的 cache_creation 对象中的 5m/1h 明细 if cc, ok := u["cache_creation"].(map[string]any); ok { @@ -368,6 +364,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/gateway_anthropic_apikey_passthrough_test.go b/backend/internal/service/gateway_anthropic_apikey_passthrough_test.go index 8b7c2d4a09..9157776810 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":{"ephemeral_5m_input_tokens":3,"ephemeral_1h_input_tokens":4}}}}` parseSSEUsagePassthrough(data, usage) @@ -1341,6 +1341,72 @@ 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}}`}, + }, + { + 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}}`}, + }, + { + name: "explicit zero replaces previous aggregate", + start: `{"cache_creation_input_tokens":9}`, + snapshots: []string{`{"cache_creation_input_tokens":0,"cache_creation":{"ephemeral_5m_input_tokens":2,"ephemeral_1h_input_tokens":1}}`}, + }, + } + 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 +1419,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":{"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 889e2faa36..dc04aa10cb 100644 --- a/backend/internal/service/gateway_anthropic_passthrough.go +++ b/backend/internal/service/gateway_anthropic_passthrough.go @@ -635,16 +635,9 @@ 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") @@ -655,22 +648,18 @@ 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) } + default: + usageNode := parsed.Get("usage") + if !usageNode.Exists() || usageNode.Type == gjson.Null { + usageNode = parsed.Get("message.usage") + } + mergeRawAnthropicCacheCreationUsage(usageNode, usage) } if usage.CacheReadInputTokens == 0 { @@ -681,18 +670,6 @@ func parseSSEUsagePassthrough(data string, usage *ClaudeUsage) { 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) - } - } // Kimi's Anthropic-compatible stream uses input_tokens with two meanings: // message_start reports total prompt input, while message_delta reports only @@ -739,17 +716,8 @@ func normalizeAnthropicCompatiblePromptUsage(usageNode gjson.Result, usage *Clau cacheReadTokens = max(int(promptCacheHitTokens.Int()), 0) } + mergeRawAnthropicCacheCreationUsage(usageNode, usage) 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) - } - } if promptCacheMissTokens.Exists() { usage.InputTokens = max(int(promptCacheMissTokens.Int()), 0) @@ -775,18 +743,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_creation_usage_test.go b/backend/internal/service/gateway_cache_creation_usage_test.go new file mode 100644 index 0000000000..28766afaae --- /dev/null +++ b/backend/internal/service/gateway_cache_creation_usage_test.go @@ -0,0 +1,497 @@ +//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 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 survives TTL updates", + snapshots: []string{`{"cache_creation_input_tokens":0,"cache_creation":{"ephemeral_1h_input_tokens":200}}`, `{"cache_creation":{"ephemeral_5m_input_tokens":50}}`}, + wantTotals: []int{0, 0}, want5m: 50, want1h: 200, + }, + { + name: "explicit zero delta clears aggregate", + snapshots: []string{`{"cache_creation_input_tokens":100}`, `{"cache_creation_input_tokens":0}`, `{"cache_creation":{"ephemeral_1h_input_tokens":200}}`}, + wantTotals: []int{100, 0, 0}, want1h: 200, + }, + { + 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{0, 0}, want5m: 20, want1h: 200, + }, + { + name: "zero to positive retains partial TTL history", + snapshots: []string{`{"cache_creation":{"ephemeral_5m_input_tokens":20}}`, `{"cache_creation_input_tokens":0,"cache_creation":{"ephemeral_1h_input_tokens":30}}`, `{"cache_creation":{"ephemeral_1h_input_tokens":50}}`, `{"cache_creation_input_tokens":35}`}, + wantTotals: []int{20, 0, 0, 35}, want5m: 20, want1h: 50, billed5m: 10, billed1h: 25, + }, + { + 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 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() + for _, customStats := range []bool{false, true} { + usageRepo := &openAIRecordUsageLogRepoStub{inserted: true} + svc := newGatewayRecordUsageServiceForTest(usageRepo, &openAIRecordUsageUserRepoStub{}, &openAIRecordUsageSubRepoStub{}) + 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{ID: 701, Platform: PlatformAnthropic}, + })) + require.NotNil(t, usageRepo.lastLog) + require.InDelta(t, wantCacheCost, usageRepo.lastLog.CacheCreationCost, 1e-12) + require.InDelta(t, 0.014+wantCacheCost, usageRepo.lastLog.TotalCost, 1e-12) + require.InDelta(t, (0.014+wantCacheCost)*0.5, usageRepo.lastLog.ActualCost, 1e-12) + require.NotNil(t, usageRepo.lastLog.AccountStatsCost) + require.InDelta(t, (0.014+wantCacheCost)*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}`, 0, true, 50, 200, 0}, + {"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 && !test.present { + wantAggregate = 0 + } + 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, 0, 0}, + {"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.Zero(t, usage.CacheCreationInputTokens) + require.Equal(t, 200, usage.CacheCreation1hTokens) + assertAnthropicCacheCreationRecordCosts(t, *usage, 0) + if prompt != "" { + require.Equal(t, 500, usage.InputTokens) + } + } + usage := &ClaudeUsage{CacheCreationInputTokens: 100} + (&AntigravityGatewayService{}).extractSSEUsage(`data: {"type":"message_delta","usage":{"cache_creation_input_tokens":0}}`, usage) + require.Zero(t, 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}}`, 0, true, 0}, + {"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}, + {"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 survives", `"cache_creation_input_tokens":0,`, 0, true, 0}, + {"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 clears aggregate with retained TTL", func(t *testing.T) { + service := &AntigravityGatewayService{} + usage := &ClaudeUsage{} + service.extractSSEUsage(`data: {"type":"message_start","message":{"usage":{"cache_creation_input_tokens":100,"cache_creation":{"ephemeral_1h_input_tokens":200}}}}`, usage) + service.extractSSEUsage(`data: {"type":"message_delta","usage":{"cache_creation_input_tokens":0}}`, usage) + service.extractSSEUsage(`data: {"type":"message_delta","usage":{"cache_creation_input_tokens":null,"cache_creation":{"ephemeral_5m_input_tokens":50}}}`, usage) + require.Zero(t, usage.CacheCreationInputTokens) + require.True(t, usage.cacheCreationInputTokensPresent) + require.Equal(t, 50, usage.CacheCreation5mTokens) + require.Equal(t, 200, usage.CacheCreation1hTokens) + assertAnthropicCacheCreationRecordCosts(t, *usage, 0) + }) +} + +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}`, 0}, + {"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}, + } { + for _, adapter := range []string{"responses", "chat", "native responses", "native chat"} { + t.Run(test.name+"/"+adapter, func(t *testing.T) { + stream := "event: message_start\ndata: {\"type\":\"message_start\",\"message\":{\"id\":\"msg_cache\",\"type\":\"message\",\"role\":\"assistant\",\"model\":\"claude-sonnet-4\",\"content\":[],\"usage\":" + test.start + "}}\n\n" + + "event: message_delta\ndata: {\"type\":\"message_delta\",\"usage\":" + test.delta + "}\n\nevent: message_stop\ndata: {\"type\":\"message_stop\"}\n\n" + recorder := httptest.NewRecorder() + ctx, _ := gin.CreateTestContext(recorder) + response := &http.Response{Body: io.NopCloser(strings.NewReader(stream))} + var aggregate int + var err error + switch adapter { + case "responses": + var result *ForwardResult + result, err = (&GatewayService{}).handleResponsesBufferedStreamingResponse(response, ctx, "claude-sonnet-4", "claude-sonnet-4", nil, time.Now(), apicompat.ResponsesClientToolMapping{}) + require.NoError(t, err) + aggregate = result.Usage.CacheCreationInputTokens + case "chat": + var result *ForwardResult + result, err = (&GatewayService{}).handleCCBufferedFromAnthropic(response, ctx, "claude-sonnet-4", "claude-sonnet-4", nil, time.Now()) + require.NoError(t, err) + aggregate = result.Usage.CacheCreationInputTokens + case "native responses": + var result *OpenAIForwardResult + result, err = (&OpenAIGatewayService{}).handleResponsesBufferedFromNativeAnthropic(response, ctx, "claude-sonnet-4", "claude-sonnet-4", "claude-sonnet-4", nil, time.Now(), apicompat.ResponsesClientToolMapping{}) + require.NoError(t, err) + aggregate = result.Usage.CacheCreationInputTokens + case "native chat": + var result *OpenAIForwardResult + result, err = (&OpenAIGatewayService{}).handleCCBufferedFromNativeAnthropic(response, ctx, "claude-sonnet-4", "claude-sonnet-4", "claude-sonnet-4", nil, time.Now()) + require.NoError(t, err) + aggregate = result.Usage.CacheCreationInputTokens + } + require.Equal(t, test.wantAggregate, aggregate) + require.Equal(t, http.StatusOK, recorder.Code) + require.True(t, json.Valid(recorder.Body.Bytes())) + inputPath := "usage.input_tokens" + cachePath := "usage.cache_creation_input_tokens" + if strings.HasSuffix(adapter, "chat") { + inputPath = "usage.prompt_tokens" + cachePath = "usage.prompt_tokens_details.cache_creation_tokens" + } + require.True(t, gjson.GetBytes(recorder.Body.Bytes(), inputPath).Exists()) + require.Equal(t, int64(test.wantAggregate), gjson.GetBytes(recorder.Body.Bytes(), inputPath).Int()) + require.Equal(t, int64(test.wantAggregate), gjson.GetBytes(recorder.Body.Bytes(), cachePath).Int()) + }) + } + } +} diff --git a/backend/internal/service/gateway_forward_as_chat_completions.go b/backend/internal/service/gateway_forward_as_chat_completions.go index 24a281d612..8beafd5dbf 100644 --- a/backend/internal/service/gateway_forward_as_chat_completions.go +++ b/backend/internal/service/gateway_forward_as_chat_completions.go @@ -316,14 +316,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_responses.go b/backend/internal/service/gateway_forward_as_responses.go index ca3af92a68..078498af78 100644 --- a/backend/internal/service/gateway_forward_as_responses.go +++ b/backend/internal/service/gateway_forward_as_responses.go @@ -304,21 +304,8 @@ func mergeAnthropicUsage(dst *ClaudeUsage, src apicompat.AnthropicUsage) { if cacheReadTokens == 0 && src.PromptCacheHitTokens != nil { cacheReadTokens = max(*src.PromptCacheHitTokens, 0) } - 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 src.CacheCreation.Ephemeral5mInputTokens != nil || src.CacheCreation.Ephemeral1hInputTokens != nil { - dst.CacheCreationInputTokens = dst.CacheCreation5mTokens + dst.CacheCreation1hTokens - } - } - cacheCreationTokens := src.CacheCreationInputTokens - if src.CacheCreation != nil && (src.CacheCreation.Ephemeral5mInputTokens != nil || src.CacheCreation.Ephemeral1hInputTokens != nil) { - cacheCreationTokens = dst.CacheCreationInputTokens - } + mergeAnthropicCacheCreationUsage(dst, src) + cacheCreationTokens := dst.CacheCreationInputTokens // Some Anthropic-compatible providers retain OpenAI-style prompt/cache // fields. Prefer those authoritative totals or hit/miss buckets over the @@ -331,7 +318,6 @@ func mergeAnthropicUsage(dst *ClaudeUsage, src apicompat.AnthropicUsage) { dst.InputTokens = max(src.PromptTokens-cacheReadTokens-cacheCreationTokens, 0) } dst.CacheReadInputTokens = cacheReadTokens - dst.CacheCreationInputTokens = cacheCreationTokens } else { // Without an authoritative prompt total or miss bucket, input_tokens is // provider-specific: it may already be the uncached bucket, or it may be @@ -344,15 +330,48 @@ func mergeAnthropicUsage(dst *ClaudeUsage, src apicompat.AnthropicUsage) { if cacheReadTokens > 0 { dst.CacheReadInputTokens = cacheReadTokens } - if cacheCreationTokens > 0 { - dst.CacheCreationInputTokens = cacheCreationTokens - } } if src.OutputTokens > 0 { dst.OutputTokens = src.OutputTokens } } +func mergeAnthropicCacheCreationUsage(dst *ClaudeUsage, src apicompat.AnthropicUsage) { + if src.HasCacheCreationInputTokens() { + dst.CacheCreationInputTokens = max(src.CacheCreationInputTokens, 0) + dst.cacheCreationInputTokensPresent = true + } + 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 && (src.CacheCreation.Ephemeral5mInputTokens != nil || src.CacheCreation.Ephemeral1hInputTokens != nil) { + dst.CacheCreationInputTokens = dst.CacheCreation5mTokens + dst.CacheCreation1hTokens + } + } +} + +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 @@ -369,6 +388,7 @@ func normalizeAnthropicEventUsageForResponses(event *apicompat.AnthropicStreamEv dst.OutputTokens = usage.OutputTokens dst.CacheReadInputTokens = usage.CacheReadInputTokens dst.CacheCreationInputTokens = usage.CacheCreationInputTokens + dst.CacheCreationInputTokensPresent = true } normalize(event.Usage) if event.Message != nil { @@ -491,14 +511,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 a992a118a6..13416b719a 100644 --- a/backend/internal/service/gateway_forward_as_responses_test.go +++ b/backend/internal/service/gateway_forward_as_responses_test.go @@ -369,6 +369,30 @@ 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 survives contradictory 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, + }, + { + 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, + }, } for _, tt := range tests { diff --git a/backend/internal/service/gateway_service.go b/backend/internal/service/gateway_service.go index 2dbec0ccaf..354e13a0ab 100644 --- a/backend/internal/service/gateway_service.go +++ b/backend/internal/service/gateway_service.go @@ -604,6 +604,8 @@ type ClaudeUsage struct { CacheCreation5mTokens int // 5分钟缓存创建token(来自嵌套 cache_creation 对象) CacheCreation1hTokens int // 1小时缓存创建token(来自嵌套 cache_creation 对象) ImageOutputTokens int `json:"image_output_tokens,omitempty"` + + cacheCreationInputTokensPresent bool } // ForwardResult 转发结果 diff --git a/backend/internal/service/gateway_upstream_response.go b/backend/internal/service/gateway_upstream_response.go index fb9368b6c0..125a0076c0 100644 --- a/backend/internal/service/gateway_upstream_response.go +++ b/backend/internal/service/gateway_upstream_response.go @@ -1211,9 +1211,9 @@ func (s *GatewayService) extractSSEUsagePatch(event map[string]any) *sseUsagePat 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 { @@ -1246,7 +1246,7 @@ 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 } @@ -1280,6 +1280,7 @@ func mergeSSEUsagePatch(usage *ClaudeUsage, patch *sseUsagePatch) { } if patch.hasCacheCreationInput { usage.CacheCreationInputTokens = patch.cacheCreationInputTokens + usage.cacheCreationInputTokensPresent = true } if patch.hasCacheReadInput { usage.CacheReadInputTokens = patch.cacheReadInputTokens @@ -1293,6 +1294,9 @@ func mergeSSEUsagePatch(usage *ClaudeUsage, patch *sseUsagePatch) { if patch.hasCacheCreation1h { usage.CacheCreation1hTokens = patch.cacheCreation1hTokens } + if !usage.cacheCreationInputTokensPresent && (patch.hasCacheCreation5m || patch.hasCacheCreation1h) { + usage.CacheCreationInputTokens = max(usage.CacheCreation5mTokens, 0) + max(usage.CacheCreation1hTokens, 0) + } } func parseSSEUsageInt(value any) (int, bool) { @@ -1419,13 +1423,7 @@ 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) // 兼容 Kimi cached_tokens → cache_read_input_tokens if response.Usage.CacheReadInputTokens == 0 { diff --git a/backend/internal/service/gateway_usage_billing.go b/backend/internal/service/gateway_usage_billing.go index 580ca81dc1..abe23eefff 100644 --- a/backend/internal/service/gateway_usage_billing.go +++ b/backend/internal/service/gateway_usage_billing.go @@ -848,13 +848,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), ) @@ -1215,6 +1209,25 @@ func (s *GatewayService) calculateImageCost( return s.billingService.CalculateImageCost(billingModel, sizeTier, result.ImageCount, groupConfig, multiplier) } +// billingUsageTokens projects explicit aggregate zero to effective zero TTL usage +// for billing and account stats, retaining raw TTL details on ClaudeUsage. +func (usage ClaudeUsage) billingUsageTokens() UsageTokens { + tokens := UsageTokens{ + InputTokens: usage.InputTokens, + OutputTokens: usage.OutputTokens, + CacheCreationTokens: usage.CacheCreationInputTokens, + CacheReadTokens: usage.CacheReadInputTokens, + CacheCreation5mTokens: usage.CacheCreation5mTokens, + CacheCreation1hTokens: usage.CacheCreation1hTokens, + ImageOutputTokens: usage.ImageOutputTokens, + } + if usage.cacheCreationInputTokensPresent && usage.CacheCreationInputTokens == 0 { + tokens.CacheCreation5mTokens = 0 + tokens.CacheCreation1hTokens = 0 + } + return tokens +} + // calculateTokenCost 计算 Token 计费:路径选择(分组/渠道定价 → 内置定价) // 统一交给 BillingService.CalculateTokenCostForRequest,与模型广场的阶梯表查询同源。 func (s *GatewayService) calculateTokenCost( @@ -1225,15 +1238,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/openai_gateway_chat_completions_anthropic_native.go b/backend/internal/service/openai_gateway_chat_completions_anthropic_native.go index f6333661f5..65be9dbea8 100644 --- a/backend/internal/service/openai_gateway_chat_completions_anthropic_native.go +++ b/backend/internal/service/openai_gateway_chat_completions_anthropic_native.go @@ -259,14 +259,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_responses_anthropic_native.go b/backend/internal/service/openai_gateway_responses_anthropic_native.go index ec4fada790..67446aee65 100644 --- a/backend/internal/service/openai_gateway_responses_anthropic_native.go +++ b/backend/internal/service/openai_gateway_responses_anthropic_native.go @@ -262,14 +262,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 From e6bde6b3c642058a4f384bf7100d510ea385029b Mon Sep 17 00:00:00 2001 From: wucm667 Date: Sun, 25 Oct 2026 11:28:55 +0800 Subject: [PATCH 03/85] fix(billing): retain native cache creation accounting --- ...penai_gateway_messages_anthropic_native.go | 11 +- ...enai_gateway_native_cache_creation_test.go | 215 ++++++++++++++++++ .../service/openai_gateway_service.go | 6 + .../internal/service/openai_gateway_usage.go | 38 ++-- 4 files changed, 251 insertions(+), 19 deletions(-) create mode 100644 backend/internal/service/openai_gateway_native_cache_creation_test.go diff --git a/backend/internal/service/openai_gateway_messages_anthropic_native.go b/backend/internal/service/openai_gateway_messages_anthropic_native.go index 12a3344068..d887ea3bfc 100644 --- a/backend/internal/service/openai_gateway_messages_anthropic_native.go +++ b/backend/internal/service/openai_gateway_messages_anthropic_native.go @@ -574,9 +574,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..40cafd0ed6 --- /dev/null +++ b/backend/internal/service/openai_gateway_native_cache_creation_test.go @@ -0,0 +1,215 @@ +//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}}`}, 0, 20, 30, 0, 0, 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, 20, 30, 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_creation":{"ephemeral_1h_input_tokens":40}}`}, 0, 20, 40, 0, 0, 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, 20, 40, 10}, + {"normalized prompt total", []string{`{"prompt_tokens":100,"cached_tokens":7,"cache_creation":{"ephemeral_5m_input_tokens":20,"ephemeral_1h_input_tokens":30}}`}, 50, 20, 30, 20, 30, 43}, + {"normalized prompt explicit zero", []string{`{"prompt_tokens":100,"cached_tokens":7,"cache_creation_input_tokens":0,"cache_creation":{"ephemeral_5m_input_tokens":20,"ephemeral_1h_input_tokens":30}}`}, 0, 20, 30, 0, 0, 93}, + } { + 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() + usageRepo := &openAIRecordUsageLogRepoStub{inserted: true} + billingRepo := &openAIRecordUsageBillingRepoStub{} + svc := newOpenAIRecordUsageServiceWithBillingRepoForTest(usageRepo, billingRepo, &openAIRecordUsageUserRepoStub{}, &openAIRecordUsageSubRepoStub{}, nil) + 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.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 + 0.0047 + 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_service.go b/backend/internal/service/openai_gateway_service.go index a29ff0d1c6..7013b0ac58 100644 --- a/backend/internal/service/openai_gateway_service.go +++ b/backend/internal/service/openai_gateway_service.go @@ -227,8 +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"` CacheReadInputTokens int `json:"cache_read_input_tokens,omitempty"` ImageOutputTokens int `json:"image_output_tokens,omitempty"` + + // An explicit aggregate zero suppresses TTL charging in the billing projection, + // while raw TTL details remain intact for usage logs. + 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 ce2e276a7e..e736906fe9 100644 --- a/backend/internal/service/openai_gateway_usage.go +++ b/backend/internal/service/openai_gateway_usage.go @@ -151,6 +151,25 @@ func groupBillsOpenAIFastAtStandard(apiKey *APIKey, account *Account, serviceTie } } +func (usage OpenAIUsage) billingUsageTokens() UsageTokens { + tokens := UsageTokens{ + InputTokens: max(usage.InputTokens-usage.CacheReadInputTokens-usage.CacheCreationInputTokens, 0), + ImageInputTokens: max(usage.ImageInputTokens-usage.ImageCacheReadTokens, 0), + ImageCacheReadTokens: usage.ImageCacheReadTokens, + OutputTokens: usage.OutputTokens, + CacheCreationTokens: usage.CacheCreationInputTokens, + CacheCreation5mTokens: usage.CacheCreation5mTokens, + CacheCreation1hTokens: usage.CacheCreation1hTokens, + CacheReadTokens: usage.CacheReadInputTokens, + ImageOutputTokens: usage.ImageOutputTokens, + } + if usage.cacheCreationInputTokensPresent && usage.CacheCreationInputTokens == 0 { + tokens.CacheCreation5mTokens = 0 + tokens.CacheCreation1hTokens = 0 + } + return tokens +} + // RecordUsage records usage and deducts balance func (s *OpenAIGatewayService) RecordUsage(ctx context.Context, input *OpenAIRecordUsageInput) error { if input == nil { @@ -179,21 +198,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, - CacheReadTokens: result.Usage.CacheReadInputTokens, - ImageOutputTokens: result.Usage.ImageOutputTokens, - } + tokens := result.Usage.billingUsageTokens() + actualInputTokens := tokens.InputTokens // Get rate multiplier multiplier := 1.0 @@ -400,6 +406,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, CacheReadTokens: result.Usage.CacheReadInputTokens, ImageInputTokens: result.Usage.ImageInputTokens, ImageOutputTokens: result.Usage.ImageOutputTokens, From 7b879c56a6002ae985fa535a33939d6f4602c97a Mon Sep 17 00:00:00 2001 From: wucm667 Date: Mon, 2 Nov 2026 09:16:06 +0800 Subject: [PATCH 04/85] chore(deps): update follow-redirects security patch --- frontend/package.json | 2 +- frontend/pnpm-lock.yaml | 10 +++++----- 2 files changed, 6 insertions(+), 6 deletions(-) diff --git a/frontend/package.json b/frontend/package.json index ef38431a73..e42bcb03f8 100644 --- a/frontend/package.json +++ b/frontend/package.json @@ -67,7 +67,7 @@ "postcss@<8.5.18": ">=8.5.18", "dompurify@<3.4.17": ">=3.4.17", "source-map-js@<1.2.2": ">=1.2.2", - "follow-redirects@<1.16.1": ">=1.16.1", + "follow-redirects@<1.16.2": ">=1.16.2", "decode-uri-component@<0.5.1": ">=0.5.1" } } diff --git a/frontend/pnpm-lock.yaml b/frontend/pnpm-lock.yaml index a6f4b60425..1bf73beac9 100644 --- a/frontend/pnpm-lock.yaml +++ b/frontend/pnpm-lock.yaml @@ -10,7 +10,7 @@ overrides: postcss@<8.5.18: '>=8.5.18' dompurify@<3.4.17: '>=3.4.17' source-map-js@<1.2.2: '>=1.2.2' - follow-redirects@<1.16.1: '>=1.16.1' + follow-redirects@<1.16.2: '>=1.16.2' decode-uri-component@<0.5.1: '>=0.5.1' importers: @@ -2566,8 +2566,8 @@ packages: flatted@3.3.3: resolution: {integrity: sha512-GX+ysw4PBCz0PzosHDepZGANEuFCMLrnRTiEy9McGjmkCQYwRq4A/X786G/fjM/+OjsWSU1ZrY5qyARZmO/uwg==} - follow-redirects@1.16.1: - resolution: {integrity: sha512-FNvFGzoMLWmE6Yj9spb/zjd7yiNCHiAW9/Tg9CXrQ8wuu32HtlJOwWO11OJafl5FfY3DxTdQ0vj42zU1kvv5jg==} + follow-redirects@1.16.2: + resolution: {integrity: sha512-/kVP2U8z596Ia0gwFrwyIeo74ta5aVmSeU1FfAUMAmcEP5EP7zydmag3SLiN64NaRKef3lxsq7i/g7ltJQDGow==} engines: {node: '>=4.0'} peerDependencies: debug: '*' @@ -6563,7 +6563,7 @@ snapshots: axios@1.20.0: dependencies: - follow-redirects: 1.16.1 + follow-redirects: 1.16.2 form-data: 4.0.6 https-proxy-agent: 5.0.1 proxy-from-env: 2.1.0 @@ -7305,7 +7305,7 @@ snapshots: flatted@3.3.3: {} - follow-redirects@1.16.1: {} + follow-redirects@1.16.2: {} for-in@1.0.2: {} From bcb0512132081c920da966e1e23c66389e948dcc Mon Sep 17 00:00:00 2001 From: wucm667 Date: Mon, 2 Nov 2026 09:16:06 +0800 Subject: [PATCH 05/85] fix(billing): account for unclassified cache creation tokens and TTL overrides --- .../internal/service/account_stats_pricing.go | 2 +- .../service/account_stats_pricing_test.go | 66 +++++ backend/internal/service/billing_service.go | 14 +- .../internal/service/billing_service_test.go | 29 ++ .../gateway_cache_creation_usage_test.go | 125 +++++++- .../gateway_cache_ttl_override_test.go | 280 ++++++++++++++++++ .../service/gateway_upstream_response.go | 48 ++- ...enai_gateway_native_cache_creation_test.go | 14 +- 8 files changed, 539 insertions(+), 39 deletions(-) create mode 100644 backend/internal/service/gateway_cache_ttl_override_test.go diff --git a/backend/internal/service/account_stats_pricing.go b/backend/internal/service/account_stats_pricing.go index dcd08e1193..f86785bcbc 100644 --- a/backend/internal/service/account_stats_pricing.go +++ b/backend/internal/service/account_stats_pricing.go @@ -243,7 +243,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 0f5d236ca1..e3221a0481 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/billing_service.go b/backend/internal/service/billing_service.go index f66293ba04..9fa525a778 100644 --- a/backend/internal/service/billing_service.go +++ b/backend/internal/service/billing_service.go @@ -1781,17 +1781,21 @@ func (s *BillingService) computeTokenBreakdown( // multiplier 用于长上下文等场景下的整体价格缩放(普通调用传 1.0 即可)。 func (s *BillingService) computeCacheCreationCost(pricing *ModelPricing, tokens UsageTokens, price, multiplier float64) float64 { 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 +} + // normalizeCacheCreationBreakdown caps contradictory 5m/1h details at an explicitly // positive aggregate while retaining their reported ratio as closely as integer tokens allow. func normalizeCacheCreationBreakdown(tokens UsageTokens) (int, int) { diff --git a/backend/internal/service/billing_service_test.go b/backend/internal/service/billing_service_test.go index cb68489b49..8a09574a93 100644 --- a/backend/internal/service/billing_service_test.go +++ b/backend/internal/service/billing_service_test.go @@ -1508,6 +1508,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_cache_creation_usage_test.go b/backend/internal/service/gateway_cache_creation_usage_test.go index 28766afaae..8f18dbe87b 100644 --- a/backend/internal/service/gateway_cache_creation_usage_test.go +++ b/backend/internal/service/gateway_cache_creation_usage_test.go @@ -124,6 +124,114 @@ func TestAnthropicCacheCreationSnapshots(t *testing.T) { } } +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 suppresses retained detail", `"cache_creation_input_tokens":3000,"cache_creation":{"ephemeral_1h_input_tokens":3000}`, `{"cache_creation_input_tokens":0}`, 0, 0, 3000, 0}, + {"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) + 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, usage.Get("prompt_tokens").Int()) + require.EqualValues(t, test.aggregate, usage.Get("prompt_tokens_details.cache_creation_tokens").Int()) + } else { + require.EqualValues(t, 10+test.aggregate, usage.Get("input_tokens").Int()) + require.EqualValues(t, 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 @@ -132,10 +240,17 @@ func assertAnthropicCacheCreationRecordCosts(t *testing.T, usage ClaudeUsage, wa } 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} - svc := newGatewayRecordUsageServiceForTest(usageRepo, &openAIRecordUsageUserRepoStub{}, &openAIRecordUsageSubRepoStub{}) + 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, @@ -162,12 +277,18 @@ func assertAnthropicCacheCreationResultCosts(t *testing.T, result *ForwardResult 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{ID: 701, Platform: PlatformAnthropic}, + 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) require.InDelta(t, 0.014+wantCacheCost, usageRepo.lastLog.TotalCost, 1e-12) require.InDelta(t, (0.014+wantCacheCost)*0.5, usageRepo.lastLog.ActualCost, 1e-12) + require.Equal(t, 1, billingRepo.calls) + require.InDelta(t, (0.014+wantCacheCost)*0.5, billingRepo.lastCmd.BalanceCost, 1e-12) require.NotNil(t, usageRepo.lastLog.AccountStatsCost) require.InDelta(t, (0.014+wantCacheCost)*statsMultiplier, *usageRepo.lastLog.AccountStatsCost, 1e-12) } 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..6b7959ce1e --- /dev/null +++ b/backend/internal/service/gateway_cache_ttl_override_test.go @@ -0,0 +1,280 @@ +//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" +) + +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}, 0, 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}`}, 0, true, 0, 3000, 0}, + {"oversized details", []string{`{"cache_creation_input_tokens":100,"cache_creation":{"ephemeral_5m_input_tokens":50,"ephemeral_1h_input_tokens":200}}`}, 100, true, 50, 200, 0.36}, + {"explicit zero snapshot", []string{`{"cache_creation_input_tokens":0,"cache_creation":{"ephemeral_5m_input_tokens":50,"ephemeral_1h_input_tokens":200}}`}, 0, true, 50, 200, 0}, + {"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 { + cache += `,"cache_creation_input_tokens":` + strconv.Itoa(test.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 == "nonstream" || (route == "standard" && test.aggregate > 0)) { + 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"] + require.True(t, rewriteCacheCreationJSON(response.Usage, target)) + want5m, want1h := 0, test.aggregate + if target == "5m" { + want5m, want1h = test.aggregate, 0 + } + 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) + }) + } + } +} diff --git a/backend/internal/service/gateway_upstream_response.go b/backend/internal/service/gateway_upstream_response.go index 125a0076c0..099579f71f 100644 --- a/backend/internal/service/gateway_upstream_response.go +++ b/backend/internal/service/gateway_upstream_response.go @@ -1329,24 +1329,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 - if total == 0 { - return false + total := max(usage.CacheCreationInputTokens, 0) + if !usage.cacheCreationInputTokensPresent && total == 0 { + 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 @@ -1358,30 +1353,25 @@ 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 { - return false - } + ccObj, _ := usageObj["cache_creation"].(map[string]any) 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) + if ccObj == nil { + ccObj = make(map[string]any) + usageObj["cache_creation"] = ccObj } + ccObj["ephemeral_5m_input_tokens"] = float64(usage.CacheCreation5mTokens) + ccObj["ephemeral_1h_input_tokens"] = float64(usage.CacheCreation1hTokens) return true } diff --git a/backend/internal/service/openai_gateway_native_cache_creation_test.go b/backend/internal/service/openai_gateway_native_cache_creation_test.go index 40cafd0ed6..2dcd9afc0c 100644 --- a/backend/internal/service/openai_gateway_native_cache_creation_test.go +++ b/backend/internal/service/openai_gateway_native_cache_creation_test.go @@ -33,13 +33,16 @@ func TestNativeAnthropicCacheCreationRouteBillingBoundary(t *testing.T) { {"missing aggregate", []string{`{"cache_creation":{"ephemeral_5m_input_tokens":20,"ephemeral_1h_input_tokens":30}}`}, 50, 20, 30, 20, 30, 10}, {"null aggregate", []string{`{"cache_creation_input_tokens":null,"cache_creation":{"ephemeral_5m_input_tokens":20,"ephemeral_1h_input_tokens":30}}`}, 50, 20, 30, 20, 30, 10}, {"explicit zero", []string{`{"cache_creation_input_tokens":0,"cache_creation":{"ephemeral_5m_input_tokens":20,"ephemeral_1h_input_tokens":30}}`}, 0, 20, 30, 0, 0, 10}, - {"details below aggregate", []string{`{"cache_creation_input_tokens":100,"cache_creation":{"ephemeral_5m_input_tokens":20,"ephemeral_1h_input_tokens":30}}`}, 100, 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_creation":{"ephemeral_1h_input_tokens":40}}`}, 0, 20, 40, 0, 0, 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, 20, 40, 10}, + {"null preserves aggregate", []string{`{"cache_creation_input_tokens":100,"cache_creation":{"ephemeral_5m_input_tokens":20,"ephemeral_1h_input_tokens":30}}`, `{"cache_creation_input_tokens":null,"cache_creation":{"ephemeral_1h_input_tokens":40}}`}, 100, 20, 40, 60, 40, 10}, {"normalized prompt total", []string{`{"prompt_tokens":100,"cached_tokens":7,"cache_creation":{"ephemeral_5m_input_tokens":20,"ephemeral_1h_input_tokens":30}}`}, 50, 20, 30, 20, 30, 43}, {"normalized prompt explicit zero", []string{`{"prompt_tokens":100,"cached_tokens":7,"cache_creation_input_tokens":0,"cache_creation":{"ephemeral_5m_input_tokens":20,"ephemeral_1h_input_tokens":30}}`}, 0, 20, 30, 0, 0, 93}, } { @@ -173,10 +176,16 @@ func assertNativeCacheCompatibleUsage(t *testing.T, body, route string, stream b } 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, @@ -200,6 +209,7 @@ func assertNativeCacheRecordUsage(t *testing.T, result *OpenAIForwardResult, acc 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) From 9e4c03d2fee29211d9026a5cbfbdfe0b4af92448 Mon Sep 17 00:00:00 2001 From: wucm667 Date: Wed, 4 Nov 2026 09:08:54 +0800 Subject: [PATCH 06/85] fix(usage): reconcile prompt totals across cache-only updates --- .../anthropic_cache_read_usage_test.go | 42 +++ backend/internal/pkg/apicompat/types.go | 51 ++- .../service/anthropic_prompt_total_test.go | 351 ++++++++++++++++++ .../service/gateway_anthropic_passthrough.go | 61 ++- .../gateway_cache_creation_usage_test.go | 10 +- .../service/gateway_forward_as_responses.go | 46 ++- backend/internal/service/gateway_service.go | 2 + .../service/gateway_upstream_response.go | 40 +- ...enai_gateway_native_cache_creation_test.go | 2 +- 9 files changed, 538 insertions(+), 67 deletions(-) create mode 100644 backend/internal/pkg/apicompat/anthropic_cache_read_usage_test.go create mode 100644 backend/internal/service/anthropic_prompt_total_test.go 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/types.go b/backend/internal/pkg/apicompat/types.go index 289bf04420..2e93469d74 100644 --- a/backend/internal/pkg/apicompat/types.go +++ b/backend/internal/pkg/apicompat/types.go @@ -163,7 +163,33 @@ 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. @@ -192,6 +218,8 @@ type AnthropicUsage struct { // 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 { @@ -199,6 +227,8 @@ func (usage *AnthropicUsage) UnmarshalJSON(data []byte) error { 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 @@ -208,6 +238,14 @@ func (usage *AnthropicUsage) UnmarshalJSON(data []byte) error { 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 } @@ -222,10 +260,19 @@ func (usage AnthropicUsage) MarshalJSON() ([]byte, error) { 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"` - }{usageAlias: usageAlias(usage), CacheCreationInputTokens: aggregate}) + CacheReadInputTokens *int `json:"cache_read_input_tokens,omitempty"` + CachedTokens *int `json:"cached_tokens,omitempty"` + }{usageAlias: usageAlias(usage), CacheCreationInputTokens: aggregate, CacheReadInputTokens: cacheReadTokens, CachedTokens: cachedTokens}) } // --------------------------------------------------------------------------- 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..ae0161982c --- /dev/null +++ b/backend/internal/service/anthropic_prompt_total_test.go @@ -0,0 +1,351 @@ +//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 clears", `"prompt_tokens":100`, []string{`{"cache_creation_input_tokens":50}`, `{"cache_creation_input_tokens":0}`, `{"cache_creation":{"ephemeral_1h_input_tokens":30}}`}, []int{50, 100, 100}}, + {"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}`, 0}, + {"cached zero", `{"cached_tokens":0}`, 0}, + {"details zero", `{"prompt_tokens_details":{"cached_tokens":0}}`, 0}, + {"hit zero", `{"prompt_cache_hit_tokens":0}`, 0}, + {"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" + 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, 90, usage.InputTokens) + require.Zero(t, 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.Zero(t, 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/gateway_anthropic_passthrough.go b/backend/internal/service/gateway_anthropic_passthrough.go index dc04aa10cb..baa1c5c5b0 100644 --- a/backend/internal/service/gateway_anthropic_passthrough.go +++ b/backend/internal/service/gateway_anthropic_passthrough.go @@ -635,7 +635,6 @@ func parseSSEUsagePassthrough(data string, usage *ClaudeUsage) { msgUsage := parsed.Get("message.usage") if msgUsage.Exists() { usage.InputTokens = int(msgUsage.Get("input_tokens").Int()) - usage.CacheReadInputTokens = int(msgUsage.Get("cache_read_input_tokens").Int()) mergeRawAnthropicCacheCreationUsage(msgUsage, usage) } @@ -648,10 +647,6 @@ func parseSSEUsagePassthrough(data string, usage *ClaudeUsage) { if v := deltaUsage.Get("output_tokens").Int(); v > 0 { usage.OutputTokens = int(v) } - if v := deltaUsage.Get("cache_read_input_tokens").Int(); v > 0 { - usage.CacheReadInputTokens = int(v) - } - mergeRawAnthropicCacheCreationUsage(deltaUsage, usage) } default: @@ -662,15 +657,6 @@ func parseSSEUsagePassthrough(data string, usage *ClaudeUsage) { mergeRawAnthropicCacheCreationUsage(usageNode, 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) - } - } - // Kimi's Anthropic-compatible stream uses input_tokens with two meanings: // message_start reports total prompt input, while message_delta reports only // uncached input. prompt_tokens remains the total in both events. Normalize @@ -680,6 +666,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 { + usage.CacheReadInputTokens = max(int(value.Int()), 0) + if usage.CacheReadInputTokens > 0 { + break + } + } + } normalizeAnthropicCompatiblePromptUsage(usageNode, usage) } @@ -694,38 +691,28 @@ 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()) + 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 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) - } mergeRawAnthropicCacheCreationUsage(usageNode, usage) - cacheCreationTokens := usage.CacheCreationInputTokens - - if promptCacheMissTokens.Exists() { - usage.InputTokens = max(int(promptCacheMissTokens.Int()), 0) - } else { - usage.InputTokens = max(int(promptTokens.Int())-cacheReadTokens-cacheCreationTokens, 0) - } 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 } diff --git a/backend/internal/service/gateway_cache_creation_usage_test.go b/backend/internal/service/gateway_cache_creation_usage_test.go index 8f18dbe87b..fbdd618e75 100644 --- a/backend/internal/service/gateway_cache_creation_usage_test.go +++ b/backend/internal/service/gateway_cache_creation_usage_test.go @@ -285,12 +285,14 @@ func assertAnthropicCacheCreationOverrideCosts(t *testing.T, result *ForwardResu 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) - require.InDelta(t, 0.014+wantCacheCost, usageRepo.lastLog.TotalCost, 1e-12) - require.InDelta(t, (0.014+wantCacheCost)*0.5, usageRepo.lastLog.ActualCost, 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, (0.014+wantCacheCost)*0.5, billingRepo.lastCmd.BalanceCost, 1e-12) + require.InDelta(t, wantTotalCost*0.5, billingRepo.lastCmd.BalanceCost, 1e-12) require.NotNil(t, usageRepo.lastLog.AccountStatsCost) - require.InDelta(t, (0.014+wantCacheCost)*statsMultiplier, *usageRepo.lastLog.AccountStatsCost, 1e-12) + require.InDelta(t, wantTotalCost*statsMultiplier, *usageRepo.lastLog.AccountStatsCost, 1e-12) } } diff --git a/backend/internal/service/gateway_forward_as_responses.go b/backend/internal/service/gateway_forward_as_responses.go index 078498af78..cb492392c2 100644 --- a/backend/internal/service/gateway_forward_as_responses.go +++ b/backend/internal/service/gateway_forward_as_responses.go @@ -294,31 +294,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) - cacheCreationTokens := dst.CacheCreationInputTokens // 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-cacheCreationTokens, 0) - } - dst.CacheReadInputTokens = cacheReadTokens - } 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 @@ -327,15 +323,31 @@ func mergeAnthropicUsage(dst *ClaudeUsage, src apicompat.AnthropicUsage) { if src.InputTokens > 0 { dst.InputTokens = src.InputTokens } - if cacheReadTokens > 0 { - dst.CacheReadInputTokens = cacheReadTokens - } } + if hasCacheReadTokens { + 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() { dst.CacheCreationInputTokens = max(src.CacheCreationInputTokens, 0) diff --git a/backend/internal/service/gateway_service.go b/backend/internal/service/gateway_service.go index 2ac91bdab6..b20b006a24 100644 --- a/backend/internal/service/gateway_service.go +++ b/backend/internal/service/gateway_service.go @@ -606,6 +606,8 @@ type ClaudeUsage struct { ImageOutputTokens int `json:"image_output_tokens,omitempty"` cacheCreationInputTokensPresent 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 099579f71f..3049f3b3d7 100644 --- a/backend/internal/service/gateway_upstream_response.go +++ b/backend/internal/service/gateway_upstream_response.go @@ -1178,6 +1178,8 @@ func (s *GatewayService) parseSSEUsage(data string, usage *ClaudeUsage) { } type sseUsagePatch struct { + promptTokens int + promptCacheMissTokens *int inputTokens int hasInputTokens bool outputTokens int @@ -1206,7 +1208,7 @@ 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 @@ -1215,10 +1217,11 @@ func (s *GatewayService) extractSSEUsagePatch(event map[string]any) *sseUsagePat 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 @@ -1237,7 +1240,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 @@ -1250,10 +1253,11 @@ func (s *GatewayService) extractSSEUsagePatch(event map[string]any) *sseUsagePat 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 @@ -1270,6 +1274,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 @@ -1297,6 +1323,7 @@ func mergeSSEUsagePatch(usage *ClaudeUsage, patch *sseUsagePatch) { if !usage.cacheCreationInputTokensPresent && (patch.hasCacheCreation5m || patch.hasCacheCreation1h) { usage.CacheCreationInputTokens = max(usage.CacheCreation5mTokens, 0) + max(usage.CacheCreation1hTokens, 0) } + normalizeAnthropicPromptTotal(usage, patch.promptTokens, patch.promptCacheMissTokens) } func parseSSEUsageInt(value any) (int, bool) { @@ -1414,6 +1441,7 @@ func (s *GatewayService) handleNonStreamingResponse(ctx context.Context, resp *h } 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 { diff --git a/backend/internal/service/openai_gateway_native_cache_creation_test.go b/backend/internal/service/openai_gateway_native_cache_creation_test.go index 2dcd9afc0c..121ade7a25 100644 --- a/backend/internal/service/openai_gateway_native_cache_creation_test.go +++ b/backend/internal/service/openai_gateway_native_cache_creation_test.go @@ -216,7 +216,7 @@ func assertNativeCacheRecordUsageWithSettings(t *testing.T, result *OpenAIForwar 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 + 0.0047 + cacheCost + 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) From 71532bf91cfe79f65f1943bdb32e896cd087238b Mon Sep 17 00:00:00 2001 From: wucm667 Date: Thu, 5 Nov 2026 09:24:56 +0800 Subject: [PATCH 07/85] fix(usage): preserve compatible cache snapshot semantics --- .../anthropic_cache_creation_usage_test.go | 84 ++++++- .../anthropic_to_responses_response.go | 17 +- .../chatcompletions_anthropic_bridge.go | 7 +- .../pkg/apicompat/responses_to_anthropic.go | 12 +- .../anthropic_chat_stream_usage_test.go | 2 +- .../service/anthropic_prompt_total_test.go | 20 +- .../service/antigravity_gateway_upstream.go | 2 +- ...teway_anthropic_apikey_passthrough_test.go | 23 +- .../service/gateway_anthropic_passthrough.go | 8 +- ...teway_cache_compatibility_boundary_test.go | 180 +++++++++++++++ .../gateway_cache_creation_usage_test.go | 213 ++++++++++++------ .../gateway_cache_ttl_override_test.go | 128 ++++++++++- .../service/gateway_forward_as_responses.go | 9 +- .../gateway_forward_as_responses_test.go | 12 +- backend/internal/service/gateway_service.go | 7 +- .../service/gateway_upstream_response.go | 19 +- .../internal/service/gateway_usage_billing.go | 12 +- ...enai_gateway_native_cache_creation_test.go | 7 +- .../internal/service/openai_gateway_usage.go | 12 +- 19 files changed, 625 insertions(+), 149 deletions(-) create mode 100644 backend/internal/service/gateway_cache_compatibility_boundary_test.go diff --git a/backend/internal/pkg/apicompat/anthropic_cache_creation_usage_test.go b/backend/internal/pkg/apicompat/anthropic_cache_creation_usage_test.go index 4d1a341d8b..a3cf369317 100644 --- a/backend/internal/pkg/apicompat/anthropic_cache_creation_usage_test.go +++ b/backend/internal/pkg/apicompat/anthropic_cache_creation_usage_test.go @@ -15,7 +15,7 @@ func TestAnthropicCacheCreationAggregatePresence(t *testing.T) { present bool }{ {"contradictory aggregate", `{"cache_creation_input_tokens":100,"cache_creation":{"ephemeral_1h_input_tokens":200}}`, 100, true}, - {"explicit zero", `{"cache_creation_input_tokens":0,"cache_creation":{"ephemeral_1h_input_tokens":200}}`, 0, true}, + {"explicit zero", `{"cache_creation_input_tokens":0,"cache_creation":{"ephemeral_1h_input_tokens":200}}`, 200, true}, {"missing aggregate", `{"cache_creation":{"ephemeral_1h_input_tokens":200}}`, 200, false}, {"null aggregate", `{"cache_creation_input_tokens":null,"cache_creation":{"ephemeral_1h_input_tokens":200}}`, 200, false}, {"null TTL", `{"cache_creation":{"ephemeral_5m_input_tokens":null,"ephemeral_1h_input_tokens":200}}`, 200, false}, @@ -112,9 +112,9 @@ func TestAnthropicUsageAdapterZeroContracts(t *testing.T) { usage AnthropicUsage present bool }{ - {"missing Responses usage", anthropicUsageFromResponsesUsage(nil), false}, + {"missing Responses usage", anthropicUsageFromResponsesUsage(nil), true}, {"explicit Responses totals", anthropicUsageFromResponsesUsage(&ResponsesUsage{}), true}, - {"missing Chat usage", chatUsageToAnthropicUsage(nil), false}, + {"missing Chat usage", chatUsageToAnthropicUsage(nil), true}, {"explicit Chat totals", chatUsageToAnthropicUsage(&ChatUsage{}), true}, } { t.Run(test.name, func(t *testing.T) { @@ -136,7 +136,8 @@ func TestAnthropicUsageAdapterZeroContracts(t *testing.T) { var decoded AnthropicStreamEvent require.NoError(t, json.Unmarshal(encoded, &decoded)) require.NotNil(t, decoded.Message) - require.False(t, decoded.Message.Usage.HasCacheCreationInputTokens()) + require.True(t, decoded.Message.Usage.HasCacheCreationInputTokens()) + require.True(t, decoded.Message.Usage.CacheReadInputTokensPresent) } terminalEvents := FinalizeResponsesAnthropicStream(responsesState) terminalEvents = append(terminalEvents, FinalizeChatCompletionsAnthropicStream(chatState)...) @@ -174,6 +175,79 @@ func TestAnthropicCacheCreationPartialSnapshots(t *testing.T) { var usage AnthropicUsage require.NoError(t, json.Unmarshal([]byte(snapshot), &usage)) state.mergeCacheCreationUsage(usage) - require.Equal(t, []int{20, 50, 50, 50, 40, 40, 0, 0, 0, 100}[index], state.CacheCreationInputTokens) + require.Equal(t, []int{20, 50, 50, 50, 40, 40, 40, 40, 40, 100}[index], state.CacheCreationInputTokens) + } +} + +func TestAnthropicConvertersRawCacheUsageLifecycle(t *testing.T) { + for _, test := range []struct { + name string + aggregate int + want []int + }{ + {"zero aggregate derives partial TTL", 0, []int{20, 50, 50, 50, 30}}, + {"positive aggregate survives placeholders", 40, []int{40, 40, 40, 40, 40}}, + } { + for _, terminal := range []string{"message_stop", "eof"} { + t.Run(test.name+"/"+terminal, func(t *testing.T) { + state := NewAnthropicEventToResponsesState() + chatState := NewResponsesEventToChatState() + chatState.IncludeUsage = true + var completed *ResponsesResponse + var chatUsage *ChatUsage + consume := func(events []ResponsesStreamEvent) { + for _, event := range events { + if event.Type == "response.completed" { + completed = event.Response + } + for _, chunk := range ResponsesEventToChatChunks(&event, chatState) { + if chunk.Usage != nil { + chatUsage = chunk.Usage + } + } + } + } + start := AnthropicStreamEvent{Type: "message_start", Message: &AnthropicResponse{ + ID: "msg_cache", Model: "claude-sonnet-4", Usage: AnthropicUsage{ + InputTokens: 10, CacheReadInputTokens: 9, + CacheCreationInputTokens: test.aggregate, CacheCreationInputTokensPresent: true, + }, + }} + consume(AnthropicEventToResponsesEvents(&start, state)) + for index, snapshot := range []string{ + `{"output_tokens":7,"cache_creation_input_tokens":0,"cache_creation":{"ephemeral_5m_input_tokens":20}}`, + `{"cache_creation_input_tokens":0,"cache_creation":{"ephemeral_1h_input_tokens":30}}`, + `{"input_tokens":0,"output_tokens":0,"cache_read_input_tokens":0,"cache_creation_input_tokens":0}`, + `{"input_tokens":0,"output_tokens":0,"cache_read_input_tokens":0,"cache_creation_input_tokens":0}`, + `{"cache_creation":{"ephemeral_5m_input_tokens":0}}`, + } { + var event AnthropicStreamEvent + require.NoError(t, json.Unmarshal([]byte(`{"type":"message_delta","usage":`+snapshot+`}`), &event)) + consume(AnthropicEventToResponsesEvents(&event, state)) + require.Equal(t, test.want[index], state.CacheCreationInputTokens, "snapshot %d", index) + require.Equal(t, 7, state.OutputTokens, "snapshot %d", index) + } + if terminal == "message_stop" { + consume(AnthropicEventToResponsesEvents(&AnthropicStreamEvent{Type: "message_stop"}, state)) + } else { + consume(FinalizeAnthropicResponsesStream(state)) + } + want := test.want[len(test.want)-1] + require.NotNil(t, completed) + require.NotNil(t, completed.Usage) + require.Equal(t, want, completed.Usage.CacheCreationInputTokens) + require.Equal(t, 19+want, completed.Usage.InputTokens) + require.Equal(t, 7, completed.Usage.OutputTokens) + require.Equal(t, 26+want, completed.Usage.TotalTokens) + require.NotNil(t, chatUsage) + require.Equal(t, 19+want, chatUsage.PromptTokens) + require.Equal(t, 7, chatUsage.CompletionTokens) + require.NotNil(t, chatUsage.PromptTokensDetails) + require.Equal(t, want, chatUsage.PromptTokensDetails.CacheCreationTokens) + require.Equal(t, 9, chatUsage.PromptTokensDetails.CachedTokens) + require.Empty(t, FinalizeAnthropicResponsesStream(state)) + require.Empty(t, FinalizeResponsesChatStream(chatState)) + }) + } } } diff --git a/backend/internal/pkg/apicompat/anthropic_to_responses_response.go b/backend/internal/pkg/apicompat/anthropic_to_responses_response.go index a9a818267d..809344daa5 100644 --- a/backend/internal/pkg/apicompat/anthropic_to_responses_response.go +++ b/backend/internal/pkg/apicompat/anthropic_to_responses_response.go @@ -30,7 +30,7 @@ func encodeAnthropicThinking(block AnthropicContentBlock) string { } func anthropicCacheCreationInputTokens(usage AnthropicUsage) int { - if usage.HasCacheCreationInputTokens() { + if usage.CacheCreationInputTokens > 0 { return max(usage.CacheCreationInputTokens, 0) } if usage.CacheCreation != nil && (usage.CacheCreation.Ephemeral5mInputTokens != nil || usage.CacheCreation.Ephemeral1hInputTokens != nil) { @@ -43,7 +43,7 @@ func anthropicCacheCreationInputTokens(usage AnthropicUsage) int { } return cacheCreationTokens } - return usage.CacheCreationInputTokens + return max(usage.CacheCreationInputTokens, 0) } // AnthropicToResponsesResponse converts an Anthropic Messages response into a @@ -238,7 +238,8 @@ type AnthropicEventToResponsesState struct { CacheCreationInputTokens int CacheCreation AnthropicCacheCreation - cacheCreationInputTokensPresent bool + cacheCreationInputTokensPresent bool + cacheCreationInputTokensFromDetails bool StopReason string } @@ -251,9 +252,10 @@ func NewAnthropicEventToResponsesState() *AnthropicEventToResponsesState { } func (state *AnthropicEventToResponsesState) mergeCacheCreationUsage(usage AnthropicUsage) { - if usage.HasCacheCreationInputTokens() { + if usage.HasCacheCreationInputTokens() && (usage.CacheCreationInputTokens > 0 || state.CacheCreationInputTokens <= 0) { state.CacheCreationInputTokens = max(usage.CacheCreationInputTokens, 0) state.cacheCreationInputTokensPresent = true + state.cacheCreationInputTokensFromDetails = false } if usage.CacheCreation != nil { if usage.CacheCreation.Ephemeral5mInputTokens != nil { @@ -265,8 +267,9 @@ func (state *AnthropicEventToResponsesState) mergeCacheCreationUsage(usage Anthr state.CacheCreation.Ephemeral1hInputTokens = &tokens } } - if !state.cacheCreationInputTokensPresent && (state.CacheCreation.Ephemeral5mInputTokens != nil || state.CacheCreation.Ephemeral1hInputTokens != nil) { + if (!state.cacheCreationInputTokensPresent || state.cacheCreationInputTokensFromDetails || state.CacheCreationInputTokens <= 0) && (state.CacheCreation.Ephemeral5mInputTokens != nil || state.CacheCreation.Ephemeral1hInputTokens != nil) { state.CacheCreationInputTokens = anthropicCacheCreationInputTokens(AnthropicUsage{CacheCreation: &state.CacheCreation}) + state.cacheCreationInputTokensFromDetails = true } } @@ -590,7 +593,9 @@ func anthToResHandleContentBlockStop(evt *AnthropicStreamEvent, state *Anthropic func anthToResHandleMessageDelta(evt *AnthropicStreamEvent, state *AnthropicEventToResponsesState) []ResponsesStreamEvent { if evt.Usage != nil { - state.OutputTokens = evt.Usage.OutputTokens + if evt.Usage.OutputTokens > 0 { + state.OutputTokens = evt.Usage.OutputTokens + } if evt.Usage.InputTokens > 0 { state.InputTokens = evt.Usage.InputTokens } diff --git a/backend/internal/pkg/apicompat/chatcompletions_anthropic_bridge.go b/backend/internal/pkg/apicompat/chatcompletions_anthropic_bridge.go index 004888b51f..893e6a29da 100644 --- a/backend/internal/pkg/apicompat/chatcompletions_anthropic_bridge.go +++ b/backend/internal/pkg/apicompat/chatcompletions_anthropic_bridge.go @@ -411,6 +411,7 @@ func ChatCompletionsResponseToAnthropic(resp *ChatCompletionsResponse, model str Type: "message", Role: "assistant", Model: model, + Usage: chatUsageToAnthropicUsage(nil), } if resp != nil { @@ -517,7 +518,7 @@ func chatFinishReasonToAnthropicStopReason(reason string, blocks []AnthropicCont // usage shape. Mirrors ChatUsageToResponsesUsage + anthropicUsageFromResponsesUsage. func chatUsageToAnthropicUsage(usage *ChatUsage) AnthropicUsage { if usage == nil { - return AnthropicUsage{} + return AnthropicUsage{CacheCreationInputTokensPresent: true, CacheReadInputTokensPresent: true} } cachedTokens := 0 @@ -545,6 +546,7 @@ func chatUsageToAnthropicUsage(usage *ChatUsage) AnthropicUsage { CacheReadInputTokens: cachedTokens, CacheCreationInputTokens: cacheCreationTokens, CacheCreationInputTokensPresent: true, + CacheReadInputTokensPresent: true, } } @@ -720,6 +722,7 @@ func FinalizeChatCompletionsAnthropicStream(state *ChatCompletionsToAnthropicStr CacheReadInputTokens: state.CacheReadInputTokens, CacheCreationInputTokens: state.CacheCreationInputTokens, CacheCreationInputTokensPresent: true, + CacheReadInputTokensPresent: true, }, }, AnthropicStreamEvent{Type: "message_stop"}, @@ -743,7 +746,7 @@ func ensureCCAnthropicMessageStart(state *ChatCompletionsToAnthropicStreamState) Content: []AnthropicContentBlock{}, Model: state.Model, StopReason: nil, // JSON null; never "" - Usage: AnthropicUsage{InputTokens: 0, OutputTokens: 0}, + Usage: chatUsageToAnthropicUsage(nil), }, }} } diff --git a/backend/internal/pkg/apicompat/responses_to_anthropic.go b/backend/internal/pkg/apicompat/responses_to_anthropic.go index 2b514b1391..11fc9b3b02 100644 --- a/backend/internal/pkg/apicompat/responses_to_anthropic.go +++ b/backend/internal/pkg/apicompat/responses_to_anthropic.go @@ -20,6 +20,7 @@ func ResponsesToAnthropic(resp *ResponsesResponse, model string) *AnthropicRespo Type: "message", Role: "assistant", Model: model, + Usage: anthropicUsageFromResponsesUsage(nil), } var blocks []AnthropicContentBlock @@ -97,7 +98,7 @@ func ResponsesToAnthropic(resp *ResponsesResponse, model string) *AnthropicRespo func anthropicUsageFromResponsesUsage(usage *ResponsesUsage) AnthropicUsage { if usage == nil { - return AnthropicUsage{} + return AnthropicUsage{CacheCreationInputTokensPresent: true, CacheReadInputTokensPresent: true} } cachedTokens := 0 @@ -116,6 +117,7 @@ func anthropicUsageFromResponsesUsage(usage *ResponsesUsage) AnthropicUsage { CacheReadInputTokens: cachedTokens, CacheCreationInputTokens: usage.CacheCreationInputTokens, CacheCreationInputTokensPresent: true, + CacheReadInputTokensPresent: true, } } @@ -291,6 +293,7 @@ func FinalizeResponsesAnthropicStream(state *ResponsesEventToAnthropicState) []A CacheReadInputTokens: state.CacheReadInputTokens, CacheCreationInputTokens: state.CacheCreationInputTokens, CacheCreationInputTokensPresent: true, + CacheReadInputTokensPresent: true, }, }, AnthropicStreamEvent{Type: "message_stop"}, @@ -338,8 +341,10 @@ func resToAnthHandleCreated(evt *ResponsesStreamEvent, state *ResponsesEventToAn Model: state.Model, StopReason: nil, Usage: AnthropicUsage{ - InputTokens: 0, - OutputTokens: 0, + InputTokens: 0, + OutputTokens: 0, + CacheCreationInputTokensPresent: true, + CacheReadInputTokensPresent: true, }, }, }} @@ -775,6 +780,7 @@ func resToAnthHandleCompleted(evt *ResponsesStreamEvent, state *ResponsesEventTo CacheReadInputTokens: state.CacheReadInputTokens, CacheCreationInputTokens: state.CacheCreationInputTokens, CacheCreationInputTokensPresent: true, + CacheReadInputTokensPresent: true, }, }, AnthropicStreamEvent{Type: "message_stop"}, diff --git a/backend/internal/service/anthropic_chat_stream_usage_test.go b/backend/internal/service/anthropic_chat_stream_usage_test.go index 77e51a8836..6a68a9d106 100644 --- a/backend/internal/service/anthropic_chat_stream_usage_test.go +++ b/backend/internal/service/anthropic_chat_stream_usage_test.go @@ -28,7 +28,7 @@ func TestAnthropicChatStreamAuthoritativeUsage(t *testing.T) { }{ {"cache", `,"usage":{"input_tokens":308,"cache_read_input_tokens":241,"cache_creation_input_tokens":17}`, `,"usage":{"output_tokens":49}`, "", true, 566, 308, 566, 49, 241, 17}, {"contradictory_cache_creation", `,"usage":{"input_tokens":10,"cache_creation_input_tokens":100,"cache_creation":{"ephemeral_1h_input_tokens":200}}`, `,"usage":{"output_tokens":7,"cache_creation":{"ephemeral_1h_input_tokens":200}}`, `,"usage":{"output_tokens":7,"cache_creation":{"ephemeral_1h_input_tokens":200}}`, true, 110, 10, 110, 7, 0, 100}, - {"zero_cache_creation", `,"usage":{"input_tokens":10,"cache_creation_input_tokens":0,"cache_creation":{"ephemeral_1h_input_tokens":200}}`, `,"usage":{"output_tokens":7,"cache_creation":{"ephemeral_1h_input_tokens":200}}`, "", true, 10, 10, 10, 7, 0, 0}, + {"zero_cache_creation", `,"usage":{"input_tokens":10,"cache_creation_input_tokens":0,"cache_creation":{"ephemeral_1h_input_tokens":200}}`, `,"usage":{"output_tokens":7,"cache_creation":{"ephemeral_1h_input_tokens":200}}`, "", true, 210, 10, 210, 7, 0, 200}, {"partial_cache_creation", `,"usage":{"input_tokens":10,"cache_creation":{"ephemeral_5m_input_tokens":20}}`, `,"usage":{"output_tokens":7,"cache_creation":{"ephemeral_1h_input_tokens":30}}`, `,"usage":{"output_tokens":7,"cache_creation":{"ephemeral_1h_input_tokens":30}}`, true, 60, 10, 60, 7, 0, 50}, {"deepseek_partial_cache", "", `,"usage":{"input_tokens":1200,"output_tokens":30,"prompt_cache_hit_tokens":800,"prompt_cache_miss_tokens":400}`, "", true, 1200, 400, 1200, 30, 800, 0}, {"openai_partial_cache", "", `,"usage":{"prompt_tokens":1200,"output_tokens":30,"prompt_tokens_details":{"cached_tokens":800}}`, "", true, 1200, 400, 1200, 30, 800, 0}, diff --git a/backend/internal/service/anthropic_prompt_total_test.go b/backend/internal/service/anthropic_prompt_total_test.go index ae0161982c..f307738c2d 100644 --- a/backend/internal/service/anthropic_prompt_total_test.go +++ b/backend/internal/service/anthropic_prompt_total_test.go @@ -30,7 +30,7 @@ func TestAnthropicPromptTotalSnapshots(t *testing.T) { {"independent input", `"input_tokens":80`, []string{`{"cache_creation":{"ephemeral_1h_input_tokens":30}}`, `{"cache_creation":{"ephemeral_1h_input_tokens":30}}`}, []int{80, 80}}, {"miss overrides total", `"prompt_tokens":100`, []string{`{"prompt_tokens":100,"prompt_cache_miss_tokens":40}`, `{"cache_creation":{"ephemeral_1h_input_tokens":30}}`}, []int{40, 40}}, {"late read aliases", `"prompt_tokens":100`, []string{`{"cached_tokens":10}`, `{"cached_tokens":15}`, `{"prompt_tokens_details":{"cached_tokens":20}}`, `{"prompt_cache_hit_tokens":25}`, `{"cache_creation":{"ephemeral_1h_input_tokens":30}}`}, []int{70, 65, 60, 55, 25}}, - {"aggregate clears", `"prompt_tokens":100`, []string{`{"cache_creation_input_tokens":50}`, `{"cache_creation_input_tokens":0}`, `{"cache_creation":{"ephemeral_1h_input_tokens":30}}`}, []int{50, 100, 100}}, + {"aggregate survives zero placeholder", `"prompt_tokens":100`, []string{`{"cache_creation_input_tokens":50}`, `{"cache_creation_input_tokens":0}`, `{"cache_creation":{"ephemeral_1h_input_tokens":30}}`}, []int{50, 50, 50}}, {"cache exceeds prompt", `"prompt_tokens":100`, []string{`{"cache_creation":{"ephemeral_1h_input_tokens":100}}`, `{"cache_creation":{"ephemeral_1h_input_tokens":30}}`}, []int{0, 50}}, } { for _, parser := range []string{"typed", "raw", "generic"} { @@ -70,10 +70,10 @@ func TestAnthropicPromptTotalCacheReadPresence(t *testing.T) { delta string read int }{ - {"canonical zero", `{"cache_read_input_tokens":0}`, 0}, - {"cached zero", `{"cached_tokens":0}`, 0}, - {"details zero", `{"prompt_tokens_details":{"cached_tokens":0}}`, 0}, - {"hit zero", `{"prompt_cache_hit_tokens":0}`, 0}, + {"canonical zero", `{"cache_read_input_tokens":0}`, 20}, + {"cached zero", `{"cached_tokens":0}`, 20}, + {"details zero", `{"prompt_tokens_details":{"cached_tokens":0}}`, 20}, + {"hit zero", `{"prompt_cache_hit_tokens":0}`, 20}, {"missing", `{"output_tokens":2}`, 20}, {"null", `{"cache_read_input_tokens":null,"cached_tokens":null,"prompt_tokens_details":{"cached_tokens":null},"prompt_cache_hit_tokens":null}`, 20}, {"canonical precedence", `{"cache_read_input_tokens":12,"cached_tokens":13,"prompt_tokens_details":{"cached_tokens":14},"prompt_cache_hit_tokens":15}`, 12}, @@ -121,7 +121,9 @@ func TestAnthropicPromptTotalCacheReadZeroForwardBoundary(t *testing.T) { for _, terminal := range []string{"stop", "eof"} { t.Run(field+"/"+route+"/"+terminal, func(t *testing.T) { payload := "event: message_start\ndata: " + `{"type":"message_start","message":{"id":"msg_zero","type":"message","role":"assistant","model":"claude-sonnet-4","content":[],"usage":{"input_tokens":100,"prompt_tokens":100,"cache_read_input_tokens":20,"cache_creation_input_tokens":10}}}` + "\n\n" - payload += "event: message_delta\ndata: " + `{"type":"message_delta","usage":{"` + field + `":0}}` + "\n\n" + for range 2 { + payload += "event: message_delta\ndata: " + `{"type":"message_delta","usage":{"` + field + `":0}}` + "\n\n" + } payload += "event: message_delta\ndata: " + `{"type":"message_delta","delta":{"stop_reason":"end_turn"},"usage":{"output_tokens":2}}` + "\n\n" if terminal == "stop" { payload += "event: message_stop\ndata: {\"type\":\"message_stop\"}\n\n" @@ -154,8 +156,8 @@ func TestAnthropicPromptTotalCacheReadZeroForwardBoundary(t *testing.T) { require.NoError(t, err) } require.NotNil(t, usage) - require.Equal(t, 90, usage.InputTokens) - require.Zero(t, usage.CacheReadInputTokens) + require.Equal(t, 70, usage.InputTokens) + require.Equal(t, 20, usage.CacheReadInputTokens) require.Equal(t, 10, usage.CacheCreationInputTokens) require.Equal(t, 2, usage.OutputTokens) }) @@ -190,7 +192,7 @@ func TestAnthropicCacheReadZeroPreservesIndependentInput(t *testing.T) { } require.Equal(t, 80, usage.InputTokens) } - require.Zero(t, usage.CacheReadInputTokens) + require.Equal(t, 20, usage.CacheReadInputTokens) require.Equal(t, 10, usage.CacheCreationInputTokens) }) } diff --git a/backend/internal/service/antigravity_gateway_upstream.go b/backend/internal/service/antigravity_gateway_upstream.go index 79b8f4042f..30c99ef307 100644 --- a/backend/internal/service/antigravity_gateway_upstream.go +++ b/backend/internal/service/antigravity_gateway_upstream.go @@ -330,7 +330,7 @@ func (s *AntigravityGatewayService) extractSSEUsage(line string, usage *ClaudeUs if v, ok := u["cache_read_input_tokens"].(float64); ok && int(v) > 0 { usage.CacheReadInputTokens = int(v) } - if v, ok := u["cache_creation_input_tokens"].(float64); ok && int(v) >= 0 { + if v, ok := u["cache_creation_input_tokens"].(float64); ok && (int(v) > 0 || usage.CacheCreationInputTokens <= 0) { usage.CacheCreationInputTokens = int(v) usage.cacheCreationInputTokensPresent = true } diff --git a/backend/internal/service/gateway_anthropic_apikey_passthrough_test.go b/backend/internal/service/gateway_anthropic_apikey_passthrough_test.go index 9157776810..70e4b3feab 100644 --- a/backend/internal/service/gateway_anthropic_apikey_passthrough_test.go +++ b/backend/internal/service/gateway_anthropic_apikey_passthrough_test.go @@ -1287,7 +1287,7 @@ func TestExtractAnthropicSSEDataLine(t *testing.T) { func TestGatewayService_ParseSSEUsagePassthrough_MessageStartFallbacks(t *testing.T) { usage := &ClaudeUsage{} - data := `{"type":"message_start","message":{"usage":{"input_tokens":12,"cache_read_input_tokens":0,"cached_tokens":9,"cache_creation":{"ephemeral_5m_input_tokens":3,"ephemeral_1h_input_tokens":4}}}}` + data := `{"type":"message_start","message":{"usage":{"input_tokens":12,"cache_read_input_tokens":0,"cached_tokens":9,"cache_creation_input_tokens":0,"cache_creation":{"ephemeral_5m_input_tokens":3,"ephemeral_1h_input_tokens":4}}}}` parseSSEUsagePassthrough(data, usage) @@ -1359,8 +1359,9 @@ func TestGatewayService_ParseSSEUsagePassthrough_OtherEventCacheCreation(t *test wantAggregate: 3, }, { - name: "explicit zero retains raw TTL", - snapshots: []string{`{"cache_creation_input_tokens":0,"cache_creation":{"ephemeral_5m_input_tokens":2,"ephemeral_1h_input_tokens":1}}`}, + name: "explicit zero retains raw TTL", + snapshots: []string{`{"cache_creation_input_tokens":0,"cache_creation":{"ephemeral_5m_input_tokens":2,"ephemeral_1h_input_tokens":1}}`}, + wantAggregate: 3, }, { name: "previous explicit aggregate survives null", @@ -1369,14 +1370,16 @@ func TestGatewayService_ParseSSEUsagePassthrough_OtherEventCacheCreation(t *test wantAggregate: 9, }, { - name: "previous explicit zero survives omitted aggregate", - start: `{"cache_creation_input_tokens":0}`, - snapshots: []string{`{"cache_creation":{"ephemeral_5m_input_tokens":2,"ephemeral_1h_input_tokens":1}}`}, + name: "previous explicit zero survives omitted aggregate", + start: `{"cache_creation_input_tokens":0}`, + snapshots: []string{`{"cache_creation":{"ephemeral_5m_input_tokens":2,"ephemeral_1h_input_tokens":1}}`}, + wantAggregate: 3, }, { - name: "explicit zero replaces previous aggregate", - start: `{"cache_creation_input_tokens":9}`, - snapshots: []string{`{"cache_creation_input_tokens":0,"cache_creation":{"ephemeral_5m_input_tokens":2,"ephemeral_1h_input_tokens":1}}`}, + name: "explicit zero preserves previous aggregate", + start: `{"cache_creation_input_tokens":9}`, + snapshots: []string{`{"cache_creation_input_tokens":0,"cache_creation":{"ephemeral_5m_input_tokens":2,"ephemeral_1h_input_tokens":1}}`}, + wantAggregate: 9, }, } for _, test := range tests { @@ -1419,7 +1422,7 @@ func TestParseClaudeUsageFromResponseBody(t *testing.T) { }) t.Run("parse all usage fields and fallback", func(t *testing.T) { - body := []byte(`{"usage":{"input_tokens":21,"output_tokens":34,"cache_read_input_tokens":0,"cached_tokens":13,"cache_creation":{"ephemeral_5m_input_tokens":5,"ephemeral_1h_input_tokens":8}}}`) + body := []byte(`{"usage":{"input_tokens":21,"output_tokens":34,"cache_read_input_tokens":0,"cached_tokens":13,"cache_creation_input_tokens":0,"cache_creation":{"ephemeral_5m_input_tokens":5,"ephemeral_1h_input_tokens":8}}}`) got := parseClaudeUsageFromResponseBody(body) require.Equal(t, 21, got.InputTokens) require.Equal(t, 34, got.OutputTokens) diff --git a/backend/internal/service/gateway_anthropic_passthrough.go b/backend/internal/service/gateway_anthropic_passthrough.go index baa1c5c5b0..7fc54db3a4 100644 --- a/backend/internal/service/gateway_anthropic_passthrough.go +++ b/backend/internal/service/gateway_anthropic_passthrough.go @@ -671,8 +671,8 @@ func parseSSEUsagePassthrough(data string, usage *ClaudeUsage) { } for _, path := range []string{"cache_read_input_tokens", "cached_tokens", "prompt_tokens_details.cached_tokens", "prompt_cache_hit_tokens"} { if value := usageNode.Get(path); value.Exists() && value.Type != gjson.Null { - usage.CacheReadInputTokens = max(int(value.Int()), 0) - if usage.CacheReadInputTokens > 0 { + if tokens := int(value.Int()); tokens > 0 { + usage.CacheReadInputTokens = tokens break } } @@ -706,7 +706,9 @@ func normalizeAnthropicCompatiblePromptUsage(usageNode gjson.Result, usage *Clau } mergeRawAnthropicCacheCreationUsage(usageNode, usage) - usage.CacheReadInputTokens = cacheReadTokens + if cacheReadTokens > 0 || usage.CacheReadInputTokens <= 0 { + usage.CacheReadInputTokens = cacheReadTokens + } var cacheMissTokens *int if promptCacheMissTokens.Exists() && promptCacheMissTokens.Type != gjson.Null { value := int(promptCacheMissTokens.Int()) diff --git a/backend/internal/service/gateway_cache_compatibility_boundary_test.go b/backend/internal/service/gateway_cache_compatibility_boundary_test.go new file mode 100644 index 0000000000..c351f009ad --- /dev/null +++ b/backend/internal/service/gateway_cache_compatibility_boundary_test.go @@ -0,0 +1,180 @@ +//go:build unit + +package service + +import ( + "io" + "net/http" + "net/http/httptest" + "strings" + "testing" + "time" + + "github.com/Wei-Shaw/sub2api/internal/pkg/apicompat" + "github.com/gin-gonic/gin" + "github.com/stretchr/testify/require" + "github.com/tidwall/gjson" +) + +func TestAnthropicConverterOutputCacheFields(t *testing.T) { + gin.SetMode(gin.TestMode) + for _, test := range []struct { + name string + chatUsage string + responsesUsage string + creation int64 + read int64 + }{ + {"missing usage", "", "", 0, 0}, + {"null usage", `,"usage":null`, `,"usage":null`, 0, 0}, + {"empty usage", `,"usage":{}`, `,"usage":{}`, 0, 0}, + {"read only", `,"usage":{"prompt_tokens":10,"prompt_tokens_details":{"cached_tokens":3}}`, `,"usage":{"input_tokens":10,"input_tokens_details":{"cached_tokens":3}}`, 0, 3}, + {"creation only", `,"usage":{"prompt_tokens":10,"prompt_tokens_details":{"cache_write_tokens":4}}`, `,"usage":{"input_tokens":10,"cache_creation_input_tokens":4}`, 4, 0}, + } { + for _, route := range []string{"chat buffered", "chat terminal", "chat eof", "responses buffered", "responses terminal", "responses eof"} { + if strings.HasSuffix(route, "eof") && test.name != "missing usage" { + continue + } + t.Run(test.name+"/"+route, func(t *testing.T) { + payload := `{"id":"chat_cache","choices":[{"message":{"role":"assistant","content":"ok"},"finish_reason":"stop"}]` + test.chatUsage + `}` + if strings.HasPrefix(route, "responses") { + payload = "data: {\"type\":\"response.created\",\"response\":{\"id\":\"resp_cache\",\"model\":\"gpt-5.4\"}}\n\n" + if !strings.HasSuffix(route, "eof") { + payload += `data: {"type":"response.completed","response":{"id":"resp_cache","status":"completed","output":[]` + test.responsesUsage + `}}` + "\n\n" + } + } else if !strings.HasSuffix(route, "buffered") { + payload = `data: {"id":"chat_cache","choices":[{"delta":{"role":"assistant","content":"ok"},"finish_reason":"stop"}]` + test.chatUsage + `}` + "\n\n" + if strings.HasSuffix(route, "terminal") { + payload += "data: [DONE]\n\n" + } + } + recorder := httptest.NewRecorder() + ctx, _ := gin.CreateTestContext(recorder) + ctx.Request = httptest.NewRequest(http.MethodPost, "/v1/messages", nil) + response := &http.Response{StatusCode: http.StatusOK, Header: make(http.Header), Body: io.NopCloser(strings.NewReader(payload))} + service := &OpenAIGatewayService{cfg: rawChatCompletionsTestConfig()} + var err error + switch route { + case "chat buffered": + _, err = service.bufferChatCompletionsAsAnthropic(ctx, response, "gpt-5.4", "gpt-5.4", "gpt-5.4", nil, nil, time.Now()) + case "chat terminal", "chat eof": + _, err = service.streamChatCompletionsAsAnthropic(ctx, response, "gpt-5.4", "gpt-5.4", "gpt-5.4", nil, nil, time.Now()) + case "responses buffered": + _, err = service.handleAnthropicBufferedStreamingResponse(response, ctx, rawChatCompletionsTestAccount(), "gpt-5.4", "gpt-5.4", "gpt-5.4", time.Now()) + default: + _, err = service.handleAnthropicStreamingResponse(response, ctx, rawChatCompletionsTestAccount(), "gpt-5.4", "gpt-5.4", "gpt-5.4", time.Now()) + } + if route == "responses eof" { + require.ErrorContains(t, err, "missing terminal event") + } else { + require.NoError(t, err) + } + require.Equal(t, http.StatusOK, recorder.Code) + assertUsage := func(usage gjson.Result, creation, read int64) { + for field, want := range map[string]int64{"cache_creation_input_tokens": creation, "cache_read_input_tokens": read} { + tokens := usage.Get(field) + require.True(t, tokens.Exists(), field) + require.Equal(t, gjson.Number, tokens.Type, field) + require.Equal(t, want, tokens.Int(), field) + } + } + if strings.HasSuffix(route, "buffered") { + assertUsage(gjson.Get(recorder.Body.String(), "usage"), test.creation, test.read) + return + } + starts, deltas, stops := 0, 0, 0 + for _, line := range strings.Split(recorder.Body.String(), "\n") { + if !strings.HasPrefix(line, "data: ") { + continue + } + event := gjson.Parse(strings.TrimPrefix(line, "data: ")) + switch event.Get("type").String() { + case "message_start": + assertUsage(event.Get("message.usage"), 0, 0) + starts++ + case "message_delta": + assertUsage(event.Get("usage"), test.creation, test.read) + deltas++ + case "message_stop": + stops++ + } + } + require.Equal(t, 1, starts) + if route == "responses eof" { + require.Zero(t, deltas) + require.Zero(t, stops) + } else { + require.Equal(t, 1, deltas) + require.Equal(t, 1, stops) + } + }) + } + } +} + +func TestAnthropicZeroCacheDeltaPromptReconciliation(t *testing.T) { + for _, parser := range []string{"raw", "typed", "generic", "antigravity"} { + t.Run(parser, func(t *testing.T) { + usage := &ClaudeUsage{} + for index, snapshot := range []string{ + `{"input_tokens":100,"prompt_tokens":100,"cache_read_input_tokens":30,"cache_creation_input_tokens":0,"cache_creation":{"ephemeral_5m_input_tokens":20}}`, + `{"input_tokens":0,"cache_read_input_tokens":0,"cache_creation_input_tokens":0,"cache_creation":{"ephemeral_1h_input_tokens":10}}`, + `{"input_tokens":0,"cache_read_input_tokens":0,"cache_creation_input_tokens":0,"cache_creation":{"ephemeral_1h_input_tokens":10}}`, + } { + event := `{"type":"message_delta","usage":` + snapshot + `}` + if index == 0 { + event = `{"type":"message_start","message":{"usage":` + snapshot + `}}` + } + switch parser { + case "raw": + parseSSEUsagePassthrough(event, usage) + case "typed": + var source apicompat.AnthropicUsage + require.NoError(t, source.UnmarshalJSON([]byte(snapshot))) + mergeAnthropicUsage(usage, source) + case "generic": + (&GatewayService{}).parseSSEUsage(event, usage) + case "antigravity": + (&AntigravityGatewayService{}).extractSSEUsage("data: "+event, usage) + } + creation := 20 + if index > 0 { + creation = 30 + } + require.Equal(t, 30, usage.CacheReadInputTokens) + if parser == "antigravity" { + require.Equal(t, 100, usage.InputTokens) + } else { + require.Equal(t, creation, usage.CacheCreationInputTokens) + require.Equal(t, 100-30-creation, usage.InputTokens) + } + cache5m, cache1h := normalizeCacheCreationBreakdown(usage.billingUsageTokens()) + require.Equal(t, creation, cache5m+cache1h) + } + }) + } +} + +func TestCacheCreationZeroAggregateBillingProjection(t *testing.T) { + claude := ClaudeUsage{ + InputTokens: 40, CacheReadInputTokens: 10, + CacheCreation5mTokens: 20, CacheCreation1hTokens: 30, + cacheCreationInputTokensPresent: true, + } + openAI := OpenAIUsage{ + InputTokens: 100, CacheReadInputTokens: 10, + CacheCreation5mTokens: 20, CacheCreation1hTokens: 30, + cacheCreationInputTokensPresent: true, + } + for _, tokens := range []UsageTokens{claude.billingUsageTokens(), openAI.billingUsageTokens()} { + require.Equal(t, 40, tokens.InputTokens) + require.Equal(t, 50, tokens.CacheCreationTokens) + require.Equal(t, 10, tokens.CacheReadTokens) + cache5m, cache1h := normalizeCacheCreationBreakdown(tokens) + require.Equal(t, 20, cache5m) + require.Equal(t, 30, cache1h) + require.InDelta(t, 0.1, (&BillingService{}).computeCacheCreationCost(&ModelPricing{}, tokens, 0.002, 1), 1e-12) + } + require.Zero(t, claude.CacheCreationInputTokens) + require.Zero(t, openAI.CacheCreationInputTokens) +} diff --git a/backend/internal/service/gateway_cache_creation_usage_test.go b/backend/internal/service/gateway_cache_creation_usage_test.go index fbdd618e75..b45e6fdcc0 100644 --- a/backend/internal/service/gateway_cache_creation_usage_test.go +++ b/backend/internal/service/gateway_cache_creation_usage_test.go @@ -51,14 +51,14 @@ func TestAnthropicCacheCreationSnapshots(t *testing.T) { wantTotals: []int{50, 40, 40, 40}, want5m: 20, want1h: 200, billed5m: 4, billed1h: 36, }, { - name: "explicit zero survives TTL updates", + name: "explicit zero falls back to TTL updates", snapshots: []string{`{"cache_creation_input_tokens":0,"cache_creation":{"ephemeral_1h_input_tokens":200}}`, `{"cache_creation":{"ephemeral_5m_input_tokens":50}}`}, - wantTotals: []int{0, 0}, want5m: 50, want1h: 200, + wantTotals: []int{200, 250}, want5m: 50, want1h: 200, billed5m: 50, billed1h: 200, }, { - name: "explicit zero delta clears aggregate", + name: "explicit zero delta preserves aggregate", snapshots: []string{`{"cache_creation_input_tokens":100}`, `{"cache_creation_input_tokens":0}`, `{"cache_creation":{"ephemeral_1h_input_tokens":200}}`}, - wantTotals: []int{100, 0, 0}, want1h: 200, + wantTotals: []int{100, 100, 100}, want1h: 200, billed1h: 100, }, { name: "repeated cumulative snapshots do not double count", @@ -78,12 +78,12 @@ func TestAnthropicCacheCreationSnapshots(t *testing.T) { { name: "null does not clear explicit zero", snapshots: []string{`{"cache_creation_input_tokens":0,"cache_creation":{"ephemeral_1h_input_tokens":200}}`, `{"cache_creation_input_tokens":null,"cache_creation":{"ephemeral_5m_input_tokens":20,"ephemeral_1h_input_tokens":null}}`}, - wantTotals: []int{0, 0}, want5m: 20, want1h: 200, + wantTotals: []int{200, 220}, want5m: 20, want1h: 200, billed5m: 20, billed1h: 200, }, { name: "zero to positive retains partial TTL history", snapshots: []string{`{"cache_creation":{"ephemeral_5m_input_tokens":20}}`, `{"cache_creation_input_tokens":0,"cache_creation":{"ephemeral_1h_input_tokens":30}}`, `{"cache_creation":{"ephemeral_1h_input_tokens":50}}`, `{"cache_creation_input_tokens":35}`}, - wantTotals: []int{20, 0, 0, 35}, want5m: 20, want1h: 50, billed5m: 10, billed1h: 25, + wantTotals: []int{20, 50, 70, 35}, want5m: 20, want1h: 50, billed5m: 10, billed1h: 25, }, { name: "all null is absent before partial TTL", @@ -140,7 +140,9 @@ func TestAnthropicCacheCreationMissingDetailForwardBillingBoundary(t *testing.T) {"mixed start remainder defaults to 5m", `"cache_creation_input_tokens":3000,"cache_creation":{"ephemeral_5m_input_tokens":1000,"ephemeral_1h_input_tokens":2000}`, `{"cache_creation_input_tokens":11000}`, 11000, 1000, 2000, 26}, {"zero start aggregate grows", `"cache_creation_input_tokens":0,"cache_creation":{"ephemeral_5m_input_tokens":0,"ephemeral_1h_input_tokens":0}`, `{"cache_creation_input_tokens":11000}`, 11000, 0, 0, 22}, {"unchanged aggregate", `"cache_creation_input_tokens":3000,"cache_creation":{"ephemeral_1h_input_tokens":3000}`, `{"cache_creation_input_tokens":3000}`, 3000, 0, 3000, 12}, - {"explicit zero suppresses retained detail", `"cache_creation_input_tokens":3000,"cache_creation":{"ephemeral_1h_input_tokens":3000}`, `{"cache_creation_input_tokens":0}`, 0, 0, 3000, 0}, + {"explicit zero preserves retained detail", `"cache_creation_input_tokens":3000,"cache_creation":{"ephemeral_1h_input_tokens":3000}`, `{"cache_creation_input_tokens":0}`, 3000, 0, 3000, 12}, + {"explicit zero uses partial details", `"cache_creation_input_tokens":0,"cache_creation":{"ephemeral_5m_input_tokens":50}`, `{"cache_creation_input_tokens":0,"cache_creation":{"ephemeral_1h_input_tokens":200}}`, 250, 50, 200, 0.9}, + {"zero cache placeholders preserve totals", `"cache_creation_input_tokens":100,"cache_read_input_tokens":9,"cache_creation":{"ephemeral_1h_input_tokens":200}`, `{"input_tokens":0,"cache_creation_input_tokens":0,"cache_read_input_tokens":0}`, 100, 0, 200, 0.4}, {"oversized detail ratio capped", `"cache_creation_input_tokens":100,"cache_creation":{"ephemeral_5m_input_tokens":50,"ephemeral_1h_input_tokens":200}`, `{"cache_creation_input_tokens":100}`, 100, 50, 200, 0.36}, } { for _, route := range []string{"standard", "passthrough", "responses", "buffered responses", "chat", "buffered chat"} { @@ -190,6 +192,8 @@ func TestAnthropicCacheCreationMissingDetailForwardBillingBoundary(t *testing.T) } require.NotNil(t, result) require.Equal(t, 10, result.Usage.InputTokens) + wantRead := int(gjson.Get("{"+test.start+"}", "cache_read_input_tokens").Int()) + require.Equal(t, wantRead, result.Usage.CacheReadInputTokens) require.Equal(t, 2, result.Usage.OutputTokens) require.Equal(t, test.aggregate, result.Usage.CacheCreationInputTokens) require.True(t, result.Usage.cacheCreationInputTokensPresent) @@ -218,10 +222,12 @@ func TestAnthropicCacheCreationMissingDetailForwardBillingBoundary(t *testing.T) } require.True(t, usage.Exists()) if strings.HasSuffix(route, "chat") { - require.EqualValues(t, 10+test.aggregate, usage.Get("prompt_tokens").Int()) + require.EqualValues(t, 10+test.aggregate+wantRead, usage.Get("prompt_tokens").Int()) + require.EqualValues(t, wantRead, usage.Get("prompt_tokens_details.cached_tokens").Int()) require.EqualValues(t, test.aggregate, usage.Get("prompt_tokens_details.cache_creation_tokens").Int()) } else { - require.EqualValues(t, 10+test.aggregate, usage.Get("input_tokens").Int()) + require.EqualValues(t, 10+test.aggregate+wantRead, usage.Get("input_tokens").Int()) + require.EqualValues(t, wantRead, usage.Get("input_tokens_details.cached_tokens").Int()) require.EqualValues(t, test.aggregate, usage.Get("cache_creation_input_tokens").Int()) } } @@ -316,7 +322,7 @@ func assertAnthropicCacheCreationForwardBoundary(t *testing.T, antigravity bool) cache1h int cacheCost float64 }{ - {"explicit aggregate zero", `"cache_creation_input_tokens":0,"cache_creation":{"ephemeral_5m_input_tokens":50,"ephemeral_1h_input_tokens":200}`, 0, true, 50, 200, 0}, + {"explicit aggregate zero", `"cache_creation_input_tokens":0,"cache_creation":{"ephemeral_5m_input_tokens":50,"ephemeral_1h_input_tokens":200}`, 250, true, 50, 200, 0.9}, {"missing aggregate", `"cache_creation":{"ephemeral_5m_input_tokens":50,"ephemeral_1h_input_tokens":200}`, 250, false, 50, 200, 0.9}, {"null aggregate", `"cache_creation_input_tokens":null,"cache_creation":{"ephemeral_5m_input_tokens":50,"ephemeral_1h_input_tokens":200}`, 250, false, 50, 200, 0.9}, {"positive aggregate caps TTL", `"cache_creation_input_tokens":100,"cache_creation":{"ephemeral_5m_input_tokens":50,"ephemeral_1h_input_tokens":200}`, 100, true, 50, 200, 0.36}, @@ -362,8 +368,8 @@ func assertAnthropicCacheCreationForwardBoundary(t *testing.T, antigravity bool) require.Equal(t, http.StatusOK, recorder.Code) require.Equal(t, body, recorder.Body.String()) wantAggregate := test.aggregate - if antigravity && !test.present { - wantAggregate = 0 + if antigravity { + wantAggregate = int(gjson.Get(usageJSON, "cache_creation_input_tokens").Int()) } require.Equal(t, wantAggregate, result.Usage.CacheCreationInputTokens) require.Equal(t, test.present, result.Usage.cacheCreationInputTokensPresent) @@ -385,7 +391,7 @@ func TestAnthropicCacheCreationMarshaledSSEBoundary(t *testing.T) { wantCacheCost float64 }{ {"missing", 0, false, 50, 0.16}, - {"explicit zero", 0, true, 0, 0}, + {"explicit zero", 0, true, 50, 0.16}, {"synthetic nonzero", 40, false, 40, 0.128}, } { for _, terminal := range []string{"message_stop", "eof"} { @@ -437,16 +443,18 @@ func TestAnthropicCacheCreationMarshaledSSEBoundary(t *testing.T) { func TestRawAnthropicCacheCreationExplicitZero(t *testing.T) { for _, prompt := range []string{"", `,"prompt_tokens":500`} { usage := parseClaudeUsageFromResponseBody([]byte(`{"usage":{"input_tokens":10,"cache_creation_input_tokens":0,"cache_creation":{"ephemeral_1h_input_tokens":200}` + prompt + `}}`)) - require.Zero(t, usage.CacheCreationInputTokens) + require.Equal(t, 200, usage.CacheCreationInputTokens) require.Equal(t, 200, usage.CacheCreation1hTokens) - assertAnthropicCacheCreationRecordCosts(t, *usage, 0) + assertAnthropicCacheCreationRecordCosts(t, *usage, 0.8) if prompt != "" { - require.Equal(t, 500, usage.InputTokens) + require.Equal(t, 300, usage.InputTokens) + } else { + require.Equal(t, 10, usage.InputTokens) } } usage := &ClaudeUsage{CacheCreationInputTokens: 100} (&AntigravityGatewayService{}).extractSSEUsage(`data: {"type":"message_delta","usage":{"cache_creation_input_tokens":0}}`, usage) - require.Zero(t, usage.CacheCreationInputTokens) + require.Equal(t, 100, usage.CacheCreationInputTokens) } func TestAnthropicCacheCreationNullBodyParity(t *testing.T) { @@ -459,7 +467,7 @@ func TestAnthropicCacheCreationNullBodyParity(t *testing.T) { }{ {"missing aggregate", `{"cache_creation":{"ephemeral_1h_input_tokens":200}}`, 200, false, 0.8}, {"null aggregate", `{"cache_creation_input_tokens":null,"cache_creation":{"ephemeral_1h_input_tokens":200}}`, 200, false, 0.8}, - {"zero aggregate", `{"cache_creation_input_tokens":0,"cache_creation":{"ephemeral_1h_input_tokens":200}}`, 0, true, 0}, + {"zero aggregate", `{"cache_creation_input_tokens":0,"cache_creation":{"ephemeral_1h_input_tokens":200}}`, 200, true, 0.8}, {"null TTL with positive aggregate", `{"cache_creation_input_tokens":100,"cache_creation":{"ephemeral_5m_input_tokens":null,"ephemeral_1h_input_tokens":null}}`, 100, true, 0.2}, {"all null", `{"cache_creation_input_tokens":null,"cache_creation":{"ephemeral_5m_input_tokens":null,"ephemeral_1h_input_tokens":null}}`, 0, false, 0}, } { @@ -488,7 +496,7 @@ func TestAntigravityCacheCreationUsage(t *testing.T) { present bool wantCost float64 }{ - {"explicit zero with TTL", `{"cache_creation_input_tokens":0,"cache_creation":{"ephemeral_5m_input_tokens":50,"ephemeral_1h_input_tokens":200}}`, 0, true, 0}, + {"explicit zero with TTL", `{"cache_creation_input_tokens":0,"cache_creation":{"ephemeral_5m_input_tokens":50,"ephemeral_1h_input_tokens":200}}`, 0, true, 0.9}, {"missing aggregate keeps TTL fallback", `{"cache_creation":{"ephemeral_5m_input_tokens":50,"ephemeral_1h_input_tokens":200}}`, 0, false, 0.9}, {"null aggregate keeps TTL fallback", `{"cache_creation_input_tokens":null,"cache_creation":{"ephemeral_5m_input_tokens":50,"ephemeral_1h_input_tokens":200}}`, 0, false, 0.9}, {"positive aggregate", `{"cache_creation_input_tokens":100,"cache_creation":{"ephemeral_1h_input_tokens":200}}`, 100, true, 0.4}, @@ -521,7 +529,7 @@ func TestAntigravityCacheCreationLateDeltas(t *testing.T) { present bool wantCost float64 }{ - {"explicit zero survives", `"cache_creation_input_tokens":0,`, 0, true, 0}, + {"explicit zero falls back", `"cache_creation_input_tokens":0,`, 0, true, 1.3}, {"missing aggregate keeps TTL fallback", "", 0, false, 1.3}, {"null aggregate keeps TTL fallback", `"cache_creation_input_tokens":null,`, 0, false, 1.3}, {"positive aggregate survives", `"cache_creation_input_tokens":100,`, 100, true, 0.372}, @@ -545,20 +553,79 @@ func TestAntigravityCacheCreationLateDeltas(t *testing.T) { }) } - t.Run("explicit zero delta clears aggregate with retained TTL", func(t *testing.T) { + t.Run("explicit zero delta preserves aggregate with retained TTL", func(t *testing.T) { service := &AntigravityGatewayService{} usage := &ClaudeUsage{} - service.extractSSEUsage(`data: {"type":"message_start","message":{"usage":{"cache_creation_input_tokens":100,"cache_creation":{"ephemeral_1h_input_tokens":200}}}}`, usage) - service.extractSSEUsage(`data: {"type":"message_delta","usage":{"cache_creation_input_tokens":0}}`, usage) + service.extractSSEUsage(`data: {"type":"message_start","message":{"usage":{"input_tokens":10,"cache_read_input_tokens":9,"cache_creation_input_tokens":100,"cache_creation":{"ephemeral_1h_input_tokens":200}}}}`, usage) + for range 2 { + service.extractSSEUsage(`data: {"type":"message_delta","usage":{"input_tokens":0,"cache_read_input_tokens":0,"cache_creation_input_tokens":0}}`, usage) + } service.extractSSEUsage(`data: {"type":"message_delta","usage":{"cache_creation_input_tokens":null,"cache_creation":{"ephemeral_5m_input_tokens":50}}}`, usage) - require.Zero(t, usage.CacheCreationInputTokens) + require.Equal(t, 100, usage.CacheCreationInputTokens) + require.Equal(t, 9, usage.CacheReadInputTokens) + require.Equal(t, 10, usage.InputTokens) require.True(t, usage.cacheCreationInputTokensPresent) require.Equal(t, 50, usage.CacheCreation5mTokens) require.Equal(t, 200, usage.CacheCreation1hTokens) - assertAnthropicCacheCreationRecordCosts(t, *usage, 0) + assertAnthropicCacheCreationRecordCosts(t, *usage, 0.36) }) } +func TestAntigravityRawCacheUsageStreamingLifecycle(t *testing.T) { + gin.SetMode(gin.TestMode) + for _, test := range []struct { + name string + aggregate string + wantTotal int + wantCost float64 + }{ + {"zero aggregate keeps TTL billing fallback", "0", 0, 1.3}, + {"positive aggregate survives zero placeholders", "100", 100, 0.372}, + } { + for _, terminal := range []string{"message_stop", "eof"} { + t.Run(test.name+"/"+terminal, func(t *testing.T) { + stream := "event: message_start\ndata: " + `{"type":"message_start","message":{"id":"msg_cache","type":"message","role":"assistant","model":"claude-sonnet-4","content":[],"usage":{"input_tokens":10,"output_tokens":0,"cache_read_input_tokens":9,"cache_creation_input_tokens":` + test.aggregate + `,"cache_creation":{"ephemeral_1h_input_tokens":200}}}}` + "\n\n" + for _, snapshot := range []string{ + `{"output_tokens":7,"cache_creation":{"ephemeral_5m_input_tokens":50}}`, + `{"cache_creation":{"ephemeral_1h_input_tokens":300}}`, + `{"input_tokens":0,"output_tokens":0,"cache_read_input_tokens":0,"cache_creation_input_tokens":0}`, + `{"input_tokens":0,"output_tokens":0,"cache_read_input_tokens":0,"cache_creation_input_tokens":0}`, + `{"cache_creation_input_tokens":null,"cache_creation":{"ephemeral_5m_input_tokens":null,"ephemeral_1h_input_tokens":null}}`, + } { + stream += "event: message_delta\ndata: " + `{"type":"message_delta","usage":` + snapshot + "}\n\n" + } + stream += "event: message_delta\ndata: " + `{"type":"message_delta","delta":{"stop_reason":"end_turn"},"usage":{"output_tokens":0,"cache_creation_input_tokens":0}}` + "\n\n" + if terminal == "message_stop" { + stream += "event: message_stop\ndata: {\"type\":\"message_stop\"}\n\n" + } + recorder := httptest.NewRecorder() + ctx, _ := gin.CreateTestContext(recorder) + ctx.Request = httptest.NewRequest(http.MethodPost, "/v1/messages", nil) + response := &http.Response{ + StatusCode: http.StatusOK, Header: http.Header{"Content-Type": []string{"text/event-stream"}}, + Body: io.NopCloser(strings.NewReader(stream)), + } + service := &AntigravityGatewayService{httpUpstream: &httpUpstreamStub{resp: response}, settingService: &SettingService{}} + result, err := service.ForwardUpstream(context.Background(), ctx, + &Account{ID: 701, Credentials: map[string]any{"base_url": "https://upstream.example", "api_key": "test-key"}}, + []byte(`{"model":"claude-sonnet-4","messages":[],"stream":true}`)) + require.NoError(t, err) + require.True(t, result.Stream) + require.Equal(t, http.StatusOK, recorder.Code) + require.Equal(t, stream, recorder.Body.String()) + require.Equal(t, 10, result.Usage.InputTokens) + require.Equal(t, 7, result.Usage.OutputTokens) + require.Equal(t, 9, result.Usage.CacheReadInputTokens) + require.Equal(t, test.wantTotal, result.Usage.CacheCreationInputTokens) + require.True(t, result.Usage.cacheCreationInputTokensPresent) + require.Equal(t, 50, result.Usage.CacheCreation5mTokens) + require.Equal(t, 300, result.Usage.CacheCreation1hTokens) + assertAnthropicCacheCreationResultCosts(t, result, test.wantCost) + }) + } + } +} + func TestAnthropicCacheOnlyBufferedSSEUsage(t *testing.T) { gin.SetMode(gin.TestMode) for _, test := range []struct { @@ -567,54 +634,62 @@ func TestAnthropicCacheOnlyBufferedSSEUsage(t *testing.T) { delta string wantAggregate int }{ - {"explicit zero transition", `{"cache_creation_input_tokens":100,"cache_creation":{"ephemeral_1h_input_tokens":200}}`, `{"cache_creation_input_tokens":0}`, 0}, + {"explicit zero transition", `{"cache_creation_input_tokens":100,"cache_creation":{"ephemeral_1h_input_tokens":200}}`, `{"cache_creation_input_tokens":0}`, 100}, {"derived zero transition", `{"cache_creation":{"ephemeral_5m_input_tokens":20}}`, `{"cache_creation":{"ephemeral_5m_input_tokens":0}}`, 0}, {"merged partial TTL", `{"cache_creation":{"ephemeral_5m_input_tokens":20}}`, `{"cache_creation_input_tokens":null,"cache_creation":{"ephemeral_5m_input_tokens":null,"ephemeral_1h_input_tokens":30}}`, 50}, + {"explicit zero partial TTL", `{"cache_creation_input_tokens":0,"cache_creation":{"ephemeral_5m_input_tokens":20}}`, `{"cache_creation_input_tokens":0,"cache_creation":{"ephemeral_1h_input_tokens":30}}`, 50}, } { for _, adapter := range []string{"responses", "chat", "native responses", "native chat"} { - t.Run(test.name+"/"+adapter, func(t *testing.T) { - stream := "event: message_start\ndata: {\"type\":\"message_start\",\"message\":{\"id\":\"msg_cache\",\"type\":\"message\",\"role\":\"assistant\",\"model\":\"claude-sonnet-4\",\"content\":[],\"usage\":" + test.start + "}}\n\n" + - "event: message_delta\ndata: {\"type\":\"message_delta\",\"usage\":" + test.delta + "}\n\nevent: message_stop\ndata: {\"type\":\"message_stop\"}\n\n" - recorder := httptest.NewRecorder() - ctx, _ := gin.CreateTestContext(recorder) - response := &http.Response{Body: io.NopCloser(strings.NewReader(stream))} - var aggregate int - var err error - switch adapter { - case "responses": - var result *ForwardResult - result, err = (&GatewayService{}).handleResponsesBufferedStreamingResponse(response, ctx, "claude-sonnet-4", "claude-sonnet-4", nil, time.Now(), apicompat.ResponsesClientToolMapping{}) - require.NoError(t, err) - aggregate = result.Usage.CacheCreationInputTokens - case "chat": - var result *ForwardResult - result, err = (&GatewayService{}).handleCCBufferedFromAnthropic(response, ctx, "claude-sonnet-4", "claude-sonnet-4", nil, time.Now()) - require.NoError(t, err) - aggregate = result.Usage.CacheCreationInputTokens - case "native responses": - var result *OpenAIForwardResult - result, err = (&OpenAIGatewayService{}).handleResponsesBufferedFromNativeAnthropic(response, ctx, "claude-sonnet-4", "claude-sonnet-4", "claude-sonnet-4", nil, time.Now(), apicompat.ResponsesClientToolMapping{}) - require.NoError(t, err) - aggregate = result.Usage.CacheCreationInputTokens - case "native chat": - var result *OpenAIForwardResult - result, err = (&OpenAIGatewayService{}).handleCCBufferedFromNativeAnthropic(response, ctx, "claude-sonnet-4", "claude-sonnet-4", "claude-sonnet-4", nil, time.Now()) - require.NoError(t, err) - aggregate = result.Usage.CacheCreationInputTokens - } - require.Equal(t, test.wantAggregate, aggregate) - require.Equal(t, http.StatusOK, recorder.Code) - require.True(t, json.Valid(recorder.Body.Bytes())) - inputPath := "usage.input_tokens" - cachePath := "usage.cache_creation_input_tokens" - if strings.HasSuffix(adapter, "chat") { - inputPath = "usage.prompt_tokens" - cachePath = "usage.prompt_tokens_details.cache_creation_tokens" - } - require.True(t, gjson.GetBytes(recorder.Body.Bytes(), inputPath).Exists()) - require.Equal(t, int64(test.wantAggregate), gjson.GetBytes(recorder.Body.Bytes(), inputPath).Int()) - require.Equal(t, int64(test.wantAggregate), gjson.GetBytes(recorder.Body.Bytes(), cachePath).Int()) - }) + for _, terminal := range []string{"message_stop", "eof"} { + t.Run(test.name+"/"+adapter+"/"+terminal, func(t *testing.T) { + stream := "event: message_start\ndata: {\"type\":\"message_start\",\"message\":{\"id\":\"msg_cache\",\"type\":\"message\",\"role\":\"assistant\",\"model\":\"claude-sonnet-4\",\"content\":[],\"usage\":" + test.start + "}}\n\n" + for range 2 { + stream += "event: message_delta\ndata: {\"type\":\"message_delta\",\"usage\":" + test.delta + "}\n\n" + } + if terminal == "message_stop" { + stream += "event: message_stop\ndata: {\"type\":\"message_stop\"}\n\n" + } + recorder := httptest.NewRecorder() + ctx, _ := gin.CreateTestContext(recorder) + response := &http.Response{Body: io.NopCloser(strings.NewReader(stream))} + var aggregate int + var err error + switch adapter { + case "responses": + var result *ForwardResult + result, err = (&GatewayService{}).handleResponsesBufferedStreamingResponse(response, ctx, "claude-sonnet-4", "claude-sonnet-4", nil, time.Now(), apicompat.ResponsesClientToolMapping{}) + require.NoError(t, err) + aggregate = result.Usage.CacheCreationInputTokens + case "chat": + var result *ForwardResult + result, err = (&GatewayService{}).handleCCBufferedFromAnthropic(response, ctx, "claude-sonnet-4", "claude-sonnet-4", nil, time.Now()) + require.NoError(t, err) + aggregate = result.Usage.CacheCreationInputTokens + case "native responses": + var result *OpenAIForwardResult + result, err = (&OpenAIGatewayService{}).handleResponsesBufferedFromNativeAnthropic(response, ctx, "claude-sonnet-4", "claude-sonnet-4", "claude-sonnet-4", nil, time.Now(), apicompat.ResponsesClientToolMapping{}) + require.NoError(t, err) + aggregate = result.Usage.CacheCreationInputTokens + case "native chat": + var result *OpenAIForwardResult + result, err = (&OpenAIGatewayService{}).handleCCBufferedFromNativeAnthropic(response, ctx, "claude-sonnet-4", "claude-sonnet-4", "claude-sonnet-4", nil, time.Now()) + require.NoError(t, err) + aggregate = result.Usage.CacheCreationInputTokens + } + require.Equal(t, test.wantAggregate, aggregate) + require.Equal(t, http.StatusOK, recorder.Code) + require.True(t, json.Valid(recorder.Body.Bytes())) + inputPath := "usage.input_tokens" + cachePath := "usage.cache_creation_input_tokens" + if strings.HasSuffix(adapter, "chat") { + inputPath = "usage.prompt_tokens" + cachePath = "usage.prompt_tokens_details.cache_creation_tokens" + } + require.True(t, gjson.GetBytes(recorder.Body.Bytes(), inputPath).Exists()) + require.Equal(t, int64(test.wantAggregate), gjson.GetBytes(recorder.Body.Bytes(), inputPath).Int()) + require.Equal(t, int64(test.wantAggregate), gjson.GetBytes(recorder.Body.Bytes(), cachePath).Int()) + }) + } } } } diff --git a/backend/internal/service/gateway_cache_ttl_override_test.go b/backend/internal/service/gateway_cache_ttl_override_test.go index 6b7959ce1e..07e29bab44 100644 --- a/backend/internal/service/gateway_cache_ttl_override_test.go +++ b/backend/internal/service/gateway_cache_ttl_override_test.go @@ -17,6 +17,7 @@ import ( "github.com/Wei-Shaw/sub2api/internal/pkg/apicompat" "github.com/gin-gonic/gin" "github.com/stretchr/testify/require" + "github.com/tidwall/gjson" ) func TestApplyCacheTTLOverrideAuthoritativeTotal(t *testing.T) { @@ -28,7 +29,7 @@ func TestApplyCacheTTLOverrideAuthoritativeTotal(t *testing.T) { }{ {"partial details", ClaudeUsage{CacheCreationInputTokens: 11000, CacheCreation1hTokens: 3000, cacheCreationInputTokensPresent: true}, 11000, true}, {"oversized details", ClaudeUsage{CacheCreationInputTokens: 100, CacheCreation5mTokens: 50, CacheCreation1hTokens: 200, cacheCreationInputTokensPresent: true}, 100, true}, - {"explicit zero", ClaudeUsage{CacheCreation5mTokens: 50, CacheCreation1hTokens: 200, cacheCreationInputTokensPresent: true}, 0, true}, + {"explicit zero", ClaudeUsage{CacheCreation5mTokens: 50, CacheCreation1hTokens: 200, cacheCreationInputTokensPresent: true}, 250, true}, {"synthetic positive aggregate", ClaudeUsage{CacheCreationInputTokens: 11000, CacheCreation1hTokens: 3000}, 11000, true}, {"synthetic detail only", ClaudeUsage{CacheCreation5mTokens: 50, CacheCreation1hTokens: 200}, 250, true}, {"synthetic negative detail", ClaudeUsage{CacheCreation5mTokens: -50, CacheCreation1hTokens: 200}, 200, true}, @@ -68,9 +69,9 @@ type cacheTTLOverrideBoundaryCase struct { func cacheTTLOverrideBoundaryCases() []cacheTTLOverrideBoundaryCase { return []cacheTTLOverrideBoundaryCase{ {"growing aggregate", []string{`{"cache_creation_input_tokens":3000,"cache_creation":{"ephemeral_1h_input_tokens":3000}}`, `{"cache_creation_input_tokens":11000}`}, 11000, true, 0, 3000, 28}, - {"explicit zero delta", []string{`{"cache_creation_input_tokens":3000,"cache_creation":{"ephemeral_1h_input_tokens":3000}}`, `{"cache_creation_input_tokens":0}`}, 0, true, 0, 3000, 0}, + {"explicit zero delta", []string{`{"cache_creation_input_tokens":3000,"cache_creation":{"ephemeral_1h_input_tokens":3000}}`, `{"cache_creation_input_tokens":0}`}, 3000, true, 0, 3000, 12}, {"oversized details", []string{`{"cache_creation_input_tokens":100,"cache_creation":{"ephemeral_5m_input_tokens":50,"ephemeral_1h_input_tokens":200}}`}, 100, true, 50, 200, 0.36}, - {"explicit zero snapshot", []string{`{"cache_creation_input_tokens":0,"cache_creation":{"ephemeral_5m_input_tokens":50,"ephemeral_1h_input_tokens":200}}`}, 0, true, 50, 200, 0}, + {"explicit zero snapshot", []string{`{"cache_creation_input_tokens":0,"cache_creation":{"ephemeral_5m_input_tokens":50,"ephemeral_1h_input_tokens":200}}`}, 250, true, 50, 200, 0.9}, {"detail only", []string{`{"cache_creation":{"ephemeral_5m_input_tokens":50,"ephemeral_1h_input_tokens":200}}`}, 250, false, 50, 200, 0.9}, {"null aggregate", []string{`{"cache_creation_input_tokens":null,"cache_creation":{"ephemeral_5m_input_tokens":50,"ephemeral_1h_input_tokens":200}}`}, 250, false, 50, 200, 0.9}, {"aggregate only", []string{`{"cache_creation_input_tokens":11000}`}, 11000, true, 0, 0, 22}, @@ -101,7 +102,11 @@ func cacheTTLOverrideBoundaryResponse(test cacheTTLOverrideBoundaryCase, stream if !stream { cache := `"cache_creation":{"ephemeral_5m_input_tokens":` + strconv.Itoa(test.ttl5m) + `,"ephemeral_1h_input_tokens":` + strconv.Itoa(test.ttl1h) + `}` if test.present { - cache += `,"cache_creation_input_tokens":` + strconv.Itoa(test.aggregate) + aggregate := test.aggregate + if len(test.snapshots) == 1 { + aggregate = int(gjson.Get(test.snapshots[0], "cache_creation_input_tokens").Int()) + } + cache += `,"cache_creation_input_tokens":` + strconv.Itoa(aggregate) } return `{"id":"msg_cache","type":"message","role":"assistant","model":"k3","content":[],"usage":{` + base + `,` + cache + `}}` } @@ -178,7 +183,46 @@ func TestCacheTTLOverrideForwardBillingBoundary(t *testing.T) { } else if target == "1h" { want5m, want1h, wantCost = 0, test.aggregate, float64(test.aggregate)*0.004 } - if target != "" && (route == "nonstream" || (route == "standard" && test.aggregate > 0)) { + if target != "" && route == "standard" { + var originalEvents, rewrittenEvents []string + for _, line := range strings.Split(payload, "\n") { + if strings.HasPrefix(line, "data: ") { + originalEvents = append(originalEvents, strings.TrimPrefix(line, "data: ")) + } + } + for _, line := range strings.Split(recorder.Body.String(), "\n") { + if strings.HasPrefix(line, "data: ") { + rewrittenEvents = append(rewrittenEvents, strings.TrimPrefix(line, "data: ")) + } + } + require.Len(t, rewrittenEvents, len(originalEvents)) + forward5m, forward1h := 0, 0 + for index, originalEvent := range originalEvents { + usagePath := "usage" + if gjson.Get(originalEvent, "type").String() == "message_start" { + usagePath = "message.usage" + } + originalUsage := gjson.Get(originalEvent, usagePath) + rewrittenUsage := gjson.Get(rewrittenEvents[index], usagePath) + require.Equal(t, originalUsage.Get("cache_creation").Exists(), rewrittenUsage.Get("cache_creation").Exists()) + require.Equal(t, originalUsage.Get("cache_creation_input_tokens").Raw, rewrittenUsage.Get("cache_creation_input_tokens").Raw) + if originalUsage.Get("cache_creation").IsObject() { + total := int(originalUsage.Get("cache_creation_input_tokens").Int()) + if total <= 0 { + total = int(originalUsage.Get("cache_creation.ephemeral_5m_input_tokens").Int() + originalUsage.Get("cache_creation.ephemeral_1h_input_tokens").Int()) + } + forward5m, forward1h = 0, total + if target == "5m" { + forward5m, forward1h = total, 0 + } + require.EqualValues(t, forward5m, rewrittenUsage.Get("cache_creation.ephemeral_5m_input_tokens").Int()) + require.EqualValues(t, forward1h, rewrittenUsage.Get("cache_creation.ephemeral_1h_input_tokens").Int()) + } + } + require.Equal(t, forward5m, result.Usage.CacheCreation5mTokens) + require.Equal(t, forward1h, result.Usage.CacheCreation1hTokens) + } + if target != "" && route == "nonstream" { require.Equal(t, want5m, result.Usage.CacheCreation5mTokens) require.Equal(t, want1h, result.Usage.CacheCreation1hTokens) } @@ -262,11 +306,14 @@ func TestRewriteCacheCreationJSONAuthoritativeTotal(t *testing.T) { } require.NoError(t, json.Unmarshal([]byte(cacheTTLOverrideBoundaryResponse(test, false, 0)), &response)) aggregate, present := response.Usage["cache_creation_input_tokens"] - require.True(t, rewriteCacheCreationJSON(response.Usage, target)) + originalDetails := response.Usage["cache_creation"].(map[string]any) + original5m := int(originalDetails["ephemeral_5m_input_tokens"].(float64)) + original1h := int(originalDetails["ephemeral_1h_input_tokens"].(float64)) want5m, want1h := 0, test.aggregate if target == "5m" { want5m, want1h = test.aggregate, 0 } + require.Equal(t, original5m != want5m || original1h != want1h, rewriteCacheCreationJSON(response.Usage, target)) details := response.Usage["cache_creation"].(map[string]any) require.EqualValues(t, want5m, details["ephemeral_5m_input_tokens"]) require.EqualValues(t, want1h, details["ephemeral_1h_input_tokens"]) @@ -278,3 +325,72 @@ func TestRewriteCacheCreationJSONAuthoritativeTotal(t *testing.T) { } } } + +func TestRewriteCacheCreationJSONPreservesAbsentDetails(t *testing.T) { + for _, payload := range []string{ + `{"cache_creation_input_tokens":100}`, + `{"cache_creation_input_tokens":100,"cache_creation":null}`, + `{"cache_creation_input_tokens":0}`, + } { + for _, target := range []string{"5m", "1h"} { + var usage map[string]any + require.NoError(t, json.Unmarshal([]byte(payload), &usage)) + for range 2 { + require.False(t, rewriteCacheCreationJSON(usage, target)) + encoded, err := json.Marshal(usage) + require.NoError(t, err) + require.JSONEq(t, payload, string(encoded)) + } + } + } +} + +func TestCacheTTLOverrideForwardPreservesAbsentDetails(t *testing.T) { + gin.SetMode(gin.TestMode) + for _, details := range []string{"", `,"cache_creation":null`} { + for _, stream := range []bool{false, true} { + for _, target := range []string{"5m", "1h"} { + t.Run(details+"/stream="+strconv.FormatBool(stream)+"/"+target, func(t *testing.T) { + account, settings, _ := cacheTTLOverrideBoundaryAccount(t, "account/"+target) + usage := `{"input_tokens":10,"output_tokens":2,"cache_creation_input_tokens":100` + details + `}` + payload := `{"id":"msg_cache","type":"message","role":"assistant","model":"k3","content":[],"usage":` + usage + `}` + contentType := "application/json" + if stream { + payload = "event: message_start\ndata: {\"type\":\"message_start\",\"message\":" + payload + "}\n\nevent: message_stop\ndata: {\"type\":\"message_stop\"}\n\n" + contentType = "text/event-stream" + } + recorder := httptest.NewRecorder() + ctx, _ := gin.CreateTestContext(recorder) + ctx.Request = httptest.NewRequest(http.MethodPost, "/v1/messages", nil) + response := &http.Response{StatusCode: http.StatusOK, Header: http.Header{"Content-Type": []string{contentType}}, Body: io.NopCloser(strings.NewReader(payload))} + service := &GatewayService{cfg: &config.Config{}, rateLimitService: &RateLimitService{}, settingService: settings} + var err error + if stream { + _, err = service.handleStreamingResponse(context.Background(), response, ctx, account, time.Now(), "k3", "k3", false) + } else { + _, err = service.handleNonStreamingResponse(context.Background(), response, ctx, account, "k3", "k3") + } + require.NoError(t, err) + if !stream { + require.JSONEq(t, payload, recorder.Body.String()) + return + } + starts := 0 + for _, line := range strings.Split(recorder.Body.String(), "\n") { + if !strings.HasPrefix(line, "data: ") { + continue + } + event := gjson.Parse(strings.TrimPrefix(line, "data: ")) + if event.Get("type").String() == "message_start" { + got := event.Get("message.usage.cache_creation") + require.False(t, got.IsObject()) + require.Equal(t, gjson.Get(usage, "cache_creation").Raw, got.Raw) + starts++ + } + } + require.Equal(t, 1, starts) + }) + } + } + } +} diff --git a/backend/internal/service/gateway_forward_as_responses.go b/backend/internal/service/gateway_forward_as_responses.go index cb492392c2..b2d12332d3 100644 --- a/backend/internal/service/gateway_forward_as_responses.go +++ b/backend/internal/service/gateway_forward_as_responses.go @@ -324,7 +324,7 @@ func mergeAnthropicUsage(dst *ClaudeUsage, src apicompat.AnthropicUsage) { dst.InputTokens = src.InputTokens } } - if hasCacheReadTokens { + if hasCacheReadTokens && (cacheReadTokens > 0 || dst.CacheReadInputTokens <= 0) { dst.CacheReadInputTokens = cacheReadTokens } normalizeAnthropicPromptTotal(dst, src.PromptTokens, src.PromptCacheMissTokens) @@ -349,9 +349,10 @@ func normalizeAnthropicPromptTotal(usage *ClaudeUsage, promptTokens int, promptC } func mergeAnthropicCacheCreationUsage(dst *ClaudeUsage, src apicompat.AnthropicUsage) { - if src.HasCacheCreationInputTokens() { + if src.HasCacheCreationInputTokens() && (src.CacheCreationInputTokens > 0 || dst.CacheCreationInputTokens <= 0) { dst.CacheCreationInputTokens = max(src.CacheCreationInputTokens, 0) dst.cacheCreationInputTokensPresent = true + dst.cacheCreationInputTokensFromDetails = false } if src.CacheCreation != nil { if src.CacheCreation.Ephemeral5mInputTokens != nil { @@ -360,8 +361,9 @@ func mergeAnthropicCacheCreationUsage(dst *ClaudeUsage, src apicompat.AnthropicU if src.CacheCreation.Ephemeral1hInputTokens != nil { dst.CacheCreation1hTokens = max(*src.CacheCreation.Ephemeral1hInputTokens, 0) } - if !dst.cacheCreationInputTokensPresent && (src.CacheCreation.Ephemeral5mInputTokens != nil || src.CacheCreation.Ephemeral1hInputTokens != nil) { + if (!dst.cacheCreationInputTokensPresent || dst.cacheCreationInputTokensFromDetails || dst.CacheCreationInputTokens <= 0) && (src.CacheCreation.Ephemeral5mInputTokens != nil || src.CacheCreation.Ephemeral1hInputTokens != nil) { dst.CacheCreationInputTokens = dst.CacheCreation5mTokens + dst.CacheCreation1hTokens + dst.cacheCreationInputTokensFromDetails = true } } } @@ -401,6 +403,7 @@ func normalizeAnthropicEventUsageForResponses(event *apicompat.AnthropicStreamEv dst.CacheReadInputTokens = usage.CacheReadInputTokens dst.CacheCreationInputTokens = usage.CacheCreationInputTokens dst.CacheCreationInputTokensPresent = true + dst.CacheCreation = nil } normalize(event.Usage) if event.Message != nil { diff --git a/backend/internal/service/gateway_forward_as_responses_test.go b/backend/internal/service/gateway_forward_as_responses_test.go index 13416b719a..c35bf0b749 100644 --- a/backend/internal/service/gateway_forward_as_responses_test.go +++ b/backend/internal/service/gateway_forward_as_responses_test.go @@ -376,10 +376,10 @@ func TestHandleResponsesStreamingResponse_NormalizesTerminalUsage(t *testing.T) wantInput: 10, wantOutput: 7, wantCacheCreation: 100, }, { - name: "explicit zero survives contradictory TTL breakdown", + name: "explicit zero falls back to TTL breakdown", startUsage: `"input_tokens":10,"cache_creation_input_tokens":0,"cache_creation":{"ephemeral_1h_input_tokens":200}`, deltaUsage: `"output_tokens":7,"cache_creation":{"ephemeral_1h_input_tokens":200}`, - wantInput: 10, wantOutput: 7, + wantInput: 10, wantOutput: 7, wantCacheCreation: 200, }, { name: "null aggregate and TTL preserve partial snapshots", @@ -391,7 +391,13 @@ func TestHandleResponsesStreamingResponse_NormalizesTerminalUsage(t *testing.T) name: "null does not clear explicit aggregate zero", startUsage: `"input_tokens":10,"cache_creation_input_tokens":0,"cache_creation":{"ephemeral_1h_input_tokens":200}`, deltaUsage: `"output_tokens":7,"cache_creation_input_tokens":null,"cache_creation":{"ephemeral_1h_input_tokens":null}`, - wantInput: 10, wantOutput: 7, + wantInput: 10, wantOutput: 7, wantCacheCreation: 200, + }, + { + name: "zero placeholders preserve normalized prompt total", + startUsage: `"input_tokens":100,"prompt_tokens":100,"cache_read_input_tokens":30,"cache_creation_input_tokens":0,"cache_creation":{"ephemeral_5m_input_tokens":20}`, + deltaUsage: `"input_tokens":0,"output_tokens":7,"cache_read_input_tokens":0,"cache_creation_input_tokens":0,"cache_creation":{"ephemeral_1h_input_tokens":10}`, + wantInput: 40, wantOutput: 7, wantCached: 30, wantCacheCreation: 30, }, } diff --git a/backend/internal/service/gateway_service.go b/backend/internal/service/gateway_service.go index b20b006a24..30499271dc 100644 --- a/backend/internal/service/gateway_service.go +++ b/backend/internal/service/gateway_service.go @@ -605,9 +605,10 @@ type ClaudeUsage struct { CacheCreation1hTokens int // 1小时缓存创建token(来自嵌套 cache_creation 对象) ImageOutputTokens int `json:"image_output_tokens,omitempty"` - cacheCreationInputTokensPresent bool - promptTotalTokens int - promptTotalPresent bool + cacheCreationInputTokensPresent bool + cacheCreationInputTokensFromDetails bool + promptTotalTokens int + promptTotalPresent bool } // ForwardResult 转发结果 diff --git a/backend/internal/service/gateway_upstream_response.go b/backend/internal/service/gateway_upstream_response.go index 3049f3b3d7..81b6809aea 100644 --- a/backend/internal/service/gateway_upstream_response.go +++ b/backend/internal/service/gateway_upstream_response.go @@ -1304,11 +1304,12 @@ func mergeSSEUsagePatch(usage *ClaudeUsage, patch *sseUsagePatch) { if patch.hasInputTokens { usage.InputTokens = patch.inputTokens } - if patch.hasCacheCreationInput { + if patch.hasCacheCreationInput && (patch.cacheCreationInputTokens > 0 || usage.CacheCreationInputTokens <= 0) { usage.CacheCreationInputTokens = patch.cacheCreationInputTokens usage.cacheCreationInputTokensPresent = true + usage.cacheCreationInputTokensFromDetails = false } - if patch.hasCacheReadInput { + if patch.hasCacheReadInput && (patch.cacheReadInputTokens > 0 || usage.CacheReadInputTokens <= 0) { usage.CacheReadInputTokens = patch.cacheReadInputTokens } if patch.hasOutputTokens { @@ -1320,8 +1321,9 @@ func mergeSSEUsagePatch(usage *ClaudeUsage, patch *sseUsagePatch) { if patch.hasCacheCreation1h { usage.CacheCreation1hTokens = patch.cacheCreation1hTokens } - if !usage.cacheCreationInputTokensPresent && (patch.hasCacheCreation5m || patch.hasCacheCreation1h) { + if (!usage.cacheCreationInputTokensPresent || usage.cacheCreationInputTokensFromDetails || usage.CacheCreationInputTokens <= 0) && (patch.hasCacheCreation5m || patch.hasCacheCreation1h) { usage.CacheCreationInputTokens = max(usage.CacheCreation5mTokens, 0) + max(usage.CacheCreation1hTokens, 0) + usage.cacheCreationInputTokensFromDetails = true } normalizeAnthropicPromptTotal(usage, patch.promptTokens, patch.promptCacheMissTokens) } @@ -1357,7 +1359,7 @@ func parseSSEUsageInt(value any) (int, bool) { // target 为 "5m" 或 "1h"。返回 true 表示发生了变更。 func applyCacheTTLOverride(usage *ClaudeUsage, target string) bool { total := max(usage.CacheCreationInputTokens, 0) - if !usage.cacheCreationInputTokensPresent && total == 0 { + if total == 0 { total = max(usage.CacheCreation5mTokens, 0) + max(usage.CacheCreation1hTokens, 0) } switch target { @@ -1381,6 +1383,9 @@ func applyCacheTTLOverride(usage *ClaudeUsage, target string) bool { // usageObj 是 usage JSON 对象(map[string]any)。 func rewriteCacheCreationJSON(usageObj map[string]any, target string) bool { ccObj, _ := usageObj["cache_creation"].(map[string]any) + if ccObj == nil { + return false + } v5m, _ := parseSSEUsageInt(ccObj["ephemeral_5m_input_tokens"]) v1h, _ := parseSSEUsageInt(ccObj["ephemeral_1h_input_tokens"]) aggregate, present := parseSSEUsageInt(usageObj["cache_creation_input_tokens"]) @@ -1393,10 +1398,6 @@ func rewriteCacheCreationJSON(usageObj map[string]any, target string) bool { if !applyCacheTTLOverride(&usage, target) { return false } - if ccObj == nil { - ccObj = make(map[string]any) - usageObj["cache_creation"] = ccObj - } ccObj["ephemeral_5m_input_tokens"] = float64(usage.CacheCreation5mTokens) ccObj["ephemeral_1h_input_tokens"] = float64(usage.CacheCreation1hTokens) return true @@ -1457,7 +1458,7 @@ func (s *GatewayService) handleNonStreamingResponse(ctx context.Context, resp *h // Cache TTL Override: 重写 non-streaming 响应中的 cache_creation 分类。 // 账号级设置优先;全局 1h 请求注入开启时,默认把 usage 计费归回 5m。 if overrideTarget, ok := s.resolveCacheTTLUsageOverrideTarget(ctx, account); ok { - if applyCacheTTLOverride(&response.Usage, overrideTarget) { + if changed := applyCacheTTLOverride(&response.Usage, overrideTarget); changed && gjson.GetBytes(body, "usage.cache_creation").IsObject() { // 同步更新 body JSON 中的嵌套 cache_creation 对象 if newBody, err := sjson.SetBytes(body, "usage.cache_creation.ephemeral_5m_input_tokens", response.Usage.CacheCreation5mTokens); err == nil { body = newBody diff --git a/backend/internal/service/gateway_usage_billing.go b/backend/internal/service/gateway_usage_billing.go index a280c1fcca..de31a2dac0 100644 --- a/backend/internal/service/gateway_usage_billing.go +++ b/backend/internal/service/gateway_usage_billing.go @@ -1243,22 +1243,20 @@ func (s *GatewayService) calculateImageCost( return s.billingService.CalculateImageCost(billingModel, sizeTier, result.ImageCount, groupConfig, multiplier) } -// billingUsageTokens projects explicit aggregate zero to effective zero TTL usage -// for billing and account stats, retaining raw TTL details on ClaudeUsage. func (usage ClaudeUsage) billingUsageTokens() UsageTokens { + creationTokens := usage.CacheCreationInputTokens + if creationTokens <= 0 { + creationTokens = max(usage.CacheCreation5mTokens, 0) + max(usage.CacheCreation1hTokens, 0) + } tokens := UsageTokens{ InputTokens: usage.InputTokens, OutputTokens: usage.OutputTokens, - CacheCreationTokens: usage.CacheCreationInputTokens, + CacheCreationTokens: creationTokens, CacheReadTokens: usage.CacheReadInputTokens, CacheCreation5mTokens: usage.CacheCreation5mTokens, CacheCreation1hTokens: usage.CacheCreation1hTokens, ImageOutputTokens: usage.ImageOutputTokens, } - if usage.cacheCreationInputTokensPresent && usage.CacheCreationInputTokens == 0 { - tokens.CacheCreation5mTokens = 0 - tokens.CacheCreation1hTokens = 0 - } return tokens } diff --git a/backend/internal/service/openai_gateway_native_cache_creation_test.go b/backend/internal/service/openai_gateway_native_cache_creation_test.go index 121ade7a25..63bfcf6c00 100644 --- a/backend/internal/service/openai_gateway_native_cache_creation_test.go +++ b/backend/internal/service/openai_gateway_native_cache_creation_test.go @@ -32,7 +32,7 @@ func TestNativeAnthropicCacheCreationRouteBillingBoundary(t *testing.T) { {"missing cache creation usage", []string{`{}`}, 0, 0, 0, 0, 0, 10}, {"missing aggregate", []string{`{"cache_creation":{"ephemeral_5m_input_tokens":20,"ephemeral_1h_input_tokens":30}}`}, 50, 20, 30, 20, 30, 10}, {"null aggregate", []string{`{"cache_creation_input_tokens":null,"cache_creation":{"ephemeral_5m_input_tokens":20,"ephemeral_1h_input_tokens":30}}`}, 50, 20, 30, 20, 30, 10}, - {"explicit zero", []string{`{"cache_creation_input_tokens":0,"cache_creation":{"ephemeral_5m_input_tokens":20,"ephemeral_1h_input_tokens":30}}`}, 0, 20, 30, 0, 0, 10}, + {"explicit zero", []string{`{"cache_creation_input_tokens":0,"cache_creation":{"ephemeral_5m_input_tokens":20,"ephemeral_1h_input_tokens":30}}`}, 50, 20, 30, 20, 30, 10}, {"details below aggregate", []string{`{"cache_creation_input_tokens":100,"cache_creation":{"ephemeral_5m_input_tokens":20,"ephemeral_1h_input_tokens":30}}`}, 100, 20, 30, 70, 30, 10}, {"aggregate grows without TTL", []string{`{"cache_creation_input_tokens":3000,"cache_creation":{"ephemeral_5m_input_tokens":3000}}`, `{"cache_creation_input_tokens":11000}`}, 11000, 3000, 0, 11000, 0, 10}, {"1h start unknown remainder uses 5m", []string{`{"cache_creation_input_tokens":3000,"cache_creation":{"ephemeral_1h_input_tokens":3000}}`, `{"cache_creation_input_tokens":11000}`}, 11000, 0, 3000, 8000, 3000, 10}, @@ -40,11 +40,12 @@ func TestNativeAnthropicCacheCreationRouteBillingBoundary(t *testing.T) { {"contradictory aggregate", []string{`{"cache_creation_input_tokens":100,"cache_creation":{"ephemeral_5m_input_tokens":50,"ephemeral_1h_input_tokens":200}}`}, 100, 50, 200, 20, 80, 10}, {"negative TTL", []string{`{"cache_creation":{"ephemeral_5m_input_tokens":-20,"ephemeral_1h_input_tokens":30}}`}, 30, 0, 30, 0, 30, 10}, {"partial TTL clear", []string{`{"cache_creation":{"ephemeral_5m_input_tokens":20}}`, `{"cache_creation":{"ephemeral_1h_input_tokens":30}}`, `{"cache_creation":{"ephemeral_5m_input_tokens":0}}`}, 30, 0, 30, 0, 30, 10}, - {"explicit zero delta", []string{`{"cache_creation_input_tokens":100,"cache_creation":{"ephemeral_5m_input_tokens":20,"ephemeral_1h_input_tokens":30}}`, `{"cache_creation_input_tokens":0}`, `{"cache_creation":{"ephemeral_1h_input_tokens":40}}`}, 0, 20, 40, 0, 0, 10}, + {"explicit zero delta", []string{`{"cache_creation_input_tokens":100,"cache_creation":{"ephemeral_5m_input_tokens":20,"ephemeral_1h_input_tokens":30}}`, `{"cache_creation_input_tokens":0,"cache_read_input_tokens":0,"input_tokens":0}`, `{"cache_creation":{"ephemeral_1h_input_tokens":40}}`}, 100, 20, 40, 60, 40, 10}, {"zero to positive", []string{`{"cache_creation_input_tokens":0,"cache_creation":{"ephemeral_5m_input_tokens":20,"ephemeral_1h_input_tokens":30}}`, `{"cache_creation_input_tokens":40}`}, 40, 20, 30, 16, 24, 10}, {"null preserves aggregate", []string{`{"cache_creation_input_tokens":100,"cache_creation":{"ephemeral_5m_input_tokens":20,"ephemeral_1h_input_tokens":30}}`, `{"cache_creation_input_tokens":null,"cache_creation":{"ephemeral_1h_input_tokens":40}}`}, 100, 20, 40, 60, 40, 10}, {"normalized prompt total", []string{`{"prompt_tokens":100,"cached_tokens":7,"cache_creation":{"ephemeral_5m_input_tokens":20,"ephemeral_1h_input_tokens":30}}`}, 50, 20, 30, 20, 30, 43}, - {"normalized prompt explicit zero", []string{`{"prompt_tokens":100,"cached_tokens":7,"cache_creation_input_tokens":0,"cache_creation":{"ephemeral_5m_input_tokens":20,"ephemeral_1h_input_tokens":30}}`}, 0, 20, 30, 0, 0, 93}, + {"normalized prompt explicit zero", []string{`{"prompt_tokens":100,"cached_tokens":7,"cache_creation_input_tokens":0,"cache_creation":{"ephemeral_5m_input_tokens":20,"ephemeral_1h_input_tokens":30}}`}, 50, 20, 30, 20, 30, 43}, + {"normalized prompt partial zero deltas", []string{`{"prompt_tokens":100,"cache_creation_input_tokens":0,"cache_creation":{"ephemeral_5m_input_tokens":20}}`, `{"cache_creation_input_tokens":0,"cache_read_input_tokens":0,"cache_creation":{"ephemeral_1h_input_tokens":30}}`}, 50, 20, 30, 20, 30, 43}, } { uncachedInput := test.uncached for _, route := range []string{"messages", "chat", "responses"} { diff --git a/backend/internal/service/openai_gateway_usage.go b/backend/internal/service/openai_gateway_usage.go index 21597489cb..59f0374a01 100644 --- a/backend/internal/service/openai_gateway_usage.go +++ b/backend/internal/service/openai_gateway_usage.go @@ -152,21 +152,21 @@ func groupBillsOpenAIFastAtStandard(apiKey *APIKey, account *Account, serviceTie } func (usage OpenAIUsage) billingUsageTokens() UsageTokens { + creationTokens := usage.CacheCreationInputTokens + if creationTokens <= 0 { + creationTokens = max(usage.CacheCreation5mTokens, 0) + max(usage.CacheCreation1hTokens, 0) + } tokens := UsageTokens{ - InputTokens: max(usage.InputTokens-usage.CacheReadInputTokens-usage.CacheCreationInputTokens, 0), + InputTokens: max(usage.InputTokens-usage.CacheReadInputTokens-creationTokens, 0), ImageInputTokens: max(usage.ImageInputTokens-usage.ImageCacheReadTokens, 0), ImageCacheReadTokens: usage.ImageCacheReadTokens, OutputTokens: usage.OutputTokens, - CacheCreationTokens: usage.CacheCreationInputTokens, + CacheCreationTokens: creationTokens, CacheCreation5mTokens: usage.CacheCreation5mTokens, CacheCreation1hTokens: usage.CacheCreation1hTokens, CacheReadTokens: usage.CacheReadInputTokens, ImageOutputTokens: usage.ImageOutputTokens, } - if usage.cacheCreationInputTokensPresent && usage.CacheCreationInputTokens == 0 { - tokens.CacheCreation5mTokens = 0 - tokens.CacheCreation1hTokens = 0 - } return tokens } From 4656364337fdadb4d4a8250f082fefe3445be041 Mon Sep 17 00:00:00 2001 From: wucm667 Date: Fri, 6 Nov 2026 12:13:35 +0800 Subject: [PATCH 08/85] test(usage): assert incomplete cache streams and isolate allocation guard --- .../gateway_cache_creation_usage_test.go | 21 +++++++++++++++---- .../openai_responses_tool_schema_test.go | 15 +++++++++++-- 2 files changed, 30 insertions(+), 6 deletions(-) diff --git a/backend/internal/service/gateway_cache_creation_usage_test.go b/backend/internal/service/gateway_cache_creation_usage_test.go index b45e6fdcc0..03a8871b64 100644 --- a/backend/internal/service/gateway_cache_creation_usage_test.go +++ b/backend/internal/service/gateway_cache_creation_usage_test.go @@ -5,6 +5,7 @@ package service import ( "context" "encoding/json" + "fmt" "io" "net/http" "net/http/httptest" @@ -658,25 +659,37 @@ func TestAnthropicCacheOnlyBufferedSSEUsage(t *testing.T) { case "responses": var result *ForwardResult result, err = (&GatewayService{}).handleResponsesBufferedStreamingResponse(response, ctx, "claude-sonnet-4", "claude-sonnet-4", nil, time.Now(), apicompat.ResponsesClientToolMapping{}) - require.NoError(t, err) + 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.NoError(t, err) + 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.NoError(t, err) + 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.NoError(t, err) + 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" diff --git a/backend/internal/service/openai_responses_tool_schema_test.go b/backend/internal/service/openai_responses_tool_schema_test.go index 7b1714e30d..06da6635d5 100644 --- a/backend/internal/service/openai_responses_tool_schema_test.go +++ b/backend/internal/service/openai_responses_tool_schema_test.go @@ -2,6 +2,8 @@ package service import ( "encoding/json" + "os" + "os/exec" "strconv" "testing" @@ -587,6 +589,17 @@ func buildToolSchemaNullTypeBody(t *testing.T, hits int) []byte { // 构造请求可以塞进百万级命中,会被放大成 TB 级 memcpy。这里用分配次数锁死该行为: // 命中数放大 500 倍,分配次数不得随之增长。 func TestSanitizeOpenAIResponsesToolParameterTypes_RewriteCountIndependentOfHits(t *testing.T) { + const isolatedAllocEnv = "SUB2API_TOOL_SCHEMA_ALLOC_ISOLATED" + if os.Getenv(isolatedAllocEnv) != "1" { + executable, err := os.Executable() + require.NoError(t, err) + command := exec.Command(executable, "-test.run=^"+t.Name()+"$", "-test.count=1", "-test.timeout=1m") + command.Env = append(os.Environ(), isolatedAllocEnv+"=1") + output, err := command.CombinedOutput() + require.NoError(t, err, "isolated allocation guard failed:\n%s", output) + return + } + small := buildToolSchemaNullTypeBody(t, 4) large := buildToolSchemaNullTypeBody(t, 2000) @@ -598,8 +611,6 @@ func TestSanitizeOpenAIResponsesToolParameterTypes_RewriteCountIndependentOfHits }) // 命中切片扩容是对数级,留出充裕余量;线性写法在这里会是 2000 量级。 - // 干净环境实测 large 约 17 allocs,200 是 10 倍余量,同时容忍 CI 慢 pod 上 - // 包内后台 goroutine(日志/ticker)对进程级 Mallocs 的噪声污染。 require.Less(t, largeAllocs, 200.0, "分配次数随命中数线性增长,说明退回了逐路径全量重写 (small=%v large=%v)", smallAllocs, largeAllocs) From 189b336f47133dabe68ad0fa5d2c35a128210c73 Mon Sep 17 00:00:00 2001 From: WGeorgezzzz <257936154+WGeorgezzzz@users.noreply.github.com> Date: Sat, 7 Nov 2026 19:45:33 +0800 Subject: [PATCH 09/85] fix(openai): enforce stream idle deadlines and pre-output failover --- .../openai_gateway_response_handling.go | 22 +++-- .../openai_stream_idle_timeout_test.go | 84 +++++++++++++++++++ 2 files changed, 100 insertions(+), 6 deletions(-) create mode 100644 backend/internal/service/openai_stream_idle_timeout_test.go diff --git a/backend/internal/service/openai_gateway_response_handling.go b/backend/internal/service/openai_gateway_response_handling.go index a2b0fae6a2..3d3e868400 100644 --- a/backend/internal/service/openai_gateway_response_handling.go +++ b/backend/internal/service/openai_gateway_response_handling.go @@ -186,14 +186,14 @@ func (s *OpenAIGatewayService) handleStreamingResponseWithReasoning(ctx context. streamInterval = resolveGrokStreamIdleTimeout(cfgSec) } // 仅监控上游数据间隔超时,不被下游写入阻塞影响 - var intervalTicker *time.Ticker + var intervalTimer *time.Timer if streamInterval > 0 { - intervalTicker = time.NewTicker(streamInterval) - defer intervalTicker.Stop() + intervalTimer = time.NewTimer(streamInterval) + defer intervalTimer.Stop() } var intervalCh <-chan time.Time - if intervalTicker != nil { - intervalCh = intervalTicker.C + if intervalTimer != nil { + intervalCh = intervalTimer.C } keepaliveInterval := time.Duration(0) @@ -937,7 +937,9 @@ func (s *OpenAIGatewayService) handleStreamingResponseWithReasoning(ctx context. return resultWithUsage(), fmt.Errorf("upstream response failed: %s", failedMessage) } lastRead := time.Unix(0, atomic.LoadInt64(&lastReadAt)) - if time.Since(lastRead) < streamInterval { + if remaining := streamInterval - time.Since(lastRead); remaining > 0 { + // Re-arm for the actual last-read deadline. + intervalTimer.Reset(remaining) continue } if codexFailureTerminal && sawBareError && !sawResponseFailed { @@ -952,6 +954,14 @@ func (s *OpenAIGatewayService) handleStreamingResponseWithReasoning(ctx context. if s.rateLimitService != nil { s.rateLimitService.HandleStreamTimeout(ctx, account, originalModel) } + if account != nil && account.Platform == PlatformOpenAI && + !openAIStreamClientOutputStarted(c, clientOutputStarted) && !eventShouldFlush { + _ = resp.Body.Close() + return resultWithUsage(), s.newOpenAIStreamFailoverErrorWithModel( + c, account, false, upstreamRequestID, nil, + "OpenAI upstream stream idle timeout before model output", mappedModel, resp.Header, + ) + } // Grok: short cool + account failover when no client-visible bytes // were committed yet (pre-commit). After output started we keep the // legacy stream_timeout path so partial SSE is not dual-written. diff --git a/backend/internal/service/openai_stream_idle_timeout_test.go b/backend/internal/service/openai_stream_idle_timeout_test.go new file mode 100644 index 0000000000..6338c25041 --- /dev/null +++ b/backend/internal/service/openai_stream_idle_timeout_test.go @@ -0,0 +1,84 @@ +package service + +import ( + "errors" + "io" + "net/http" + "net/http/httptest" + "testing" + "time" + + "github.com/Wei-Shaw/sub2api/internal/config" + "github.com/gin-gonic/gin" + "github.com/stretchr/testify/require" +) + +func TestRelayStallsIdleDeadlineTracksLastRead(t *testing.T) { + gin.SetMode(gin.TestMode) + svc := &OpenAIGatewayService{cfg: &config.Config{Gateway: config.GatewayConfig{ + MaxLineSize: defaultMaxLineSize, StreamDataIntervalTimeout: 1, + }}} + pr, pw := io.Pipe() + defer func() { _ = pr.Close() }() + defer func() { _ = pw.Close() }() + go func() { + time.Sleep(250 * time.Millisecond) + _, _ = io.WriteString(pw, "data: {\"type\":\"response.created\",\"response\":{\"id\":\"r\"}}\n\n") + }() + rec := httptest.NewRecorder() + c, _ := gin.CreateTestContext(rec) + c.Request = httptest.NewRequest(http.MethodPost, "/v1/responses", nil) + resp := &http.Response{StatusCode: http.StatusOK, Header: http.Header{}, Body: pr} + account := &Account{ID: 1, Platform: PlatformOpenAI, Type: AccountTypeOAuth} + start := time.Now() + _, err := svc.handleStreamingResponse(c.Request.Context(), resp, c, account, start, "model", "model") + elapsed := time.Since(start) + t.Logf("idle timeout after %s (last upstream read at approximately 250ms)", elapsed) + require.Error(t, err) + require.GreaterOrEqual(t, elapsed, 1200*time.Millisecond, "do not shorten the configured idle interval") + require.Less(t, elapsed, 1800*time.Millisecond, "do not wait for the next full polling interval") + var failover *UpstreamFailoverError + require.True(t, errors.As(err, &failover), "an idle attempt with no model output should remain failover-safe") + require.Empty(t, rec.Body.String()) +} + +func TestRelayStallsIdleFailoverBoundary(t *testing.T) { + gin.SetMode(gin.TestMode) + for _, output := range []bool{false, true} { + name := "before_output" + if output { + name = "after_output" + } + t.Run(name, func(t *testing.T) { + svc := &OpenAIGatewayService{cfg: &config.Config{Gateway: config.GatewayConfig{ + MaxLineSize: defaultMaxLineSize, StreamDataIntervalTimeout: 1, + }}} + pr, pw := io.Pipe() + defer func() { _ = pr.Close() }() + defer func() { _ = pw.Close() }() + go func() { + frame := "data: {\"type\":\"response.created\",\"response\":{\"id\":\"r\"}}\n\n" + if output { + frame += "data: {\"type\":\"response.output_text.delta\",\"delta\":\"hello\"}\n\n" + } + _, _ = io.WriteString(pw, frame) + }() + rec := httptest.NewRecorder() + c, _ := gin.CreateTestContext(rec) + c.Request = httptest.NewRequest(http.MethodPost, "/v1/responses", nil) + resp := &http.Response{StatusCode: http.StatusOK, Header: http.Header{}, Body: pr} + account := &Account{ID: 1, Platform: PlatformOpenAI, Type: AccountTypeOAuth} + _, err := svc.handleStreamingResponse(c.Request.Context(), resp, c, account, time.Now(), "model", "model") + require.Error(t, err) + var failover *UpstreamFailoverError + if output { + require.False(t, errors.As(err, &failover), "partial output must not be replayed") + require.Contains(t, rec.Body.String(), "hello") + require.Contains(t, rec.Body.String(), "stream_timeout") + } else { + require.ErrorAs(t, err, &failover) + require.Empty(t, rec.Body.String()) + } + }) + } +} From 8a1315e8ccb60bf4389f6a436deb5447445ac560 Mon Sep 17 00:00:00 2001 From: lkon <76028488+lkon2112@users.noreply.github.com> Date: Sun, 8 Nov 2026 16:43:43 +0800 Subject: [PATCH 10/85] test(billing): reuse rate resolver and isolate heap checks --- .../billing_inflight_reservation_test.go | 42 ++++++++++++++++--- 1 file changed, 37 insertions(+), 5 deletions(-) diff --git a/backend/internal/service/billing_inflight_reservation_test.go b/backend/internal/service/billing_inflight_reservation_test.go index fa9281823b..7ae199fb11 100644 --- a/backend/internal/service/billing_inflight_reservation_test.go +++ b/backend/internal/service/billing_inflight_reservation_test.go @@ -6,6 +6,9 @@ import ( "context" "fmt" "math" + "os" + "os/exec" + "regexp" "runtime" "sync" "sync/atomic" @@ -13,6 +16,7 @@ import ( "time" "github.com/Wei-Shaw/sub2api/internal/config" + gocache "github.com/patrickmn/go-cache" "github.com/stretchr/testify/require" ) @@ -74,12 +78,21 @@ func newInflightEstimateGateway(t *testing.T, channelService *ChannelService) *G cfg := &config.Config{} cfg.Billing.InflightReservation = config.InflightReservationConfig{Enabled: true, DefaultMaxTokens: 1000, MaxInputTokens: 200000, MaxOutputTokens: 128000} billing := NewBillingService(cfg, nil) - return &GatewayService{ - cfg: cfg, - billingService: billing, - resolver: NewModelPricingResolver(channelService, billing), - channelService: channelService, + userGroupRateTTL := resolveUserGroupRateCacheTTL(cfg) + svc := &GatewayService{ + cfg: cfg, + billingService: billing, + resolver: NewModelPricingResolver(channelService, billing), + channelService: channelService, + userGroupRateCache: gocache.New(userGroupRateTTL, 0), } + // Match NewGatewayService's shared resolver. Leaving it nil creates a new + // cache and janitor per estimate; their asynchronous finalizers distort heap + // measurements. This fixture needs no background expiration worker. + svc.userGroupRateResolver = newUserGroupRateResolver( + nil, svc.userGroupRateCache, userGroupRateTTL, &svc.userGroupRateSF, "service.gateway", + ) + return svc } func TestInflightEstimate_ChannelAliasUsesMappedModel(t *testing.T) { @@ -434,6 +447,21 @@ func attachInflightSnapshot(svc *GatewayService, snap *inflightSnapshotCacheStub // 已定价模型永不查账号映射;随机未定价模型名不直接查库、不产生按模型名的缓存(内存有界)。 func TestInflightEstimate_AccountMappingNoDBAndBoundedMemory(t *testing.T) { + // HeapAlloc is process-wide: unrelated background work in other service + // tests must not be counted as memory retained by this estimate path. + const childEnv = "SUB2API_BILLING_HEAP_TEST_CHILD" + if os.Getenv(childEnv) != "1" { + ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second) + defer cancel() + executable, err := os.Executable() + require.NoError(t, err) + cmd := exec.CommandContext(ctx, executable, "-test.run=^"+regexp.QuoteMeta(t.Name())+"$", "-test.count=1") + cmd.Env = append(os.Environ(), childEnv+"=1") + output, err := cmd.CombinedOutput() + require.NoError(t, err, "isolated heap test failed:\n%s", output) + return + } + groupID := int64(40) svc := newInflightEstimateGateway(t, nil) snap := &inflightSnapshotCacheStub{byBucket: map[string][]Account{inflightBucketKey(groupID, PlatformAnthropic): { @@ -459,6 +487,10 @@ func TestInflightEstimate_AccountMappingNoDBAndBoundedMemory(t *testing.T) { } runtime.GC() runtime.ReadMemStats(&after) + // Keep the measured service and request reachable through the final GC so + // a per-model cache regression cannot disappear with a dead test fixture. + runtime.KeepAlive(svc) + runtime.KeepAlive(apiKey) require.Zero(t, repo.dbCalls.Load(), "no direct DB query on the request path") require.Equal(t, int64(n), snap.reads.Load(), "unpriced lookups read the scheduler snapshot only") require.Less(t, int64(after.HeapAlloc)-int64(before.HeapAlloc), int64(8<<20), "no per-model cache growth") From bf292550a6d45088c46dd0792d9bffddb2c65e92 Mon Sep 17 00:00:00 2001 From: Anankke Date: Sat, 14 Nov 2026 02:54:25 -0800 Subject: [PATCH 11/85] feat(websearch): add Exa as a web search emulation provider The web search emulation answers a WebSearch tool call on accounts without native search by querying a configured provider. Only Brave and Tavily are available. This adds Exa as a third keyed provider, "exa", in the same place the others are registered. ExaProvider posts {query, numResults, contents: {highlights: true}} to https://api.exa.ai/search with the key in the x-api-key header. The search type and highlight length are left to Exa's defaults. Each result maps url and title as they are, publishedDate to page_age, and its highlights joined by newlines to the snippet. A result without highlights has no snippet. A non-200 answer is returned as an error with the status and the start of the body, as for Tavily. "exa" is accepted by the emulation config validator, built by the manager and offered in the admin settings provider dropdown. --- backend/internal/pkg/websearch/exa.go | 112 ++++++++++++++++++ backend/internal/pkg/websearch/exa_test.go | 91 ++++++++++++++ backend/internal/pkg/websearch/manager.go | 4 +- backend/internal/pkg/websearch/provider.go | 2 +- backend/internal/pkg/websearch/types.go | 1 + backend/internal/service/websearch_config.go | 5 +- .../service/websearch_config_exa_test.go | 17 +++ frontend/src/api/admin/settings.ts | 2 +- frontend/src/views/admin/SettingsView.vue | 1 + 9 files changed, 230 insertions(+), 5 deletions(-) create mode 100644 backend/internal/pkg/websearch/exa.go create mode 100644 backend/internal/pkg/websearch/exa_test.go create mode 100644 backend/internal/service/websearch_config_exa_test.go diff --git a/backend/internal/pkg/websearch/exa.go b/backend/internal/pkg/websearch/exa.go new file mode 100644 index 0000000000..e5ed4f00b3 --- /dev/null +++ b/backend/internal/pkg/websearch/exa.go @@ -0,0 +1,112 @@ +package websearch + +import ( + "bytes" + "context" + "encoding/json" + "fmt" + "io" + "net/http" + "strings" +) + +const ( + exaSearchEndpoint = "https://api.exa.ai/search" + exaProviderName = "exa" +) + +// ExaProvider implements web search via the Exa Search API. +type ExaProvider struct { + apiKey string + httpClient *http.Client +} + +// NewExaProvider creates an Exa Search provider. +// The caller is responsible for configuring the http.Client with proxy/timeouts. +func NewExaProvider(apiKey string, httpClient *http.Client) *ExaProvider { + if httpClient == nil { + httpClient = http.DefaultClient + } + return &ExaProvider{apiKey: apiKey, httpClient: httpClient} +} + +func (e *ExaProvider) Name() string { return exaProviderName } + +func (e *ExaProvider) Search(ctx context.Context, req SearchRequest) (*SearchResponse, error) { + numResults := req.MaxResults + if numResults <= 0 { + numResults = defaultMaxResults + } + + // Search type and highlight length are left to Exa's defaults. + payload := exaRequest{ + Query: req.Query, + NumResults: numResults, + Contents: exaContents{Highlights: true}, + } + + bodyBytes, err := json.Marshal(payload) + if err != nil { + return nil, fmt.Errorf("exa: encode request: %w", err) + } + + httpReq, err := http.NewRequestWithContext(ctx, http.MethodPost, exaSearchEndpoint, bytes.NewReader(bodyBytes)) + if err != nil { + return nil, fmt.Errorf("exa: build request: %w", err) + } + httpReq.Header.Set("Content-Type", "application/json") + httpReq.Header.Set("x-api-key", e.apiKey) + + resp, err := e.httpClient.Do(httpReq) + if err != nil { + return nil, fmt.Errorf("exa: request failed: %w", err) + } + defer func() { _ = resp.Body.Close() }() + + body, err := io.ReadAll(io.LimitReader(resp.Body, maxResponseSize)) + if err != nil { + return nil, fmt.Errorf("exa: read body: %w", err) + } + + if resp.StatusCode != http.StatusOK { + return nil, fmt.Errorf("exa: status %d: %s", resp.StatusCode, truncateBody(body)) + } + + var raw exaResponse + if err := json.Unmarshal(body, &raw); err != nil { + return nil, fmt.Errorf("exa: decode response: %w", err) + } + + results := make([]SearchResult, 0, len(raw.Results)) + for _, r := range raw.Results { + results = append(results, SearchResult{ + URL: r.URL, + Title: r.Title, + Snippet: strings.Join(r.Highlights, "\n"), + PageAge: r.PublishedDate, + }) + } + + return &SearchResponse{Results: results, Query: req.Query}, nil +} + +type exaRequest struct { + Query string `json:"query"` + NumResults int `json:"numResults"` + Contents exaContents `json:"contents"` +} + +type exaContents struct { + Highlights bool `json:"highlights"` +} + +type exaResponse struct { + Results []exaResult `json:"results"` +} + +type exaResult struct { + URL string `json:"url"` + Title string `json:"title"` + PublishedDate string `json:"publishedDate"` + Highlights []string `json:"highlights"` +} diff --git a/backend/internal/pkg/websearch/exa_test.go b/backend/internal/pkg/websearch/exa_test.go new file mode 100644 index 0000000000..d18d8742b4 --- /dev/null +++ b/backend/internal/pkg/websearch/exa_test.go @@ -0,0 +1,91 @@ +package websearch + +import ( + "context" + "encoding/json" + "io" + "net/http" + "strings" + "testing" + + "github.com/stretchr/testify/require" +) + +type exaRoundTripFunc func(*http.Request) (*http.Response, error) + +func (f exaRoundTripFunc) RoundTrip(r *http.Request) (*http.Response, error) { return f(r) } + +func exaTestClient(status int, body string, seen *http.Request, seenBody *[]byte) *http.Client { + return &http.Client{Transport: exaRoundTripFunc(func(r *http.Request) (*http.Response, error) { + *seen = *r + b, _ := io.ReadAll(r.Body) + *seenBody = b + return &http.Response{ + StatusCode: status, + Body: io.NopCloser(strings.NewReader(body)), + Header: make(http.Header), + }, nil + })} +} + +func TestExaProvider_Name(t *testing.T) { + require.Equal(t, "exa", NewExaProvider("key", nil).Name()) +} + +func TestManagerBuildsExaProvider(t *testing.T) { + p := (&Manager{}).buildProvider(ProviderConfig{Type: ProviderTypeExa, APIKey: "k"}, nil) + require.IsType(t, &ExaProvider{}, p) +} + +func TestExaProvider_Search(t *testing.T) { + var seen http.Request + var seenBody []byte + resp := `{"requestId":"r1","results":[` + + `{"url":"https://go.dev","title":"Go","publishedDate":"2026-10-01T00:00:00.000Z","highlights":["Go is a language.","It compiles fast."]},` + + `{"url":"https://example.com","title":"Example","publishedDate":null,"highlights":[]}]}` + p := NewExaProvider("exa-key", exaTestClient(http.StatusOK, resp, &seen, &seenBody)) + + out, err := p.Search(context.Background(), SearchRequest{Query: "golang", MaxResults: 3}) + + require.NoError(t, err) + require.Equal(t, http.MethodPost, seen.Method) + require.Equal(t, "https://api.exa.ai/search", seen.URL.String()) + require.Equal(t, "exa-key", seen.Header.Get("x-api-key")) + require.Equal(t, "application/json", seen.Header.Get("Content-Type")) + var body map[string]any + require.NoError(t, json.Unmarshal(seenBody, &body)) + require.Equal(t, map[string]any{ + "query": "golang", + "numResults": float64(3), + "contents": map[string]any{"highlights": true}, + }, body) + + require.Equal(t, "golang", out.Query) + require.Equal(t, []SearchResult{ + {URL: "https://go.dev", Title: "Go", Snippet: "Go is a language.\nIt compiles fast.", PageAge: "2026-10-01T00:00:00.000Z"}, + {URL: "https://example.com", Title: "Example"}, + }, out.Results) +} + +func TestExaProvider_SearchDefaultsNumResults(t *testing.T) { + var seen http.Request + var seenBody []byte + p := NewExaProvider("k", exaTestClient(http.StatusOK, `{"results":[]}`, &seen, &seenBody)) + + _, err := p.Search(context.Background(), SearchRequest{Query: "q"}) + + require.NoError(t, err) + var body map[string]any + require.NoError(t, json.Unmarshal(seenBody, &body)) + require.Equal(t, float64(defaultMaxResults), body["numResults"]) +} + +func TestExaProvider_SearchHTTPError(t *testing.T) { + var seen http.Request + var seenBody []byte + p := NewExaProvider("bad", exaTestClient(http.StatusUnauthorized, `{"error":"invalid api key"}`, &seen, &seenBody)) + + _, err := p.Search(context.Background(), SearchRequest{Query: "q"}) + + require.ErrorContains(t, err, "exa: status 401") +} diff --git a/backend/internal/pkg/websearch/manager.go b/backend/internal/pkg/websearch/manager.go index 307aa1e9c7..938d142825 100644 --- a/backend/internal/pkg/websearch/manager.go +++ b/backend/internal/pkg/websearch/manager.go @@ -21,7 +21,7 @@ import ( // ProviderConfig holds the configuration for a single search provider. type ProviderConfig struct { - Type string `json:"type"` // ProviderTypeBrave | ProviderTypeTavily + Type string `json:"type"` // ProviderTypeBrave | ProviderTypeTavily | ProviderTypeExa APIKey string `json:"api_key"` // secret QuotaLimit int64 `json:"quota_limit"` // 0 = unlimited SubscribedAt *int64 `json:"subscribed_at,omitempty"` // subscription start (unix seconds); quota resets monthly from this date @@ -464,6 +464,8 @@ func (m *Manager) buildProvider(cfg ProviderConfig, client *http.Client) Provide return NewBraveProvider(cfg.APIKey, client) case tavilyProviderName: return NewTavilyProvider(cfg.APIKey, client) + case exaProviderName: + return NewExaProvider(cfg.APIKey, client) default: slog.Warn("websearch: unknown provider type, falling back to brave", "type", cfg.Type) diff --git a/backend/internal/pkg/websearch/provider.go b/backend/internal/pkg/websearch/provider.go index 3424c05618..9665a910ee 100644 --- a/backend/internal/pkg/websearch/provider.go +++ b/backend/internal/pkg/websearch/provider.go @@ -4,7 +4,7 @@ import "context" // Provider is the interface every search backend must implement. type Provider interface { - // Name returns the provider identifier ("brave" or "tavily"). + // Name returns the provider identifier ("brave", "tavily" or "exa"). Name() string // Search executes a web search and returns results. Search(ctx context.Context, req SearchRequest) (*SearchResponse, error) diff --git a/backend/internal/pkg/websearch/types.go b/backend/internal/pkg/websearch/types.go index bb48969009..ff6d3f9653 100644 --- a/backend/internal/pkg/websearch/types.go +++ b/backend/internal/pkg/websearch/types.go @@ -27,4 +27,5 @@ const defaultMaxResults = 5 const ( ProviderTypeBrave = "brave" ProviderTypeTavily = "tavily" + ProviderTypeExa = "exa" ) diff --git a/backend/internal/service/websearch_config.go b/backend/internal/service/websearch_config.go index d4b0823adc..993a94bb7c 100644 --- a/backend/internal/service/websearch_config.go +++ b/backend/internal/service/websearch_config.go @@ -20,9 +20,9 @@ type WebSearchEmulationConfig struct { Providers []WebSearchProviderConfig `json:"providers"` } -// WebSearchProviderConfig describes a single search provider (Brave or Tavily). +// WebSearchProviderConfig describes a single search provider (Brave, Tavily or Exa). type WebSearchProviderConfig struct { - Type string `json:"type"` // websearch.ProviderTypeBrave | Tavily + Type string `json:"type"` // websearch.ProviderTypeBrave | Tavily | Exa APIKey string `json:"api_key,omitempty"` // secret — omitted in API responses APIKeyConfigured bool `json:"api_key_configured"` // read-only mask QuotaLimit *int64 `json:"quota_limit"` // nil = unlimited, >0 = limited @@ -39,6 +39,7 @@ const maxWebSearchProviders = 10 var validProviderTypes = map[string]bool{ websearch.ProviderTypeBrave: true, websearch.ProviderTypeTavily: true, + websearch.ProviderTypeExa: true, } func validateWebSearchConfig(cfg *WebSearchEmulationConfig) error { diff --git a/backend/internal/service/websearch_config_exa_test.go b/backend/internal/service/websearch_config_exa_test.go new file mode 100644 index 0000000000..427f3fd01a --- /dev/null +++ b/backend/internal/service/websearch_config_exa_test.go @@ -0,0 +1,17 @@ +//go:build unit + +package service + +import ( + "testing" + + "github.com/stretchr/testify/require" +) + +func TestValidateWebSearchConfig_AcceptsExa(t *testing.T) { + cfg := &WebSearchEmulationConfig{ + Enabled: true, + Providers: []WebSearchProviderConfig{{Type: "exa", QuotaLimit: int64Ptr(1000)}}, + } + require.NoError(t, validateWebSearchConfig(cfg)) +} diff --git a/frontend/src/api/admin/settings.ts b/frontend/src/api/admin/settings.ts index 184cc9170e..db531fa121 100644 --- a/frontend/src/api/admin/settings.ts +++ b/frontend/src/api/admin/settings.ts @@ -1558,7 +1558,7 @@ export async function updateBetaPolicySettings( // --- Web Search Emulation Config --- export interface WebSearchProviderConfig { - type: "brave" | "tavily"; + type: "brave" | "tavily" | "exa"; api_key: string; api_key_configured: boolean; quota_limit: number | null; diff --git a/frontend/src/views/admin/SettingsView.vue b/frontend/src/views/admin/SettingsView.vue index 6e63f04232..0db478ce1d 100644 --- a/frontend/src/views/admin/SettingsView.vue +++ b/frontend/src/views/admin/SettingsView.vue @@ -5962,6 +5962,7 @@ :options="[ { value: 'brave', label: 'Brave Search' }, { value: 'tavily', label: 'Tavily' }, + { value: 'exa', label: 'Exa' }, ]" class="w-36" @click.stop From aa5a020bd16bcac8c9c18f71040abfa50e2c9984 Mon Sep 17 00:00:00 2001 From: Anankke Date: Sat, 14 Nov 2026 02:54:30 -0800 Subject: [PATCH 12/85] feat(apicompat): return web_search sources in web_search_tool_result blocks The Messages bridge always answered an OpenAI web_search_call with an empty web_search_tool_result, so clients never saw the pages the search used. Bridge requests on the OpenAI platform that carry a web_search tool now ask for web_search_call.action.sources. Each call's sources, or the page a completed open_page opened, become that call's web_search_tool_result entries, in both the streaming and non-streaming paths. Sources are decoded entry by entry so a malformed entry cannot drop the terminal event. --- .../pkg/apicompat/responses_to_anthropic.go | 8 +- .../apicompat/responses_web_search_sources.go | 57 ++++++++ .../responses_web_search_sources_test.go | 110 ++++++++++++++++ backend/internal/pkg/apicompat/types.go | 4 + .../service/openai_gateway_messages.go | 3 + ...ateway_messages_web_search_sources_test.go | 123 ++++++++++++++++++ 6 files changed, 299 insertions(+), 6 deletions(-) create mode 100644 backend/internal/pkg/apicompat/responses_web_search_sources.go create mode 100644 backend/internal/pkg/apicompat/responses_web_search_sources_test.go create mode 100644 backend/internal/service/openai_gateway_messages_web_search_sources_test.go diff --git a/backend/internal/pkg/apicompat/responses_to_anthropic.go b/backend/internal/pkg/apicompat/responses_to_anthropic.go index 5eab6d9489..a1c6485164 100644 --- a/backend/internal/pkg/apicompat/responses_to_anthropic.go +++ b/backend/internal/pkg/apicompat/responses_to_anthropic.go @@ -67,11 +67,10 @@ func ResponsesToAnthropic(resp *ResponsesResponse, model string) *AnthropicRespo Name: "web_search", Input: inputJSON, }) - emptyResults, _ := json.Marshal([]struct{}{}) blocks = append(blocks, AnthropicContentBlock{ Type: "web_search_tool_result", ToolUseID: toolUseID, - Content: emptyResults, + Content: webSearchCallResults(&item), }) } } @@ -670,9 +669,6 @@ func resToAnthHandleWebSearchDone(evt *ResponsesStreamEvent, state *ResponsesEve state.ContentBlockIndex++ // Emit web_search_tool_result block (start + stop). - // Content is empty because OpenAI does not expose individual search results; - // the model consumes them internally and produces text output. - emptyResults, _ := json.Marshal([]struct{}{}) idx2 := state.ContentBlockIndex events = append(events, AnthropicStreamEvent{ Type: "content_block_start", @@ -680,7 +676,7 @@ func resToAnthHandleWebSearchDone(evt *ResponsesStreamEvent, state *ResponsesEve ContentBlock: &AnthropicContentBlock{ Type: "web_search_tool_result", ToolUseID: toolUseID, - Content: emptyResults, + Content: webSearchCallResults(evt.Item), }, }) events = append(events, AnthropicStreamEvent{ diff --git a/backend/internal/pkg/apicompat/responses_web_search_sources.go b/backend/internal/pkg/apicompat/responses_web_search_sources.go new file mode 100644 index 0000000000..39efc7370d --- /dev/null +++ b/backend/internal/pkg/apicompat/responses_web_search_sources.go @@ -0,0 +1,57 @@ +package apicompat + +import ( + "encoding/json" + "slices" +) + +const webSearchSourcesInclude = "web_search_call.action.sources" + +// IncludeWebSearchSources asks a hosted web_search to report the pages it +// used; without it a web_search_call carries only its query. +func IncludeWebSearchSources(req *ResponsesRequest) { + for _, tool := range req.Tools { + if tool.Type == "web_search" { + if !slices.Contains(req.Include, webSearchSourcesInclude) { + req.Include = append(req.Include, webSearchSourcesInclude) + } + return + } + } +} + +type webSearchResult struct { + Type string `json:"type"` + URL string `json:"url"` + Title string `json:"title"` +} + +// webSearchCallResults is the web_search_tool_result content for one call: a +// search's action.sources, or the single page a completed open_page opened. +// Sources are decoded entry by entry, so one malformed entry cannot fail the +// terminal event that carries the call. +func webSearchCallResults(item *ResponsesOutput) json.RawMessage { + results := []webSearchResult{} + if action := item.Action; action != nil { + var sources []json.RawMessage + if json.Unmarshal(action.Sources, &sources) == nil && sources != nil { + for _, raw := range sources { + var source map[string]any + _ = json.Unmarshal(raw, &source) + if rawURL, ok := source["url"].(string); ok && rawURL != "" { + results = append(results, newWebSearchResult(rawURL)) + } + } + } else if action.Type == "open_page" && item.Status == "completed" && action.URL != "" { + results = append(results, newWebSearchResult(action.URL)) + } + } + out, _ := json.Marshal(results) + return out +} + +// newWebSearchResult uses the URL as the title because Responses sources carry +// no title and the Anthropic block requires one. +func newWebSearchResult(rawURL string) webSearchResult { + return webSearchResult{Type: "web_search_result", URL: rawURL, Title: rawURL} +} diff --git a/backend/internal/pkg/apicompat/responses_web_search_sources_test.go b/backend/internal/pkg/apicompat/responses_web_search_sources_test.go new file mode 100644 index 0000000000..07742de86c --- /dev/null +++ b/backend/internal/pkg/apicompat/responses_web_search_sources_test.go @@ -0,0 +1,110 @@ +//go:build unit + +package apicompat + +import ( + "encoding/json" + "testing" + + "github.com/stretchr/testify/require" +) + +const ( + webSearchCallWithTwoSources = `{"type":"web_search_call","id":"ws_1","status":"completed","action":{"type":"search","query":"q1","sources":[` + + `{"type":"url","url":"https://a.example/1"},{"type":"url","url":"https://a.example/2"}]}}` + webSearchCallWithOneSource = `{"type":"web_search_call","id":"ws_2","status":"completed","action":{"type":"search","query":"q2","sources":[` + + `{"type":"url","url":"https://b.example/1"}]}}` + webSearchSourcesWantWS1 = `[{"type":"web_search_result","url":"https://a.example/1","title":"https://a.example/1"},` + + `{"type":"web_search_result","url":"https://a.example/2","title":"https://a.example/2"}]` + webSearchSourcesWantWS2 = `[{"type":"web_search_result","url":"https://b.example/1","title":"https://b.example/1"}]` +) + +func decodeWebSearchItem(t *testing.T, raw string) ResponsesOutput { + t.Helper() + var item ResponsesOutput + require.NoError(t, json.Unmarshal([]byte(raw), &item)) + return item +} + +// webSearchResultContents returns each web_search_tool_result content keyed by +// the server_tool_use id it answers. +func webSearchResultContents(blocks []AnthropicContentBlock) map[string]string { + out := map[string]string{} + for _, block := range blocks { + if block.Type == "web_search_tool_result" { + out[block.ToolUseID] = string(block.Content) + } + } + return out +} + +func nonStreamingWebSearchResults(t *testing.T, items ...string) map[string]string { + t.Helper() + resp := &ResponsesResponse{ID: "resp_ws", Status: "completed"} + for _, raw := range items { + resp.Output = append(resp.Output, decodeWebSearchItem(t, raw)) + } + return webSearchResultContents(ResponsesToAnthropic(resp, "gpt-5.5").Content) +} + +func streamingWebSearchResults(t *testing.T, items ...string) map[string]string { + t.Helper() + state := NewResponsesEventToAnthropicState() + events := ResponsesEventToAnthropicEvents(&ResponsesStreamEvent{ + Type: "response.created", + Response: &ResponsesResponse{ID: "resp_ws", Model: "gpt-5.5"}, + }, state) + for i, raw := range items { + item := decodeWebSearchItem(t, raw) + events = append(events, ResponsesEventToAnthropicEvents(&ResponsesStreamEvent{ + Type: "response.output_item.done", + OutputIndex: i, + Item: &item, + }, state)...) + } + var blocks []AnthropicContentBlock + for _, evt := range events { + if evt.Type == "content_block_start" && evt.ContentBlock != nil { + blocks = append(blocks, *evt.ContentBlock) + } + } + return webSearchResultContents(blocks) +} + +func TestResponsesEventToAnthropic_WebSearchSources(t *testing.T) { + got := streamingWebSearchResults(t, webSearchCallWithTwoSources, webSearchCallWithOneSource) + require.Len(t, got, 2) + require.JSONEq(t, webSearchSourcesWantWS1, got["srvtoolu_ws_1"]) + require.JSONEq(t, webSearchSourcesWantWS2, got["srvtoolu_ws_2"]) +} + +func TestResponsesToAnthropic_WebSearchSources(t *testing.T) { + got := nonStreamingWebSearchResults(t, webSearchCallWithTwoSources, webSearchCallWithOneSource) + require.Len(t, got, 2) + require.JSONEq(t, webSearchSourcesWantWS1, got["srvtoolu_ws_1"]) + require.JSONEq(t, webSearchSourcesWantWS2, got["srvtoolu_ws_2"]) +} + +func TestWebSearchSourcesEntryRules(t *testing.T) { + got := nonStreamingWebSearchResults(t, `{"type":"web_search_call","id":"ws_1","status":"completed","action":{"type":"search","query":"q",`+ + `"sources":[{"url":"https://a"},{"url":""},{"url":1},"https://b",{"title":"x"}]}}`) + require.JSONEq(t, `[{"type":"web_search_result","url":"https://a","title":"https://a"}]`, got["srvtoolu_ws_1"]) +} + +func TestWebSearchOpenPageReturnsSinglePage(t *testing.T) { + got := nonStreamingWebSearchResults(t, `{"type":"web_search_call","id":"ws_1","status":"completed",`+ + `"action":{"type":"open_page","url":"https://docs.example/page?id=1#top"}}`) + require.JSONEq(t, `[{"type":"web_search_result","url":"https://docs.example/page?id=1#top","title":"https://docs.example/page?id=1#top"}]`, + got["srvtoolu_ws_1"]) +} + +func TestWebSearchOpenPageRequiresCompletedURL(t *testing.T) { + for name, item := range map[string]string{ + "in progress": `{"type":"web_search_call","id":"ws_1","status":"in_progress","action":{"type":"open_page","url":"https://docs.example/page"}}`, + "empty url": `{"type":"web_search_call","id":"ws_1","status":"completed","action":{"type":"open_page","url":""}}`, + } { + t.Run(name, func(t *testing.T) { + require.JSONEq(t, `[]`, nonStreamingWebSearchResults(t, item)["srvtoolu_ws_1"]) + }) + } +} diff --git a/backend/internal/pkg/apicompat/types.go b/backend/internal/pkg/apicompat/types.go index 130f0ff63b..a603d64147 100644 --- a/backend/internal/pkg/apicompat/types.go +++ b/backend/internal/pkg/apicompat/types.go @@ -492,6 +492,10 @@ func (o *ResponsesOutput) UnmarshalJSON(data []byte) error { type WebSearchAction struct { Type string `json:"type,omitempty"` // "search" Query string `json:"query,omitempty"` // primary search query + URL string `json:"url,omitempty"` // open_page / find_in_page target + // Sources stays raw: a strictly typed entry of an unexpected shape would + // fail decoding the whole terminal event that carries this call. + Sources json.RawMessage `json:"sources,omitempty"` } // ResponsesSummary is a summary text block inside a reasoning output. diff --git a/backend/internal/service/openai_gateway_messages.go b/backend/internal/service/openai_gateway_messages.go index 4756d83383..ca58d0aeaf 100644 --- a/backend/internal/service/openai_gateway_messages.go +++ b/backend/internal/service/openai_gateway_messages.go @@ -214,6 +214,9 @@ func (s *OpenAIGatewayService) ForwardAsAnthropic( logFields = append(logFields, zap.Bool("compat_turn_state_attached", true)) } logger.L().Debug("openai messages: model mapping applied", logFields...) + if account.Platform == PlatformOpenAI { + apicompat.IncludeWebSearchSources(responsesReq) + } // 4. Marshal Responses request body, then apply the ChatGPT/Codex transform. responsesBody, err := json.Marshal(responsesReq) diff --git a/backend/internal/service/openai_gateway_messages_web_search_sources_test.go b/backend/internal/service/openai_gateway_messages_web_search_sources_test.go new file mode 100644 index 0000000000..9c859cc3b0 --- /dev/null +++ b/backend/internal/service/openai_gateway_messages_web_search_sources_test.go @@ -0,0 +1,123 @@ +//go:build unit + +package service + +import ( + "bytes" + "context" + "io" + "net/http" + "net/http/httptest" + "strings" + "testing" + + "github.com/gin-gonic/gin" + "github.com/stretchr/testify/require" + "github.com/tidwall/gjson" +) + +const messagesWebSearchBody = `{"model":"gpt-5.5","max_tokens":64,"stream":true, + "tools":[{"type":"web_search_20250305","name":"web_search"}], + "messages":[{"role":"user","content":"search the web"}]}` + +const messagesWithoutWebSearchBody = `{"model":"gpt-5.5","max_tokens":64,"stream":true, + "messages":[{"role":"user","content":"hello"}]}` + +const webSearchCompletedSSE = "data: {\"type\":\"response.completed\",\"response\":{\"id\":\"resp_ws\",\"status\":\"completed\",\"output\":[],\"usage\":{\"input_tokens\":5,\"output_tokens\":2,\"total_tokens\":7}}}\n\n" + +func codexOAuthWebSearchTestAccount() *Account { + return &Account{ + ID: 1, Name: "openai-oauth", Platform: PlatformOpenAI, Type: AccountTypeOAuth, Concurrency: 1, + Credentials: map[string]any{"access_token": "oauth-token", "chatgpt_account_id": "chatgpt-acc"}, + } +} + +func upstreamInclude(body []byte) []string { + var include []string + for _, v := range gjson.GetBytes(body, "include").Array() { + include = append(include, v.String()) + } + return include +} + +func forwardMessagesWebSearch(t *testing.T, account *Account, requestBody, upstreamSSE string) (*httpUpstreamRecorder, *httptest.ResponseRecorder) { + t.Helper() + gin.SetMode(gin.TestMode) + rec := httptest.NewRecorder() + c, _ := gin.CreateTestContext(rec) + body := []byte(requestBody) + c.Request = httptest.NewRequest(http.MethodPost, "/v1/messages", bytes.NewReader(body)) + c.Request.Header.Set("Content-Type", "application/json") + upstream := &httpUpstreamRecorder{resp: &http.Response{ + StatusCode: http.StatusOK, + Header: http.Header{"Content-Type": []string{"text/event-stream"}}, + Body: io.NopCloser(strings.NewReader(upstreamSSE)), + }} + svc := &OpenAIGatewayService{ + httpUpstream: upstream, + cfg: rawChatCompletionsTestConfig(), + } + _, err := svc.ForwardAsAnthropic(context.Background(), c, account, body, "", "gpt-5.5") + require.NoError(t, err) + return upstream, rec +} + +func forwardGrokMessages(t *testing.T, requestBody string) *httpUpstreamRecorder { + t.Helper() + gin.SetMode(gin.TestMode) + c, _ := gin.CreateTestContext(httptest.NewRecorder()) + body := []byte(requestBody) + c.Request = httptest.NewRequest(http.MethodPost, "/v1/messages", bytes.NewReader(body)) + account := healthyGrokOAuthGatewayTestAccount(71, "access-token") + repo := &grokQuotaAccountRepo{mockAccountRepoForPlatform: &mockAccountRepoForPlatform{accountsByID: map[int64]*Account{71: account}}} + upstream := &httpUpstreamRecorder{resp: grokMessagesSSECompletedResponse("resp_grok_ws", 0)} + svc := &OpenAIGatewayService{httpUpstream: upstream, grokTokenProvider: NewGrokTokenProvider(repo, nil), accountRepo: repo} + + _, err := svc.ForwardAsAnthropic(context.Background(), c, account, body, "", "") + require.NoError(t, err) + return upstream +} + +func TestForwardAsAnthropic_WebSearchRequestsSources(t *testing.T) { + for name, account := range map[string]*Account{ + "openai apikey": rawChatCompletionsTestAccount(), + "codex oauth": codexOAuthWebSearchTestAccount(), + } { + t.Run(name, func(t *testing.T) { + upstream, _ := forwardMessagesWebSearch(t, account, messagesWebSearchBody, webSearchCompletedSSE) + require.Equal(t, []string{"reasoning.encrypted_content", "web_search_call.action.sources"}, upstreamInclude(upstream.lastBody)) + }) + } +} + +func TestForwardAsAnthropic_WebSearchSourcesNotRequestedWithoutTool(t *testing.T) { + for name, account := range map[string]*Account{ + "openai apikey": rawChatCompletionsTestAccount(), + "codex oauth": codexOAuthWebSearchTestAccount(), + } { + t.Run(name, func(t *testing.T) { + upstream, _ := forwardMessagesWebSearch(t, account, messagesWithoutWebSearchBody, webSearchCompletedSSE) + require.NotContains(t, upstreamInclude(upstream.lastBody), "web_search_call.action.sources") + }) + } + t.Run("grok with web_search tool", func(t *testing.T) { + upstream := forwardGrokMessages(t, messagesWebSearchBody) + require.NotEmpty(t, gjson.GetBytes(upstream.lastBody, "tools").Array(), "the web_search tool reaches xAI") + require.NotContains(t, upstreamInclude(upstream.lastBody), "web_search_call.action.sources") + }) +} + +// A source entry of an unexpected shape must not cost the terminal event that +// carries it: that would turn a finished answer into a missing-terminal error. +func TestWebSearchMalformedSourcesKeepTerminalEvent(t *testing.T) { + sse := "data: {\"type\":\"response.created\",\"response\":{\"id\":\"resp_ws\",\"model\":\"gpt-5.5\"}}\n\n" + + "data: {\"type\":\"response.output_text.delta\",\"output_index\":0,\"content_index\":0,\"delta\":\"found it\"}\n\n" + + "data: {\"type\":\"response.completed\",\"response\":{\"id\":\"resp_ws\",\"status\":\"completed\",\"output\":[" + + "{\"type\":\"message\",\"id\":\"msg_1\",\"role\":\"assistant\",\"status\":\"completed\",\"content\":[{\"type\":\"output_text\",\"text\":\"found it\"}]}," + + "{\"type\":\"web_search_call\",\"id\":\"ws_1\",\"status\":\"completed\",\"action\":{\"type\":\"search\",\"query\":\"q\",\"sources\":[\"https://a\"]}}]," + + "\"usage\":{\"input_tokens\":5,\"output_tokens\":2,\"total_tokens\":7}}}\n\n" + _, rec := forwardMessagesWebSearch(t, rawChatCompletionsTestAccount(), messagesWebSearchBody, sse) + + out := strings.TrimSpace(rec.Body.String()) + require.True(t, strings.HasSuffix(out, `{"type":"message_stop"}`), "body: %s", out) +} From e2631bbb385a8fa04a7b006678417713600aa270 Mon Sep 17 00:00:00 2001 From: Anankke Date: Sat, 14 Nov 2026 03:55:33 -0800 Subject: [PATCH 13/85] feat(gateway): write Claude Code compaction requests at 5m cache TTL With the 1h cache TTL injection on, every breakpoint of a compaction request was rewritten to 1h, although the conversation is replaced by the summary afterwards and nothing reads the tokens added since the last main-thread breakpoint again. A compaction request is recognised by the fixed preamble of the compact prompt in the last user message. Every breakpoint becomes 5m, including one the client already wrote as 1h. A 5m breakpoint still reads the prefix the main thread cached at 1h, and an all-5m request keeps the tools, system, messages TTL order Anthropic requires. The admin settings hint for the switch names the exception. --- .../service/gateway_claude_oauth_body.go | 47 ++++++++++ .../gateway_compaction_cache_ttl_test.go | 87 +++++++++++++++++++ .../src/i18n/locales/en/admin/settings.ts | 2 +- .../src/i18n/locales/zh/admin/settings.ts | 2 +- 4 files changed, 136 insertions(+), 2 deletions(-) create mode 100644 backend/internal/service/gateway_compaction_cache_ttl_test.go diff --git a/backend/internal/service/gateway_claude_oauth_body.go b/backend/internal/service/gateway_claude_oauth_body.go index 44e9aaaac1..0132917142 100644 --- a/backend/internal/service/gateway_claude_oauth_body.go +++ b/backend/internal/service/gateway_claude_oauth_body.go @@ -1192,10 +1192,57 @@ func normalizeCacheControlTTLOrder(body []byte) []byte { // injectAnthropicCacheControlTTL1h 将已有 ephemeral cache_control 块的 ttl 强制写为 1h。 // 仅修改已经存在的 cache_control,不新增缓存断点。 +// +// Claude Code compaction requests are written at 5m instead: the conversation is +// replaced by the summary afterwards, so nothing reads the extra tokens again, +// and a 5m breakpoint still reads the prefix the main thread wrote at 1h. func injectAnthropicCacheControlTTL1h(body []byte) []byte { + if isClaudeCodeCompactionRequest(body) { + return forceEphemeralCacheControlTTL(body, cacheTTLTarget5m) + } return forceEphemeralCacheControlTTL(body, cacheTTLTarget1h) } +// claudeCodeCompactPreamble opens the compact prompt of Claude Code 2.1.282 in +// its full, partial-from and partial-up-to variants, and no other prompt it sends. +const claudeCodeCompactPreamble = "CRITICAL: Respond with TEXT ONLY. Do NOT call any tools.\n\n" + +// isClaudeCodeCompactionRequest reports whether the last user message is a compact +// prompt. When auto-compaction fires during a tool loop the prompt arrives as a text +// block merged into the user message that carries the tool_result. +func isClaudeCodeCompactionRequest(body []byte) bool { + return claudeLastUserTextHasPrefix(body, claudeCodeCompactPreamble) +} + +// claudeLastUserTextHasPrefix reports whether a text block (or the string content) of +// the last user message starts with any of prefixes. +func claudeLastUserTextHasPrefix(body []byte, prefixes ...string) bool { + hasPrefix := func(s string) bool { + for _, p := range prefixes { + if strings.HasPrefix(s, p) { + return true + } + } + return false + } + var last gjson.Result + gjson.GetBytes(body, "messages").ForEach(func(_, msg gjson.Result) bool { + if msg.Get("role").String() == "user" { + last = msg.Get("content") + } + return true + }) + if last.Type == gjson.String { + return hasPrefix(last.Str) + } + found := false + last.ForEach(func(_, block gjson.Result) bool { + found = block.Get("type").String() == "text" && hasPrefix(block.Get("text").String()) + return !found + }) + return found +} + func forceEphemeralCacheControlTTL(body []byte, ttl string) []byte { if len(body) == 0 || ttl == "" { return body diff --git a/backend/internal/service/gateway_compaction_cache_ttl_test.go b/backend/internal/service/gateway_compaction_cache_ttl_test.go new file mode 100644 index 0000000000..5dfb1a39c7 --- /dev/null +++ b/backend/internal/service/gateway_compaction_cache_ttl_test.go @@ -0,0 +1,87 @@ +package service + +import ( + "encoding/json" + "fmt" + "testing" + + "github.com/stretchr/testify/require" + "github.com/tidwall/gjson" +) + +// Only the preamble is the real marker; the rest of the prompt is placeholder text. +const testCompactPrompt = claudeCodeCompactPreamble + "placeholder compact instructions" + +// compactionTestBody builds a request with three breakpoints (two system blocks and +// the assistant message before the last user message) and a trailing role:system +// message. lastUser is the JSON content of the last user message; a non-empty +// cacheTTL is written into every breakpoint. +func compactionTestBody(t *testing.T, lastUser string, cacheTTL string) []byte { + t.Helper() + cc := `{"type":"ephemeral"}` + if cacheTTL != "" { + cc = fmt.Sprintf(`{"type":"ephemeral","ttl":%q}`, cacheTTL) + } + body := fmt.Sprintf(`{"model":"claude-test","messages":[`+ + `{"role":"user","content":[{"type":"text","text":"first question"}]},`+ + `{"role":"assistant","content":[{"type":"tool_use","id":"toolu_1","name":"Bash","input":{"command":"ls"},"cache_control":%[1]s}]},`+ + `{"role":"user","content":%[2]s},`+ + `{"role":"system","content":"placeholder trailing system message"}],`+ + `"system":[{"type":"text","text":"billing block"},`+ + `{"type":"text","text":"system block one","cache_control":%[1]s},`+ + `{"type":"text","text":"system block two","cache_control":%[1]s}],`+ + `"tools":[{"name":"Bash","input_schema":{}}],"max_tokens":1024,"stream":true}`, cc, lastUser) + require.True(t, json.Valid([]byte(body))) + return []byte(body) +} + +func compactionTestJSONString(t *testing.T, s string) string { + t.Helper() + b, err := json.Marshal(s) + require.NoError(t, err) + return string(b) +} + +func requireCompactionTestTTLs(t *testing.T, body []byte, want string) { + t.Helper() + for _, path := range []string{"system.1.cache_control", "system.2.cache_control", "messages.1.content.0.cache_control"} { + require.Equal(t, want, gjson.GetBytes(body, path+".ttl").String(), path) + } +} + +func TestInjectAnthropicCacheControlTTL1h_CompactionUses5m(t *testing.T) { + prompt := compactionTestJSONString(t, testCompactPrompt) + cases := map[string]string{ + "merged_with_tool_result": `[{"type":"tool_result","tool_use_id":"toolu_1","content":"ok"},{"type":"text","text":` + prompt + `}]`, + "own_message": prompt, + } + for name, lastUser := range cases { + for _, clientTTL := range []string{"", "1h"} { + t.Run(name+"/client_ttl="+clientTTL, func(t *testing.T) { + out := injectAnthropicCacheControlTTL1h(compactionTestBody(t, lastUser, clientTTL)) + require.NotContains(t, string(out), `"1h"`) + requireCompactionTestTTLs(t, out, "5m") + }) + } + } +} + +func TestInjectAnthropicCacheControlTTL1h_NonCompactionStill1h(t *testing.T) { + cases := map[string]string{ + "tool_result_and_reminder": `[{"type":"tool_result","tool_use_id":"toolu_1","content":"ok"},{"type":"text","text":"keep going"}]`, + "preamble_not_at_start": compactionTestJSONString(t, "note: "+testCompactPrompt), + } + for name, lastUser := range cases { + t.Run(name, func(t *testing.T) { + out := injectAnthropicCacheControlTTL1h(compactionTestBody(t, lastUser, "")) + requireCompactionTestTTLs(t, out, "1h") + }) + } +} + +func TestIsClaudeCodeCompactionRequest_OnlyLastUserMessageCounts(t *testing.T) { + earlier := `{"messages":[{"role":"user","content":` + compactionTestJSONString(t, testCompactPrompt) + `},{"role":"assistant","content":"summary"},{"role":"user","content":"next question"}]}` + require.False(t, isClaudeCodeCompactionRequest([]byte(earlier))) + require.False(t, isClaudeCodeCompactionRequest([]byte(`{"messages":[]}`))) + require.False(t, isClaudeCodeCompactionRequest([]byte(`{}`))) +} diff --git a/frontend/src/i18n/locales/en/admin/settings.ts b/frontend/src/i18n/locales/en/admin/settings.ts index 868097a92d..cd0482cc02 100644 --- a/frontend/src/i18n/locales/en/admin/settings.ts +++ b/frontend/src/i18n/locales/en/admin/settings.ts @@ -576,7 +576,7 @@ export default { cacheTTL5m: '5 minutes', cacheTTL1h: '1 hour', anthropicCacheTTL1hInjection: 'Anthropic Cache TTL Injection', - anthropicCacheTTL1hInjectionHint: 'When enabled, existing ephemeral cache_control blocks in Anthropic OAuth/Setup Token request bodies are forced to 1h; response usage is billed back as 5m by default, with account-level TTL billing override taking priority.', + anthropicCacheTTL1hInjectionHint: 'When enabled, existing ephemeral cache_control blocks in Anthropic OAuth/Setup Token request bodies are forced to 1h, except Claude Code compaction requests, which use 5m; response usage is billed back as 5m by default, with account-level TTL billing override taking priority.', rewriteMessageCacheControl: 'Rewrite Message Cache Breakpoints', rewriteMessageCacheControlHint: 'Default off: preserve client cache_control on message content blocks. When enabled, client breakpoints are stripped and proxy breakpoints are injected for clients that do not manage caching themselves.', clientDatelineNormalization: 'Client Dateline Normalization', diff --git a/frontend/src/i18n/locales/zh/admin/settings.ts b/frontend/src/i18n/locales/zh/admin/settings.ts index 31c2dba3f3..81b8cb8ac9 100644 --- a/frontend/src/i18n/locales/zh/admin/settings.ts +++ b/frontend/src/i18n/locales/zh/admin/settings.ts @@ -569,7 +569,7 @@ export default { cacheTTL5m: '5 分钟', cacheTTL1h: '1 小时', anthropicCacheTTL1hInjection: 'Anthropic 缓存 TTL 注入', - anthropicCacheTTL1hInjectionHint: '开启后,对 Anthropic OAuth/Setup Token 请求体中已有的 ephemeral 缓存块强制写入 1h;响应 usage 默认按 5m 回写计费,账号级 TTL 计费设置优先。', + anthropicCacheTTL1hInjectionHint: '开启后,对 Anthropic OAuth/Setup Token 请求体中已有的 ephemeral 缓存块强制写入 1h,Claude Code 压缩请求除外,写入 5m;响应 usage 默认按 5m 回写计费,账号级 TTL 计费设置优先。', rewriteMessageCacheControl: '改写消息缓存断点', rewriteMessageCacheControlHint: '默认关闭,保留客户端在 messages 内容块中的 cache_control。开启后会清除客户端断点并注入代理断点,适合不自行管理缓存策略的客户端。', clientDatelineNormalization: '客户端 dateline 归一化', From 5e322694e72ef39ffb59ec7b5920e206239eb895 Mon Sep 17 00:00:00 2001 From: Anankke Date: Sat, 14 Nov 2026 03:51:44 -0800 Subject: [PATCH 14/85] fix(apicompat): map ToolSearch to native tool_search for Codex OAuth The Messages to Responses bridge turned every ToolSearch tool_result made of tool_reference blocks into "(empty)" and sent every defer_loading tool as a top-level function. On ChatGPT/Codex accounts whose model reports supports_search_tool (Grok excluded, xAI has no tool_search) ToolSearch now maps to the native client-executed tool_search, history becomes tool_search_call and tool_search_output carrying the revealed definitions, and an upstream tool_search_call comes back as a ToolSearch tool_use on both the streaming and buffered paths. Deferred tools stay out of the top-level tools so the prompt cache prefix is the same before and after a reveal. Requests that do not declare ToolSearch are left untouched. --- .../pkg/apicompat/anthropic_tool_search.go | 191 ++++++++++++++++++ .../apicompat/anthropic_tool_search_test.go | 174 ++++++++++++++++ .../pkg/apicompat/responses_to_anthropic.go | 6 + .../apicompat/responses_to_chatcompletions.go | 9 +- backend/internal/pkg/apicompat/types.go | 7 + .../service/openai_gateway_messages.go | 10 + ...penai_gateway_messages_tool_search_test.go | 158 +++++++++++++++ 7 files changed, 554 insertions(+), 1 deletion(-) create mode 100644 backend/internal/pkg/apicompat/anthropic_tool_search.go create mode 100644 backend/internal/pkg/apicompat/anthropic_tool_search_test.go create mode 100644 backend/internal/service/openai_gateway_messages_tool_search_test.go diff --git a/backend/internal/pkg/apicompat/anthropic_tool_search.go b/backend/internal/pkg/apicompat/anthropic_tool_search.go new file mode 100644 index 0000000000..55518e0db4 --- /dev/null +++ b/backend/internal/pkg/apicompat/anthropic_tool_search.go @@ -0,0 +1,191 @@ +package apicompat + +import ( + "encoding/json" +) + +// ToolSearchToolName is Claude Code's client-executed tool-search tool. Under +// the native protocol it maps to the Responses `tool_search` tool, its +// tool_use to a `tool_search_call` and its tool_result to a +// `tool_search_output`; an upstream tool_search_call comes back under this name. +const ToolSearchToolName = "ToolSearch" + +// ApplyNativeToolSearch rewrites a Responses request produced by +// AnthropicToResponses so Claude Code's ToolSearch uses the native +// client-executed tool_search protocol of the ChatGPT/Codex backend. +// +// Deferred tools never reach the top-level tools: revealed definitions ride in +// the history's tool_search_output instead, so the top-level tools (the head of +// the prompt-cache prefix) stay identical before and after a reveal. +func ApplyNativeToolSearch(req *AnthropicRequest, out *ResponsesRequest) error { + declared := false + for _, t := range req.Tools { + if t.Name == ToolSearchToolName && !t.DeferLoading { + declared = true + break + } + } + if !declared { + return nil + } + + schemas := make(map[string]AnthropicTool, len(req.Tools)) + kept := make([]AnthropicTool, 0, len(req.Tools)) + for _, t := range req.Tools { + schemas[t.Name] = t + if t.DeferLoading { + continue + } + kept = append(kept, t) + } + tools := convertAnthropicToolsToResponses(kept) + for i, t := range kept { + if t.Name == ToolSearchToolName { + // Codex declares this tool without a name or strict. + tools[i] = ResponsesTool{ + Type: "tool_search", + Execution: "client", + Description: t.Description, + Parameters: normalizeToolParameters(t.InputSchema), + } + } + } + out.Tools = tools + + revealed := toolSearchReveals(req.Messages) + if len(revealed) == 0 { + return nil + } + var items []json.RawMessage + if err := json.Unmarshal(out.Input, &items); err != nil { + return err + } + for i, raw := range items { + var item ResponsesInputItem + if err := json.Unmarshal(raw, &item); err != nil { + return err + } + names, isSearch := revealed[item.CallID] + if !isSearch { + continue + } + var native any + switch item.Type { + case "function_call": + native = map[string]any{ + "type": "tool_search_call", + "call_id": item.CallID, + "execution": "client", + "status": "completed", + "arguments": jsonObjectOrEmpty(item.Arguments), + } + case "function_call_output": + loaded := make([]any, 0, len(names)) + for _, name := range names { + t, ok := schemas[name] + if !ok { + continue + } + loaded = append(loaded, map[string]any{ + "type": "function", + "name": name, + "description": t.Description, + "defer_loading": true, + "strict": false, + "parameters": normalizeToolParameters(t.InputSchema), + }) + } + native = map[string]any{ + "type": "tool_search_output", + "call_id": item.CallID, + "execution": "client", + "status": "completed", + "tools": loaded, + } + default: + continue + } + encoded, err := json.Marshal(native) + if err != nil { + return err + } + items[i] = encoded + } + input, err := json.Marshal(items) + if err != nil { + return err + } + out.Input = input + return nil +} + +// toolSearchReveals maps each ToolSearch tool_use id in the history to the +// tool names its tool_result referenced, first occurrence first. +func toolSearchReveals(msgs []AnthropicMessage) map[string][]string { + reveals := make(map[string][]string) + for _, m := range msgs { + var blocks []AnthropicContentBlock + if json.Unmarshal(m.Content, &blocks) != nil { + continue + } + for _, b := range blocks { + switch { + case b.Type == "tool_use" && b.Name == ToolSearchToolName && b.ID != "": + reveals[toResponsesCallID(b.ID)] = nil + case b.Type == "tool_result": + id := toResponsesCallID(b.ToolUseID) + if _, isSearch := reveals[id]; !isSearch { + continue + } + var inner []AnthropicContentBlock + _ = json.Unmarshal(b.Content, &inner) + seen := make(map[string]bool) + for _, ib := range inner { + if ib.Type == "tool_reference" && ib.ToolName != "" && !seen[ib.ToolName] { + seen[ib.ToolName] = true + reveals[id] = append(reveals[id], ib.ToolName) + } + } + } + } + } + return reveals +} + +// toolSearchCallToolUse turns an upstream tool_search_call back into the +// ToolSearch tool_use Claude Code executes; its call_id round-trips as the +// tool_use id that the next turn's tool_result answers. +func toolSearchCallToolUse(item ResponsesOutput) AnthropicContentBlock { + return AnthropicContentBlock{ + Type: "tool_use", + ID: fromResponsesCallID(item.CallID), + Name: ToolSearchToolName, + Input: jsonObjectOrEmpty(item.Arguments), + } +} + +// jsonObjectOrEmpty keeps raw when it is a JSON object; both tool_search_call +// arguments and tool_use input must be objects. +func jsonObjectOrEmpty(raw string) json.RawMessage { + var probe map[string]json.RawMessage + if json.Unmarshal([]byte(raw), &probe) != nil || probe == nil { + return json.RawMessage(`{}`) + } + return json.RawMessage(raw) +} + +func resToAnthHandleToolSearchDone(evt *ResponsesStreamEvent, state *ResponsesEventToAnthropicState) []AnthropicStreamEvent { + events := closeCurrentBlock(state) + block := toolSearchCallToolUse(*evt.Item) + input := block.Input + block.Input = json.RawMessage(`{}`) + idx := state.ContentBlockIndex + state.HasToolCall = true + events = append(events, + AnthropicStreamEvent{Type: "content_block_start", Index: &idx, ContentBlock: &block}, + AnthropicStreamEvent{Type: "content_block_delta", Index: &idx, Delta: &AnthropicDelta{Type: "input_json_delta", PartialJSON: string(input)}}, + AnthropicStreamEvent{Type: "content_block_stop", Index: &idx}, + ) + state.ContentBlockIndex++ + return events +} diff --git a/backend/internal/pkg/apicompat/anthropic_tool_search_test.go b/backend/internal/pkg/apicompat/anthropic_tool_search_test.go new file mode 100644 index 0000000000..3729a16e8b --- /dev/null +++ b/backend/internal/pkg/apicompat/anthropic_tool_search_test.go @@ -0,0 +1,174 @@ +//go:build unit + +package apicompat + +import ( + "encoding/json" + "testing" + + "github.com/stretchr/testify/require" + "github.com/tidwall/gjson" +) + +const toolSearchTestSchema = `{"type":"object","properties":{"query":{"type":"string"},"max_results":{"type":"number"}},"required":["query","max_results"]}` + +func toolSearchTestRequest(t *testing.T, raw string) *AnthropicRequest { + t.Helper() + var req AnthropicRequest + require.NoError(t, json.Unmarshal([]byte(raw), &req)) + return &req +} + +func nativeToolSearchJSON(t *testing.T, req *AnthropicRequest) []byte { + t.Helper() + out, err := AnthropicToResponses(req) + require.NoError(t, err) + require.NoError(t, ApplyNativeToolSearch(req, out)) + body, err := json.Marshal(out) + require.NoError(t, err) + return body +} + +// Before the reveal Claude Code sends Bash + ToolSearch; after it, the revealed +// WebFetch schema joins tools[] with defer_loading:true and the history carries +// the ToolSearch call plus its tool_reference result. +const toolSearchBeforeReveal = `{"model":"gpt-6-astra","max_tokens":64, + "tools":[ + {"name":"Bash","description":"run","input_schema":{"type":"object","properties":{"command":{"type":"string"}}}}, + {"name":"ToolSearch","description":"search deferred tools","input_schema":` + toolSearchTestSchema + `}], + "messages":[{"role":"user","content":"fetch the page"}]}` + +const toolSearchAfterReveal = `{"model":"gpt-6-astra","max_tokens":64, + "tools":[ + {"name":"Bash","description":"run","input_schema":{"type":"object","properties":{"command":{"type":"string"}}}}, + {"name":"ToolSearch","description":"search deferred tools","input_schema":` + toolSearchTestSchema + `}, + {"name":"WebFetch","description":"fetch a url","input_schema":{"type":"object","properties":{"url":{"type":"string"}},"required":["url"]},"defer_loading":true}], + "messages":[ + {"role":"user","content":"fetch the page"}, + {"role":"assistant","content":[{"type":"tool_use","id":"toolu_search","name":"ToolSearch","input":{"query":"select:WebFetch","max_results":5}}]}, + {"role":"user","content":[{"type":"tool_result","tool_use_id":"toolu_search","content":[{"type":"tool_reference","tool_name":"WebFetch"},{"type":"tool_reference","tool_name":"WebFetch"},{"type":"tool_reference","tool_name":"Unknown"}]}]}]}` + +func TestApplyNativeToolSearch_TopLevelToolsStableAcrossReveal(t *testing.T) { + before := nativeToolSearchJSON(t, toolSearchTestRequest(t, toolSearchBeforeReveal)) + after := nativeToolSearchJSON(t, toolSearchTestRequest(t, toolSearchAfterReveal)) + + require.JSONEq(t, gjson.GetBytes(before, "tools").Raw, gjson.GetBytes(after, "tools").Raw, + "top-level tools must not change when a deferred tool is revealed (prompt cache prefix)") + + tools := gjson.GetBytes(after, "tools").Array() + require.Len(t, tools, 2) + require.Equal(t, "function", tools[0].Get("type").String()) + require.Equal(t, "Bash", tools[0].Get("name").String()) + + search := tools[1] + require.Equal(t, "tool_search", search.Get("type").String()) + require.Equal(t, "client", search.Get("execution").String()) + require.Equal(t, "search deferred tools", search.Get("description").String()) + require.JSONEq(t, toolSearchTestSchema, search.Get("parameters").Raw) + require.False(t, search.Get("name").Exists(), "tool_search carries no function name") + require.False(t, search.Get("strict").Exists(), "tool_search is declared without strict") +} + +func TestApplyNativeToolSearch_HistoryMapsToNativeItems(t *testing.T) { + body := nativeToolSearchJSON(t, toolSearchTestRequest(t, toolSearchAfterReveal)) + input := gjson.GetBytes(body, "input").Array() + require.Len(t, input, 3) + + call := input[1] + require.Equal(t, "tool_search_call", call.Get("type").String()) + require.Equal(t, "toolu_search", call.Get("call_id").String()) + require.Equal(t, "client", call.Get("execution").String()) + require.Equal(t, "completed", call.Get("status").String()) + require.True(t, call.Get("arguments").IsObject(), "tool_search_call arguments are a JSON object") + require.Equal(t, "select:WebFetch", call.Get("arguments.query").String()) + + output := input[2] + require.Equal(t, "tool_search_output", output.Get("type").String()) + require.Equal(t, "toolu_search", output.Get("call_id").String()) + require.Equal(t, "client", output.Get("execution").String()) + require.Equal(t, "completed", output.Get("status").String()) + revealed := output.Get("tools").Array() + require.Len(t, revealed, 1, "duplicate and unknown references are dropped") + require.Equal(t, "function", revealed[0].Get("type").String()) + require.Equal(t, "WebFetch", revealed[0].Get("name").String()) + require.Equal(t, "fetch a url", revealed[0].Get("description").String()) + require.True(t, revealed[0].Get("defer_loading").Bool()) + require.False(t, revealed[0].Get("strict").Bool()) + require.True(t, revealed[0].Get("strict").Exists()) + require.Equal(t, "url", revealed[0].Get("parameters.required.0").String()) +} + +func TestApplyNativeToolSearch_NoToolSearchDeclaredKeepsFunctionTools(t *testing.T) { + req := toolSearchTestRequest(t, toolSearchAfterReveal) + tools := req.Tools[:0:0] + for _, tool := range req.Tools { + if tool.Name != "ToolSearch" { + tools = append(tools, tool) + } + } + req.Tools = tools + + body := nativeToolSearchJSON(t, req) + var names []string + for _, tool := range gjson.GetBytes(body, "tools").Array() { + require.Equal(t, "function", tool.Get("type").String()) + names = append(names, tool.Get("name").String()) + } + require.Equal(t, []string{"Bash", "WebFetch"}, names) + require.NotContains(t, string(body), "tool_search_call") +} + +func TestResponsesToAnthropic_RestoresToolSearchCall(t *testing.T) { + var resp ResponsesResponse + require.NoError(t, json.Unmarshal([]byte(`{"id":"resp_1","status":"completed","output":[ + {"type":"tool_search_call","call_id":"call_search","execution":"client","status":"completed","arguments":{"query":"select:WebFetch","max_results":5}}]}`), &resp)) + + out := ResponsesToAnthropic(&resp, "gpt-6-astra") + require.Len(t, out.Content, 1) + block := out.Content[0] + require.Equal(t, "tool_use", block.Type) + require.Equal(t, "call_search", block.ID) + require.Equal(t, "ToolSearch", block.Name) + require.JSONEq(t, `{"query":"select:WebFetch","max_results":5}`, string(block.Input)) + require.Equal(t, "tool_use", AnthropicStopReasonString(out.StopReason)) +} + +func TestResponsesEventToAnthropic_RestoresToolSearchCall(t *testing.T) { + state := NewResponsesEventToAnthropicState() + var events []AnthropicStreamEvent + for _, raw := range []string{ + `{"type":"response.created","response":{"id":"resp_1","model":"gpt-6-astra"}}`, + `{"type":"response.output_item.added","output_index":0,"item":{"type":"tool_search_call","call_id":"call_search","execution":"client"}}`, + `{"type":"response.output_item.done","output_index":0,"item":{"type":"tool_search_call","call_id":"call_search","execution":"client","status":"completed","arguments":{"query":"docs","max_results":5}}}`, + `{"type":"response.completed","response":{"id":"resp_1","status":"completed","output":[]}}`, + } { + var evt ResponsesStreamEvent + require.NoError(t, json.Unmarshal([]byte(raw), &evt)) + events = append(events, ResponsesEventToAnthropicEvents(&evt, state)...) + } + + var start, delta, stop *AnthropicStreamEvent + for i := range events { + switch events[i].Type { + case "content_block_start": + start = &events[i] + case "content_block_delta": + delta = &events[i] + case "content_block_stop": + stop = &events[i] + } + } + require.NotNil(t, start) + require.Equal(t, "tool_use", start.ContentBlock.Type) + require.Equal(t, "call_search", start.ContentBlock.ID) + require.Equal(t, "ToolSearch", start.ContentBlock.Name) + require.NotNil(t, delta) + require.Equal(t, "input_json_delta", delta.Delta.Type) + require.JSONEq(t, `{"query":"docs","max_results":5}`, delta.Delta.PartialJSON) + require.NotNil(t, stop) + require.Equal(t, *start.Index, *stop.Index) + + last := events[len(events)-2] + require.Equal(t, "message_delta", last.Type) + require.Equal(t, "tool_use", last.Delta.StopReason) +} diff --git a/backend/internal/pkg/apicompat/responses_to_anthropic.go b/backend/internal/pkg/apicompat/responses_to_anthropic.go index 5eab6d9489..f2f3e6ecd8 100644 --- a/backend/internal/pkg/apicompat/responses_to_anthropic.go +++ b/backend/internal/pkg/apicompat/responses_to_anthropic.go @@ -54,6 +54,8 @@ func ResponsesToAnthropic(resp *ResponsesResponse, model string) *AnthropicRespo Name: item.Name, Input: sanitizeAnthropicToolUseInput(item.Name, item.Arguments), }) + case "tool_search_call": + blocks = append(blocks, toolSearchCallToolUse(item)) case "web_search_call": toolUseID := "srvtoolu_" + item.ID query := "" @@ -623,6 +625,10 @@ func resToAnthHandleOutputItemDone(evt *ResponsesStreamEvent, state *ResponsesEv if evt.Item.Type == "web_search_call" && evt.Item.Status == "completed" { return resToAnthHandleWebSearchDone(evt, state) } + // The native tool_search_call carries its arguments only on done. + if evt.Item.Type == "tool_search_call" { + return resToAnthHandleToolSearchDone(evt, state) + } // Capture encrypted_content on reasoning item done (often only present here). if evt.Item.Type == "reasoning" { diff --git a/backend/internal/pkg/apicompat/responses_to_chatcompletions.go b/backend/internal/pkg/apicompat/responses_to_chatcompletions.go index f33d4792b1..f1857a0a2a 100644 --- a/backend/internal/pkg/apicompat/responses_to_chatcompletions.go +++ b/backend/internal/pkg/apicompat/responses_to_chatcompletions.go @@ -515,6 +515,8 @@ type BufferedResponseAccumulator struct { reasoning strings.Builder funcCalls []bufferedFuncCall outputIndexToFuncIdx map[int]int + // tool_search_call items arrive complete on output_item.done. + toolSearchCalls []ResponsesOutput } // NewBufferedResponseAccumulator returns an initialised accumulator. @@ -566,6 +568,10 @@ func (a *BufferedResponseAccumulator) ProcessEvent(event *ResponsesStreamEvent) _, _ = a.funcCalls[idx].Args.WriteString(completed) } } + case "response.output_item.done": + if event.Item != nil && event.Item.Type == "tool_search_call" { + a.toolSearchCalls = append(a.toolSearchCalls, *event.Item) + } case "response.reasoning_summary_text.delta", "response.reasoning_text.delta": if event.Delta != "" { _, _ = a.reasoning.WriteString(event.Delta) @@ -575,7 +581,7 @@ func (a *BufferedResponseAccumulator) ProcessEvent(event *ResponsesStreamEvent) // HasContent reports whether any content has been accumulated. func (a *BufferedResponseAccumulator) HasContent() bool { - return a.text.Len() > 0 || a.refusal.Len() > 0 || len(a.funcCalls) > 0 || a.reasoning.Len() > 0 + return a.text.Len() > 0 || a.refusal.Len() > 0 || len(a.funcCalls) > 0 || len(a.toolSearchCalls) > 0 || a.reasoning.Len() > 0 } // BuildOutput constructs a []ResponsesOutput from the accumulated delta @@ -619,6 +625,7 @@ func (a *BufferedResponseAccumulator) BuildOutput() []ResponsesOutput { Arguments: a.funcCalls[i].Args.String(), }) } + out = append(out, a.toolSearchCalls...) return out } diff --git a/backend/internal/pkg/apicompat/types.go b/backend/internal/pkg/apicompat/types.go index 130f0ff63b..494f0766d6 100644 --- a/backend/internal/pkg/apicompat/types.go +++ b/backend/internal/pkg/apicompat/types.go @@ -80,6 +80,9 @@ type AnthropicContentBlock struct { ToolUseID string `json:"tool_use_id,omitempty"` Content json.RawMessage `json:"content,omitempty"` // string or []AnthropicContentBlock IsError bool `json:"is_error,omitempty"` + + // type=tool_reference (inside a ToolSearch tool_result) + ToolName string `json:"tool_name,omitempty"` } func (b AnthropicContentBlock) MarshalJSON() ([]byte, error) { @@ -122,6 +125,8 @@ type AnthropicTool struct { Description string `json:"description,omitempty"` InputSchema json.RawMessage `json:"input_schema,omitempty"` // JSON Schema object CacheControl *AnthropicCacheControl `json:"cache_control,omitempty"` + // DeferLoading marks a tool Claude Code reveals through ToolSearch. + DeferLoading bool `json:"defer_loading,omitempty"` } // AnthropicCacheControl 对应 Anthropic API 的 cache_control 字段。 @@ -334,6 +339,8 @@ type ResponsesTool struct { Description string `json:"description,omitempty"` Parameters json.RawMessage `json:"parameters,omitempty"` Strict *bool `json:"strict,omitempty"` + // type=tool_search: "client" means the caller executes the search. + Execution string `json:"execution,omitempty"` // type=namespace 的子工具列表(tools 与 children 二选一,语义相同)。 Tools []ResponsesTool `json:"tools,omitempty"` diff --git a/backend/internal/service/openai_gateway_messages.go b/backend/internal/service/openai_gateway_messages.go index 4756d83383..e87c729ac9 100644 --- a/backend/internal/service/openai_gateway_messages.go +++ b/backend/internal/service/openai_gateway_messages.go @@ -172,6 +172,16 @@ func (s *OpenAIGatewayService) ForwardAsAnthropic( responsesReq.ServiceTier = "priority" } + // 3c. ChatGPT/Codex accounts whose model supports tool_search get Claude + // Code's ToolSearch as the native protocol, keeping deferred tools out of + // the top-level tools. + if account.UsesOpenAICodexProtocol() && account.Platform != PlatformGrok && + string(accountCodexToolCapabilities(account, upstreamModel)["supports_search_tool"]) == "true" { + if err := apicompat.ApplyNativeToolSearch(&anthropicReq, responsesReq); err != nil { + return nil, fmt.Errorf("apply native tool_search: %w", err) + } + } + responsesReq.Model = upstreamModel if responsesReq.Reasoning != nil { responsesReq.Reasoning.Effort = openAICompatAnthropicReasoningEffort(&anthropicReq, upstreamModel, responsesReq.Reasoning.Effort) diff --git a/backend/internal/service/openai_gateway_messages_tool_search_test.go b/backend/internal/service/openai_gateway_messages_tool_search_test.go new file mode 100644 index 0000000000..7effea4e08 --- /dev/null +++ b/backend/internal/service/openai_gateway_messages_tool_search_test.go @@ -0,0 +1,158 @@ +//go:build unit + +package service + +import ( + "bytes" + "context" + "io" + "net/http" + "net/http/httptest" + "strings" + "testing" + + "github.com/gin-gonic/gin" + "github.com/stretchr/testify/require" + "github.com/tidwall/gjson" +) + +const messagesToolSearchBody = `{"model":"gpt-6-astra","max_tokens":64,"stream":true, + "tools":[ + {"name":"Bash","description":"run","input_schema":{"type":"object","properties":{"command":{"type":"string"}}}}, + {"name":"ToolSearch","description":"search deferred tools","input_schema":{"type":"object","properties":{"query":{"type":"string"},"max_results":{"type":"number"}},"required":["query","max_results"]}}, + {"name":"WebFetch","description":"fetch a url","input_schema":{"type":"object","properties":{"url":{"type":"string"}}},"defer_loading":true}], + "messages":[ + {"role":"user","content":"fetch the page"}, + {"role":"assistant","content":[{"type":"tool_use","id":"toolu_search","name":"ToolSearch","input":{"query":"select:WebFetch","max_results":5}}]}, + {"role":"user","content":[{"type":"tool_result","tool_use_id":"toolu_search","content":[{"type":"tool_reference","tool_name":"WebFetch"}]}]}]}` + +func forwardMessagesToolSearch(t *testing.T, account *Account, requestBody, upstreamSSE, mappedModel string) (*httpUpstreamRecorder, *httptest.ResponseRecorder) { + t.Helper() + gin.SetMode(gin.TestMode) + rec := httptest.NewRecorder() + c, _ := gin.CreateTestContext(rec) + body := []byte(requestBody) + c.Request = httptest.NewRequest(http.MethodPost, "/v1/messages", bytes.NewReader(body)) + c.Request.Header.Set("Content-Type", "application/json") + upstream := &httpUpstreamRecorder{resp: &http.Response{ + StatusCode: http.StatusOK, + Header: http.Header{"Content-Type": []string{"text/event-stream"}}, + Body: io.NopCloser(strings.NewReader(upstreamSSE)), + }} + svc := &OpenAIGatewayService{ + httpUpstream: upstream, + cfg: rawChatCompletionsTestConfig(), + } + _, err := svc.ForwardAsAnthropic(context.Background(), c, account, body, "", mappedModel) + require.NoError(t, err) + return upstream, rec +} + +const toolSearchCallSSE = "data: {\"type\":\"response.created\",\"response\":{\"id\":\"resp_ts\",\"model\":\"gpt-6-astra\"}}\n\n" + + "data: {\"type\":\"response.output_item.done\",\"output_index\":0,\"item\":{\"type\":\"tool_search_call\",\"call_id\":\"call_search_2\",\"execution\":\"client\",\"status\":\"completed\",\"arguments\":{\"query\":\"notebook\",\"max_results\":5}}}\n\n" + + "data: {\"type\":\"response.completed\",\"response\":{\"id\":\"resp_ts\",\"status\":\"completed\",\"output\":[],\"usage\":{\"input_tokens\":5,\"output_tokens\":2,\"total_tokens\":7}}}\n\n" + +func TestForwardAsAnthropic_CodexOAuthUsesNativeToolSearch(t *testing.T) { + account := &Account{ + ID: 1, Name: "openai-oauth", Platform: PlatformOpenAI, Type: AccountTypeOAuth, Concurrency: 1, + Credentials: map[string]any{"access_token": "oauth-token", "chatgpt_account_id": "chatgpt-acc"}, + } + upstream, rec := forwardMessagesToolSearch(t, account, messagesToolSearchBody, toolSearchCallSSE, "gpt-6-astra") + + tools := gjson.GetBytes(upstream.lastBody, "tools").Array() + require.Len(t, tools, 2, "deferred WebFetch stays out of the top-level tools") + require.Equal(t, "Bash", tools[0].Get("name").String()) + require.Equal(t, "tool_search", tools[1].Get("type").String()) + require.Equal(t, "client", tools[1].Get("execution").String()) + + var types []string + for _, item := range gjson.GetBytes(upstream.lastBody, "input").Array() { + types = append(types, item.Get("type").String()) + } + require.Contains(t, types, "tool_search_call") + require.Contains(t, types, "tool_search_output") + require.NotContains(t, types, "function_call") + + out := rec.Body.String() + require.Contains(t, out, `"name":"ToolSearch"`) + require.Contains(t, out, `"id":"call_search_2"`) + require.Contains(t, out, `"stop_reason":"tool_use"`) +} + +func TestForwardAsAnthropic_NonCodexAccountKeepsFunctionToolSearch(t *testing.T) { + completed := "data: {\"type\":\"response.completed\",\"response\":{\"id\":\"resp_fn\",\"status\":\"completed\",\"output\":[],\"usage\":{\"input_tokens\":5,\"output_tokens\":2,\"total_tokens\":7}}}\n\n" + upstream, _ := forwardMessagesToolSearch(t, rawChatCompletionsTestAccount(), messagesToolSearchBody, completed, "gpt-6-astra") + + var names []string + for _, tool := range gjson.GetBytes(upstream.lastBody, "tools").Array() { + require.Equal(t, "function", tool.Get("type").String()) + names = append(names, tool.Get("name").String()) + } + require.Equal(t, []string{"Bash", "ToolSearch", "WebFetch"}, names) + require.NotContains(t, string(upstream.lastBody), "tool_search_call") +} + +// A Codex OAuth model without supports_search_tool keeps ToolSearch and the +// deferred tools as plain function tools. +func TestForwardAsAnthropic_CodexOAuthModelWithoutSearchSupportKeepsFunctionToolSearch(t *testing.T) { + account := &Account{ + ID: 1, Name: "openai-oauth", Platform: PlatformOpenAI, Type: AccountTypeOAuth, Concurrency: 1, + Credentials: map[string]any{"access_token": "oauth-token", "chatgpt_account_id": "chatgpt-acc"}, + } + completed := "data: {\"type\":\"response.completed\",\"response\":{\"id\":\"resp_fn\",\"status\":\"completed\",\"output\":[],\"usage\":{\"input_tokens\":5,\"output_tokens\":2,\"total_tokens\":7}}}\n\n" + body := strings.Replace(messagesToolSearchBody, `"model":"gpt-6-astra"`, `"model":"gpt-5.5"`, 1) + upstream, _ := forwardMessagesToolSearch(t, account, body, completed, "gpt-5.5") + + var names []string + for _, tool := range gjson.GetBytes(upstream.lastBody, "tools").Array() { + require.Equal(t, "function", tool.Get("type").String()) + names = append(names, tool.Get("name").String()) + } + require.Equal(t, []string{"Bash", "ToolSearch", "WebFetch"}, names) + require.NotContains(t, string(upstream.lastBody), "tool_search_call") +} + +// Claude Code also sends stream:false turns; their upstream stream can end +// with an empty terminal output, rebuilt from the buffered output items. +func TestForwardAsAnthropic_CodexOAuthNonStreamingRestoresToolSearchCall(t *testing.T) { + account := &Account{ + ID: 1, Name: "openai-oauth", Platform: PlatformOpenAI, Type: AccountTypeOAuth, Concurrency: 1, + Credentials: map[string]any{"access_token": "oauth-token", "chatgpt_account_id": "chatgpt-acc"}, + } + body := strings.Replace(messagesToolSearchBody, `"stream":true`, `"stream":false`, 1) + _, rec := forwardMessagesToolSearch(t, account, body, toolSearchCallSSE, "gpt-6-astra") + + out := rec.Body.String() + require.Contains(t, out, `"name":"ToolSearch"`) + require.Contains(t, out, `"id":"call_search_2"`) + require.Contains(t, out, `"stop_reason":"tool_use"`) + require.Equal(t, "notebook", gjson.Get(out, "content.0.input.query").String()) +} + +// Grok OAuth accounts also speak the Codex protocol, but xAI has no native +// tool_search: ToolSearch and deferred tools stay function tools there. +func TestForwardAsAnthropic_GrokOAuthKeepsFunctionToolSearch(t *testing.T) { + gin.SetMode(gin.TestMode) + c, _ := gin.CreateTestContext(httptest.NewRecorder()) + body := []byte(messagesToolSearchBody) + c.Request = httptest.NewRequest(http.MethodPost, "/v1/messages", bytes.NewReader(body)) + account := healthyGrokOAuthGatewayTestAccount(71, "access-token") + repo := &grokQuotaAccountRepo{mockAccountRepoForPlatform: &mockAccountRepoForPlatform{accountsByID: map[int64]*Account{71: account}}} + upstream := &httpUpstreamRecorder{resp: grokMessagesSSECompletedResponse("resp_grok_ts", 0)} + svc := &OpenAIGatewayService{httpUpstream: upstream, grokTokenProvider: NewGrokTokenProvider(repo, nil), accountRepo: repo} + + _, err := svc.ForwardAsAnthropic(context.Background(), c, account, body, "", "") + require.NoError(t, err) + + var functions []string + for _, tool := range gjson.GetBytes(upstream.lastBody, "tools").Array() { + require.NotEqual(t, "tool_search", tool.Get("type").String()) + if tool.Get("type").String() == "function" { + functions = append(functions, tool.Get("name").String()) + } + } + require.Contains(t, functions, "ToolSearch") + require.Contains(t, functions, "WebFetch") + require.NotContains(t, string(upstream.lastBody), "tool_search_call") + require.NotContains(t, string(upstream.lastBody), "tool_search_output") +} From 30152d1b16fb2fbc5d3d58a8ca71d2bd6fea8a89 Mon Sep 17 00:00:00 2001 From: Anankke Date: Sat, 14 Nov 2026 07:09:38 -0800 Subject: [PATCH 15/85] fix(apicompat): tolerate non-string action.url and skip unfinished web_search calls WebSearchAction.URL was a strict string, so a web_search_call whose action.url was not a string failed decoding of the whole Responses event and the Messages stream lost its terminal event. It is now raw like Sources and read as a string only for open_page. The non-streaming converter also filled results for web_search_call items that had not completed, while the streaming one only handles completed items. Both now emit blocks for completed calls only. --- .../pkg/apicompat/responses_to_anthropic.go | 3 +++ .../apicompat/responses_web_search_sources.go | 13 ++++++---- .../responses_web_search_sources_test.go | 24 +++++++++++++++++-- backend/internal/pkg/apicompat/types.go | 6 ++--- 4 files changed, 36 insertions(+), 10 deletions(-) diff --git a/backend/internal/pkg/apicompat/responses_to_anthropic.go b/backend/internal/pkg/apicompat/responses_to_anthropic.go index a1c6485164..7ac3ffe0c7 100644 --- a/backend/internal/pkg/apicompat/responses_to_anthropic.go +++ b/backend/internal/pkg/apicompat/responses_to_anthropic.go @@ -55,6 +55,9 @@ func ResponsesToAnthropic(resp *ResponsesResponse, model string) *AnthropicRespo Input: sanitizeAnthropicToolUseInput(item.Name, item.Arguments), }) case "web_search_call": + if item.Status != "completed" { + continue + } toolUseID := "srvtoolu_" + item.ID query := "" if item.Action != nil { diff --git a/backend/internal/pkg/apicompat/responses_web_search_sources.go b/backend/internal/pkg/apicompat/responses_web_search_sources.go index 39efc7370d..f6f0bf16a7 100644 --- a/backend/internal/pkg/apicompat/responses_web_search_sources.go +++ b/backend/internal/pkg/apicompat/responses_web_search_sources.go @@ -27,9 +27,9 @@ type webSearchResult struct { } // webSearchCallResults is the web_search_tool_result content for one call: a -// search's action.sources, or the single page a completed open_page opened. -// Sources are decoded entry by entry, so one malformed entry cannot fail the -// terminal event that carries the call. +// search's action.sources, or the single page an open_page opened. Callers +// pass completed calls only. Sources and the page URL are decoded leniently, so +// a malformed value cannot fail the terminal event that carries the call. func webSearchCallResults(item *ResponsesOutput) json.RawMessage { results := []webSearchResult{} if action := item.Action; action != nil { @@ -42,8 +42,11 @@ func webSearchCallResults(item *ResponsesOutput) json.RawMessage { results = append(results, newWebSearchResult(rawURL)) } } - } else if action.Type == "open_page" && item.Status == "completed" && action.URL != "" { - results = append(results, newWebSearchResult(action.URL)) + } else if action.Type == "open_page" { + var pageURL string + if json.Unmarshal(action.URL, &pageURL) == nil && pageURL != "" { + results = append(results, newWebSearchResult(pageURL)) + } } } out, _ := json.Marshal(results) diff --git a/backend/internal/pkg/apicompat/responses_web_search_sources_test.go b/backend/internal/pkg/apicompat/responses_web_search_sources_test.go index 07742de86c..3cf9c04f3e 100644 --- a/backend/internal/pkg/apicompat/responses_web_search_sources_test.go +++ b/backend/internal/pkg/apicompat/responses_web_search_sources_test.go @@ -100,11 +100,31 @@ func TestWebSearchOpenPageReturnsSinglePage(t *testing.T) { func TestWebSearchOpenPageRequiresCompletedURL(t *testing.T) { for name, item := range map[string]string{ - "in progress": `{"type":"web_search_call","id":"ws_1","status":"in_progress","action":{"type":"open_page","url":"https://docs.example/page"}}`, - "empty url": `{"type":"web_search_call","id":"ws_1","status":"completed","action":{"type":"open_page","url":""}}`, + "empty url": `{"type":"web_search_call","id":"ws_1","status":"completed","action":{"type":"open_page","url":""}}`, } { t.Run(name, func(t *testing.T) { require.JSONEq(t, `[]`, nonStreamingWebSearchResults(t, item)["srvtoolu_ws_1"]) }) } } + +func TestWebSearchNonStringActionURLKeepsEvent(t *testing.T) { + for name, url := range map[string]string{"number": `123`, "object": `{"a":1}`, "array": `["a"]`} { + t.Run(name, func(t *testing.T) { + raw := `{"type":"web_search_call","id":"ws_1","status":"completed","action":{"type":"open_page","url":` + url + `}}` + got := nonStreamingWebSearchResults(t, raw) + require.JSONEq(t, `[]`, got["srvtoolu_ws_1"]) + require.JSONEq(t, `[]`, streamingWebSearchResults(t, raw)["srvtoolu_ws_1"]) + }) + } +} + +func TestWebSearchCallsThatDidNotCompleteProduceNoBlocks(t *testing.T) { + for _, status := range []string{"failed", "in_progress"} { + t.Run(status, func(t *testing.T) { + raw := `{"type":"web_search_call","id":"ws_1","status":"` + status + `","action":{"type":"search","query":"q","sources":[{"url":"https://a.example/1"}]}}` + require.Empty(t, nonStreamingWebSearchResults(t, raw)) + require.Empty(t, streamingWebSearchResults(t, raw)) + }) + } +} diff --git a/backend/internal/pkg/apicompat/types.go b/backend/internal/pkg/apicompat/types.go index a603d64147..d421feef78 100644 --- a/backend/internal/pkg/apicompat/types.go +++ b/backend/internal/pkg/apicompat/types.go @@ -492,9 +492,9 @@ func (o *ResponsesOutput) UnmarshalJSON(data []byte) error { type WebSearchAction struct { Type string `json:"type,omitempty"` // "search" Query string `json:"query,omitempty"` // primary search query - URL string `json:"url,omitempty"` // open_page / find_in_page target - // Sources stays raw: a strictly typed entry of an unexpected shape would - // fail decoding the whole terminal event that carries this call. + // URL and Sources stay raw: a strictly typed value of an unexpected shape + // would fail decoding the whole terminal event that carries this call. + URL json.RawMessage `json:"url,omitempty"` // open_page / find_in_page target Sources json.RawMessage `json:"sources,omitempty"` } From 3f1a7c6d9d1906989a19aba330d477b8e72b80c1 Mon Sep 17 00:00:00 2001 From: Anankke Date: Sat, 14 Nov 2026 06:15:40 -0800 Subject: [PATCH 16/85] fix(apicompat): keep forced tools, result text and reserved names intact A revealed tool was declared in tool_search_output under its own name while its replayed function_call used the Codex reserved-name alias, so the two disagreed for python. Reserved-name collection now walks tool_search_output tools like additional_tools. The collector is shared with the /v1/responses passthrough entries, so they now alias tool_search_output definitions too. The Responses API has no tool_choice value that forces tool_search or a tool that only tool_search_output declares, so a request forcing ToolSearch or a deferred tool keeps the plain function mapping and its body is unchanged. tool_search_output has no field for the result text, so text and errors from a ToolSearch result ride in a separate input_text part of the user message after the tool outputs, ahead of the user's own parts. --- .../pkg/apicompat/anthropic_tool_search.go | 92 +++++++++++++++++-- .../apicompat/anthropic_tool_search_test.go | 82 +++++++++++++++++ .../service/openai_codex_tool_names.go | 2 +- ...penai_gateway_messages_tool_search_test.go | 76 +++++++++++++++ 4 files changed, 245 insertions(+), 7 deletions(-) diff --git a/backend/internal/pkg/apicompat/anthropic_tool_search.go b/backend/internal/pkg/apicompat/anthropic_tool_search.go index 55518e0db4..b21636d0b7 100644 --- a/backend/internal/pkg/apicompat/anthropic_tool_search.go +++ b/backend/internal/pkg/apicompat/anthropic_tool_search.go @@ -2,6 +2,7 @@ package apicompat import ( "encoding/json" + "strings" ) // ToolSearchToolName is Claude Code's client-executed tool-search tool. Under @@ -10,6 +11,10 @@ import ( // `tool_search_output`; an upstream tool_search_call comes back under this name. const ToolSearchToolName = "ToolSearch" +// emptyToolResultOutput is what convertToolResultOutput emits for a +// tool_result without text. +const emptyToolResultOutput = "(empty)" + // ApplyNativeToolSearch rewrites a Responses request produced by // AnthropicToResponses so Claude Code's ToolSearch uses the native // client-executed tool_search protocol of the ChatGPT/Codex backend. @@ -19,13 +24,18 @@ const ToolSearchToolName = "ToolSearch" // the prompt-cache prefix) stay identical before and after a reveal. func ApplyNativeToolSearch(req *AnthropicRequest, out *ResponsesRequest) error { declared := false + deferred := make(map[string]bool) for _, t := range req.Tools { - if t.Name == ToolSearchToolName && !t.DeferLoading { + if t.DeferLoading { + deferred[t.Name] = true + } else if t.Name == ToolSearchToolName { declared = true - break } } - if !declared { + // The Responses API has no tool_choice value that forces tool_search or a + // tool declared only in tool_search_output, so a request forcing either + // keeps every tool and call as a plain function. + if !declared || forcesHiddenTool(req.ToolChoice, deferred) { return nil } @@ -60,13 +70,34 @@ func ApplyNativeToolSearch(req *AnthropicRequest, out *ResponsesRequest) error { if err := json.Unmarshal(out.Input, &items); err != nil { return err } - for i, raw := range items { + rewritten := make([]json.RawMessage, 0, len(items)) + var pendingText []string + flush := func(next json.RawMessage) (json.RawMessage, error) { + text := strings.Join(pendingText, "\n\n") + pendingText = nil + return userMessageWithLeadingText(next, text) + } + for _, raw := range items { var item ResponsesInputItem if err := json.Unmarshal(raw, &item); err != nil { return err } + if len(pendingText) > 0 && item.Type != "function_call_output" { + // A tool_search_output has no field for the result text, so it rides + // in the user message that follows the run of tool outputs. + merged, err := flush(raw) + if err != nil { + return err + } + if item.Type == "message" && item.Role == "user" { + raw = merged + } else { + rewritten = append(rewritten, merged) + } + } names, isSearch := revealed[item.CallID] if !isSearch { + rewritten = append(rewritten, raw) continue } var native any @@ -102,16 +133,27 @@ func ApplyNativeToolSearch(req *AnthropicRequest, out *ResponsesRequest) error { "status": "completed", "tools": loaded, } + if item.Output != "" && item.Output != emptyToolResultOutput { + pendingText = append(pendingText, item.Output) + } default: + rewritten = append(rewritten, raw) continue } encoded, err := json.Marshal(native) if err != nil { return err } - items[i] = encoded + rewritten = append(rewritten, encoded) } - input, err := json.Marshal(items) + if len(pendingText) > 0 { + tail, err := flush(nil) + if err != nil { + return err + } + rewritten = append(rewritten, tail) + } + input, err := json.Marshal(rewritten) if err != nil { return err } @@ -119,6 +161,44 @@ func ApplyNativeToolSearch(req *AnthropicRequest, out *ResponsesRequest) error { return nil } +// userMessageWithLeadingText returns next with a separate input_text part for +// text placed ahead of its existing parts when next is a user message, and +// otherwise a new user message holding text. Existing parts stay untouched. +func userMessageWithLeadingText(next json.RawMessage, text string) (json.RawMessage, error) { + lead, err := json.Marshal(ResponsesContentPart{Type: "input_text", Text: text}) + if err != nil { + return nil, err + } + var msg ResponsesInputItem + if len(next) > 0 && json.Unmarshal(next, &msg) == nil && msg.Type == "message" && msg.Role == "user" { + var parts []json.RawMessage + if json.Unmarshal(msg.Content, &parts) == nil { + content, err := json.Marshal(append([]json.RawMessage{lead}, parts...)) + if err != nil { + return nil, err + } + msg.Content = content + return json.Marshal(msg) + } + } + content, err := json.Marshal([]json.RawMessage{lead}) + if err != nil { + return nil, err + } + return json.Marshal(ResponsesInputItem{Type: "message", Role: "user", Content: content}) +} + +func forcesHiddenTool(raw json.RawMessage, deferred map[string]bool) bool { + var choice struct { + Type string `json:"type"` + Name string `json:"name"` + } + if len(raw) == 0 || json.Unmarshal(raw, &choice) != nil { + return false + } + return choice.Type == "tool" && (choice.Name == ToolSearchToolName || deferred[choice.Name]) +} + // toolSearchReveals maps each ToolSearch tool_use id in the history to the // tool names its tool_result referenced, first occurrence first. func toolSearchReveals(msgs []AnthropicMessage) map[string][]string { diff --git a/backend/internal/pkg/apicompat/anthropic_tool_search_test.go b/backend/internal/pkg/apicompat/anthropic_tool_search_test.go index 3729a16e8b..76446588c6 100644 --- a/backend/internal/pkg/apicompat/anthropic_tool_search_test.go +++ b/backend/internal/pkg/apicompat/anthropic_tool_search_test.go @@ -118,6 +118,88 @@ func TestApplyNativeToolSearch_NoToolSearchDeclaredKeepsFunctionTools(t *testing require.NotContains(t, string(body), "tool_search_call") } +func TestApplyNativeToolSearch_ForcedHiddenToolLeavesRequestUntouched(t *testing.T) { + for _, name := range []string{"ToolSearch", "WebFetch"} { + for _, raw := range []string{toolSearchBeforeReveal, toolSearchAfterReveal} { + req := toolSearchTestRequest(t, raw) + if name == "WebFetch" { + req.Tools = append(req.Tools, AnthropicTool{Name: "WebFetch", InputSchema: json.RawMessage(`{"type":"object"}`), DeferLoading: true}) + } + req.ToolChoice = json.RawMessage(`{"type":"tool","name":"` + name + `"}`) + want, err := AnthropicToResponses(req) + require.NoError(t, err) + wantBody, err := json.Marshal(want) + require.NoError(t, err) + + require.Equal(t, string(wantBody), string(nativeToolSearchJSON(t, req)), name) + require.NotContains(t, string(wantBody), "tool_search", name) + } + } +} + +func TestApplyNativeToolSearch_OtherToolChoicesKeepNativeMapping(t *testing.T) { + for _, choice := range []string{ + `{"type":"tool","name":"Bash"}`, + `{"type":"auto"}`, + `{"type":"any"}`, + } { + req := toolSearchTestRequest(t, toolSearchAfterReveal) + req.ToolChoice = json.RawMessage(choice) + body := nativeToolSearchJSON(t, req) + require.Equal(t, "tool_search", gjson.GetBytes(body, "tools.1.type").String(), choice) + require.Contains(t, string(body), "tool_search_output", choice) + } +} + +func toolSearchResultRequest(t *testing.T, result string, trailing string) *AnthropicRequest { + t.Helper() + return toolSearchTestRequest(t, `{"model":"gpt-6-astra","max_tokens":64, + "tools":[ + {"name":"ToolSearch","description":"search deferred tools","input_schema":`+toolSearchTestSchema+`}, + {"name":"WebFetch","description":"fetch a url","input_schema":{"type":"object"},"defer_loading":true}], + "messages":[ + {"role":"user","content":"fetch the page"}, + {"role":"assistant","content":[{"type":"tool_use","id":"toolu_search","name":"ToolSearch","input":{"query":"x","max_results":5}}]}, + {"role":"user","content":[{"type":"tool_result","tool_use_id":"toolu_search",`+result+`}`+trailing+`]}]}`) +} + +func TestApplyNativeToolSearch_ResultTextRidesInFollowingUserMessage(t *testing.T) { + cases := []struct { + name, result, trailing, wantText, wantUser string + wantTools int + }{ + {"error", `"is_error":true,"content":"InputValidationError"`, "", "InputValidationError", "", 0}, + {"no match string", `"content":"No matching deferred tools found"`, "", "No matching deferred tools found", "", 0}, + {"text with reference", `"content":[{"type":"text","text":"found one"},{"type":"tool_reference","tool_name":"WebFetch"}]`, "", "found one", "", 1}, + {"separate part ahead of following text", `"content":"No matching deferred tools found"`, `,{"type":"text","text":"retry"}`, "No matching deferred tools found", "retry", 0}, + } + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + body := nativeToolSearchJSON(t, toolSearchResultRequest(t, tc.result, tc.trailing)) + input := gjson.GetBytes(body, "input").Array() + require.Len(t, input, 4) + require.Equal(t, "tool_search_call", input[1].Get("type").String()) + require.Equal(t, "tool_search_output", input[2].Get("type").String()) + require.Len(t, input[2].Get("tools").Array(), tc.wantTools) + require.Equal(t, "message", input[3].Get("type").String()) + require.Equal(t, "user", input[3].Get("role").String()) + parts := input[3].Get("content").Array() + require.Equal(t, tc.wantText, parts[0].Get("text").String()) + if tc.wantUser == "" { + require.Len(t, parts, 1) + return + } + require.Len(t, parts, 2) + require.Equal(t, `{"type":"input_text","text":"`+tc.wantUser+`"}`, parts[1].Raw) + }) + } + + t.Run("reference only adds no message", func(t *testing.T) { + body := nativeToolSearchJSON(t, toolSearchResultRequest(t, `"content":[{"type":"tool_reference","tool_name":"WebFetch"}]`, "")) + require.Len(t, gjson.GetBytes(body, "input").Array(), 3) + }) +} + func TestResponsesToAnthropic_RestoresToolSearchCall(t *testing.T) { var resp ResponsesResponse require.NoError(t, json.Unmarshal([]byte(`{"id":"resp_1","status":"completed","output":[ diff --git a/backend/internal/service/openai_codex_tool_names.go b/backend/internal/service/openai_codex_tool_names.go index 849a45e417..45b1af0ab3 100644 --- a/backend/internal/service/openai_codex_tool_names.go +++ b/backend/internal/service/openai_codex_tool_names.go @@ -132,7 +132,7 @@ func collectOpenAIResponsesToolNameFields(reqBody map[string]any) []codexToolNam continue } typ := strings.ToLower(strings.TrimSpace(firstNonEmptyString(item["type"]))) - if typ == "additional_tools" { + if typ == "additional_tools" || typ == "tool_search_output" { collectTools(item["tools"]) } if typ == "function_call" { diff --git a/backend/internal/service/openai_gateway_messages_tool_search_test.go b/backend/internal/service/openai_gateway_messages_tool_search_test.go index 7effea4e08..27c22fea45 100644 --- a/backend/internal/service/openai_gateway_messages_tool_search_test.go +++ b/backend/internal/service/openai_gateway_messages_tool_search_test.go @@ -112,6 +112,82 @@ func TestForwardAsAnthropic_CodexOAuthModelWithoutSearchSupportKeepsFunctionTool require.NotContains(t, string(upstream.lastBody), "tool_search_call") } +func codexOAuthToolSearchAccount() *Account { + return &Account{ + ID: 1, Name: "openai-oauth", Platform: PlatformOpenAI, Type: AccountTypeOAuth, Concurrency: 1, + Credentials: map[string]any{"access_token": "oauth-token", "chatgpt_account_id": "chatgpt-acc"}, + } +} + +const toolSearchNoopSSE = "data: {\"type\":\"response.completed\",\"response\":{\"id\":\"resp_noop\",\"status\":\"completed\",\"output\":[],\"usage\":{\"input_tokens\":5,\"output_tokens\":2,\"total_tokens\":7}}}\n\n" + +// A revealed tool is declared in tool_search_output and replayed as a +// function_call; both must carry the same upstream name. +func TestForwardAsAnthropic_CodexOAuthRevealedToolNameMatchesReplay(t *testing.T) { + for _, tc := range []struct{ name, want string }{ + {"python", "python__sub2api"}, + {"Python", "python__sub2api"}, + {"Echo", "Echo"}, + } { + t.Run(tc.name, func(t *testing.T) { + body := strings.ReplaceAll(messagesToolSearchBody, "WebFetch", tc.name) + body = strings.TrimSuffix(body, "]}") + `, + {"role":"assistant","content":[{"type":"tool_use","id":"toolu_call","name":"` + tc.name + `","input":{"url":"https://example.com"}}]}, + {"role":"user","content":[{"type":"tool_result","tool_use_id":"toolu_call","content":"ok"}]}]}` + upstream, _ := forwardMessagesToolSearch(t, codexOAuthToolSearchAccount(), body, toolSearchNoopSSE, "gpt-6-astra") + + var declared, replayed []string + for _, item := range gjson.GetBytes(upstream.lastBody, "input").Array() { + switch item.Get("type").String() { + case "tool_search_output": + for _, tool := range item.Get("tools").Array() { + declared = append(declared, tool.Get("name").String()) + } + case "function_call": + replayed = append(replayed, item.Get("name").String()) + } + } + require.Equal(t, []string{tc.want}, declared) + require.Equal(t, []string{tc.want}, replayed) + }) + } +} + +// Selections that name a top-level function or carry no name are forwarded +// as the bridge produced them. +func TestForwardAsAnthropic_CodexOAuthToolChoiceControls(t *testing.T) { + for choice, want := range map[string]string{ + `{"type":"tool","name":"Bash"}`: `{"type":"function","name":"Bash"}`, + `{"type":"auto"}`: `"auto"`, + `{"type":"any"}`: `"required"`, + } { + t.Run(choice, func(t *testing.T) { + body := strings.Replace(messagesToolSearchBody, `"stream":true,`, `"stream":true,"tool_choice":`+choice+`,`, 1) + upstream, _ := forwardMessagesToolSearch(t, codexOAuthToolSearchAccount(), body, toolSearchNoopSSE, "gpt-6-astra") + require.JSONEq(t, want, gjson.GetBytes(upstream.lastBody, "tool_choice").Raw) + }) + } +} + +func TestForwardAsAnthropic_CodexOAuthForcedHiddenToolKeepsFunctionTools(t *testing.T) { + for _, name := range []string{"ToolSearch", "WebFetch"} { + t.Run(name, func(t *testing.T) { + body := strings.Replace(messagesToolSearchBody, `"stream":true,`, `"stream":true,"tool_choice":{"type":"tool","name":"`+name+`"},`, 1) + upstream, _ := forwardMessagesToolSearch(t, codexOAuthToolSearchAccount(), body, toolSearchNoopSSE, "gpt-6-astra") + + var names []string + for _, tool := range gjson.GetBytes(upstream.lastBody, "tools").Array() { + require.Equal(t, "function", tool.Get("type").String()) + names = append(names, tool.Get("name").String()) + } + require.Equal(t, []string{"Bash", "ToolSearch", "WebFetch"}, names) + require.JSONEq(t, `{"type":"function","name":"`+name+`"}`, gjson.GetBytes(upstream.lastBody, "tool_choice").Raw) + require.NotContains(t, string(upstream.lastBody), "tool_search_call") + require.NotContains(t, string(upstream.lastBody), "tool_search_output") + }) + } +} + // Claude Code also sends stream:false turns; their upstream stream can end // with an empty terminal output, rebuilt from the buffered output items. func TestForwardAsAnthropic_CodexOAuthNonStreamingRestoresToolSearchCall(t *testing.T) { From f72ef070975445fe077c6c267369f08e38ca52e7 Mon Sep 17 00:00:00 2001 From: Anankke Date: Sat, 14 Nov 2026 06:18:52 -0800 Subject: [PATCH 17/85] fix(openai): keep hosted output items in buffered compat responses Non-streaming /v1/messages and /v1/chat/completions force an upstream stream and read it with readOpenAICompatBufferedTerminal, and the Codex OAuth backend ends that stream with an empty terminal output. The delta accumulator rebuilds only reasoning, message and function calls, so web_search_call, image_generation_call and other hosted items were dropped and /v1/messages lost its server_tool_use and web_search_tool_result blocks. The reader now collects the output_item.done items of every type the accumulator does not produce and adds them to an empty terminal output, after the leading reasoning item and ahead of the message and function calls. The accumulator's own items stay exactly as it builds them, so reasoning text, function call arguments and custom tool calls are unchanged, and a non-empty terminal output is untouched. --- .../openai_gateway_buffered_hosted_items.go | 102 ++++++ ...enai_gateway_buffered_hosted_items_test.go | 346 ++++++++++++++++++ .../service/openai_gateway_messages.go | 5 + 3 files changed, 453 insertions(+) create mode 100644 backend/internal/service/openai_gateway_buffered_hosted_items.go create mode 100644 backend/internal/service/openai_gateway_buffered_hosted_items_test.go diff --git a/backend/internal/service/openai_gateway_buffered_hosted_items.go b/backend/internal/service/openai_gateway_buffered_hosted_items.go new file mode 100644 index 0000000000..133ae6dc55 --- /dev/null +++ b/backend/internal/service/openai_gateway_buffered_hosted_items.go @@ -0,0 +1,102 @@ +package service + +import ( + "encoding/json" + "slices" + "sort" + "strings" + + "github.com/Wei-Shaw/sub2api/internal/pkg/apicompat" + "github.com/tidwall/gjson" +) + +// openAICompatAccumulatedItemTypes are the output item types that +// apicompat.BufferedResponseAccumulator rebuilds from deltas. Every other type +// can only be recovered from its response.output_item.done event. +var openAICompatAccumulatedItemTypes = map[string]struct{}{ + "reasoning": {}, + "message": {}, + "function_call": {}, + "custom_tool_call": {}, +} + +type openAICompatHostedItem struct { + index int64 + indexed bool + raw json.RawMessage +} + +// openAICompatHostedItems collects the response.output_item.done items of types +// the delta accumulator does not produce, such as web_search_call and +// image_generation_call. +type openAICompatHostedItems struct { + items []openAICompatHostedItem +} + +func (h *openAICompatHostedItems) Observe(payload []byte) { + if h == nil || strings.TrimSpace(gjson.GetBytes(payload, "type").String()) != "response.output_item.done" || !gjson.ValidBytes(payload) { + return + } + item := gjson.GetBytes(payload, "item") + if !item.IsObject() { + return + } + itemType := strings.TrimSpace(item.Get("type").String()) + if _, ok := openAICompatAccumulatedItemTypes[itemType]; ok || itemType == "" { + return + } + entry := openAICompatHostedItem{raw: json.RawMessage(item.Raw)} + if index := gjson.GetBytes(payload, "output_index"); index.Exists() { + entry.index, entry.indexed = index.Int(), true + for i := range h.items { + if h.items[i].indexed && h.items[i].index == entry.index { + h.items[i] = entry + return + } + } + } + h.items = append(h.items, entry) +} + +// fillTerminalOutput gives an empty terminal output the collected hosted items +// ahead of what the accumulator rebuilds, after its leading reasoning item. +// Only terminals that carry a result are filled; the output of response.failed +// and error terminals never reaches the client and is left as the upstream sent it. +// Hosted items keep their output_index order; items reported without an +// output_index follow the indexed ones in arrival order. +func (h *openAICompatHostedItems) fillTerminalOutput(eventType string, response *apicompat.ResponsesResponse, acc *apicompat.BufferedResponseAccumulator) { + switch strings.TrimSpace(eventType) { + case "response.completed", "response.done", "response.incomplete": + default: + return + } + if h == nil || len(h.items) == 0 || response == nil || len(response.Output) > 0 { + return + } + sort.SliceStable(h.items, func(i, j int) bool { + a, b := h.items[i], h.items[j] + if a.indexed != b.indexed { + return a.indexed + } + return a.indexed && a.index < b.index + }) + hosted := make([]apicompat.ResponsesOutput, 0, len(h.items)) + for _, entry := range h.items { + var item apicompat.ResponsesOutput + if err := json.Unmarshal(entry.raw, &item); err == nil { + hosted = append(hosted, item) + } + } + if len(hosted) == 0 { + return + } + var output []apicompat.ResponsesOutput + if acc != nil && acc.HasContent() { + output = acc.BuildOutput() + } + at := 0 + for at < len(output) && output[at].Type == "reasoning" { + at++ + } + response.Output = slices.Insert(output, at, hosted...) +} diff --git a/backend/internal/service/openai_gateway_buffered_hosted_items_test.go b/backend/internal/service/openai_gateway_buffered_hosted_items_test.go new file mode 100644 index 0000000000..435d3fe6a3 --- /dev/null +++ b/backend/internal/service/openai_gateway_buffered_hosted_items_test.go @@ -0,0 +1,346 @@ +//go:build unit + +package service + +import ( + "bytes" + "context" + "io" + "net/http" + "net/http/httptest" + "strings" + "testing" + + "github.com/gin-gonic/gin" + "github.com/stretchr/testify/require" + "github.com/tidwall/gjson" +) + +const bufferedHostedItemsMessagesBody = `{"model":"gpt-5.5","max_tokens":64,"stream":false,"messages":[{"role":"user","content":"search the web"}]}` + +const bufferedHostedItemsThinkingBody = `{"model":"gpt-5.5","max_tokens":4096,"stream":false,"thinking":{"type":"enabled","budget_tokens":2048},"messages":[{"role":"user","content":"search the web"}]}` + +const bufferedHostedItemsChatBody = `{"model":"gpt-5.5","stream":false,"messages":[{"role":"user","content":"search the web"}]}` + +const bufferedHostedItemsCreated = `{"type":"response.created","response":{"id":"resp_1","model":"gpt-5.5"}}` + +const bufferedHostedItemsCompleted = `{"type":"response.completed","response":{"id":"resp_1","status":"completed","output":[],"usage":{"input_tokens":5,"output_tokens":2,"total_tokens":7}}}` + +const ( + bufferedHostedItemsWebSearchDone = `{"type":"response.output_item.done","output_index":0,"item":{"type":"web_search_call","id":"ws_1","status":"completed","action":{"type":"search","query":"q","sources":[{"type":"url","url":"https://a.example/1"}]}}}` + bufferedHostedItemsImageDone = `{"type":"response.output_item.done","output_index":1,"item":{"type":"image_generation_call","id":"ig_1","status":"completed","result":"aGVsbG8="}}` + bufferedHostedItemsTextDelta = `{"type":"response.output_text.delta","output_index":2,"delta":"found it"}` + bufferedHostedItemsMessageDone = `{"type":"response.output_item.done","output_index":2,"item":{"type":"message","id":"msg_1","role":"assistant","status":"completed","content":[{"type":"output_text","text":"found it"}]}}` +) + +// bufferedItemsSSE joins JSON events into an SSE body. +func bufferedItemsSSE(events ...string) string { + var b strings.Builder + for _, event := range events { + b.WriteString("data: " + event + "\n\n") + } + return b.String() +} + +// The upstream reports every output item on output_item.done but ends with an +// empty terminal output. +var bufferedHostedItemsSSE = bufferedItemsSSE( + bufferedHostedItemsCreated, + `{"type":"response.output_item.added","output_index":0,"item":{"type":"web_search_call","id":"ws_1","status":"in_progress"}}`, + bufferedHostedItemsWebSearchDone, + bufferedHostedItemsImageDone, + bufferedHostedItemsTextDelta, + bufferedHostedItemsMessageDone, + bufferedHostedItemsCompleted, +) + +func bufferedHostedItemsOAuthAccount() *Account { + return &Account{ + ID: 1, Name: "openai-oauth", Platform: PlatformOpenAI, Type: AccountTypeOAuth, Concurrency: 1, + Credentials: map[string]any{"access_token": "oauth-token", "chatgpt_account_id": "chatgpt-acc"}, + } +} + +func bufferedHostedItemsSSEResponse(sse string) *http.Response { + return &http.Response{ + StatusCode: http.StatusOK, + Header: http.Header{"Content-Type": []string{"text/event-stream"}}, + Body: io.NopCloser(strings.NewReader(sse)), + } +} + +func forwardBufferedHostedItems(t *testing.T, path, requestBody, upstreamSSE string) string { + t.Helper() + gin.SetMode(gin.TestMode) + rec := httptest.NewRecorder() + c, _ := gin.CreateTestContext(rec) + body := []byte(requestBody) + c.Request = httptest.NewRequest(http.MethodPost, path, bytes.NewReader(body)) + c.Request.Header.Set("Content-Type", "application/json") + svc := &OpenAIGatewayService{ + httpUpstream: &httpUpstreamRecorder{resp: bufferedHostedItemsSSEResponse(upstreamSSE)}, + cfg: rawChatCompletionsTestConfig(), + } + account := bufferedHostedItemsOAuthAccount() + var err error + if path == "/v1/chat/completions" { + _, err = svc.ForwardAsChatCompletions(context.Background(), c, account, body, "", "") + } else { + _, err = svc.ForwardAsAnthropic(context.Background(), c, account, body, "", "") + } + require.NoError(t, err) + require.Equal(t, http.StatusOK, rec.Code, rec.Body.String()) + return rec.Body.String() +} + +func TestForwardAsAnthropic_CodexOAuthNonStreamingKeepsHostedOutputItems(t *testing.T) { + out := forwardBufferedHostedItems(t, "/v1/messages", bufferedHostedItemsMessagesBody, bufferedHostedItemsSSE) + + content := gjson.Get(out, "content").Array() + require.Len(t, content, 3, out) + require.Equal(t, "server_tool_use", content[0].Get("type").String()) + require.Equal(t, "web_search", content[0].Get("name").String()) + require.Equal(t, "q", content[0].Get("input.query").String()) + require.Equal(t, "web_search_tool_result", content[1].Get("type").String()) + require.Equal(t, content[0].Get("id").String(), content[1].Get("tool_use_id").String()) + require.Equal(t, "text", content[2].Get("type").String()) + require.Equal(t, "found it", content[2].Get("text").String()) +} + +func TestForwardAsAnthropic_BufferedHostedItemsFollowReasoning(t *testing.T) { + sse := bufferedItemsSSE( + bufferedHostedItemsCreated, + `{"type":"response.reasoning_summary_text.delta","output_index":0,"summary_index":0,"delta":"plan"}`, + `{"type":"response.output_item.done","output_index":0,"item":{"type":"reasoning","id":"rs_1","summary":[]}}`, + `{"type":"response.output_item.done","output_index":1,"item":{"type":"web_search_call","id":"ws_1","status":"completed","action":{"type":"search","query":"q"}}}`, + `{"type":"response.output_text.delta","output_index":2,"delta":"found it"}`, + bufferedHostedItemsCompleted, + ) + out := forwardBufferedHostedItems(t, "/v1/messages", bufferedHostedItemsThinkingBody, sse) + + var types []string + for _, block := range gjson.Get(out, "content").Array() { + types = append(types, block.Get("type").String()) + } + require.Equal(t, []string{"thinking", "server_tool_use", "web_search_tool_result", "text"}, types, out) +} + +func TestReadOpenAICompatBufferedTerminal_EmptyTerminalOutputGainsHostedItems(t *testing.T) { + gin.SetMode(gin.TestMode) + c, _ := gin.CreateTestContext(httptest.NewRecorder()) + c.Request = httptest.NewRequest(http.MethodPost, "/v1/chat/completions", nil) + account := &Account{ID: 1, Platform: PlatformOpenAI, Type: AccountTypeOAuth, Concurrency: 1} + + response, _, acc, _, err := (&OpenAIGatewayService{}).readOpenAICompatBufferedTerminal( + bufferedHostedItemsSSEResponse(bufferedHostedItemsSSE), c, account, "openai chat buffered", "req-1") + require.NoError(t, err) + require.NotNil(t, response) + + var types []string + for _, item := range response.Output { + types = append(types, item.Type) + } + require.Equal(t, []string{"web_search_call", "image_generation_call", "message"}, types) + + // The handler supplements the output afterwards; the text must not be added twice. + acc.SupplementResponseOutput(response) + require.Len(t, response.Output, 3) +} + +func TestReadOpenAICompatBufferedTerminal_HostedItemsWithoutOutputIndexKeepArrivalOrder(t *testing.T) { + gin.SetMode(gin.TestMode) + c, _ := gin.CreateTestContext(httptest.NewRecorder()) + c.Request = httptest.NewRequest(http.MethodPost, "/v1/chat/completions", nil) + account := &Account{ID: 1, Platform: PlatformOpenAI, Type: AccountTypeOAuth, Concurrency: 1} + sse := bufferedItemsSSE( + bufferedHostedItemsCreated, + `{"type":"response.output_item.done","item":{"type":"web_search_call","id":"ws_1","status":"completed"}}`, + `{"type":"response.output_item.done","item":{"type":"image_generation_call","id":"ig_1","status":"completed"}}`, + bufferedHostedItemsCompleted, + ) + + response, _, _, _, err := (&OpenAIGatewayService{}).readOpenAICompatBufferedTerminal( + bufferedHostedItemsSSEResponse(sse), c, account, "openai chat buffered", "req-1") + require.NoError(t, err) + + var ids []string + for _, item := range response.Output { + ids = append(ids, item.ID) + } + require.Equal(t, []string{"ws_1", "ig_1"}, ids) +} + +// With an empty terminal output the accumulator keeps building reasoning, text +// and function calls from deltas. Only the types it does not know are added. +func TestBufferedCompat_EmptyTerminalOutputKeepsAccumulatedItems(t *testing.T) { + fnTool := `"tools":[{"type":"function","function":{"name":"get","parameters":{"type":"object"}}}]` + customTool := `"tools":[{"type":"custom","custom":{"name":"exec","description":"run"}}]` + chatBody := func(extra string) string { + return `{"model":"gpt-5.5","stream":false,` + extra + `,"messages":[{"role":"user","content":"hi"}]}` + } + toolMessagesBody := `{"model":"gpt-5.5","max_tokens":64,"stream":false,"tools":[{"name":"get","input_schema":{"type":"object"}}],"messages":[{"role":"user","content":"hi"}]}` + + // The reasoning done item has an empty summary; its text only streamed as deltas. + reasoningSSE := bufferedItemsSSE( + bufferedHostedItemsCreated, + `{"type":"response.output_item.added","output_index":0,"item":{"type":"reasoning","id":"rs_1","summary":[]}}`, + `{"type":"response.reasoning_summary_text.delta","output_index":0,"summary_index":0,"delta":"thinking hard"}`, + `{"type":"response.output_item.done","output_index":0,"item":{"type":"reasoning","id":"rs_1","summary":[]}}`, + `{"type":"response.output_text.delta","output_index":1,"delta":"answer"}`, + `{"type":"response.output_item.done","output_index":1,"item":{"type":"message","id":"msg_1","role":"assistant","status":"completed","content":[{"type":"output_text","text":"answer"}]}}`, + bufferedHostedItemsCompleted, + ) + // Item events without output_index, two calls. + noIndexSSE := bufferedItemsSSE( + bufferedHostedItemsCreated, + `{"type":"response.output_item.added","item":{"type":"function_call","id":"fc_1","call_id":"call_1","name":"get","arguments":""}}`, + `{"type":"response.function_call_arguments.delta","item_id":"fc_1","delta":"{\"a\":1}"}`, + `{"type":"response.output_item.done","item":{"type":"function_call","id":"fc_1","call_id":"call_1","name":"get","arguments":"{\"a\":1}","status":"completed"}}`, + `{"type":"response.output_item.added","item":{"type":"function_call","id":"fc_2","call_id":"call_2","name":"get","arguments":""}}`, + `{"type":"response.function_call_arguments.delta","item_id":"fc_2","delta":"{\"b\":2}"}`, + `{"type":"response.output_item.done","item":{"type":"function_call","id":"fc_2","call_id":"call_2","name":"get","arguments":"{\"b\":2}","status":"completed"}}`, + bufferedHostedItemsCompleted, + ) + customSSE := bufferedItemsSSE( + bufferedHostedItemsCreated, + `{"type":"response.output_item.added","output_index":0,"item":{"type":"custom_tool_call","id":"ctc_1","call_id":"call_1","name":"exec","input":""}}`, + `{"type":"response.custom_tool_call_input.delta","output_index":0,"item_id":"ctc_1","delta":"dir"}`, + `{"type":"response.custom_tool_call_input.done","output_index":0,"item_id":"ctc_1","input":"dir"}`, + `{"type":"response.output_item.done","output_index":0,"item":{"type":"custom_tool_call","id":"ctc_1","call_id":"call_1","name":"exec","input":"dir","status":"completed"}}`, + bufferedHostedItemsCompleted, + ) + + t.Run("reasoning text from deltas, chat", func(t *testing.T) { + out := forwardBufferedHostedItems(t, "/v1/chat/completions", chatBody(`"reasoning_effort":"high"`), reasoningSSE) + require.Equal(t, "thinking hard", gjson.Get(out, "choices.0.message.reasoning_content").String(), out) + require.Equal(t, "answer", gjson.Get(out, "choices.0.message.content").String(), out) + }) + t.Run("reasoning text from deltas, messages", func(t *testing.T) { + out := forwardBufferedHostedItems(t, "/v1/messages", bufferedHostedItemsThinkingBody, reasoningSSE) + require.Equal(t, "thinking", gjson.Get(out, "content.0.type").String(), out) + require.Equal(t, "thinking hard", gjson.Get(out, "content.0.thinking").String(), out) + require.Equal(t, "answer", gjson.Get(out, "content.1.text").String(), out) + }) + t.Run("two function calls without output_index, chat", func(t *testing.T) { + out := forwardBufferedHostedItems(t, "/v1/chat/completions", chatBody(fnTool), noIndexSSE) + calls := gjson.Get(out, "choices.0.message.tool_calls").Array() + require.Len(t, calls, 2, out) + require.Equal(t, "call_1", calls[0].Get("id").String()) + require.Equal(t, "call_2", calls[1].Get("id").String()) + }) + t.Run("two function calls without output_index, messages", func(t *testing.T) { + out := forwardBufferedHostedItems(t, "/v1/messages", toolMessagesBody, noIndexSSE) + content := gjson.Get(out, "content").Array() + require.Len(t, content, 2, out) + require.Equal(t, "call_1", content[0].Get("id").String()) + require.Equal(t, "call_2", content[1].Get("id").String()) + }) + t.Run("custom tool call, chat", func(t *testing.T) { + out := forwardBufferedHostedItems(t, "/v1/chat/completions", chatBody(customTool), customSSE) + calls := gjson.Get(out, "choices.0.message.tool_calls").Array() + require.Len(t, calls, 1, out) + require.Equal(t, "exec", calls[0].Get("function.name").String()) + require.Equal(t, "dir", calls[0].Get("function.arguments").String()) + }) +} + +// Native search calls are billed from the terminal Responses body, so an empty +// terminal output that is rebuilt with hosted items must count them, and a +// terminal output that already has items must keep the count it reports. +func TestBufferedCompat_GrokSearchCountFromRebuiltHostedItems(t *testing.T) { + const searchDone = `{"type":"response.output_item.done","output_index":0,"item":{"type":"web_search_call","id":"ws_1","status":"completed","action":{"type":"search","query":"q"}}}` + const xSearchDone = `{"type":"response.output_item.done","output_index":1,"item":{"type":"x_search_call","id":"xs_1","status":"completed"}}` + const messageDone = `{"type":"response.output_item.done","output_index":2,"item":{"type":"message","id":"msg_1","role":"assistant","status":"completed","content":[{"type":"output_text","text":"found it"}]}}` + const usage = `"usage":{"input_tokens":5,"output_tokens":2,"total_tokens":7}` + completed := func(output string) string { + return `{"type":"response.completed","response":{"id":"resp_1","status":"completed","output":` + output + `,` + usage + `}}` + } + stream := func(terminalOutput string) string { + return bufferedItemsSSE(bufferedHostedItemsCreated, searchDone, xSearchDone, bufferedHostedItemsTextDelta, messageDone, completed(terminalOutput)) + } + + cases := []struct { + name string + terminalOutput string + wantSearches int + }{ + {"empty terminal output", `[]`, 2}, + {"terminal output with the search items", `[{"type":"web_search_call","id":"ws_1","status":"completed"},{"type":"x_search_call","id":"xs_1","status":"completed"},{"type":"message","id":"msg_1","role":"assistant","status":"completed","content":[{"type":"output_text","text":"found it"}]}]`, 2}, + {"terminal output without search items", `[{"type":"message","id":"msg_1","role":"assistant","status":"completed","content":[{"type":"output_text","text":"found it"}]}]`, 0}, + } + for _, tc := range cases { + for _, path := range []string{"/v1/messages", "/v1/chat/completions"} { + t.Run(tc.name+" "+path, func(t *testing.T) { + gin.SetMode(gin.TestMode) + rec := httptest.NewRecorder() + c, _ := gin.CreateTestContext(rec) + body := []byte(`{"model":"grok-4.7","stream":false,"messages":[{"role":"user","content":"hi"}]}`) + c.Request = httptest.NewRequest(http.MethodPost, path, bytes.NewReader(body)) + c.Request.Header.Set("Content-Type", "application/json") + c.Set("api_key", &APIKey{ID: 88000}) + account := healthyGrokOAuthGatewayTestAccount(4242, "access-token") + svc := grokAuditOAuthService(&httpUpstreamRecorder{resp: bufferedHostedItemsSSEResponse(stream(tc.terminalOutput))}, account) + + var result *OpenAIForwardResult + var err error + if path == "/v1/chat/completions" { + result, err = svc.ForwardAsChatCompletions(context.Background(), c, account, body, "", "") + } else { + result, err = svc.ForwardAsAnthropic(context.Background(), c, account, body, "", "") + } + require.NoError(t, err) + require.Equal(t, http.StatusOK, rec.Code, rec.Body.String()) + require.NotNil(t, result) + require.Equal(t, tc.wantSearches, result.SearchCount) + }) + } + } +} + +// The output of a failed terminal only feeds the error payload, so hosted items +// reported before the failure must not change the payload recorded for ops. +func TestBufferedCompat_FailedTerminalKeepsErrorPayload(t *testing.T) { + const failed = `{"type":"response.failed","response":{"id":"resp_err","object":"response","status":"failed","error":{"type":"rate_limit_error","message":"Rate limit reached"},"output":[],"usage":{"input_tokens":10,"output_tokens":0,"total_tokens":10}}}` + plain := bufferedItemsSSE(bufferedHostedItemsCreated, failed) + withHosted := bufferedItemsSSE(bufferedHostedItemsCreated, bufferedHostedItemsWebSearchDone, bufferedHostedItemsImageDone, failed) + + recordedPayload := func(t *testing.T, path, requestBody, sse string) string { + t.Helper() + gin.SetMode(gin.TestMode) + c, _ := gin.CreateTestContext(httptest.NewRecorder()) + body := []byte(requestBody) + c.Request = httptest.NewRequest(http.MethodPost, path, bytes.NewReader(body)) + c.Request.Header.Set("Content-Type", "application/json") + cfg := rawChatCompletionsTestConfig() + cfg.Gateway.LogUpstreamErrorBody = true + cfg.Gateway.LogUpstreamErrorBodyMaxBytes = 4096 + svc := &OpenAIGatewayService{ + httpUpstream: &httpUpstreamRecorder{resp: bufferedHostedItemsSSEResponse(sse)}, + cfg: cfg, + } + account := bufferedHostedItemsOAuthAccount() + var err error + if path == "/v1/chat/completions" { + _, err = svc.ForwardAsChatCompletions(context.Background(), c, account, body, "", "") + } else { + _, err = svc.ForwardAsAnthropic(context.Background(), c, account, body, "", "") + } + var failoverErr *UpstreamFailoverError + require.ErrorAs(t, err, &failoverErr) + events, _ := c.Get(OpsUpstreamErrorsKey) + recorded, _ := events.([]*OpsUpstreamErrorEvent) + require.NotEmpty(t, recorded) + return recorded[0].Detail + } + + for path, requestBody := range map[string]string{ + "/v1/messages": bufferedHostedItemsMessagesBody, + "/v1/chat/completions": bufferedHostedItemsChatBody, + } { + t.Run(path, func(t *testing.T) { + want := recordedPayload(t, path, requestBody, plain) + require.Contains(t, want, `"output":[]`) + require.Equal(t, want, recordedPayload(t, path, requestBody, withHosted)) + }) + } +} diff --git a/backend/internal/service/openai_gateway_messages.go b/backend/internal/service/openai_gateway_messages.go index 14aaee67a2..593067e491 100644 --- a/backend/internal/service/openai_gateway_messages.go +++ b/backend/internal/service/openai_gateway_messages.go @@ -835,6 +835,7 @@ func (s *OpenAIGatewayService) readOpenAICompatBufferedTerminal( ) (*apicompat.ResponsesResponse, OpenAIUsage, *apicompat.BufferedResponseAccumulator, openAICompatPriorModelAudit, error) { acc := apicompat.NewBufferedResponseAccumulator() acc.XAIServerSideSearch = account != nil && account.IsGrok() + hostedItems := &openAICompatHostedItems{} var usage OpenAIUsage if resp == nil || resp.Body == nil { return nil, usage, acc, openAICompatPriorModelAudit{}, errors.New("upstream response body is nil") @@ -923,6 +924,7 @@ func (s *OpenAIGatewayService) readOpenAICompatBufferedTerminal( if frame, ok := parser.Finish(); ok { payload := openAICompatPayloadWithEventType(frame.Data, frame.EventType) payload = string(restoreCodexToolNamesFromContext(c, []byte(payload))) + hostedItems.Observe([]byte(payload)) var event apicompat.ResponsesStreamEvent if err := json.Unmarshal([]byte(payload), &event); err == nil { s.parseSSEUsageBytesWithType([]byte(payload), event.Type, &usage) @@ -938,6 +940,7 @@ func (s *OpenAIGatewayService) readOpenAICompatBufferedTerminal( if response.Usage != nil { usage = copyOpenAIUsageFromResponsesUsage(response.Usage) } + hostedItems.fillTerminalOutput(event.Type, response, acc) return response, usage, acc, prior, nil } } @@ -964,6 +967,7 @@ func (s *OpenAIGatewayService) readOpenAICompatBufferedTerminal( } payload := openAICompatPayloadWithEventType(frame.Data, frame.EventType) payload = string(restoreCodexToolNamesFromContext(c, []byte(payload))) + hostedItems.Observe([]byte(payload)) var event apicompat.ResponsesStreamEvent if err := json.Unmarshal([]byte(payload), &event); err != nil { @@ -988,6 +992,7 @@ func (s *OpenAIGatewayService) readOpenAICompatBufferedTerminal( if response.Usage != nil { usage = copyOpenAIUsageFromResponsesUsage(response.Usage) } + hostedItems.fillTerminalOutput(event.Type, response, acc) return response, usage, acc, prior, nil } From 00b09b892d7bbbf14c004b4246771ffe3e019ad0 Mon Sep 17 00:00:00 2001 From: Anankke Date: Sat, 14 Nov 2026 12:49:12 -0800 Subject: [PATCH 18/85] fix(openai): rebuild empty buffered terminal output from done items An empty terminal output was rebuilt from merged deltas, so reasoning lost its per-item signature and segmentation, and message and tool order followed the accumulator instead of output_index. The buffered reader now records every output item and rebuilds the terminal output from the output_item.done items in output_index order, taking deltas only for a field a done item left empty or for an item that never got a done event. Items merge by item id, so items sharing an output_index stay apart and a repeated item replaces its earlier copy; response.cancelled terminals are filled too. A non-empty terminal output is untouched. A new test compares /v1/messages and /v1/chat/completions with the streaming path on shapes taken from real Codex streams. --- .../openai_gateway_buffered_hosted_items.go | 342 ++++++++++++++--- ...enai_gateway_buffered_hosted_items_test.go | 61 +++ ...nai_gateway_buffered_stream_parity_test.go | 347 ++++++++++++++++++ .../service/openai_gateway_messages.go | 10 +- 4 files changed, 694 insertions(+), 66 deletions(-) create mode 100644 backend/internal/service/openai_gateway_buffered_stream_parity_test.go diff --git a/backend/internal/service/openai_gateway_buffered_hosted_items.go b/backend/internal/service/openai_gateway_buffered_hosted_items.go index 133ae6dc55..c0e74c4abf 100644 --- a/backend/internal/service/openai_gateway_buffered_hosted_items.go +++ b/backend/internal/service/openai_gateway_buffered_hosted_items.go @@ -2,7 +2,6 @@ package service import ( "encoding/json" - "slices" "sort" "strings" @@ -10,93 +9,314 @@ import ( "github.com/tidwall/gjson" ) -// openAICompatAccumulatedItemTypes are the output item types that -// apicompat.BufferedResponseAccumulator rebuilds from deltas. Every other type -// can only be recovered from its response.output_item.done event. -var openAICompatAccumulatedItemTypes = map[string]struct{}{ - "reasoning": {}, - "message": {}, - "function_call": {}, - "custom_tool_call": {}, +// openAICompatOutputSlot is everything the upstream stream said about one output +// item: the item of its output_item.added and output_item.done events and the +// text, refusal and argument deltas that arrived for it. +type openAICompatOutputSlot struct { + index int64 + indexed bool + itemType string + added *apicompat.ResponsesOutput + done *apicompat.ResponsesOutput + reasoning strings.Builder + text strings.Builder + refusal strings.Builder + args strings.Builder + argsDone string } -type openAICompatHostedItem struct { - index int64 - indexed bool - raw json.RawMessage +// openAICompatOutputSlots records the output items of a buffered upstream stream +// so that an empty terminal output can be rebuilt from them. +type openAICompatOutputSlots struct { + slots []*openAICompatOutputSlot } -// openAICompatHostedItems collects the response.output_item.done items of types -// the delta accumulator does not produce, such as web_search_call and -// image_generation_call. -type openAICompatHostedItems struct { - items []openAICompatHostedItem +func openAICompatIsToolCallType(itemType string) bool { + return itemType == "function_call" || itemType == "custom_tool_call" } -func (h *openAICompatHostedItems) Observe(payload []byte) { - if h == nil || strings.TrimSpace(gjson.GetBytes(payload, "type").String()) != "response.output_item.done" || !gjson.ValidBytes(payload) { +func (o *openAICompatOutputSlots) Observe(payload []byte) { + if o == nil { return } - item := gjson.GetBytes(payload, "item") - if !item.IsObject() { - return - } - itemType := strings.TrimSpace(item.Get("type").String()) - if _, ok := openAICompatAccumulatedItemTypes[itemType]; ok || itemType == "" { - return - } - entry := openAICompatHostedItem{raw: json.RawMessage(item.Raw)} - if index := gjson.GetBytes(payload, "output_index"); index.Exists() { - entry.index, entry.indexed = index.Int(), true - for i := range h.items { - if h.items[i].indexed && h.items[i].index == entry.index { - h.items[i] = entry - return + switch strings.TrimSpace(gjson.GetBytes(payload, "type").String()) { + case "response.output_item.added": + if item, ok := openAICompatEventItem(payload); ok { + slot := o.slot(payload, item.Type, item.ID, false, true) + slot.added = &item + } + case "response.output_item.done": + if item, ok := openAICompatEventItem(payload); ok { + slot := o.slot(payload, item.Type, item.ID, true, true) + slot.done = &item + } + case "response.output_text.delta": + if delta := gjson.GetBytes(payload, "delta").String(); delta != "" { + _, _ = o.slot(payload, "message", "", false, true).text.WriteString(delta) + } + case "response.refusal.delta": + if delta := gjson.GetBytes(payload, "delta").String(); delta != "" { + _, _ = o.slot(payload, "message", "", false, true).refusal.WriteString(delta) + } + case "response.reasoning_summary_text.delta", "response.reasoning_text.delta": + if delta := gjson.GetBytes(payload, "delta").String(); delta != "" { + _, _ = o.slot(payload, "reasoning", "", false, true).reasoning.WriteString(delta) + } + case "response.function_call_arguments.delta", "response.custom_tool_call_input.delta": + if delta := gjson.GetBytes(payload, "delta").String(); delta != "" { + if slot := o.slot(payload, "function_call", "", false, false); slot != nil { + _, _ = slot.args.WriteString(delta) + } + } + case "response.function_call_arguments.done": + if slot := o.slot(payload, "function_call", "", false, false); slot != nil { + if completed := gjson.GetBytes(payload, "arguments").String(); completed != "" { + slot.argsDone = completed + } + } + case "response.custom_tool_call_input.done": + if slot := o.slot(payload, "function_call", "", false, false); slot != nil { + if completed := gjson.GetBytes(payload, "input").String(); completed != "" { + slot.argsDone = completed } } } - h.items = append(h.items, entry) } -// fillTerminalOutput gives an empty terminal output the collected hosted items -// ahead of what the accumulator rebuilds, after its leading reasoning item. -// Only terminals that carry a result are filled; the output of response.failed -// and error terminals never reaches the client and is left as the upstream sent it. -// Hosted items keep their output_index order; items reported without an -// output_index follow the indexed ones in arrival order. -func (h *openAICompatHostedItems) fillTerminalOutput(eventType string, response *apicompat.ResponsesResponse, acc *apicompat.BufferedResponseAccumulator) { +func openAICompatEventItem(payload []byte) (apicompat.ResponsesOutput, bool) { + var item apicompat.ResponsesOutput + raw := gjson.GetBytes(payload, "item") + if !raw.IsObject() || !gjson.ValidBytes(payload) || json.Unmarshal([]byte(raw.Raw), &item) != nil { + return item, false + } + item.Type = strings.TrimSpace(item.Type) + return item, item.Type != "" +} + +// slot finds the slot an event belongs to. A done event whose item has an id +// belongs to the slot that already holds a done item with that id, so a repeated +// item replaces its earlier copy and items that merely share an output_index stay +// apart. Otherwise an event with an output_index belongs to the newest slot of +// that index (an added event: the newest one that has none yet; a done event +// without an id replaces the done item of that slot). An event without an +// output_index belongs to the newest unindexed slot of its kind (a done event: +// the oldest one still without a done item), and an added event always starts a +// new slot, so unindexed items keep arrival order. With create unset, a missing +// slot returns nil. +func (o *openAICompatOutputSlots) slot(payload []byte, kind, id string, done, create bool) *openAICompatOutputSlot { + index := gjson.GetBytes(payload, "output_index") + added := strings.TrimSpace(gjson.GetBytes(payload, "type").String()) == "response.output_item.added" + matches := func(slot *openAICompatOutputSlot) bool { + if slot.itemType == "" || slot.itemType == kind { + return true + } + return openAICompatIsToolCallType(kind) && openAICompatIsToolCallType(slot.itemType) + } + newest := func(accept func(*openAICompatOutputSlot) bool) *openAICompatOutputSlot { + for i := len(o.slots) - 1; i >= 0; i-- { + if accept(o.slots[i]) { + return o.slots[i] + } + } + return nil + } + var found *openAICompatOutputSlot + if done && id != "" { + found = newest(func(slot *openAICompatOutputSlot) bool { return slot.done != nil && slot.done.ID == id }) + } + if found == nil { + switch { + case index.Exists(): + atIndex := func(slot *openAICompatOutputSlot) bool { return slot.indexed && slot.index == index.Int() } + switch { + case done && id != "": + found = newest(func(slot *openAICompatOutputSlot) bool { return atIndex(slot) && slot.done == nil }) + case added: + found = newest(func(slot *openAICompatOutputSlot) bool { return atIndex(slot) && slot.added == nil }) + default: + found = newest(atIndex) + } + case added: + case done: + for _, slot := range o.slots { + if !slot.indexed && slot.done == nil && slot.itemType == kind { + found = slot + break + } + } + default: + found = newest(func(slot *openAICompatOutputSlot) bool { return !slot.indexed && matches(slot) }) + } + } + if found == nil { + if !create { + return nil + } + found = &openAICompatOutputSlot{} + if index.Exists() { + found.index, found.indexed = index.Int(), true + } + o.slots = append(o.slots, found) + } + if found.itemType == "" || done || added { + found.itemType = kind + } + return found +} + +// fillTerminalOutput rebuilds an empty terminal output from the stream's output +// items, in output_index order, items without an output_index after the indexed +// ones in arrival order. Items with the same output_index keep arrival order. An item that received output_item.done is taken from +// that event, completed with the deltas where the event left a text, refusal or +// the arguments empty; an item that never received it is rebuilt from its +// deltas. Only terminals that carry a result are filled; the output of +// response.failed and error terminals never reaches the client and is left as +// the upstream sent it. +func (o *openAICompatOutputSlots) fillTerminalOutput(eventType string, response *apicompat.ResponsesResponse) { switch strings.TrimSpace(eventType) { - case "response.completed", "response.done", "response.incomplete": + case "response.completed", "response.done", "response.incomplete", "response.cancelled", "response.canceled": default: return } - if h == nil || len(h.items) == 0 || response == nil || len(response.Output) > 0 { + if o == nil || response == nil || len(response.Output) > 0 { return } - sort.SliceStable(h.items, func(i, j int) bool { - a, b := h.items[i], h.items[j] + slots := append([]*openAICompatOutputSlot(nil), o.slots...) + sort.SliceStable(slots, func(i, j int) bool { + a, b := slots[i], slots[j] if a.indexed != b.indexed { return a.indexed } return a.indexed && a.index < b.index }) - hosted := make([]apicompat.ResponsesOutput, 0, len(h.items)) - for _, entry := range h.items { - var item apicompat.ResponsesOutput - if err := json.Unmarshal(entry.raw, &item); err == nil { - hosted = append(hosted, item) + for _, slot := range slots { + if item, ok := slot.build(); ok { + response.Output = append(response.Output, item) } } - if len(hosted) == 0 { - return +} + +func (s *openAICompatOutputSlot) build() (apicompat.ResponsesOutput, bool) { + switch s.itemType { + case "reasoning": + return s.buildReasoning() + case "message": + return s.buildMessage() + case "function_call", "custom_tool_call": + return s.buildToolCall() } - var output []apicompat.ResponsesOutput - if acc != nil && acc.HasContent() { - output = acc.BuildOutput() + if s.done == nil { + return apicompat.ResponsesOutput{}, false } - at := 0 - for at < len(output) && output[at].Type == "reasoning" { - at++ + return *s.done, true +} + +func openAICompatReasoningItemText(item apicompat.ResponsesOutput) string { + var text strings.Builder + for _, part := range item.Summary { + if part.Type == "summary_text" { + _, _ = text.WriteString(part.Text) + } } - response.Output = slices.Insert(output, at, hosted...) + if text.Len() == 0 { + for _, part := range item.Content { + if part.Type == "reasoning_text" { + _, _ = text.WriteString(part.Text) + } + } + } + return text.String() +} + +func (s *openAICompatOutputSlot) buildReasoning() (apicompat.ResponsesOutput, bool) { + item := apicompat.ResponsesOutput{Type: "reasoning"} + if s.done != nil { + item = *s.done + } + if s.reasoning.Len() > 0 && openAICompatReasoningItemText(item) == "" { + item.Summary = []apicompat.ResponsesSummary{{Type: "summary_text", Text: s.reasoning.String()}} + item.Content = nil + } + return item, s.done != nil || s.reasoning.Len() > 0 +} + +func (s *openAICompatOutputSlot) buildMessage() (apicompat.ResponsesOutput, bool) { + item := apicompat.ResponsesOutput{Type: "message", Role: "assistant"} + if s.done != nil { + item = *s.done + item.Content = append([]apicompat.ResponsesContentPart(nil), item.Content...) + } + if s.text.Len() > 0 { + filled := false + hasText := false + for i := range item.Content { + part := &item.Content[i] + if part.Type != "output_text" { + continue + } + if strings.TrimSpace(part.Text) != "" { + hasText = true + break + } + if !filled { + part.Text, filled = s.text.String(), true + } + } + if !hasText && !filled { + item.Content = append(item.Content, apicompat.ResponsesContentPart{Type: "output_text", Text: s.text.String()}) + } + } + if s.refusal.Len() > 0 { + hasRefusal := false + for _, part := range item.Content { + if part.Type == "refusal" && part.Refusal != "" { + hasRefusal = true + } + } + if !hasRefusal { + item.Content = append(item.Content, apicompat.ResponsesContentPart{Type: "refusal", Refusal: s.refusal.String()}) + } + } + return item, s.done != nil || s.text.Len() > 0 || s.refusal.Len() > 0 +} + +// buildToolCall returns a function_call item. A custom_tool_call is returned in +// that form as well, with its input as the arguments, because that is the shape +// the Chat Completions and Messages converters render as a tool call. +func (s *openAICompatOutputSlot) buildToolCall() (apicompat.ResponsesOutput, bool) { + if s.done == nil && s.added == nil { + return apicompat.ResponsesOutput{}, false + } + var item apicompat.ResponsesOutput + if s.done != nil { + item = *s.done + } else { + item = *s.added + } + if s.added != nil { + if item.CallID == "" { + item.CallID = s.added.CallID + } + if item.Name == "" { + item.Name = s.added.Name + } + if item.Namespace == "" { + item.Namespace = s.added.Namespace + } + if item.EncryptedFunctionArgs == nil { + item.EncryptedFunctionArgs = s.added.EncryptedFunctionArgs + } + } + arguments := item.Arguments + if item.Type == "custom_tool_call" { + arguments = item.Input + } + if arguments == "" { + arguments = s.argsDone + } + if arguments == "" { + arguments = s.args.String() + } + item.Type, item.Input, item.Arguments = "function_call", "", arguments + return item, true } diff --git a/backend/internal/service/openai_gateway_buffered_hosted_items_test.go b/backend/internal/service/openai_gateway_buffered_hosted_items_test.go index 435d3fe6a3..87159ed762 100644 --- a/backend/internal/service/openai_gateway_buffered_hosted_items_test.go +++ b/backend/internal/service/openai_gateway_buffered_hosted_items_test.go @@ -8,6 +8,7 @@ import ( "io" "net/http" "net/http/httptest" + "strconv" "strings" "testing" @@ -344,3 +345,63 @@ func TestBufferedCompat_FailedTerminalKeepsErrorPayload(t *testing.T) { }) } } + +func readBufferedOutputItems(t *testing.T, sse string) []string { + t.Helper() + gin.SetMode(gin.TestMode) + c, _ := gin.CreateTestContext(httptest.NewRecorder()) + c.Request = httptest.NewRequest(http.MethodPost, "/v1/chat/completions", nil) + account := &Account{ID: 1, Platform: PlatformOpenAI, Type: AccountTypeOAuth, Concurrency: 1} + response, _, _, _, err := (&OpenAIGatewayService{}).readOpenAICompatBufferedTerminal( + bufferedHostedItemsSSEResponse(sse), c, account, "openai chat buffered", "req-1") + require.NoError(t, err) + require.NotNil(t, response) + var items []string + for _, item := range response.Output { + items = append(items, item.Type+":"+item.ID+":"+item.Arguments+":"+item.Input) + } + return items +} + +// Items that share an output_index stay apart; the same item reported again +// replaces its earlier copy; equal indexes keep arrival order. +func TestReadOpenAICompatBufferedTerminal_DoneItemsMergeByItemID(t *testing.T) { + done := func(index int, id string) string { + return `{"type":"response.output_item.done","output_index":` + strconv.Itoa(index) + `,"item":{"type":"web_search_call","id":"` + id + `","status":"completed"}}` + } + items := readBufferedOutputItems(t, bufferedItemsSSE( + bufferedHostedItemsCreated, + done(0, "ws_a"), done(0, "ws_b"), done(1, "ws_c"), done(0, "ws_a"), + bufferedHostedItemsCompleted, + )) + require.Equal(t, []string{"web_search_call:ws_a::", "web_search_call:ws_b::", "web_search_call:ws_c::"}, items) +} + +// The done item is the upstream's final form of an item; deltas only complete a +// text, refusal or arguments field that the done item left empty, and rebuild an +// item that never got a done event. +func TestReadOpenAICompatBufferedTerminal_DoneItemsWinOverDeltas(t *testing.T) { + items := readBufferedOutputItems(t, bufferedItemsSSE( + bufferedHostedItemsCreated, + `{"type":"response.output_item.added","output_index":0,"item":{"type":"function_call","id":"fc_1","call_id":"call_1","name":"get","arguments":""}}`, + `{"type":"response.function_call_arguments.delta","output_index":0,"delta":"{\"stale\":1}"}`, + `{"type":"response.function_call_arguments.done","output_index":0,"arguments":"{\"a\":1}"}`, + `{"type":"response.output_item.done","output_index":0,"item":{"type":"function_call","id":"fc_1","call_id":"call_1","name":"get","arguments":""}}`, + `{"type":"response.output_item.added","output_index":1,"item":{"type":"function_call","id":"fc_2","call_id":"call_2","name":"get","arguments":""}}`, + `{"type":"response.function_call_arguments.delta","output_index":1,"delta":"{\"b\":2}"}`, + `{"type":"response.output_item.done","output_index":2,"item":{"type":"function_call","id":"fc_3","call_id":"call_3","name":"get","arguments":"{\"c\":3}"}}`, + bufferedHostedItemsCompleted, + )) + require.Equal(t, []string{ + `function_call:fc_1:{"a":1}:`, + `function_call:fc_2:{"b":2}:`, + `function_call:fc_3:{"c":3}:`, + }, items) +} + +func TestForwardAsAnthropic_CancelledTerminalKeepsHostedOutputItems(t *testing.T) { + cancelled := `{"type":"response.cancelled","response":{"id":"resp_1","status":"cancelled","output":[],"usage":{"input_tokens":5,"output_tokens":2,"total_tokens":7}}}` + out := forwardBufferedHostedItems(t, "/v1/messages", bufferedHostedItemsMessagesBody, + bufferedItemsSSE(bufferedHostedItemsCreated, bufferedHostedItemsWebSearchDone, cancelled)) + require.Equal(t, "server_tool_use", gjson.Get(out, "content.0.type").String(), out) +} diff --git a/backend/internal/service/openai_gateway_buffered_stream_parity_test.go b/backend/internal/service/openai_gateway_buffered_stream_parity_test.go new file mode 100644 index 0000000000..455c5e5875 --- /dev/null +++ b/backend/internal/service/openai_gateway_buffered_stream_parity_test.go @@ -0,0 +1,347 @@ +//go:build unit + +package service + +import ( + "bytes" + "context" + "fmt" + "net/http" + "net/http/httptest" + "sort" + "strings" + "testing" + + "github.com/gin-gonic/gin" + "github.com/stretchr/testify/require" + "github.com/tidwall/gjson" +) + +const bufferedParityMessagesBody = `{"model":"gpt-5.5","max_tokens":4096,"stream":%t,"thinking":{"type":"enabled","budget_tokens":2048},"tools":[{"name":"record_version","input_schema":{"type":"object"}}],"messages":[{"role":"user","content":"USER_PROMPT_PLACEHOLDER"}]}` + +const bufferedParityChatBody = `{"model":"gpt-5.5","stream":%t,"reasoning_effort":"medium","tools":[{"type":"function","function":{"name":"record_version","parameters":{"type":"object"}}}],"messages":[{"role":"user","content":"USER_PROMPT_PLACEHOLDER"}]}` + +func bufferedParityReasoning(index int, id, text, encrypted string) []string { + summary := `[]` + if text != "" { + summary = fmt.Sprintf(`[{"type":"summary_text","text":%q}]`, text) + } + events := []string{ + fmt.Sprintf(`{"type":"response.output_item.added","output_index":%d,"item":{"type":"reasoning","id":%q,"summary":[]}}`, index, id), + } + if text != "" { + events = append(events, + fmt.Sprintf(`{"type":"response.reasoning_summary_part.added","output_index":%d,"summary_index":0,"part":{"type":"summary_text","text":""}}`, index), + fmt.Sprintf(`{"type":"response.reasoning_summary_text.delta","output_index":%d,"summary_index":0,"delta":%q}`, index, text), + fmt.Sprintf(`{"type":"response.reasoning_summary_text.done","output_index":%d,"summary_index":0,"text":%q}`, index, text), + ) + } + return append(events, fmt.Sprintf(`{"type":"response.output_item.done","output_index":%d,"item":{"type":"reasoning","id":%q,"summary":%s,"encrypted_content":%q}}`, index, id, summary, encrypted)) +} + +func bufferedParityWebSearch(index int, id, query string) []string { + return []string{ + fmt.Sprintf(`{"type":"response.output_item.added","output_index":%d,"item":{"type":"web_search_call","id":%q,"status":"in_progress"}}`, index, id), + fmt.Sprintf(`{"type":"response.web_search_call.in_progress","output_index":%d,"item_id":%q}`, index, id), + fmt.Sprintf(`{"type":"response.web_search_call.searching","output_index":%d,"item_id":%q}`, index, id), + fmt.Sprintf(`{"type":"response.web_search_call.completed","output_index":%d,"item_id":%q}`, index, id), + fmt.Sprintf(`{"type":"response.output_item.done","output_index":%d,"item":{"type":"web_search_call","id":%q,"status":"completed","action":{"type":"search","query":%q}}}`, index, id, query), + } +} + +func bufferedParityFunctionCall(index int) []string { + return []string{ + fmt.Sprintf(`{"type":"response.output_item.added","output_index":%d,"item":{"type":"function_call","id":"fc_1","call_id":"call_c","name":"record_version","arguments":""}}`, index), + fmt.Sprintf(`{"type":"response.function_call_arguments.delta","output_index":%d,"item_id":"fc_1","delta":"{\"version\""}`, index), + fmt.Sprintf(`{"type":"response.function_call_arguments.delta","output_index":%d,"item_id":"fc_1","delta":":\"1.25\"}"}`, index), + fmt.Sprintf(`{"type":"response.function_call_arguments.done","output_index":%d,"item_id":"fc_1","arguments":"{\"version\":\"1.25\"}"}`, index), + fmt.Sprintf(`{"type":"response.output_item.done","output_index":%d,"item":{"type":"function_call","id":"fc_1","call_id":"call_c","name":"record_version","arguments":"{\"version\":\"1.25\"}","status":"completed"}}`, index), + } +} + +func bufferedParityMessage(index int, text string) []string { + content := `[{"type":"output_text","text":""}]` + events := []string{ + fmt.Sprintf(`{"type":"response.output_item.added","output_index":%d,"item":{"type":"message","id":"msg_1","role":"assistant","status":"in_progress","phase":"final_answer","content":[]}}`, index), + fmt.Sprintf(`{"type":"response.content_part.added","output_index":%d,"content_index":0,"part":{"type":"output_text","text":""}}`, index), + } + if text != "" { + content = fmt.Sprintf(`[{"type":"output_text","text":%q}]`, text) + events = append(events, + fmt.Sprintf(`{"type":"response.output_text.delta","output_index":%d,"content_index":0,"delta":%q}`, index, text), + fmt.Sprintf(`{"type":"response.output_text.done","output_index":%d,"content_index":0,"text":%q}`, index, text), + ) + } + return append(events, + fmt.Sprintf(`{"type":"response.content_part.done","output_index":%d,"content_index":0,"part":{"type":"output_text","text":%q}}`, index, text), + fmt.Sprintf(`{"type":"response.output_item.done","output_index":%d,"item":{"type":"message","id":"msg_1","role":"assistant","status":"completed","phase":"final_answer","content":%s}}`, index, content), + ) +} + +func bufferedParityStream(terminalOutput string, groups ...[]string) string { + events := []string{bufferedHostedItemsCreated} + for _, group := range groups { + events = append(events, group...) + } + events = append(events, fmt.Sprintf(`{"type":"response.completed","response":{"id":"resp_1","status":"completed","output":%s,"usage":{"input_tokens":5,"output_tokens":2,"total_tokens":7}}}`, terminalOutput)) + return bufferedItemsSSE(events...) +} + +// bufferedParityBlocks reduces an Anthropic content array to one line per block. +func bufferedParityBlocks(blocks []gjson.Result) []string { + var lines []string + for _, block := range blocks { + switch block.Get("type").String() { + case "thinking": + lines = append(lines, fmt.Sprintf("thinking %q signature=%q", block.Get("thinking").String(), block.Get("signature").String())) + case "text": + lines = append(lines, fmt.Sprintf("text %q", block.Get("text").String())) + case "tool_use": + lines = append(lines, fmt.Sprintf("tool_use %s %s %s", block.Get("id").String(), block.Get("name").String(), block.Get("input").Raw)) + case "server_tool_use": + lines = append(lines, fmt.Sprintf("server_tool_use %s %s", block.Get("id").String(), block.Get("input").Raw)) + case "web_search_tool_result": + lines = append(lines, fmt.Sprintf("web_search_tool_result %s", block.Get("tool_use_id").String())) + default: + lines = append(lines, "other "+block.Get("type").String()) + } + } + return lines +} + +// bufferedParityStreamBlocks folds an Anthropic SSE body back into content blocks. +func bufferedParityStreamBlocks(t *testing.T, sse string) []string { + t.Helper() + type streamed struct { + kind, id, name, toolUseID, thinking, text, signature, input string + } + byIndex := map[int64]*streamed{} + for _, line := range strings.Split(sse, "\n") { + data, ok := strings.CutPrefix(line, "data: ") + if !ok || !gjson.Valid(data) { + continue + } + index := gjson.Get(data, "index").Int() + switch gjson.Get(data, "type").String() { + case "content_block_start": + block := gjson.Get(data, "content_block") + byIndex[index] = &streamed{ + kind: block.Get("type").String(), id: block.Get("id").String(), name: block.Get("name").String(), + toolUseID: block.Get("tool_use_id").String(), input: block.Get("input").Raw, + } + case "content_block_delta": + block := byIndex[index] + require.NotNil(t, block, data) + delta := gjson.Get(data, "delta") + switch delta.Get("type").String() { + case "thinking_delta": + block.thinking += delta.Get("thinking").String() + case "text_delta": + block.text += delta.Get("text").String() + case "signature_delta": + block.signature = delta.Get("signature").String() + case "input_json_delta": + if block.input == "{}" { + block.input = "" + } + block.input += delta.Get("partial_json").String() + } + } + } + indexes := make([]int64, 0, len(byIndex)) + for index := range byIndex { + indexes = append(indexes, index) + } + sort.Slice(indexes, func(i, j int) bool { return indexes[i] < indexes[j] }) + var lines []string + for _, index := range indexes { + block := byIndex[index] + switch block.kind { + case "thinking": + lines = append(lines, fmt.Sprintf("thinking %q signature=%q", block.thinking, block.signature)) + case "text": + lines = append(lines, fmt.Sprintf("text %q", block.text)) + case "tool_use": + lines = append(lines, fmt.Sprintf("tool_use %s %s %s", block.id, block.name, block.input)) + case "server_tool_use": + lines = append(lines, fmt.Sprintf("server_tool_use %s %s", block.id, block.input)) + case "web_search_tool_result": + lines = append(lines, fmt.Sprintf("web_search_tool_result %s", block.toolUseID)) + default: + lines = append(lines, "other "+block.kind) + } + } + return lines +} + +// bufferedParityChat reduces a Chat Completions answer to the fields a client reads. +func bufferedParityChatSummary(reasoning, content string, calls []string, finish string) string { + return fmt.Sprintf("reasoning=%q content=%q tool_calls=%v finish_reason=%s", reasoning, content, calls, finish) +} + +func bufferedParityChatNonStream(body string) string { + message := gjson.Get(body, "choices.0.message") + var calls []string + for _, call := range message.Get("tool_calls").Array() { + calls = append(calls, fmt.Sprintf("%s %s %s", call.Get("id").String(), call.Get("function.name").String(), call.Get("function.arguments").String())) + } + return bufferedParityChatSummary(message.Get("reasoning_content").String(), message.Get("content").String(), calls, gjson.Get(body, "choices.0.finish_reason").String()) +} + +func bufferedParityChatStream(sse string) string { + var reasoning, content, finish string + type call struct{ id, name, args string } + calls := map[int64]*call{} + for _, line := range strings.Split(sse, "\n") { + data, ok := strings.CutPrefix(line, "data: ") + if !ok || !gjson.Valid(data) { + continue + } + choice := gjson.Get(data, "choices.0") + reasoning += choice.Get("delta.reasoning_content").String() + content += choice.Get("delta.content").String() + if reason := choice.Get("finish_reason"); reason.Exists() && reason.Type != gjson.Null { + finish = reason.String() + } + for _, tc := range choice.Get("delta.tool_calls").Array() { + index := tc.Get("index").Int() + if calls[index] == nil { + calls[index] = &call{} + } + if id := tc.Get("id").String(); id != "" { + calls[index].id = id + } + if name := tc.Get("function.name").String(); name != "" { + calls[index].name = name + } + calls[index].args += tc.Get("function.arguments").String() + } + } + indexes := make([]int64, 0, len(calls)) + for index := range calls { + indexes = append(indexes, index) + } + sort.Slice(indexes, func(i, j int) bool { return indexes[i] < indexes[j] }) + var lines []string + for _, index := range indexes { + lines = append(lines, fmt.Sprintf("%s %s %s", calls[index].id, calls[index].name, calls[index].args)) + } + return bufferedParityChatSummary(reasoning, content, lines, finish) +} + +func forwardBufferedParity(t *testing.T, path, requestBody, upstreamSSE string) string { + t.Helper() + gin.SetMode(gin.TestMode) + rec := httptest.NewRecorder() + c, _ := gin.CreateTestContext(rec) + body := []byte(requestBody) + c.Request = httptest.NewRequest(http.MethodPost, path, bytes.NewReader(body)) + c.Request.Header.Set("Content-Type", "application/json") + svc := &OpenAIGatewayService{ + httpUpstream: &httpUpstreamRecorder{resp: bufferedHostedItemsSSEResponse(upstreamSSE)}, + cfg: rawChatCompletionsTestConfig(), + } + account := bufferedHostedItemsOAuthAccount() + var err error + if path == "/v1/chat/completions" { + _, err = svc.ForwardAsChatCompletions(context.Background(), c, account, body, "", "") + } else { + _, err = svc.ForwardAsAnthropic(context.Background(), c, account, body, "", "") + } + require.NoError(t, err) + require.Equal(t, http.StatusOK, rec.Code, rec.Body.String()) + return rec.Body.String() +} + +// A buffered /v1/messages or /v1/chat/completions answer must carry what the +// streaming path delivers for the same upstream event stream. The shapes are the +// ones real Codex streams produced; texts are placeholders. +func TestBufferedCompat_MatchesStreamingPathOnRealStreamShapes(t *testing.T) { + reasoningThenMessage := func(terminal string) string { + return bufferedParityStream(terminal, + bufferedParityReasoning(0, "rs_1", "REASON_TEXT_PLACEHOLDER", "ENC_PLACEHOLDER_1"), + bufferedParityMessage(1, "ANSWER_PLACEHOLDER")) + } + signatureOnlyThenEmptyMessage := func(terminal string) string { + return bufferedParityStream(terminal, + bufferedParityReasoning(0, "rs_1", "", "ENC_PLACEHOLDER_1"), + bufferedParityMessage(1, "")) + } + const filledTerminal = `[{"type":"reasoning","id":"rs_1","summary":[{"type":"summary_text","text":"REASON_TEXT_PLACEHOLDER"}],"encrypted_content":"ENC_PLACEHOLDER_1"},{"type":"message","id":"msg_1","role":"assistant","status":"completed","content":[{"type":"output_text","text":"ANSWER_PLACEHOLDER"}]}]` + const signatureOnlyTerminal = `[{"type":"reasoning","id":"rs_1","summary":[],"encrypted_content":"ENC_PLACEHOLDER_1"},{"type":"message","id":"msg_1","role":"assistant","status":"completed","content":[{"type":"output_text","text":""}]}]` + webSearchTurn := bufferedParityStream(`[]`, + bufferedParityReasoning(0, "rs_1", "REASON_ONE_PLACEHOLDER", "ENC_PLACEHOLDER_1"), + bufferedParityWebSearch(1, "ws_1", "QUERY_ONE_PLACEHOLDER"), + bufferedParityReasoning(2, "rs_2", "REASON_TWO_PLACEHOLDER", "ENC_PLACEHOLDER_2"), + bufferedParityWebSearch(3, "ws_2", "QUERY_TWO_PLACEHOLDER"), + bufferedParityReasoning(4, "rs_3", "REASON_THREE_PLACEHOLDER", "ENC_PLACEHOLDER_3"), + bufferedParityFunctionCall(5)) + + cases := []struct { + name string + sse string + wantMessages []string + wantChat string + }{ + { + name: "reasoning and message, filled terminal", + sse: reasoningThenMessage(filledTerminal), + wantMessages: []string{ + `thinking "REASON_TEXT_PLACEHOLDER" signature="ENC_PLACEHOLDER_1"`, + `text "ANSWER_PLACEHOLDER"`, + }, + wantChat: bufferedParityChatSummary("REASON_TEXT_PLACEHOLDER", "ANSWER_PLACEHOLDER", nil, "stop"), + }, + { + name: "reasoning and message, empty terminal", + sse: reasoningThenMessage(`[]`), + wantMessages: []string{ + `thinking "REASON_TEXT_PLACEHOLDER" signature="ENC_PLACEHOLDER_1"`, + `text "ANSWER_PLACEHOLDER"`, + }, + wantChat: bufferedParityChatSummary("REASON_TEXT_PLACEHOLDER", "ANSWER_PLACEHOLDER", nil, "stop"), + }, + { + name: "signature only reasoning and empty message, filled terminal", + sse: signatureOnlyThenEmptyMessage(signatureOnlyTerminal), + wantMessages: []string{`thinking "" signature="ENC_PLACEHOLDER_1"`}, + wantChat: bufferedParityChatSummary("", "", nil, "stop"), + }, + { + name: "signature only reasoning and empty message, empty terminal", + sse: signatureOnlyThenEmptyMessage(`[]`), + wantMessages: []string{`thinking "" signature="ENC_PLACEHOLDER_1"`}, + wantChat: bufferedParityChatSummary("", "", nil, "stop"), + }, + { + name: "web search turn with a client tool, empty terminal", + sse: webSearchTurn, + wantMessages: []string{ + `thinking "REASON_ONE_PLACEHOLDER" signature="ENC_PLACEHOLDER_1"`, + `server_tool_use srvtoolu_ws_1 {"query":"QUERY_ONE_PLACEHOLDER"}`, + `web_search_tool_result srvtoolu_ws_1`, + `thinking "REASON_TWO_PLACEHOLDER" signature="ENC_PLACEHOLDER_2"`, + `server_tool_use srvtoolu_ws_2 {"query":"QUERY_TWO_PLACEHOLDER"}`, + `web_search_tool_result srvtoolu_ws_2`, + `thinking "REASON_THREE_PLACEHOLDER" signature="ENC_PLACEHOLDER_3"`, + `tool_use call_c record_version {"version":"1.25"}`, + }, + wantChat: bufferedParityChatSummary("REASON_ONE_PLACEHOLDERREASON_TWO_PLACEHOLDERREASON_THREE_PLACEHOLDER", "", []string{`call_c record_version {"version":"1.25"}`}, "tool_calls"), + }, + } + for _, tc := range cases { + t.Run(tc.name+" messages", func(t *testing.T) { + buffered := forwardBufferedParity(t, "/v1/messages", fmt.Sprintf(bufferedParityMessagesBody, false), tc.sse) + streamed := forwardBufferedParity(t, "/v1/messages", fmt.Sprintf(bufferedParityMessagesBody, true), tc.sse) + require.Equal(t, tc.wantMessages, bufferedParityBlocks(gjson.Get(buffered, "content").Array()), buffered) + streamedBlocks := bufferedParityStreamBlocks(t, streamed) + require.Equal(t, tc.wantMessages, streamedBlocks, streamed) + }) + t.Run(tc.name+" chat", func(t *testing.T) { + buffered := forwardBufferedParity(t, "/v1/chat/completions", fmt.Sprintf(bufferedParityChatBody, false), tc.sse) + streamed := forwardBufferedParity(t, "/v1/chat/completions", fmt.Sprintf(bufferedParityChatBody, true), tc.sse) + require.Equal(t, tc.wantChat, bufferedParityChatNonStream(buffered), buffered) + require.Equal(t, tc.wantChat, bufferedParityChatStream(streamed), streamed) + }) + } +} diff --git a/backend/internal/service/openai_gateway_messages.go b/backend/internal/service/openai_gateway_messages.go index 593067e491..b4ba5ba25a 100644 --- a/backend/internal/service/openai_gateway_messages.go +++ b/backend/internal/service/openai_gateway_messages.go @@ -835,7 +835,7 @@ func (s *OpenAIGatewayService) readOpenAICompatBufferedTerminal( ) (*apicompat.ResponsesResponse, OpenAIUsage, *apicompat.BufferedResponseAccumulator, openAICompatPriorModelAudit, error) { acc := apicompat.NewBufferedResponseAccumulator() acc.XAIServerSideSearch = account != nil && account.IsGrok() - hostedItems := &openAICompatHostedItems{} + outputSlots := &openAICompatOutputSlots{} var usage OpenAIUsage if resp == nil || resp.Body == nil { return nil, usage, acc, openAICompatPriorModelAudit{}, errors.New("upstream response body is nil") @@ -924,7 +924,7 @@ func (s *OpenAIGatewayService) readOpenAICompatBufferedTerminal( if frame, ok := parser.Finish(); ok { payload := openAICompatPayloadWithEventType(frame.Data, frame.EventType) payload = string(restoreCodexToolNamesFromContext(c, []byte(payload))) - hostedItems.Observe([]byte(payload)) + outputSlots.Observe([]byte(payload)) var event apicompat.ResponsesStreamEvent if err := json.Unmarshal([]byte(payload), &event); err == nil { s.parseSSEUsageBytesWithType([]byte(payload), event.Type, &usage) @@ -940,7 +940,7 @@ func (s *OpenAIGatewayService) readOpenAICompatBufferedTerminal( if response.Usage != nil { usage = copyOpenAIUsageFromResponsesUsage(response.Usage) } - hostedItems.fillTerminalOutput(event.Type, response, acc) + outputSlots.fillTerminalOutput(event.Type, response) return response, usage, acc, prior, nil } } @@ -967,7 +967,7 @@ func (s *OpenAIGatewayService) readOpenAICompatBufferedTerminal( } payload := openAICompatPayloadWithEventType(frame.Data, frame.EventType) payload = string(restoreCodexToolNamesFromContext(c, []byte(payload))) - hostedItems.Observe([]byte(payload)) + outputSlots.Observe([]byte(payload)) var event apicompat.ResponsesStreamEvent if err := json.Unmarshal([]byte(payload), &event); err != nil { @@ -992,7 +992,7 @@ func (s *OpenAIGatewayService) readOpenAICompatBufferedTerminal( if response.Usage != nil { usage = copyOpenAIUsageFromResponsesUsage(response.Usage) } - hostedItems.fillTerminalOutput(event.Type, response, acc) + outputSlots.fillTerminalOutput(event.Type, response) return response, usage, acc, prior, nil } From fbe8c39a90e8b2b3153f418cc828dc6f97281ed9 Mon Sep 17 00:00:00 2001 From: Anankke Date: Sat, 14 Nov 2026 12:56:42 -0800 Subject: [PATCH 19/85] fix(apicompat): keep tool_use input a JSON object in buffered responses A tool call whose arguments were not a JSON object (truncated by max_output_tokens, empty, or the free-form input of a custom_tool_call) made json.Marshal fail, so /v1/messages answered 200 with an empty body. ResponsesToAnthropic now keeps an object as it is, uses {} for a function_call with anything else, and wraps a custom_tool_call input as {"input": ...}, the shape extractCustomToolCallInput reads back. Both converters now render custom_tool_call items, which were dropped when the terminal output carried them. The streaming converter is unchanged: it forwards the argument deltas as the upstream sent them. --- .../pkg/apicompat/responses_to_anthropic.go | 28 +++++++- .../responses_to_anthropic_tool_input_test.go | 68 +++++++++++++++++++ .../apicompat/responses_to_chatcompletions.go | 9 +++ .../openai_gateway_buffered_hosted_items.go | 11 +-- ...enai_gateway_buffered_hosted_items_test.go | 31 +++++++++ 5 files changed, 142 insertions(+), 5 deletions(-) create mode 100644 backend/internal/pkg/apicompat/responses_to_anthropic_tool_input_test.go diff --git a/backend/internal/pkg/apicompat/responses_to_anthropic.go b/backend/internal/pkg/apicompat/responses_to_anthropic.go index 1d5654b7c4..08fff49003 100644 --- a/backend/internal/pkg/apicompat/responses_to_anthropic.go +++ b/backend/internal/pkg/apicompat/responses_to_anthropic.go @@ -52,7 +52,14 @@ func ResponsesToAnthropic(resp *ResponsesResponse, model string) *AnthropicRespo Type: "tool_use", ID: fromResponsesCallID(item.CallID), Name: item.Name, - Input: sanitizeAnthropicToolUseInput(item.Name, item.Arguments), + Input: anthropicToolUseInput(item.Type, item.Name, item.Arguments), + }) + case "custom_tool_call": + blocks = append(blocks, AnthropicContentBlock{ + Type: "tool_use", + ID: fromResponsesCallID(item.CallID), + Name: item.Name, + Input: anthropicToolUseInput(item.Type, item.Name, item.Input), }) case "web_search_call": toolUseID := "srvtoolu_" + item.ID @@ -139,6 +146,25 @@ func containsAnthropicToolUseBlock(blocks []AnthropicContentBlock) bool { return false } +// anthropicToolUseInput returns the input of a non-streaming tool_use block, +// which must be a JSON object. An object is kept as it is. A function_call whose +// arguments are not an object (truncated by max_output_tokens, or empty) gets {}; +// a custom_tool_call's free-form input is wrapped in the same {"input": ...} +// shape that downgrades a custom tool to a function tool, so that +// extractCustomToolCallInput gives the text back. +func anthropicToolUseInput(itemType, name, raw string) json.RawMessage { + if trimmed := strings.TrimSpace(raw); strings.HasPrefix(trimmed, "{") && json.Valid([]byte(trimmed)) { + return sanitizeAnthropicToolUseInput(name, raw) + } + if itemType == "custom_tool_call" { + wrapped, err := json.Marshal(map[string]string{"input": raw}) + if err == nil { + return wrapped + } + } + return json.RawMessage("{}") +} + func sanitizeAnthropicToolUseInput(name string, raw string) json.RawMessage { if name != "Read" || raw == "" { return json.RawMessage(raw) diff --git a/backend/internal/pkg/apicompat/responses_to_anthropic_tool_input_test.go b/backend/internal/pkg/apicompat/responses_to_anthropic_tool_input_test.go new file mode 100644 index 0000000000..1e64c11c5c --- /dev/null +++ b/backend/internal/pkg/apicompat/responses_to_anthropic_tool_input_test.go @@ -0,0 +1,68 @@ +package apicompat + +import ( + "encoding/json" + "testing" + + "github.com/stretchr/testify/require" +) + +func TestAnthropicToolUseInput(t *testing.T) { + tests := []struct { + name string + itemType string + raw string + want string + }{ + {"object kept", "function_call", "{\"a\":1}", "{\"a\":1}"}, + {"object with padding kept", "function_call", " {\"a\": 1}\n", " {\"a\": 1}\n"}, + {"truncated function arguments", "function_call", "{\"a\":1", "{}"}, + {"empty function arguments", "function_call", "", "{}"}, + {"non-object function arguments", "function_call", "[1]", "{}"}, + {"custom input wrapped", "custom_tool_call", "dir /b", "{\"input\":\"dir /b\"}"}, + {"empty custom input wrapped", "custom_tool_call", "", "{\"input\":\"\"}"}, + {"custom input that is an object kept", "custom_tool_call", "{\"a\":1}", "{\"a\":1}"}, + } + for _, tc := range tests { + t.Run(tc.name, func(t *testing.T) { + got := anthropicToolUseInput(tc.itemType, "exec", tc.raw) + require.Equal(t, tc.want, string(got)) + require.True(t, json.Valid(got)) + }) + } +} + +// The wrapper must round-trip through the helper that undoes the custom tool +// downgrade, including text that is itself valid JSON or has outer whitespace. +func TestAnthropicToolUseInputCustomRoundTrip(t *testing.T) { + for _, text := range []string{"dir", " padded text\n", "", "\"quoted\"", "[1,2]", "line1\nline2"} { + wrapped := anthropicToolUseInput("custom_tool_call", "exec", text) + require.Equal(t, text, extractCustomToolCallInput(string(wrapped)), text) + } +} + +func TestResponsesToAnthropicInvalidToolInputStillMarshals(t *testing.T) { + resp := &ResponsesResponse{ID: "resp_1", Status: "incomplete", IncompleteDetails: &ResponsesIncompleteDetails{Reason: "max_output_tokens"}, Output: []ResponsesOutput{ + {Type: "reasoning", Summary: []ResponsesSummary{{Type: "summary_text", Text: "plan"}}}, + {Type: "function_call", CallID: "call_1", Name: "get", Arguments: "{\"a\":1"}, + {Type: "custom_tool_call", CallID: "call_2", Name: "exec", Input: "dir"}, + }} + out := ResponsesToAnthropic(resp, "m") + body, err := json.Marshal(out) + require.NoError(t, err) + require.Len(t, out.Content, 3) + require.Equal(t, "thinking", out.Content[0].Type) + require.Equal(t, "{}", string(out.Content[1].Input)) + require.Equal(t, "{\"input\":\"dir\"}", string(out.Content[2].Input)) + require.Equal(t, "max_tokens", *out.StopReason, string(body)) +} + +func TestResponsesToChatCompletionsRendersCustomToolCall(t *testing.T) { + resp := &ResponsesResponse{ID: "resp_1", Status: "completed", Output: []ResponsesOutput{ + {Type: "custom_tool_call", CallID: "call_1", Name: "exec", Input: "dir"}, + }} + out := ResponsesToChatCompletions(resp, "m") + require.Len(t, out.Choices[0].Message.ToolCalls, 1) + require.Equal(t, "dir", out.Choices[0].Message.ToolCalls[0].Function.Arguments) + require.Equal(t, "tool_calls", out.Choices[0].FinishReason) +} diff --git a/backend/internal/pkg/apicompat/responses_to_chatcompletions.go b/backend/internal/pkg/apicompat/responses_to_chatcompletions.go index ebbf9367b4..29cb176189 100644 --- a/backend/internal/pkg/apicompat/responses_to_chatcompletions.go +++ b/backend/internal/pkg/apicompat/responses_to_chatcompletions.go @@ -56,6 +56,15 @@ func ResponsesToChatCompletions(resp *ResponsesResponse, model string) *ChatComp Arguments: item.Arguments, }, }) + case "custom_tool_call": + toolCalls = append(toolCalls, ChatToolCall{ + ID: item.CallID, + Type: "function", + Function: ChatFunctionCall{ + Name: item.Name, + Arguments: item.Input, + }, + }) case "reasoning": reasoningText += responsesReasoningText(item) case "web_search_call": diff --git a/backend/internal/service/openai_gateway_buffered_hosted_items.go b/backend/internal/service/openai_gateway_buffered_hosted_items.go index c0e74c4abf..396d26af4c 100644 --- a/backend/internal/service/openai_gateway_buffered_hosted_items.go +++ b/backend/internal/service/openai_gateway_buffered_hosted_items.go @@ -280,9 +280,8 @@ func (s *openAICompatOutputSlot) buildMessage() (apicompat.ResponsesOutput, bool return item, s.done != nil || s.text.Len() > 0 || s.refusal.Len() > 0 } -// buildToolCall returns a function_call item. A custom_tool_call is returned in -// that form as well, with its input as the arguments, because that is the shape -// the Chat Completions and Messages converters render as a tool call. +// buildToolCall returns the function_call or custom_tool_call item of the slot, +// with the arguments or input a done item left empty taken from the deltas. func (s *openAICompatOutputSlot) buildToolCall() (apicompat.ResponsesOutput, bool) { if s.done == nil && s.added == nil { return apicompat.ResponsesOutput{}, false @@ -317,6 +316,10 @@ func (s *openAICompatOutputSlot) buildToolCall() (apicompat.ResponsesOutput, boo if arguments == "" { arguments = s.args.String() } - item.Type, item.Input, item.Arguments = "function_call", "", arguments + if item.Type == "custom_tool_call" { + item.Input = arguments + } else { + item.Arguments = arguments + } return item, true } diff --git a/backend/internal/service/openai_gateway_buffered_hosted_items_test.go b/backend/internal/service/openai_gateway_buffered_hosted_items_test.go index 87159ed762..8792b57a63 100644 --- a/backend/internal/service/openai_gateway_buffered_hosted_items_test.go +++ b/backend/internal/service/openai_gateway_buffered_hosted_items_test.go @@ -405,3 +405,34 @@ func TestForwardAsAnthropic_CancelledTerminalKeepsHostedOutputItems(t *testing.T bufferedItemsSSE(bufferedHostedItemsCreated, bufferedHostedItemsWebSearchDone, cancelled)) require.Equal(t, "server_tool_use", gjson.Get(out, "content.0.type").String(), out) } + +// A tool call whose arguments are not a JSON object must not empty the response: +// a truncated function call gets {}, a custom tool call its input wrapped. +func TestForwardAsAnthropic_BufferedNonObjectToolInput(t *testing.T) { + toolBody := `{"model":"gpt-5.5","max_tokens":64,"stream":false,"tools":[{"name":"get","input_schema":{"type":"object"}}],"messages":[{"role":"user","content":"hi"}]}` + truncated := bufferedItemsSSE( + bufferedHostedItemsCreated, + `{"type":"response.output_item.done","output_index":0,"item":{"type":"reasoning","id":"rs_1","summary":[{"type":"summary_text","text":"plan"}]}}`, + `{"type":"response.output_item.added","output_index":1,"item":{"type":"function_call","id":"fc_1","call_id":"call_1","name":"get","arguments":""}}`, + `{"type":"response.function_call_arguments.delta","output_index":1,"delta":"{\"a\":1"}`, + `{"type":"response.incomplete","response":{"id":"resp_1","status":"incomplete","incomplete_details":{"reason":"max_output_tokens"},"output":[]}}`, + ) + out := forwardBufferedHostedItems(t, "/v1/messages", toolBody, truncated) + require.Equal(t, "thinking", gjson.Get(out, "content.0.type").String(), out) + require.Equal(t, "plan", gjson.Get(out, "content.0.thinking").String(), out) + require.Equal(t, "tool_use", gjson.Get(out, "content.1.type").String(), out) + require.Equal(t, "{}", gjson.Get(out, "content.1.input").Raw, out) + require.Equal(t, "max_tokens", gjson.Get(out, "stop_reason").String(), out) + + custom := bufferedItemsSSE( + bufferedHostedItemsCreated, + `{"type":"response.output_item.added","output_index":0,"item":{"type":"custom_tool_call","id":"ctc_1","call_id":"call_1","name":"get","input":""}}`, + `{"type":"response.custom_tool_call_input.delta","output_index":0,"delta":"dir"}`, + `{"type":"response.output_item.done","output_index":0,"item":{"type":"custom_tool_call","id":"ctc_1","call_id":"call_1","name":"get","input":"dir"}}`, + bufferedHostedItemsCompleted, + ) + out = forwardBufferedHostedItems(t, "/v1/messages", toolBody, custom) + require.Equal(t, "tool_use", gjson.Get(out, "content.0.type").String(), out) + require.Equal(t, `{"input":"dir"}`, gjson.Get(out, "content.0.input").Raw, out) + require.Equal(t, "tool_use", gjson.Get(out, "stop_reason").String(), out) +} From 49ef5f6909661a2c0dfc88b586d83568fd3cde70 Mon Sep 17 00:00:00 2001 From: Anankke Date: Sat, 14 Nov 2026 17:40:48 -0800 Subject: [PATCH 20/85] fix(openai): render custom tool calls only from rebuilt buffered output A custom_tool_call in an output the upstream delivered is not a client tool call; 250deb70e5 rendered it on that path too, which turns xAI server-side searches into tool_use. ResponsesResponse.RenderCustomToolCalls is set only when the buffered reader rebuilds an empty output, so a delivered output behaves as before the rework. A reasoning done item that carries both a summary and raw reasoning_text content now takes its text from the deltas again, as the streaming path shows it. --- .../pkg/apicompat/responses_to_anthropic.go | 3 ++ .../responses_to_anthropic_tool_input_test.go | 16 ++++++- .../apicompat/responses_to_chatcompletions.go | 3 ++ backend/internal/pkg/apicompat/types.go | 5 +++ .../openai_gateway_buffered_hosted_items.go | 43 +++++++++---------- ...enai_gateway_buffered_hosted_items_test.go | 14 ++++++ 6 files changed, 60 insertions(+), 24 deletions(-) diff --git a/backend/internal/pkg/apicompat/responses_to_anthropic.go b/backend/internal/pkg/apicompat/responses_to_anthropic.go index 08fff49003..1f073972cb 100644 --- a/backend/internal/pkg/apicompat/responses_to_anthropic.go +++ b/backend/internal/pkg/apicompat/responses_to_anthropic.go @@ -55,6 +55,9 @@ func ResponsesToAnthropic(resp *ResponsesResponse, model string) *AnthropicRespo Input: anthropicToolUseInput(item.Type, item.Name, item.Arguments), }) case "custom_tool_call": + if !resp.RenderCustomToolCalls { + continue + } blocks = append(blocks, AnthropicContentBlock{ Type: "tool_use", ID: fromResponsesCallID(item.CallID), diff --git a/backend/internal/pkg/apicompat/responses_to_anthropic_tool_input_test.go b/backend/internal/pkg/apicompat/responses_to_anthropic_tool_input_test.go index 1e64c11c5c..3c6f819bce 100644 --- a/backend/internal/pkg/apicompat/responses_to_anthropic_tool_input_test.go +++ b/backend/internal/pkg/apicompat/responses_to_anthropic_tool_input_test.go @@ -46,7 +46,7 @@ func TestResponsesToAnthropicInvalidToolInputStillMarshals(t *testing.T) { {Type: "reasoning", Summary: []ResponsesSummary{{Type: "summary_text", Text: "plan"}}}, {Type: "function_call", CallID: "call_1", Name: "get", Arguments: "{\"a\":1"}, {Type: "custom_tool_call", CallID: "call_2", Name: "exec", Input: "dir"}, - }} + }, RenderCustomToolCalls: true} out := ResponsesToAnthropic(resp, "m") body, err := json.Marshal(out) require.NoError(t, err) @@ -60,9 +60,21 @@ func TestResponsesToAnthropicInvalidToolInputStillMarshals(t *testing.T) { func TestResponsesToChatCompletionsRendersCustomToolCall(t *testing.T) { resp := &ResponsesResponse{ID: "resp_1", Status: "completed", Output: []ResponsesOutput{ {Type: "custom_tool_call", CallID: "call_1", Name: "exec", Input: "dir"}, - }} + }, RenderCustomToolCalls: true} out := ResponsesToChatCompletions(resp, "m") require.Len(t, out.Choices[0].Message.ToolCalls, 1) require.Equal(t, "dir", out.Choices[0].Message.ToolCalls[0].Function.Arguments) require.Equal(t, "tool_calls", out.Choices[0].FinishReason) } + +// An output the upstream delivered keeps custom_tool_call items unrendered. +func TestResponsesToAnthropicAndChatSkipDeliveredCustomToolCall(t *testing.T) { + resp := &ResponsesResponse{ID: "resp_1", Status: "completed", Output: []ResponsesOutput{ + {Type: "custom_tool_call", CallID: "xs_123", Name: "x_keyword_search", Input: "{}"}, + }} + require.Len(t, ResponsesToAnthropic(resp, "m").Content, 1) + require.Equal(t, "text", ResponsesToAnthropic(resp, "m").Content[0].Type) + chat := ResponsesToChatCompletions(resp, "m") + require.Empty(t, chat.Choices[0].Message.ToolCalls) + require.Equal(t, "stop", chat.Choices[0].FinishReason) +} diff --git a/backend/internal/pkg/apicompat/responses_to_chatcompletions.go b/backend/internal/pkg/apicompat/responses_to_chatcompletions.go index 29cb176189..c7c1c0afdb 100644 --- a/backend/internal/pkg/apicompat/responses_to_chatcompletions.go +++ b/backend/internal/pkg/apicompat/responses_to_chatcompletions.go @@ -57,6 +57,9 @@ func ResponsesToChatCompletions(resp *ResponsesResponse, model string) *ChatComp }, }) case "custom_tool_call": + if !resp.RenderCustomToolCalls { + continue + } toolCalls = append(toolCalls, ChatToolCall{ ID: item.CallID, Type: "function", diff --git a/backend/internal/pkg/apicompat/types.go b/backend/internal/pkg/apicompat/types.go index 130f0ff63b..fc084f9c10 100644 --- a/backend/internal/pkg/apicompat/types.go +++ b/backend/internal/pkg/apicompat/types.go @@ -384,6 +384,11 @@ type ResponsesResponse struct { // Error is present when status="failed" Error *ResponsesError `json:"error,omitempty"` + + // RenderCustomToolCalls is set on an output rebuilt from stream events, where + // the accumulator has always handed custom_tool_call items to the converters + // as tool calls. An output the upstream delivered keeps them unrendered. + RenderCustomToolCalls bool `json:"-"` } // ResponsesError describes an error in a failed response. diff --git a/backend/internal/service/openai_gateway_buffered_hosted_items.go b/backend/internal/service/openai_gateway_buffered_hosted_items.go index 396d26af4c..e2c787dd69 100644 --- a/backend/internal/service/openai_gateway_buffered_hosted_items.go +++ b/backend/internal/service/openai_gateway_buffered_hosted_items.go @@ -166,8 +166,8 @@ func (o *openAICompatOutputSlots) slot(payload []byte, kind, id string, done, cr // fillTerminalOutput rebuilds an empty terminal output from the stream's output // items, in output_index order, items without an output_index after the indexed -// ones in arrival order. Items with the same output_index keep arrival order. An item that received output_item.done is taken from -// that event, completed with the deltas where the event left a text, refusal or +// ones in arrival order. Items with the same output_index keep arrival order. +// An item that received output_item.done is taken from that event, completed with the deltas where the event left a text, refusal or // the arguments empty; an item that never received it is rebuilt from its // deltas. Only terminals that carry a result are filled; the output of // response.failed and error terminals never reaches the client and is left as @@ -192,6 +192,9 @@ func (o *openAICompatOutputSlots) fillTerminalOutput(eventType string, response for _, slot := range slots { if item, ok := slot.build(); ok { response.Output = append(response.Output, item) + if item.Type == "custom_tool_call" { + response.RenderCustomToolCalls = true + } } } } @@ -211,31 +214,27 @@ func (s *openAICompatOutputSlot) build() (apicompat.ResponsesOutput, bool) { return *s.done, true } -func openAICompatReasoningItemText(item apicompat.ResponsesOutput) string { - var text strings.Builder - for _, part := range item.Summary { - if part.Type == "summary_text" { - _, _ = text.WriteString(part.Text) - } - } - if text.Len() == 0 { - for _, part := range item.Content { - if part.Type == "reasoning_text" { - _, _ = text.WriteString(part.Text) - } - } - } - return text.String() -} - func (s *openAICompatOutputSlot) buildReasoning() (apicompat.ResponsesOutput, bool) { item := apicompat.ResponsesOutput{Type: "reasoning"} if s.done != nil { item = *s.done } - if s.reasoning.Len() > 0 && openAICompatReasoningItemText(item) == "" { - item.Summary = []apicompat.ResponsesSummary{{Type: "summary_text", Text: s.reasoning.String()}} - item.Content = nil + // The converters render the summary text and fall back to the reasoning_text + // content only when the summary has none, so an item carrying both would lose + // one. The deltas carried every text the client is shown, so they stand in + // for a text field that is empty or that would be dropped. + if s.reasoning.Len() > 0 { + var summary, content bool + for _, part := range item.Summary { + summary = summary || (part.Type == "summary_text" && part.Text != "") + } + for _, part := range item.Content { + content = content || (part.Type == "reasoning_text" && part.Text != "") + } + if summary == content { + item.Summary = []apicompat.ResponsesSummary{{Type: "summary_text", Text: s.reasoning.String()}} + item.Content = nil + } } return item, s.done != nil || s.reasoning.Len() > 0 } diff --git a/backend/internal/service/openai_gateway_buffered_hosted_items_test.go b/backend/internal/service/openai_gateway_buffered_hosted_items_test.go index 8792b57a63..e3fc5c14d7 100644 --- a/backend/internal/service/openai_gateway_buffered_hosted_items_test.go +++ b/backend/internal/service/openai_gateway_buffered_hosted_items_test.go @@ -436,3 +436,17 @@ func TestForwardAsAnthropic_BufferedNonObjectToolInput(t *testing.T) { require.Equal(t, `{"input":"dir"}`, gjson.Get(out, "content.0.input").Raw, out) require.Equal(t, "tool_use", gjson.Get(out, "stop_reason").String(), out) } + +// A reasoning item with a summary and raw reasoning_text content: the converters render one of the two, +// so the deltas that carried both supply the text, as the streaming path shows it. +func TestForwardAsAnthropic_BufferedReasoningSummaryAndContentKeepBoth(t *testing.T) { + sse := bufferedItemsSSE( + bufferedHostedItemsCreated, + `{"type":"response.reasoning_text.delta","output_index":0,"content_index":0,"delta":"raw thoughts"}`, + `{"type":"response.reasoning_summary_text.delta","output_index":0,"summary_index":0,"delta":"summary"}`, + `{"type":"response.output_item.done","output_index":0,"item":{"type":"reasoning","id":"rs_1","summary":[{"type":"summary_text","text":"summary"}],"content":[{"type":"reasoning_text","text":"raw thoughts"}]}}`, + bufferedHostedItemsCompleted, + ) + out := forwardBufferedHostedItems(t, "/v1/messages", bufferedHostedItemsThinkingBody, sse) + require.Equal(t, "raw thoughtssummary", gjson.Get(out, "content.0.thinking").String(), out) +} From 5279823757cc8d836316243e5f37a13715ce4b81 Mon Sep 17 00:00:00 2001 From: Anankke Date: Sun, 15 Nov 2026 02:35:40 -0800 Subject: [PATCH 21/85] fix(openai): complete buffered item parts by their own index A message or reasoning item with several parts lost or doubled text when its done item left only some of them empty and the terminal output was empty. Observe now keeps the deltas per content_index or summary_index, apart for output_text, refusal, summary_text and reasoning_text. buildMessage and buildReasoning fill only the blank part whose own index has deltas and keep the parts with text and their order as the done item has them. Deltas of an index the done item has no part for follow its parts. --- .../openai_gateway_buffered_hosted_items.go | 195 +++++++++++++----- ...enai_gateway_buffered_hosted_items_test.go | 140 +++++++++++++ ...nai_gateway_buffered_stream_parity_test.go | 90 ++++++++ 3 files changed, 379 insertions(+), 46 deletions(-) diff --git a/backend/internal/service/openai_gateway_buffered_hosted_items.go b/backend/internal/service/openai_gateway_buffered_hosted_items.go index e2c787dd69..da592bffd2 100644 --- a/backend/internal/service/openai_gateway_buffered_hosted_items.go +++ b/backend/internal/service/openai_gateway_buffered_hosted_items.go @@ -2,6 +2,7 @@ package service import ( "encoding/json" + "math" "sort" "strings" @@ -9,20 +10,69 @@ import ( "github.com/tidwall/gjson" ) +// openAICompatPartText keeps the delta text of one kind per part index, the +// content_index or summary_index of its events, so that a part of an item is +// completed with the text of that part only. +type openAICompatPartText struct { + parts map[int64]*strings.Builder +} + +func (p *openAICompatPartText) write(index int64, delta string) { + if p.parts == nil { + p.parts = map[int64]*strings.Builder{} + } + if p.parts[index] == nil { + p.parts[index] = &strings.Builder{} + } + _, _ = p.parts[index].WriteString(delta) +} + +func (p *openAICompatPartText) any() bool { + return len(p.parts) > 0 +} + +func (p *openAICompatPartText) at(index int64) string { + if builder := p.parts[index]; builder != nil { + return builder.String() + } + return "" +} + +// unclaimed joins, in part order, the text of the parts from index from on that +// are not in claimed. +func (p *openAICompatPartText) unclaimed(claimed map[int64]bool, from int64) string { + indexes := make([]int64, 0, len(p.parts)) + for index := range p.parts { + if index >= from && !claimed[index] { + indexes = append(indexes, index) + } + } + sort.Slice(indexes, func(i, j int) bool { return indexes[i] < indexes[j] }) + var text strings.Builder + for _, index := range indexes { + _, _ = text.WriteString(p.parts[index].String()) + } + return text.String() +} + // openAICompatOutputSlot is everything the upstream stream said about one output // item: the item of its output_item.added and output_item.done events and the -// text, refusal and argument deltas that arrived for it. +// text, refusal and argument deltas that arrived for it. Text, refusal and the +// two kinds of reasoning text are kept per part, and the reasoning text also in +// arrival order across its kinds. type openAICompatOutputSlot struct { - index int64 - indexed bool - itemType string - added *apicompat.ResponsesOutput - done *apicompat.ResponsesOutput - reasoning strings.Builder - text strings.Builder - refusal strings.Builder - args strings.Builder - argsDone string + index int64 + indexed bool + itemType string + added *apicompat.ResponsesOutput + done *apicompat.ResponsesOutput + reasoning strings.Builder + summaryText openAICompatPartText + reasoningText openAICompatPartText + text openAICompatPartText + refusal openAICompatPartText + args strings.Builder + argsDone string } // openAICompatOutputSlots records the output items of a buffered upstream stream @@ -52,15 +102,23 @@ func (o *openAICompatOutputSlots) Observe(payload []byte) { } case "response.output_text.delta": if delta := gjson.GetBytes(payload, "delta").String(); delta != "" { - _, _ = o.slot(payload, "message", "", false, true).text.WriteString(delta) + o.slot(payload, "message", "", false, true).text.write(gjson.GetBytes(payload, "content_index").Int(), delta) } case "response.refusal.delta": if delta := gjson.GetBytes(payload, "delta").String(); delta != "" { - _, _ = o.slot(payload, "message", "", false, true).refusal.WriteString(delta) + o.slot(payload, "message", "", false, true).refusal.write(gjson.GetBytes(payload, "content_index").Int(), delta) } - case "response.reasoning_summary_text.delta", "response.reasoning_text.delta": + case "response.reasoning_summary_text.delta": if delta := gjson.GetBytes(payload, "delta").String(); delta != "" { - _, _ = o.slot(payload, "reasoning", "", false, true).reasoning.WriteString(delta) + slot := o.slot(payload, "reasoning", "", false, true) + _, _ = slot.reasoning.WriteString(delta) + slot.summaryText.write(gjson.GetBytes(payload, "summary_index").Int(), delta) + } + case "response.reasoning_text.delta": + if delta := gjson.GetBytes(payload, "delta").String(); delta != "" { + slot := o.slot(payload, "reasoning", "", false, true) + _, _ = slot.reasoning.WriteString(delta) + slot.reasoningText.write(gjson.GetBytes(payload, "content_index").Int(), delta) } case "response.function_call_arguments.delta", "response.custom_tool_call_input.delta": if delta := gjson.GetBytes(payload, "delta").String(); delta != "" { @@ -168,8 +226,8 @@ func (o *openAICompatOutputSlots) slot(payload []byte, kind, id string, done, cr // items, in output_index order, items without an output_index after the indexed // ones in arrival order. Items with the same output_index keep arrival order. // An item that received output_item.done is taken from that event, completed with the deltas where the event left a text, refusal or -// the arguments empty; an item that never received it is rebuilt from its -// deltas. Only terminals that carry a result are filled; the output of +// the arguments empty, a part with the deltas of its own content_index or +// summary_index; an item that never received it is rebuilt from its deltas. Only terminals that carry a result are filled; the output of // response.failed and error terminals never reaches the client and is left as // the upstream sent it. func (o *openAICompatOutputSlots) fillTerminalOutput(eventType string, response *apicompat.ResponsesResponse) { @@ -231,9 +289,40 @@ func (s *openAICompatOutputSlot) buildReasoning() (apicompat.ResponsesOutput, bo for _, part := range item.Content { content = content || (part.Type == "reasoning_text" && part.Text != "") } - if summary == content { + switch { + case summary == content: item.Summary = []apicompat.ResponsesSummary{{Type: "summary_text", Text: s.reasoning.String()}} item.Content = nil + case summary: + // The item keeps its text; a summary part it left empty takes the + // deltas of its own summary_index. + item.Summary = append([]apicompat.ResponsesSummary(nil), item.Summary...) + claimed := map[int64]bool{} + for i := range item.Summary { + if part := &item.Summary[i]; part.Type == "summary_text" { + claimed[int64(i)] = true + if part.Text == "" { + part.Text = s.summaryText.at(int64(i)) + } + } + } + if rest := s.summaryText.unclaimed(claimed, int64(len(item.Summary))); rest != "" { + item.Summary = append(item.Summary, apicompat.ResponsesSummary{Type: "summary_text", Text: rest}) + } + default: + item.Content = append([]apicompat.ResponsesContentPart(nil), item.Content...) + claimed := map[int64]bool{} + for i := range item.Content { + if part := &item.Content[i]; part.Type == "reasoning_text" { + claimed[int64(i)] = true + if part.Text == "" { + part.Text = s.reasoningText.at(int64(i)) + } + } + } + if rest := s.reasoningText.unclaimed(claimed, int64(len(item.Content))); rest != "" { + item.Content = append(item.Content, apicompat.ResponsesContentPart{Type: "reasoning_text", Text: rest}) + } } } return item, s.done != nil || s.reasoning.Len() > 0 @@ -245,38 +334,52 @@ func (s *openAICompatOutputSlot) buildMessage() (apicompat.ResponsesOutput, bool item = *s.done item.Content = append([]apicompat.ResponsesContentPart(nil), item.Content...) } - if s.text.Len() > 0 { - filled := false - hasText := false - for i := range item.Content { - part := &item.Content[i] - if part.Type != "output_text" { - continue - } - if strings.TrimSpace(part.Text) != "" { - hasText = true - break - } - if !filled { - part.Text, filled = s.text.String(), true - } - } - if !hasText && !filled { - item.Content = append(item.Content, apicompat.ResponsesContentPart{Type: "output_text", Text: s.text.String()}) + declared := int64(len(item.Content)) + if s.text.any() { + blank := func(text string) bool { return strings.TrimSpace(text) == "" } + if rest := completeContentParts(item.Content, &s.text, "output_text", declared, blank); rest != "" { + item.Content = append(item.Content, apicompat.ResponsesContentPart{Type: "output_text", Text: rest}) } } - if s.refusal.Len() > 0 { - hasRefusal := false - for _, part := range item.Content { - if part.Type == "refusal" && part.Refusal != "" { - hasRefusal = true - } - } - if !hasRefusal { - item.Content = append(item.Content, apicompat.ResponsesContentPart{Type: "refusal", Refusal: s.refusal.String()}) + if s.refusal.any() { + blank := func(text string) bool { return text == "" } + if rest := completeContentParts(item.Content, &s.refusal, "refusal", declared, blank); rest != "" { + item.Content = append(item.Content, apicompat.ResponsesContentPart{Type: "refusal", Refusal: rest}) } } - return item, s.done != nil || s.text.Len() > 0 || s.refusal.Len() > 0 + return item, s.done != nil || s.text.any() || s.refusal.any() +} + +// completeContentParts gives each blank part of partType the deltas of its own +// content_index, the position of the part in the content, and leaves the parts +// that have text as they are. It returns the deltas of the indexes that have no +// part of that type: all of them when no part has text, else those beyond the +// last of the declared parts of the done item. +func completeContentParts(content []apicompat.ResponsesContentPart, deltas *openAICompatPartText, partType string, declared int64, blank func(string) bool) string { + claimed := map[int64]bool{} + present := false + for i := range content { + part := &content[i] + if part.Type != partType { + continue + } + field := &part.Text + if partType == "refusal" { + field = &part.Refusal + } + claimed[int64(i)] = true + if blank(*field) { + if delta := deltas.at(int64(i)); delta != "" { + *field = delta + } + } + present = present || !blank(*field) + } + from := declared + if !present { + from = math.MinInt64 + } + return deltas.unclaimed(claimed, from) } // buildToolCall returns the function_call or custom_tool_call item of the slot, diff --git a/backend/internal/service/openai_gateway_buffered_hosted_items_test.go b/backend/internal/service/openai_gateway_buffered_hosted_items_test.go index e3fc5c14d7..da05eb1ec8 100644 --- a/backend/internal/service/openai_gateway_buffered_hosted_items_test.go +++ b/backend/internal/service/openai_gateway_buffered_hosted_items_test.go @@ -450,3 +450,143 @@ func TestForwardAsAnthropic_BufferedReasoningSummaryAndContentKeepBoth(t *testin out := forwardBufferedHostedItems(t, "/v1/messages", bufferedHostedItemsThinkingBody, sse) require.Equal(t, "raw thoughtssummary", gjson.Get(out, "content.0.thinking").String(), out) } + +// bufferedPartsEntries are the two buffered entries, each with the request that +// makes it show the field under test. +var bufferedPartsEntries = []struct{ name, path, body string }{ + {"messages", "/v1/messages", bufferedHostedItemsThinkingBody}, + {"chat", "/v1/chat/completions", `{"model":"gpt-5.5","stream":false,"reasoning_effort":"high","messages":[{"role":"user","content":"search the web"}]}`}, +} + +// bufferedPartsVisible is the text of one kind ("text", "thinking" or "refusal") +// the client is shown: the text or thinking blocks joined for /v1/messages, the +// content, reasoning_content or refusal of the message for /v1/chat/completions. +func bufferedPartsVisible(out, path, kind string) string { + if path == "/v1/chat/completions" { + return gjson.Get(out, "choices.0.message."+map[string]string{"text": "content", "thinking": "reasoning_content", "refusal": "refusal"}[kind]).String() + } + var text strings.Builder + for _, block := range gjson.Get(out, "content").Array() { + if block.Get("type").String() == kind { + text.WriteString(block.Get(kind).String()) + } + } + return text.String() +} + +// One item with several parts whose done item leaves only some of them empty, and +// an empty terminal output: a part is completed with the deltas of its own part +// index, a part that has text and the order of the parts stay as the done item +// has them. +func TestBufferedCompat_PartialTextParts(t *testing.T) { + text := func(s string) string { return `{"type":"output_text","text":"` + s + `"}` } + cases := []struct { + name, parts, want string + deltas []string + }{ + {"first empty", "[" + text("") + "," + text("second") + "]", "first second", []string{"first ", "second"}}, + {"second empty", "[" + text("first ") + "," + text("") + "]", "first second", []string{"first ", "second"}}, + {"both empty", "[" + text("") + "," + text("") + "]", "first second", []string{"first ", "second"}}, + {"both with text, the done item wins", "[" + text("one ") + "," + text("two") + "]", "one two", []string{"first ", "second"}}, + {"middle with text of three", "[" + text("") + "," + text("b ") + "," + text("") + "]", "a b c", []string{"a ", "b ", "c"}}, + } + for _, entry := range bufferedPartsEntries { + for _, tc := range cases { + t.Run(entry.name+" "+tc.name, func(t *testing.T) { + events := []string{ + bufferedHostedItemsCreated, + `{"type":"response.output_item.added","output_index":0,"item":{"type":"message","id":"msg_1","role":"assistant","content":[]}}`, + } + for index, delta := range tc.deltas { + events = append(events, `{"type":"response.output_text.delta","output_index":0,"content_index":`+strconv.Itoa(index)+`,"delta":"`+delta+`"}`) + } + events = append(events, + `{"type":"response.output_item.done","output_index":0,"item":{"type":"message","id":"msg_1","role":"assistant","content":`+tc.parts+`}}`, + bufferedHostedItemsCompleted) + sse := bufferedItemsSSE(events...) + out := forwardBufferedHostedItems(t, entry.path, entry.body, sse) + require.Equal(t, tc.want, bufferedPartsVisible(out, entry.path, "text"), out) + }) + } + } +} + +// The same for the refusal parts of a message, which only /v1/chat/completions renders. +func TestBufferedCompat_PartialRefusalParts(t *testing.T) { + refusal := func(s string) string { return `{"type":"refusal","refusal":"` + s + `"}` } + cases := []struct{ name, parts, want string }{ + {"first empty", "[" + refusal("") + "," + refusal("second") + "]", "first second"}, + {"second empty", "[" + refusal("first ") + "," + refusal("") + "]", "first second"}, + {"both empty", "[" + refusal("") + "," + refusal("") + "]", "first second"}, + {"both with text, the done item wins", "[" + refusal("one ") + "," + refusal("two") + "]", "one two"}, + } + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + sse := bufferedItemsSSE( + bufferedHostedItemsCreated, + `{"type":"response.refusal.delta","output_index":0,"content_index":0,"delta":"first "}`, + `{"type":"response.refusal.delta","output_index":0,"content_index":1,"delta":"second"}`, + `{"type":"response.output_item.done","output_index":0,"item":{"type":"message","id":"msg_1","role":"assistant","content":`+tc.parts+`}}`, + bufferedHostedItemsCompleted, + ) + out := forwardBufferedHostedItems(t, "/v1/chat/completions", bufferedHostedItemsChatBody, sse) + require.Equal(t, tc.want, bufferedPartsVisible(out, "/v1/chat/completions", "refusal"), out) + }) + } +} + +// A refusal part and a text part of one message keep their own deltas. +func TestBufferedCompat_RefusalAndTextPartsKeepTheirOwnDeltas(t *testing.T) { + sse := bufferedItemsSSE( + bufferedHostedItemsCreated, + `{"type":"response.output_text.delta","output_index":0,"content_index":0,"delta":"answer"}`, + `{"type":"response.refusal.delta","output_index":0,"content_index":1,"delta":"no"}`, + `{"type":"response.output_item.done","output_index":0,"item":{"type":"message","id":"msg_1","role":"assistant","content":[{"type":"output_text","text":""},{"type":"refusal","refusal":""}]}}`, + bufferedHostedItemsCompleted, + ) + out := forwardBufferedHostedItems(t, "/v1/chat/completions", bufferedHostedItemsChatBody, sse) + require.Equal(t, "answer", bufferedPartsVisible(out, "/v1/chat/completions", "text"), out) + require.Equal(t, "no", bufferedPartsVisible(out, "/v1/chat/completions", "refusal"), out) +} + +// Reasoning with several summary parts, or several reasoning_text parts, whose +// done item leaves only some of them empty. +func TestBufferedCompat_PartialReasoningParts(t *testing.T) { + summary := func(s string) string { return `{"type":"summary_text","text":"` + s + `"}` } + raw := func(s string) string { return `{"type":"reasoning_text","text":"` + s + `"}` } + summaryDeltas := []string{ + `{"type":"response.reasoning_summary_text.delta","output_index":0,"summary_index":0,"delta":"first "}`, + `{"type":"response.reasoning_summary_text.delta","output_index":0,"summary_index":1,"delta":"second"}`, + } + rawDeltas := []string{ + `{"type":"response.reasoning_text.delta","output_index":0,"content_index":0,"delta":"first "}`, + `{"type":"response.reasoning_text.delta","output_index":0,"content_index":1,"delta":"second"}`, + } + cases := []struct { + name string + deltas []string + summary, content string + want string + }{ + {"summary, first empty", summaryDeltas, "[" + summary("") + "," + summary("second") + "]", "[]", "first second"}, + {"summary, second empty", summaryDeltas, "[" + summary("first ") + "," + summary("") + "]", "[]", "first second"}, + {"summary, both empty", summaryDeltas, "[" + summary("") + "," + summary("") + "]", "[]", "first second"}, + {"summary, both with text, the done item wins", summaryDeltas, "[" + summary("one ") + "," + summary("two") + "]", "[]", "one two"}, + {"reasoning_text, first empty", rawDeltas, "[]", "[" + raw("") + "," + raw("second") + "]", "first second"}, + {"reasoning_text, second empty", rawDeltas, "[]", "[" + raw("first ") + "," + raw("") + "]", "first second"}, + {"reasoning_text, both empty", rawDeltas, "[]", "[" + raw("") + "," + raw("") + "]", "first second"}, + {"reasoning_text, both with text, the done item wins", rawDeltas, "[]", "[" + raw("one ") + "," + raw("two") + "]", "one two"}, + } + for _, entry := range bufferedPartsEntries { + for _, tc := range cases { + t.Run(entry.name+" "+tc.name, func(t *testing.T) { + events := append([]string{bufferedHostedItemsCreated}, tc.deltas...) + events = append(events, + `{"type":"response.output_item.done","output_index":0,"item":{"type":"reasoning","id":"rs_1","summary":`+tc.summary+`,"content":`+tc.content+`}}`, + bufferedHostedItemsCompleted) + out := forwardBufferedHostedItems(t, entry.path, entry.body, bufferedItemsSSE(events...)) + require.Equal(t, tc.want, bufferedPartsVisible(out, entry.path, "thinking"), out) + }) + } + } +} diff --git a/backend/internal/service/openai_gateway_buffered_stream_parity_test.go b/backend/internal/service/openai_gateway_buffered_stream_parity_test.go index 455c5e5875..322798f09c 100644 --- a/backend/internal/service/openai_gateway_buffered_stream_parity_test.go +++ b/backend/internal/service/openai_gateway_buffered_stream_parity_test.go @@ -345,3 +345,93 @@ func TestBufferedCompat_MatchesStreamingPathOnRealStreamShapes(t *testing.T) { }) } } + +// bufferedParityStreamedText folds the text of one kind ("text", "thinking" or +// "refusal") out of a streamed answer of the entry at path. +func bufferedParityStreamedText(sse, path, kind string) string { + var text strings.Builder + for _, line := range strings.Split(sse, "\n") { + data, ok := strings.CutPrefix(line, "data: ") + if !ok || !gjson.Valid(data) { + continue + } + if path == "/v1/chat/completions" { + text.WriteString(gjson.Get(data, "choices.0.delta."+map[string]string{"text": "content", "thinking": "reasoning_content", "refusal": "refusal"}[kind]).String()) + continue + } + if delta := gjson.Get(data, "delta"); delta.Get("type").String() == kind+"_delta" { + text.WriteString(delta.Get(kind).String()) + } + } + return text.String() +} + +// bufferedParityPartItem is a streamed item of several parts: every part gets its +// own part.added, delta and done events, with its own content_index or +// summary_index, and the item.done event carries the part texts of done. +func bufferedParityPartItem(kind string, deltas, done []string) []string { + var events []string + itemType, doneKey, deltaType, indexKey, partType, partKey := "message", "content", "response.output_text.delta", "content_index", "output_text", "text" + switch kind { + case "refusal": + deltaType, partType, partKey = "response.refusal.delta", "refusal", "refusal" + case "summary": + itemType, doneKey, deltaType, indexKey, partType = "reasoning", "summary", "response.reasoning_summary_text.delta", "summary_index", "summary_text" + case "reasoning_text": + itemType, deltaType, partType = "reasoning", "response.reasoning_text.delta", "reasoning_text" + } + events = append(events, fmt.Sprintf(`{"type":"response.output_item.added","output_index":0,"item":{"type":%q,"id":"item_1","role":"assistant","summary":[],"content":[]}}`, itemType)) + for i, delta := range deltas { + events = append(events, fmt.Sprintf(`{"type":%q,"output_index":0,%q:%d,"delta":%q}`, deltaType, indexKey, i, delta)) + } + parts := make([]string, len(done)) + for i, text := range done { + parts[i] = fmt.Sprintf(`{"type":%q,%q:%q}`, partType, partKey, text) + } + item := fmt.Sprintf(`{"type":%q,"id":"item_1","role":"assistant","status":"completed",%q:[%s]`, itemType, doneKey, strings.Join(parts, ",")) + if itemType == "reasoning" && doneKey == "content" { + item += `,"summary":[]` + } + return append(events, `{"type":"response.output_item.done","output_index":0,"item":`+item+`}}`) +} + +// An item with several parts, of which the done item leaves some empty, and an +// empty terminal output: the buffered answer carries the text the streaming path +// delivers, for every kind of part that has a part index. +func TestBufferedCompat_MatchesStreamingPathOnMultiPartItems(t *testing.T) { + deltas := []string{"first ", "second"} + variants := []struct { + name string + done []string + }{ + {"first part empty", []string{"", "second"}}, + {"second part empty", []string{"first ", ""}}, + {"both parts empty", []string{"", ""}}, + {"both parts with text", []string{"first ", "second"}}, + } + kinds := []struct{ kind, shown string }{ + {"text", "text"}, + {"summary", "thinking"}, + {"reasoning_text", "thinking"}, + {"refusal", "refusal"}, + } + for _, k := range kinds { + for _, v := range variants { + sse := bufferedParityStream(`[]`, bufferedParityPartItem(k.kind, deltas, v.done)) + for _, entry := range []struct{ name, path, body string }{ + {"messages", "/v1/messages", bufferedParityMessagesBody}, + {"chat", "/v1/chat/completions", bufferedParityChatBody}, + } { + if k.shown == "refusal" && entry.path == "/v1/messages" { + continue // an Anthropic message has no refusal block + } + t.Run(k.kind+" "+v.name+" "+entry.name, func(t *testing.T) { + buffered := forwardBufferedParity(t, entry.path, fmt.Sprintf(entry.body, false), sse) + streamed := forwardBufferedParity(t, entry.path, fmt.Sprintf(entry.body, true), sse) + require.Equal(t, "first second", bufferedParityStreamedText(streamed, entry.path, k.shown), streamed) + require.Equal(t, "first second", bufferedPartsVisible(buffered, entry.path, k.shown), buffered) + }) + } + } + } +} From 7f1ecfaa2dab996e39165ffbeadb71c0fb371927 Mon Sep 17 00:00:00 2001 From: Anankke Date: Sun, 15 Nov 2026 04:10:53 -0800 Subject: [PATCH 22/85] fix(openai): follow the streaming path for rebuilt buffered items A rebuilt output skips a web search that is not completed, gives an empty custom tool input as {} and keeps a reasoning signature that only the added event carries. Deltas without an output_index join their item by item_id or as the newest open item of their kind, and deltas that came before the item was added belong to it. Items that share an output_index or have none keep their own events: an item of another kind, a done item that is already closed and a different call_id each get their own slot. --- .../pkg/apicompat/responses_to_anthropic.go | 5 +- .../responses_to_anthropic_tool_input_test.go | 2 +- .../openai_gateway_buffered_hosted_items.go | 99 +++++++--- ...enai_gateway_buffered_hosted_items_test.go | 185 ++++++++++++++++++ 4 files changed, 260 insertions(+), 31 deletions(-) diff --git a/backend/internal/pkg/apicompat/responses_to_anthropic.go b/backend/internal/pkg/apicompat/responses_to_anthropic.go index 1f073972cb..7bd8c8d788 100644 --- a/backend/internal/pkg/apicompat/responses_to_anthropic.go +++ b/backend/internal/pkg/apicompat/responses_to_anthropic.go @@ -154,12 +154,13 @@ func containsAnthropicToolUseBlock(blocks []AnthropicContentBlock) bool { // arguments are not an object (truncated by max_output_tokens, or empty) gets {}; // a custom_tool_call's free-form input is wrapped in the same {"input": ...} // shape that downgrades a custom tool to a function tool, so that -// extractCustomToolCallInput gives the text back. +// extractCustomToolCallInput gives the text back; an empty custom input is {} as +// it is in the streamed tool_use. func anthropicToolUseInput(itemType, name, raw string) json.RawMessage { if trimmed := strings.TrimSpace(raw); strings.HasPrefix(trimmed, "{") && json.Valid([]byte(trimmed)) { return sanitizeAnthropicToolUseInput(name, raw) } - if itemType == "custom_tool_call" { + if itemType == "custom_tool_call" && raw != "" { wrapped, err := json.Marshal(map[string]string{"input": raw}) if err == nil { return wrapped diff --git a/backend/internal/pkg/apicompat/responses_to_anthropic_tool_input_test.go b/backend/internal/pkg/apicompat/responses_to_anthropic_tool_input_test.go index 3c6f819bce..a0a99d3798 100644 --- a/backend/internal/pkg/apicompat/responses_to_anthropic_tool_input_test.go +++ b/backend/internal/pkg/apicompat/responses_to_anthropic_tool_input_test.go @@ -20,7 +20,7 @@ func TestAnthropicToolUseInput(t *testing.T) { {"empty function arguments", "function_call", "", "{}"}, {"non-object function arguments", "function_call", "[1]", "{}"}, {"custom input wrapped", "custom_tool_call", "dir /b", "{\"input\":\"dir /b\"}"}, - {"empty custom input wrapped", "custom_tool_call", "", "{\"input\":\"\"}"}, + {"empty custom input is an empty object", "custom_tool_call", "", "{}"}, {"custom input that is an object kept", "custom_tool_call", "{\"a\":1}", "{\"a\":1}"}, } for _, tc := range tests { diff --git a/backend/internal/service/openai_gateway_buffered_hosted_items.go b/backend/internal/service/openai_gateway_buffered_hosted_items.go index da592bffd2..772f0bc1af 100644 --- a/backend/internal/service/openai_gateway_buffered_hosted_items.go +++ b/backend/internal/service/openai_gateway_buffered_hosted_items.go @@ -64,6 +64,7 @@ type openAICompatOutputSlot struct { index int64 indexed bool itemType string + id string added *apicompat.ResponsesOutput done *apicompat.ResponsesOutput reasoning strings.Builder @@ -92,48 +93,48 @@ func (o *openAICompatOutputSlots) Observe(payload []byte) { switch strings.TrimSpace(gjson.GetBytes(payload, "type").String()) { case "response.output_item.added": if item, ok := openAICompatEventItem(payload); ok { - slot := o.slot(payload, item.Type, item.ID, false, true) + slot := o.slot(payload, item.Type, item.ID, item.CallID, false, true) slot.added = &item } case "response.output_item.done": if item, ok := openAICompatEventItem(payload); ok { - slot := o.slot(payload, item.Type, item.ID, true, true) + slot := o.slot(payload, item.Type, item.ID, item.CallID, true, true) slot.done = &item } case "response.output_text.delta": if delta := gjson.GetBytes(payload, "delta").String(); delta != "" { - o.slot(payload, "message", "", false, true).text.write(gjson.GetBytes(payload, "content_index").Int(), delta) + o.slot(payload, "message", gjson.GetBytes(payload, "item_id").String(), "", false, true).text.write(gjson.GetBytes(payload, "content_index").Int(), delta) } case "response.refusal.delta": if delta := gjson.GetBytes(payload, "delta").String(); delta != "" { - o.slot(payload, "message", "", false, true).refusal.write(gjson.GetBytes(payload, "content_index").Int(), delta) + o.slot(payload, "message", gjson.GetBytes(payload, "item_id").String(), "", false, true).refusal.write(gjson.GetBytes(payload, "content_index").Int(), delta) } case "response.reasoning_summary_text.delta": if delta := gjson.GetBytes(payload, "delta").String(); delta != "" { - slot := o.slot(payload, "reasoning", "", false, true) + slot := o.slot(payload, "reasoning", gjson.GetBytes(payload, "item_id").String(), "", false, true) _, _ = slot.reasoning.WriteString(delta) slot.summaryText.write(gjson.GetBytes(payload, "summary_index").Int(), delta) } case "response.reasoning_text.delta": if delta := gjson.GetBytes(payload, "delta").String(); delta != "" { - slot := o.slot(payload, "reasoning", "", false, true) + slot := o.slot(payload, "reasoning", gjson.GetBytes(payload, "item_id").String(), "", false, true) _, _ = slot.reasoning.WriteString(delta) slot.reasoningText.write(gjson.GetBytes(payload, "content_index").Int(), delta) } case "response.function_call_arguments.delta", "response.custom_tool_call_input.delta": if delta := gjson.GetBytes(payload, "delta").String(); delta != "" { - if slot := o.slot(payload, "function_call", "", false, false); slot != nil { + if slot := o.slot(payload, "function_call", gjson.GetBytes(payload, "item_id").String(), "", false, false); slot != nil { _, _ = slot.args.WriteString(delta) } } case "response.function_call_arguments.done": - if slot := o.slot(payload, "function_call", "", false, false); slot != nil { + if slot := o.slot(payload, "function_call", gjson.GetBytes(payload, "item_id").String(), "", false, false); slot != nil { if completed := gjson.GetBytes(payload, "arguments").String(); completed != "" { slot.argsDone = completed } } case "response.custom_tool_call_input.done": - if slot := o.slot(payload, "function_call", "", false, false); slot != nil { + if slot := o.slot(payload, "function_call", gjson.GetBytes(payload, "item_id").String(), "", false, false); slot != nil { if completed := gjson.GetBytes(payload, "input").String(); completed != "" { slot.argsDone = completed } @@ -151,17 +152,24 @@ func openAICompatEventItem(payload []byte) (apicompat.ResponsesOutput, bool) { return item, item.Type != "" } -// slot finds the slot an event belongs to. A done event whose item has an id +// slot finds the slot an event belongs to. id is the id of the item the event +// is about (the item of an added or done event, the item_id of a delta) and +// callID the call_id of a tool call item. A done event whose item has an id // belongs to the slot that already holds a done item with that id, so a repeated -// item replaces its earlier copy and items that merely share an output_index stay -// apart. Otherwise an event with an output_index belongs to the newest slot of -// that index (an added event: the newest one that has none yet; a done event -// without an id replaces the done item of that slot). An event without an -// output_index belongs to the newest unindexed slot of its kind (a done event: -// the oldest one still without a done item), and an added event always starts a -// new slot, so unindexed items keep arrival order. With create unset, a missing -// slot returns nil. -func (o *openAICompatOutputSlots) slot(payload []byte, kind, id string, done, create bool) *openAICompatOutputSlot { +// item replaces its earlier copy. Otherwise an event whose id a slot already +// has, because the deltas or the added event of that item opened it, belongs to +// that slot, also when the event has no output_index. Otherwise an event with an +// output_index belongs to the newest slot of that index that can hold its kind +// of item and has no other id (an added event: the newest one without an added or +// done item; a done event with an id: the newest one without a done item; a done +// event without an id replaces the done item of that slot), so items that merely +// share an output_index stay apart. An event without an output_index belongs to +// the newest slot of its kind that is not done, else to the newest unindexed +// one; a done event with a call_id belongs to the slot of that call, else to the +// oldest unindexed slot of its kind without a done item, and an added event +// always starts a new slot, so unindexed items keep arrival order. With create +// unset, a missing slot returns nil. +func (o *openAICompatOutputSlots) slot(payload []byte, kind, id, callID string, done, create bool) *openAICompatOutputSlot { index := gjson.GetBytes(payload, "output_index") added := strings.TrimSpace(gjson.GetBytes(payload, "type").String()) == "response.output_item.added" matches := func(slot *openAICompatOutputSlot) bool { @@ -170,6 +178,9 @@ func (o *openAICompatOutputSlots) slot(payload []byte, kind, id string, done, cr } return openAICompatIsToolCallType(kind) && openAICompatIsToolCallType(slot.itemType) } + fits := func(slot *openAICompatOutputSlot) bool { + return matches(slot) && (slot.id == "" || id == "" || slot.id == id) + } newest := func(accept func(*openAICompatOutputSlot) bool) *openAICompatOutputSlot { for i := len(o.slots) - 1; i >= 0; i-- { if accept(o.slots[i]) { @@ -182,40 +193,64 @@ func (o *openAICompatOutputSlots) slot(payload []byte, kind, id string, done, cr if done && id != "" { found = newest(func(slot *openAICompatOutputSlot) bool { return slot.done != nil && slot.done.ID == id }) } + if found == nil && id != "" && (done || added || !index.Exists()) { + found = newest(func(slot *openAICompatOutputSlot) bool { + return slot.id == id && matches(slot) && slot.done == nil && (!added || slot.added == nil) + }) + } if found == nil { switch { case index.Exists(): - atIndex := func(slot *openAICompatOutputSlot) bool { return slot.indexed && slot.index == index.Int() } + atIndex := func(slot *openAICompatOutputSlot) bool { + return slot.indexed && slot.index == index.Int() && matches(slot) + } switch { case done && id != "": found = newest(func(slot *openAICompatOutputSlot) bool { return atIndex(slot) && slot.done == nil }) case added: - found = newest(func(slot *openAICompatOutputSlot) bool { return atIndex(slot) && slot.added == nil }) + found = newest(func(slot *openAICompatOutputSlot) bool { return atIndex(slot) && slot.added == nil && slot.done == nil }) default: found = newest(atIndex) } case added: case done: + if callID != "" { + found = newest(func(slot *openAICompatOutputSlot) bool { + return slot.done == nil && slot.added != nil && slot.added.CallID == callID && matches(slot) + }) + } for _, slot := range o.slots { - if !slot.indexed && slot.done == nil && slot.itemType == kind { + if found == nil && !slot.indexed && slot.done == nil && slot.itemType == kind { found = slot - break } } default: - found = newest(func(slot *openAICompatOutputSlot) bool { return !slot.indexed && matches(slot) }) + found = newest(func(slot *openAICompatOutputSlot) bool { return slot.done == nil && fits(slot) }) + if found == nil { + found = newest(func(slot *openAICompatOutputSlot) bool { return !slot.indexed && fits(slot) }) + } } } + if found == nil && index.Exists() && (added || done) { + // Deltas that came with no output_index and before their item was announced + // belong to the newest such item of this kind. + found = newest(func(slot *openAICompatOutputSlot) bool { + return !slot.indexed && slot.added == nil && slot.done == nil && fits(slot) + }) + } if found == nil { if !create { return nil } found = &openAICompatOutputSlot{} - if index.Exists() { - found.index, found.indexed = index.Int(), true - } o.slots = append(o.slots, found) } + if index.Exists() && !found.indexed { + found.index, found.indexed = index.Int(), true + } + if found.id == "" { + found.id = id + } if found.itemType == "" || done || added { found.itemType = kind } @@ -249,6 +284,10 @@ func (o *openAICompatOutputSlots) fillTerminalOutput(eventType string, response }) for _, slot := range slots { if item, ok := slot.build(); ok { + // The streaming converters render a web search only once it is completed. + if item.Type == "web_search_call" && item.Status != "completed" { + continue + } response.Output = append(response.Output, item) if item.Type == "custom_tool_call" { response.RenderCustomToolCalls = true @@ -277,6 +316,10 @@ func (s *openAICompatOutputSlot) buildReasoning() (apicompat.ResponsesOutput, bo if s.done != nil { item = *s.done } + // The signature may be on the added event only. + if s.added != nil && strings.TrimSpace(item.EncryptedContent) == "" { + item.EncryptedContent = s.added.EncryptedContent + } // The converters render the summary text and fall back to the reasoning_text // content only when the summary has none, so an item carrying both would lose // one. The deltas carried every text the client is shown, so they stand in @@ -325,7 +368,7 @@ func (s *openAICompatOutputSlot) buildReasoning() (apicompat.ResponsesOutput, bo } } } - return item, s.done != nil || s.reasoning.Len() > 0 + return item, s.done != nil || s.reasoning.Len() > 0 || strings.TrimSpace(item.EncryptedContent) != "" } func (s *openAICompatOutputSlot) buildMessage() (apicompat.ResponsesOutput, bool) { diff --git a/backend/internal/service/openai_gateway_buffered_hosted_items_test.go b/backend/internal/service/openai_gateway_buffered_hosted_items_test.go index da05eb1ec8..d137fe14e7 100644 --- a/backend/internal/service/openai_gateway_buffered_hosted_items_test.go +++ b/backend/internal/service/openai_gateway_buffered_hosted_items_test.go @@ -590,3 +590,188 @@ func TestBufferedCompat_PartialReasoningParts(t *testing.T) { } } } + +// The streaming converters render a web search once it is completed, so a +// rebuilt output does the same. +func TestBufferedCompat_WebSearchNotCompletedIsNotRebuilt(t *testing.T) { + for _, tc := range []struct { + status string + want []string + }{ + {"completed", []string{"server_tool_use", "web_search_tool_result"}}, + {"in_progress", []string{"text"}}, + } { + t.Run(tc.status, func(t *testing.T) { + sse := bufferedItemsSSE( + bufferedHostedItemsCreated, + `{"type":"response.output_item.done","output_index":0,"item":{"type":"web_search_call","id":"ws_1","status":"`+tc.status+`","action":{"type":"search","query":"q"}}}`, + bufferedHostedItemsCompleted, + ) + out := forwardBufferedHostedItems(t, "/v1/messages", bufferedHostedItemsMessagesBody, sse) + var types []string + for _, block := range gjson.Get(out, "content").Array() { + types = append(types, block.Get("type").String()) + } + require.Equal(t, tc.want, types, out) + }) + } +} + +// A custom tool call without input is {} as in the streamed tool_use. +func TestBufferedCompat_EmptyCustomToolInputIsAnEmptyObject(t *testing.T) { + sse := bufferedItemsSSE( + bufferedHostedItemsCreated, + `{"type":"response.output_item.added","output_index":0,"item":{"type":"custom_tool_call","id":"ctc_1","call_id":"call_1","name":"exec","input":""}}`, + `{"type":"response.output_item.done","output_index":0,"item":{"type":"custom_tool_call","id":"ctc_1","call_id":"call_1","name":"exec","input":""}}`, + bufferedHostedItemsCompleted, + ) + toolBody := `{"model":"gpt-5.5","max_tokens":64,"stream":false,"tools":[{"name":"exec","input_schema":{"type":"object"}}],"messages":[{"role":"user","content":"hi"}]}` + out := forwardBufferedHostedItems(t, "/v1/messages", toolBody, sse) + require.Equal(t, "tool_use", gjson.Get(out, "content.0.type").String(), out) + require.Equal(t, "{}", gjson.Get(out, "content.0.input").Raw, out) +} + +// Deltas without an output_index belong to their item, found by item_id or as the +// newest open item of their kind, not to a second copy of it. +func TestBufferedCompat_DeltasWithoutOutputIndexJoinTheirItem(t *testing.T) { + customBody := `{"model":"gpt-5.5","stream":false,"tools":[{"type":"custom","custom":{"name":"exec","description":"run"}}],"messages":[{"role":"user","content":"hi"}]}` + cases := []struct { + name, shown string + sse string + }{ + {"item_id, no added event", "text", bufferedItemsSSE(bufferedHostedItemsCreated, + `{"type":"response.output_text.delta","item_id":"msg_1","content_index":0,"delta":"hello"}`, + `{"type":"response.output_item.done","output_index":0,"item":{"type":"message","id":"msg_1","role":"assistant","content":[{"type":"output_text","text":"hello"}]}}`, + bufferedHostedItemsCompleted)}, + {"item_id, after added", "thinking", bufferedItemsSSE(bufferedHostedItemsCreated, + `{"type":"response.output_item.added","output_index":0,"item":{"type":"reasoning","id":"rs_1","summary":[]}}`, + `{"type":"response.reasoning_text.delta","item_id":"rs_1","content_index":0,"delta":"hello"}`, + `{"type":"response.output_item.done","output_index":0,"item":{"type":"reasoning","id":"rs_1","summary":[],"content":[{"type":"reasoning_text","text":"hello"}]}}`, + bufferedHostedItemsCompleted)}, + {"no item_id, after added", "text", bufferedItemsSSE(bufferedHostedItemsCreated, + `{"type":"response.output_item.added","output_index":1,"item":{"type":"message","role":"assistant","content":[]}}`, + `{"type":"response.output_text.delta","content_index":0,"delta":"hello"}`, + `{"type":"response.output_item.done","output_index":1,"item":{"type":"message","role":"assistant","content":[{"type":"output_text","text":"hello"}]}}`, + bufferedHostedItemsCompleted)}, + } + for _, entry := range bufferedPartsEntries { + for _, tc := range cases { + t.Run(entry.name+" "+tc.name, func(t *testing.T) { + out := forwardBufferedHostedItems(t, entry.path, entry.body, tc.sse) + require.Equal(t, "hello", bufferedPartsVisible(out, entry.path, tc.shown), out) + }) + } + } + t.Run("custom tool call input", func(t *testing.T) { + sse := bufferedItemsSSE(bufferedHostedItemsCreated, + `{"type":"response.output_item.added","output_index":1,"item":{"type":"reasoning","summary":[]}}`, + `{"type":"response.reasoning_summary_text.delta","summary_index":0,"delta":"plan"}`, + `{"type":"response.output_item.added","output_index":0,"item":{"type":"custom_tool_call","call_id":"call_1","name":"exec","input":""}}`, + `{"type":"response.custom_tool_call_input.delta","delta":"dir"}`, + `{"type":"response.custom_tool_call_input.done"}`, + `{"type":"response.output_item.done","output_index":0,"item":{"type":"custom_tool_call","call_id":"call_1","name":"exec","input":""}}`, + bufferedHostedItemsCompleted) + out := forwardBufferedHostedItems(t, "/v1/chat/completions", customBody, sse) + require.Equal(t, "dir", gjson.Get(out, "choices.0.message.tool_calls.0.function.arguments").String(), out) + require.Equal(t, "plan", gjson.Get(out, "choices.0.message.reasoning_content").String(), out) + }) +} + +// Items that share an output_index, or have none, and lack an added or a done +// event keep their own deltas. +func TestBufferedCompat_ItemsOfOneOutputIndexKeepTheirOwnEvents(t *testing.T) { + fnBody := `{"model":"gpt-5.5","stream":false,"tools":[{"type":"function","function":{"name":"get","parameters":{"type":"object"}}}],"messages":[{"role":"user","content":"hi"}]}` + t.Run("reasoning deltas, then a message added at the same index", func(t *testing.T) { + sse := bufferedItemsSSE(bufferedHostedItemsCreated, + `{"type":"response.reasoning_summary_text.delta","output_index":0,"summary_index":0,"delta":"plan"}`, + `{"type":"response.output_item.added","output_index":0,"item":{"type":"message","id":"msg_1","role":"assistant","content":[]}}`, + `{"type":"response.output_text.delta","output_index":0,"content_index":0,"item_id":"msg_1","delta":"answer"}`, + `{"type":"response.output_item.done","output_index":0,"item":{"type":"message","id":"msg_1","role":"assistant","content":[{"type":"output_text","text":"answer"}]}}`, + bufferedHostedItemsCompleted) + for _, entry := range bufferedPartsEntries { + out := forwardBufferedHostedItems(t, entry.path, entry.body, sse) + require.Equal(t, "plan", bufferedPartsVisible(out, entry.path, "thinking"), out) + require.Equal(t, "answer", bufferedPartsVisible(out, entry.path, "text"), out) + } + }) + t.Run("a message done, then another message added at the same index", func(t *testing.T) { + sse := bufferedItemsSSE(bufferedHostedItemsCreated, + `{"type":"response.output_text.delta","output_index":0,"content_index":0,"delta":"first "}`, + `{"type":"response.output_item.done","output_index":0,"item":{"type":"message","role":"assistant","content":[{"type":"output_text","text":""}]}}`, + `{"type":"response.output_item.added","output_index":0,"item":{"type":"message","role":"assistant","content":[]}}`, + `{"type":"response.output_text.delta","output_index":0,"content_index":0,"delta":"second"}`, + `{"type":"response.output_item.done","output_index":0,"item":{"type":"message","role":"assistant","content":[{"type":"output_text","text":"second"}]}}`, + bufferedHostedItemsCompleted) + for _, entry := range bufferedPartsEntries { + out := forwardBufferedHostedItems(t, entry.path, entry.body, sse) + require.Equal(t, "first second", bufferedPartsVisible(out, entry.path, "text"), out) + } + }) + t.Run("a hosted call added at the index of delta-only text", func(t *testing.T) { + sse := bufferedItemsSSE(bufferedHostedItemsCreated, + `{"type":"response.refusal.delta","output_index":0,"content_index":0,"delta":"no"}`, + `{"type":"response.output_item.added","output_index":0,"item":{"type":"web_search_call","status":"in_progress"}}`, + `{"type":"response.output_item.done","output_index":0,"item":{"type":"web_search_call","status":"completed"}}`, + bufferedHostedItemsCompleted) + out := forwardBufferedHostedItems(t, "/v1/chat/completions", bufferedHostedItemsChatBody, sse) + require.Equal(t, "no", bufferedPartsVisible(out, "/v1/chat/completions", "refusal"), out) + }) + t.Run("two function calls without index and id", func(t *testing.T) { + sse := bufferedItemsSSE(bufferedHostedItemsCreated, + `{"type":"response.output_item.added","item":{"type":"function_call","call_id":"call_a","name":"get","arguments":""}}`, + `{"type":"response.function_call_arguments.delta","delta":"{\"a\":1}"}`, + `{"type":"response.output_item.added","item":{"type":"function_call","call_id":"call_b","name":"get","arguments":""}}`, + `{"type":"response.function_call_arguments.delta","delta":"{\"b\":2}"}`, + `{"type":"response.output_item.done","item":{"type":"function_call","call_id":"call_b","name":"get","arguments":""}}`, + bufferedHostedItemsCompleted) + out := forwardBufferedHostedItems(t, "/v1/chat/completions", fnBody, sse) + calls := gjson.Get(out, "choices.0.message.tool_calls").Array() + require.Len(t, calls, 2, out) + require.Equal(t, "call_a", calls[0].Get("id").String()) + require.Equal(t, `{"a":1}`, calls[0].Get("function.arguments").String()) + require.Equal(t, "call_b", calls[1].Get("id").String()) + require.Equal(t, `{"b":2}`, calls[1].Get("function.arguments").String()) + }) +} + +// The signature of a reasoning item may be on its added event only; the item is +// kept for it even without text, as the streaming path keeps it. +func TestBufferedCompat_ReasoningSignatureOnAddedEventIsKept(t *testing.T) { + cases := []struct { + name, sse string + want []string + }{ + {"with text deltas and a done item without it", bufferedItemsSSE(bufferedHostedItemsCreated, + `{"type":"response.output_item.added","output_index":0,"item":{"type":"reasoning","id":"rs_1","summary":[],"encrypted_content":"ENC"}}`, + `{"type":"response.reasoning_summary_text.delta","output_index":0,"summary_index":0,"delta":"plan"}`, + `{"type":"response.output_item.done","output_index":0,"item":{"type":"reasoning","id":"rs_1","summary":[{"type":"summary_text","text":"plan"}]}}`, + bufferedHostedItemsCompleted), []string{`thinking "plan" ENC`}}, + {"added event only", bufferedItemsSSE(bufferedHostedItemsCreated, + `{"type":"response.output_item.added","output_index":0,"item":{"type":"reasoning","id":"rs_1","summary":[],"encrypted_content":"ENC"}}`, + bufferedHostedItemsCompleted), []string{`thinking "" ENC`}}, + } + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + out := forwardBufferedHostedItems(t, "/v1/messages", bufferedHostedItemsThinkingBody, tc.sse) + var got []string + for _, block := range gjson.Get(out, "content").Array() { + got = append(got, block.Get("type").String()+" "+strconv.Quote(block.Get("thinking").String())+" "+block.Get("signature").String()) + } + require.Equal(t, tc.want, got, out) + }) + } +} + +// Reasoning deltas that came with no output_index before the item was added belong +// to that item, so the text keeps its arrival order. +func TestBufferedCompat_UnindexedReasoningDeltasJoinTheItemAddedLater(t *testing.T) { + sse := bufferedItemsSSE(bufferedHostedItemsCreated, + `{"type":"response.reasoning_text.delta","content_index":0,"delta":"first "}`, + `{"type":"response.output_item.added","output_index":1,"item":{"type":"reasoning","summary":[]}}`, + `{"type":"response.reasoning_summary_text.delta","summary_index":0,"delta":"second"}`, + bufferedHostedItemsCompleted) + for _, entry := range bufferedPartsEntries { + out := forwardBufferedHostedItems(t, entry.path, entry.body, sse) + require.Equal(t, "first second", bufferedPartsVisible(out, entry.path, "thinking"), out) + } +} From 413f1cb08a449d855aaa5220b12940c93704bd88 Mon Sep 17 00:00:00 2001 From: Anankke Date: Mon, 16 Nov 2026 00:43:36 -0800 Subject: [PATCH 23/85] fix(openai): keep xAI server-side search out of rebuilt buffered tool calls A buffered request on a Grok account rebuilds an empty terminal output from the done items and renders its custom_tool_call items as tool_use or tool_calls. An item that apicompat.IsServerSideSearchCall accepts is a search xAI ran itself, so it is no longer rendered as a client tool call. The item stays in the output, so Grok SearchCount still counts it, and stop_reason and finish_reason follow the remaining content. A new test covers an empty terminal on /v1/messages and /v1/chat/completions, with and without a client tool next to the search. --- .../pkg/apicompat/responses_to_anthropic.go | 2 +- .../apicompat/responses_to_chatcompletions.go | 2 +- backend/internal/pkg/apicompat/types.go | 5 ++ .../openai_gateway_buffered_hosted_items.go | 4 ++ ...ateway_buffered_server_side_search_test.go | 65 +++++++++++++++++++ .../service/openai_gateway_messages.go | 2 +- 6 files changed, 77 insertions(+), 3 deletions(-) create mode 100644 backend/internal/service/openai_gateway_buffered_server_side_search_test.go diff --git a/backend/internal/pkg/apicompat/responses_to_anthropic.go b/backend/internal/pkg/apicompat/responses_to_anthropic.go index 7bd8c8d788..45dcfaad38 100644 --- a/backend/internal/pkg/apicompat/responses_to_anthropic.go +++ b/backend/internal/pkg/apicompat/responses_to_anthropic.go @@ -55,7 +55,7 @@ func ResponsesToAnthropic(resp *ResponsesResponse, model string) *AnthropicRespo Input: anthropicToolUseInput(item.Type, item.Name, item.Arguments), }) case "custom_tool_call": - if !resp.RenderCustomToolCalls { + if !resp.RenderCustomToolCalls || (resp.XAIServerSideSearch && IsServerSideSearchCall(item.Type, item.CallID)) { continue } blocks = append(blocks, AnthropicContentBlock{ diff --git a/backend/internal/pkg/apicompat/responses_to_chatcompletions.go b/backend/internal/pkg/apicompat/responses_to_chatcompletions.go index c7c1c0afdb..6d1227a205 100644 --- a/backend/internal/pkg/apicompat/responses_to_chatcompletions.go +++ b/backend/internal/pkg/apicompat/responses_to_chatcompletions.go @@ -57,7 +57,7 @@ func ResponsesToChatCompletions(resp *ResponsesResponse, model string) *ChatComp }, }) case "custom_tool_call": - if !resp.RenderCustomToolCalls { + if !resp.RenderCustomToolCalls || (resp.XAIServerSideSearch && IsServerSideSearchCall(item.Type, item.CallID)) { continue } toolCalls = append(toolCalls, ChatToolCall{ diff --git a/backend/internal/pkg/apicompat/types.go b/backend/internal/pkg/apicompat/types.go index fc084f9c10..c3812ae960 100644 --- a/backend/internal/pkg/apicompat/types.go +++ b/backend/internal/pkg/apicompat/types.go @@ -389,6 +389,11 @@ type ResponsesResponse struct { // the accumulator has always handed custom_tool_call items to the converters // as tool calls. An output the upstream delivered keeps them unrendered. RenderCustomToolCalls bool `json:"-"` + + // XAIServerSideSearch is set with RenderCustomToolCalls when the upstream is + // xAI. A custom_tool_call that IsServerSideSearchCall then stays in the + // output but is not rendered as a tool call, because xAI runs it itself. + XAIServerSideSearch bool `json:"-"` } // ResponsesError describes an error in a failed response. diff --git a/backend/internal/service/openai_gateway_buffered_hosted_items.go b/backend/internal/service/openai_gateway_buffered_hosted_items.go index 772f0bc1af..69ac8f6205 100644 --- a/backend/internal/service/openai_gateway_buffered_hosted_items.go +++ b/backend/internal/service/openai_gateway_buffered_hosted_items.go @@ -80,6 +80,9 @@ type openAICompatOutputSlot struct { // so that an empty terminal output can be rebuilt from them. type openAICompatOutputSlots struct { slots []*openAICompatOutputSlot + // xaiServerSideSearch is set when the upstream is xAI, so that the rebuilt + // output keeps a server-side search call out of the client tool calls. + xaiServerSideSearch bool } func openAICompatIsToolCallType(itemType string) bool { @@ -291,6 +294,7 @@ func (o *openAICompatOutputSlots) fillTerminalOutput(eventType string, response response.Output = append(response.Output, item) if item.Type == "custom_tool_call" { response.RenderCustomToolCalls = true + response.XAIServerSideSearch = o.xaiServerSideSearch } } } diff --git a/backend/internal/service/openai_gateway_buffered_server_side_search_test.go b/backend/internal/service/openai_gateway_buffered_server_side_search_test.go new file mode 100644 index 0000000000..99be34e349 --- /dev/null +++ b/backend/internal/service/openai_gateway_buffered_server_side_search_test.go @@ -0,0 +1,65 @@ +//go:build unit + +package service + +import ( + "testing" + + "github.com/stretchr/testify/require" +) + +// A nonstreaming request rebuilds an empty terminal output from the output_item.done items and +// renders its custom_tool_call items as tool calls. On xAI an xs_ / as_ item is a search the +// server ran, so it is not a tool call but still counts as a Grok search. +func TestGrokBufferedRebuiltOutputKeepsServerSideSearchOutOfToolCalls(t *testing.T) { + account := healthyGrokOAuthGatewayTestAccount(4242, "access-token") + for _, path := range []string{"/v1/messages", "/v1/chat/completions"} { + t.Run(path+" search only", func(t *testing.T) { + sse := grokCustomToolCallStream([]string{grokXSearchItemJSON}, `[]`) + got := forwardGrokCustomToolCallStream(t, path, false, account, sse) + + require.Equal(t, 1, got.searchCount) + require.NotContains(t, got.body, "tool_use", got.body) + require.NotContains(t, got.body, "tool_calls", got.body) + require.NotContains(t, got.body, "x_keyword_search", got.body) + require.Contains(t, got.body, "found it", got.body) + if path == "/v1/messages" { + require.Contains(t, got.body, `"stop_reason":"end_turn"`, got.body) + } else { + require.Contains(t, got.body, `"finish_reason":"stop"`, got.body) + } + }) + t.Run(path+" search next to a client tool", func(t *testing.T) { + sse := grokCustomToolCallStream([]string{grokXSearchItemJSON, grokClientToolJSON}, `[]`) + got := forwardGrokCustomToolCallStream(t, path, false, account, sse) + + require.Equal(t, 1, got.searchCount) + require.NotContains(t, got.body, "x_keyword_search", got.body) + require.Contains(t, got.body, "exec", got.body) + if path == "/v1/messages" { + require.Contains(t, got.body, `"stop_reason":"tool_use"`, got.body) + } else { + require.Contains(t, got.body, `"finish_reason":"tool_calls"`, got.body) + } + }) + } +} + +// Off xAI the same call_id is an ordinary custom tool call and stays one. +func TestOpenAIBufferedRebuiltOutputKeepsXSCallIDAsToolCall(t *testing.T) { + account := rawChatCompletionsTestAccount() + for _, path := range []string{"/v1/messages", "/v1/chat/completions"} { + t.Run(path, func(t *testing.T) { + sse := grokCustomToolCallStream([]string{grokXSearchItemJSON}, `[]`) + got := forwardGrokCustomToolCallStream(t, path, false, account, sse) + + require.Equal(t, 0, got.searchCount) + require.Contains(t, got.body, "x_keyword_search", got.body) + if path == "/v1/messages" { + require.Contains(t, got.body, "tool_use", got.body) + } else { + require.Contains(t, got.body, "tool_calls", got.body) + } + }) + } +} diff --git a/backend/internal/service/openai_gateway_messages.go b/backend/internal/service/openai_gateway_messages.go index b4ba5ba25a..227fb70a9e 100644 --- a/backend/internal/service/openai_gateway_messages.go +++ b/backend/internal/service/openai_gateway_messages.go @@ -835,7 +835,7 @@ func (s *OpenAIGatewayService) readOpenAICompatBufferedTerminal( ) (*apicompat.ResponsesResponse, OpenAIUsage, *apicompat.BufferedResponseAccumulator, openAICompatPriorModelAudit, error) { acc := apicompat.NewBufferedResponseAccumulator() acc.XAIServerSideSearch = account != nil && account.IsGrok() - outputSlots := &openAICompatOutputSlots{} + outputSlots := &openAICompatOutputSlots{xaiServerSideSearch: acc.XAIServerSideSearch} var usage OpenAIUsage if resp == nil || resp.Body == nil { return nil, usage, acc, openAICompatPriorModelAudit{}, errors.New("upstream response body is nil") From 2c587f78b07e35f23e79ac63d180a06234bee050 Mon Sep 17 00:00:00 2001 From: Anankke Date: Mon, 16 Nov 2026 04:06:12 -0800 Subject: [PATCH 24/85] fix(grok): bill search calls from xAI usage success counts When a Grok response usage carries server_side_tool_usage_details, take SearchCount from web_search_calls, x_search_calls and document_search_calls instead of counting output items. xAI documents server_side_tool_usage as the successful calls that determine billing, so failed calls and server-side tools that return nothing are no longer billed. Classes the item counter does not count and the x_posts_fetched / x_users_fetched item counts are not read. Without server_side_tool_usage_details the existing item counting is unchanged. The usage is read from the JSON body, the SSE body and the terminal stream event, for /v1/responses, /v1/messages and /v1/chat/completions, streaming and not. ResponsesUsage keeps the raw object so the buffered paths, which count from a decoded response, can read it. --- backend/internal/pkg/apicompat/types.go | 4 + backend/internal/service/grok_search_count.go | 45 ++++++ .../service/grok_search_usage_billing_test.go | 147 ++++++++++++++++++ .../openai_gateway_chat_completions.go | 1 + .../service/openai_gateway_messages.go | 1 + .../openai_gateway_response_handling.go | 1 + 6 files changed, 199 insertions(+) create mode 100644 backend/internal/service/grok_search_usage_billing_test.go diff --git a/backend/internal/pkg/apicompat/types.go b/backend/internal/pkg/apicompat/types.go index 130f0ff63b..c73b98f13c 100644 --- a/backend/internal/pkg/apicompat/types.go +++ b/backend/internal/pkg/apicompat/types.go @@ -510,6 +510,10 @@ type ResponsesUsage struct { // Optional detailed breakdown InputTokensDetails *ResponsesInputTokensDetails `json:"input_tokens_details,omitempty"` OutputTokensDetails *ResponsesOutputTokensDetails `json:"output_tokens_details,omitempty"` + + // ServerSideToolUsageDetails is xAI's per-class success count object, + // kept raw so Grok search counting can read it from a decoded response. + ServerSideToolUsageDetails json.RawMessage `json:"server_side_tool_usage_details,omitempty"` } func (u *ResponsesUsage) UnmarshalJSON(data []byte) error { diff --git a/backend/internal/service/grok_search_count.go b/backend/internal/service/grok_search_count.go index 2b8136b62f..e641072d2d 100644 --- a/backend/internal/service/grok_search_count.go +++ b/backend/internal/service/grok_search_count.go @@ -13,10 +13,18 @@ import ( // Counts: web_search_call, x_search_call, tool_search_call, and function_call // named tool_search / web_search / x_search, and custom_tool_call items the xAI // server runs itself (apicompat.IsServerSideSearchCall: call_id xs_ / as_). +// +// When usage.server_side_tool_usage_details is present, xAI's reported success +// counts replace the item count (see grokSearchCountFromUsage). func countGrokNativeSearchCallsFromJSONBytes(body []byte) int { if len(body) == 0 || !gjson.ValidBytes(body) { return 0 } + for _, path := range []string{"response.usage", "usage"} { + if n, ok := grokSearchCountFromUsage(gjson.GetBytes(body, path)); ok { + return n + } + } // Responses envelopes normally expose either top-level output (JSON mode) // or response.output (terminal SSE payload). Compatibility layers can retain // both copies; counting both would bill the same search twice. Prefer the @@ -35,10 +43,47 @@ func countGrokNativeSearchCallsFromSSEBody(body string) int { total := 0 forEachOpenAISSEDataPayload(body, func(data []byte) { total += countGrokNativeSearchCallsInSSEDataDedup(data, seen) + total = grokSearchCountWithTerminalUsage(total, data) }) return total } +// grokSearchCountFromUsage reads xAI's per-class success counts from a usage +// object. xAI documents these counts as what determines billing for per-call +// tools (https://docs.x.ai/developers/tools/tool-usage-details#server-side-tool-calls-vs-tool-usage). +// Only the classes the item counter also counts are read: web_search_calls +// (web_search_call items), x_search_calls (xs_ custom_tool_call items) and +// document_search_calls (as_ custom_tool_call items). Other classes and the +// X Search item counts (x_posts_fetched, x_users_fetched) are not read. ok is +// false when server_side_tool_usage_details is absent, so callers keep the +// item count. +func grokSearchCountFromUsage(usage gjson.Result) (int, bool) { + details := usage.Get("server_side_tool_usage_details") + if !details.IsObject() { + return 0, false + } + total := details.Get("web_search_calls").Int() + + details.Get("x_search_calls").Int() + + details.Get("document_search_calls").Int() + if total < 0 { + total = 0 + } + return int(total), true +} + +// grokSearchCountWithTerminalUsage returns xAI's usage-reported count when data +// is a terminal stream event carrying server_side_tool_usage_details (the +// request total per the xAI X Search docs), else keeps the running total. +func grokSearchCountWithTerminalUsage(total int, data []byte) int { + switch strings.TrimSpace(gjson.GetBytes(data, "type").String()) { + case "response.completed", "response.incomplete", "response.done": + if n, ok := grokSearchCountFromUsage(gjson.GetBytes(data, "response.usage")); ok { + return n + } + } + return total +} + // countGrokNativeSearchCallsInSSEData counts search tool calls in one SSE // payload without cross-event dedup. Prefer countGrokNativeSearchCallsInSSEDataDedup // for live streams so item.done + response.completed do not double-bill. diff --git a/backend/internal/service/grok_search_usage_billing_test.go b/backend/internal/service/grok_search_usage_billing_test.go new file mode 100644 index 0000000000..6b41aa8587 --- /dev/null +++ b/backend/internal/service/grok_search_usage_billing_test.go @@ -0,0 +1,147 @@ +//go:build unit + +package service + +import ( + "bytes" + "context" + "fmt" + "io" + "net/http" + "net/http/httptest" + "strings" + "testing" + "time" + + "github.com/gin-gonic/gin" + "github.com/stretchr/testify/require" +) + +// Usage fixtures follow the public xAI Responses captures: x_search_calls and the +// x_posts_fetched / x_users_fetched item counts as in big-AGI grok-4.3_x-search, and the +// web_search_calls + x_search_calls + code_interpreter_calls mix as in grok-4.3_web+x-search+code. +// document_search_calls is listed in the xAI ModelOutput schema (server_side_tool_usage_details). +const ( + grokUsageXSearchDetails = `{"x_search_calls":3,"x_posts_fetched":13,"x_users_fetched":3}` + grokUsageWebXCodeDetails = `{"web_search_calls":2,"x_search_calls":1,"code_interpreter_calls":1,"x_posts_fetched":6}` + grokUsageDocumentDetails = `{"document_search_calls":5}` + grokUsageUnrelatedDetails = `{"code_interpreter_calls":1,"file_search_calls":1,"mcp_calls":1,"x_posts_fetched":7,"x_users_fetched":2}` + grokFailedXSearchItemJSON = `{"type":"custom_tool_call","id":"ctc_4","call_id":"xs_999","name":"x_thread_fetch","input":"{}","status":"failed"}` +) + +func grokUsageJSON(details string) string { + usage := `{"input_tokens":5,"output_tokens":2,"total_tokens":7` + if details != "" { + usage += `,"server_side_tool_usage_details":` + details + } + return usage + "}" +} + +type grokUsageCase struct { + name string + items []string + details string + want int +} + +func grokUsageCases() []grokUsageCase { + return []grokUsageCase{ + {"x_search_calls only, posts and users fetched not read", []string{grokXSearchItemJSON}, grokUsageXSearchDetails, 3}, + {"web_search_calls, x_search_calls summed, code_interpreter_calls not read", []string{grokXSearchItemJSON}, grokUsageWebXCodeDetails, 3}, + {"document_search_calls", []string{grokXSearchItemJSON}, grokUsageDocumentDetails, 5}, + {"all three fields", []string{grokXSearchItemJSON}, `{"web_search_calls":1,"x_search_calls":2,"document_search_calls":3}`, 6}, + {"only unrelated classes: usage wins with zero", []string{grokXSearchItemJSON, grokASearchItemJSON}, grokUsageUnrelatedDetails, 0}, + {"usage absent: items counted", []string{grokXSearchItemJSON, grokASearchItemJSON, grokClientToolJSON}, "", 2}, + {"usage lower than items: failed call not billed", []string{grokXSearchItemJSON, grokFailedXSearchItemJSON}, `{"x_search_calls":1}`, 1}, + {"usage zero, items present", []string{grokXSearchItemJSON}, `{"x_search_calls":0}`, 0}, + } +} + +func TestGrokSearchCountFromUsageJSON(t *testing.T) { + for _, tc := range grokUsageCases() { + t.Run(tc.name, func(t *testing.T) { + output := "[" + strings.Join(tc.items, ",") + "]" + top := `{"output":` + output + `,"usage":` + grokUsageJSON(tc.details) + "}" + nested := `{"response":{"output":` + output + `,"usage":` + grokUsageJSON(tc.details) + "}}" + require.Equal(t, tc.want, countGrokNativeSearchCallsFromJSONBytes([]byte(top))) + require.Equal(t, tc.want, countGrokNativeSearchCallsFromJSONBytes([]byte(nested))) + }) + } +} + +func TestGrokSearchCountFromUsageSSEBody(t *testing.T) { + for _, tc := range grokUsageCases() { + t.Run(tc.name, func(t *testing.T) { + sse := withGrokUsage(grokCustomToolCallStream(tc.items, "[]"), tc.details) + require.Equal(t, tc.want, countGrokNativeSearchCallsFromSSEBody(sse)) + }) + } +} + +func TestGrokSearchCountWithTerminalUsage(t *testing.T) { + usage := `"usage":` + grokUsageJSON(`{"x_search_calls":4}`) + for _, eventType := range []string{"response.completed", "response.incomplete", "response.done"} { + data := []byte(fmt.Sprintf(`{"type":%q,"response":{"output":[],%s}}`, eventType, usage)) + require.Equal(t, 4, grokSearchCountWithTerminalUsage(1, data), eventType) + } + for _, eventType := range []string{"response.created", "response.in_progress", "response.output_item.done"} { + data := []byte(fmt.Sprintf(`{"type":%q,"response":{%s}}`, eventType, usage)) + require.Equal(t, 1, grokSearchCountWithTerminalUsage(1, data), eventType) + } + require.Equal(t, 1, grokSearchCountWithTerminalUsage(1, []byte(`{"type":"response.completed","response":{"usage":{"input_tokens":1}}}`))) +} + +func withGrokUsage(sse, details string) string { + return strings.Replace(sse, `"usage":{"input_tokens":5,"output_tokens":2,"total_tokens":7}`, `"usage":`+grokUsageJSON(details), 1) +} + +func TestGrokSearchCountFromUsageAcrossEndpoints(t *testing.T) { + account := healthyGrokOAuthGatewayTestAccount(4243, "access-token") + for _, tc := range grokUsageCases() { + sse := withGrokUsage(grokCustomToolCallStream(tc.items, "[]"), tc.details) + for _, path := range []string{"/v1/messages", "/v1/chat/completions"} { + for _, streaming := range []bool{false, true} { + t.Run(fmt.Sprintf("%s %s stream=%v", tc.name, path, streaming), func(t *testing.T) { + got := forwardGrokCustomToolCallStream(t, path, streaming, account, sse) + require.Equal(t, tc.want, got.searchCount) + }) + } + } + t.Run(fmt.Sprintf("%s /v1/responses stream", tc.name), func(t *testing.T) { + require.Equal(t, tc.want, forwardGrokResponsesSearchCount(t, true, sse)) + }) + t.Run(fmt.Sprintf("%s /v1/responses json", tc.name), func(t *testing.T) { + body := `{"id":"resp_1","object":"response","model":"grok-4.7","status":"completed","output":[` + + strings.Join(tc.items, ",") + `],"usage":` + grokUsageJSON(tc.details) + "}" + require.Equal(t, tc.want, forwardGrokResponsesSearchCount(t, false, body)) + }) + } +} + +func forwardGrokResponsesSearchCount(t *testing.T, streaming bool, upstreamBody string) int { + t.Helper() + gin.SetMode(gin.TestMode) + body := []byte(fmt.Sprintf(`{"model":"grok","input":"search","stream":%t}`, streaming)) + c, _ := gin.CreateTestContext(httptest.NewRecorder()) + c.Request = httptest.NewRequest(http.MethodPost, "/v1/responses", bytes.NewReader(body)) + account := healthyGrokOAuthGatewayTestAccount(9903, "access-token") + repo := &mockAccountRepoForPlatform{accountsByID: map[int64]*Account{account.ID: account}} + contentType := "application/json" + if streaming { + contentType = "text/event-stream" + } + upstream := &httpUpstreamRecorder{resp: &http.Response{ + StatusCode: http.StatusOK, + Header: http.Header{"Content-Type": []string{contentType}}, + Body: io.NopCloser(strings.NewReader(upstreamBody)), + }} + svc := &OpenAIGatewayService{ + httpUpstream: upstream, + grokTokenProvider: NewGrokTokenProvider(repo, nil), + accountRepo: repo, + } + result, err := svc.forwardGrokResponses(context.Background(), c, account, body, "grok", streaming, time.Now()) + require.NoError(t, err) + require.NotNil(t, result) + return result.SearchCount +} diff --git a/backend/internal/service/openai_gateway_chat_completions.go b/backend/internal/service/openai_gateway_chat_completions.go index 482060ec8e..3cd2421c3d 100644 --- a/backend/internal/service/openai_gateway_chat_completions.go +++ b/backend/internal/service/openai_gateway_chat_completions.go @@ -909,6 +909,7 @@ func (s *OpenAIGatewayService) handleChatStreamingResponse( } if countSearch { searchCount += countGrokNativeSearchCallsInSSEDataDedup([]byte(payload), streamSearchSeen) + searchCount = grokSearchCountWithTerminalUsage(searchCount, []byte(payload)) } var event apicompat.ResponsesStreamEvent diff --git a/backend/internal/service/openai_gateway_messages.go b/backend/internal/service/openai_gateway_messages.go index 14aaee67a2..87b88cbd30 100644 --- a/backend/internal/service/openai_gateway_messages.go +++ b/backend/internal/service/openai_gateway_messages.go @@ -1117,6 +1117,7 @@ func (s *OpenAIGatewayService) handleAnthropicStreamingResponse( } if countSearch { searchCount += countGrokNativeSearchCallsInSSEDataDedup([]byte(payload), streamSearchSeen) + searchCount = grokSearchCountWithTerminalUsage(searchCount, []byte(payload)) } var event apicompat.ResponsesStreamEvent diff --git a/backend/internal/service/openai_gateway_response_handling.go b/backend/internal/service/openai_gateway_response_handling.go index ec1427d821..2f6d340fae 100644 --- a/backend/internal/service/openai_gateway_response_handling.go +++ b/backend/internal/service/openai_gateway_response_handling.go @@ -660,6 +660,7 @@ func (s *OpenAIGatewayService) handleStreamingResponseWithReasoning(ctx context. } imageCounter.AddSSEData(dataBytes) searchCounter += countGrokNativeSearchCallsInSSEDataDedup(dataBytes, streamSearchSeen) + searchCounter = grokSearchCountWithTerminalUsage(searchCounter, dataBytes) // Correct Codex tool calls if needed (apply_patch -> edit, etc.) if correctedData, corrected := s.toolCorrector.CorrectToolCallsInSSEBytes(dataBytes); corrected { From fa796b309a613785396a0c658b710ba8c13b3a1f Mon Sep 17 00:00:00 2001 From: wucm667 Date: Mon, 16 Nov 2026 20:52:14 +0800 Subject: [PATCH 25/85] fix(accounts): refresh Claude and Gemini usage snapshots --- .../components/account/AccountUsageCell.vue | 22 ++++--- .../__tests__/AccountUsageCell.spec.ts | 62 +++++++++++++++++++ .../__tests__/accountUsageRefresh.spec.ts | 27 +++++++- frontend/src/utils/accountUsageRefresh.ts | 26 ++++++++ frontend/src/views/admin/AccountsView.vue | 11 ++-- .../admin/__tests__/AccountsView.lite.spec.ts | 48 +++++++++++++- 6 files changed, 178 insertions(+), 18 deletions(-) diff --git a/frontend/src/components/account/AccountUsageCell.vue b/frontend/src/components/account/AccountUsageCell.vue index ff73bde66a..3efe58803a 100644 --- a/frontend/src/components/account/AccountUsageCell.vue +++ b/frontend/src/components/account/AccountUsageCell.vue @@ -769,7 +769,7 @@ import { ref, computed, onMounted, onBeforeUnmount, onUnmounted, watch } from 'v import { useI18n } from 'vue-i18n' import { adminAPI } from '@/api/admin' import type { Account, AccountUsageInfo, GeminiCredentials, WindowStats } from '@/types' -import { buildOpenAIUsageRefreshKey } from '@/utils/accountUsageRefresh' +import { buildAccountUsageRefreshKey } from '@/utils/accountUsageRefresh' import { enqueueUsageRequest } from '@/utils/usageLoadQueue' import { formatCompactNumber, formatDateTime } from '@/utils/format' import { isOfficialGeminiBaseUrl } from '@/utils/geminiExplicitCache' @@ -790,7 +790,7 @@ import { import OpenCodeGoUsageCell from './OpenCodeGoUsageCell.vue' // Module-level cache shared across all AccountUsageCell instances -const _usageCache = new Map() +const _usageCache = new Map() const USAGE_CACHE_TTL = 5 * 60 * 1000 // 5 minutes const props = withDefaults( @@ -941,7 +941,7 @@ const openAISevenDayEstimatedTotalCost = computed(() => { return Number.isFinite(estimate) && estimate > 0 ? estimate : null }) -const openAIUsageRefreshKey = computed(() => buildOpenAIUsageRefreshKey(props.account)) +const usageRefreshKey = computed(() => buildAccountUsageRefreshKey(props.account)) const shouldAutoLoadUsageOnMount = computed(() => { return shouldFetchUsage.value @@ -1569,7 +1569,7 @@ const loadUsage = async (options?: { source?: 'passive' | 'active'; bypassCache? // Check cache if (!options?.bypassCache) { const cached = _usageCache.get(props.account.id) - if (cached && Date.now() - cached.ts < USAGE_CACHE_TTL) { + if (cached && cached.refreshKey === usageRefreshKey.value && Date.now() - cached.ts < USAGE_CACHE_TTL) { usageInfo.value = cached.data loading.value = false return @@ -1578,6 +1578,7 @@ const loadUsage = async (options?: { source?: 'passive' | 'active'; bypassCache? loading.value = true error.value = null + const refreshKey = usageRefreshKey.value try { const fetchFn = () => options?.source @@ -1586,7 +1587,7 @@ const loadUsage = async (options?: { source?: 'passive' | 'active'; bypassCache? const result = await enqueueUsageRequest(props.account, fetchFn) if (!unmounted.value) { usageInfo.value = result - _usageCache.set(props.account.id, { data: result, ts: Date.now() }) + _usageCache.set(props.account.id, { data: result, ts: Date.now(), refreshKey }) } } catch (e: any) { if (!unmounted.value) { @@ -1650,13 +1651,14 @@ const attachVisibilityObserver = () => { const loadActiveUsage = async () => { const accountID = props.account.id + const refreshKey = usageRefreshKey.value activeQueryLoading.value = true error.value = null try { const result = await adminAPI.accounts.getUsage(accountID, 'active', true) if (!unmounted.value && props.account.id === accountID) { usageInfo.value = result - _usageCache.set(accountID, { data: result, ts: Date.now() }) + _usageCache.set(accountID, { data: result, ts: Date.now(), refreshKey }) } } catch (e: any) { if (!unmounted.value && props.account.id === accountID) { @@ -1830,17 +1832,17 @@ watch( { flush: 'post' } ) -watch(openAIUsageRefreshKey, (nextKey, prevKey) => { +watch(usageRefreshKey, (nextKey, prevKey) => { if (!prevKey || nextKey === prevKey) return - if (props.account.platform !== 'openai' || props.account.type !== 'oauth') return + if (!shouldFetchUsage.value) return if (isBatchManaged.value) { - requestParentBatchUsage({ force: true }) + requestParentBatchUsage(props.account.platform === 'openai' ? { force: true } : undefined) return } _usageCache.delete(props.account.id) - requestAutoLoad() + requestAutoLoad(isAnthropicOAuthOrSetupToken.value ? 'passive' : undefined) }) watch( diff --git a/frontend/src/components/account/__tests__/AccountUsageCell.spec.ts b/frontend/src/components/account/__tests__/AccountUsageCell.spec.ts index 38b7918cc1..33a2f6dfd0 100644 --- a/frontend/src/components/account/__tests__/AccountUsageCell.spec.ts +++ b/frontend/src/components/account/__tests__/AccountUsageCell.spec.ts @@ -113,6 +113,68 @@ const cnUsageCellStubs = { } describe('AccountUsageCell', () => { + it.each([ + ['anthropic', 'oauth'], ['anthropic', 'setup-token'], ['gemini', 'oauth'], ['gemini', 'apikey'] + ] as const)('refreshes %s %s snapshots without forcing upstream reads and reuses the new cache', async (platform, type) => { + const account = makeAccount({ id: 98200 + (platform === 'gemini' ? 10 : 0) + (type === 'oauth' ? 1 : 2), platform, type, extra: {} }) + getUsage.mockResolvedValue({ five_hour: { utilization: 21 }, seven_day: { utilization: 31 }, gemini_shared_daily: { utilization: 31 } }) + const wrapper = mount(AccountUsageCell, { props: { account } }) + await flushPromises() + expect(getUsage).toHaveBeenCalledTimes(1) + getUsage.mockResolvedValue({ five_hour: { utilization: 44 }, seven_day: { utilization: 54 }, gemini_shared_daily: { utilization: 54 } }) + const next = { ...account, last_used_at: platform === 'gemini' ? '2026-11-16T10:00:00Z' : null, extra: { passive_usage_7d_utilization: 0.54 } } + await wrapper.setProps({ account: next }) + await flushPromises() + expect(getUsage).toHaveBeenCalledTimes(2) + expect(getUsage).toHaveBeenLastCalledWith(...(platform === 'anthropic' ? [account.id, 'passive', false] : [account.id])) + expect(wrapper.text()).toContain('54') + await wrapper.setProps({ account: { ...next, updated_at: 'unrelated', current_concurrency: 3 } }) + await flushPromises() + expect(getUsage).toHaveBeenCalledTimes(2) + wrapper.unmount() + }) + + it.each(['anthropic', 'gemini'] as const)('asks the desktop batch manager to refresh %s without force', async (platform) => { + const account = makeAccount({ id: 98301, platform, extra: {} }) + const requestBatchedUsage = vi.fn() + const wrapper = mount(AccountUsageCell, { props: { account, requestBatchedUsage } }) + await flushPromises() + requestBatchedUsage.mockClear() + await wrapper.setProps({ account: { ...account, last_used_at: '2026-11-16T10:00:00Z' } }) + expect(requestBatchedUsage).toHaveBeenCalledTimes(1) + expect(requestBatchedUsage).toHaveBeenCalledWith(expect.objectContaining({ id: account.id }), undefined) + expect(getUsage).not.toHaveBeenCalled() + wrapper.unmount() + }) + + it.each(['anthropic', 'gemini'] as const)('defers mobile %s snapshot refresh until visible', async (platform) => { + vi.mocked(window.matchMedia).mockReturnValue({ matches: false, addEventListener: vi.fn(), removeEventListener: vi.fn() } as unknown as MediaQueryList) + let notify: IntersectionObserverCallback = () => {} + vi.stubGlobal('IntersectionObserver', class { + constructor(callback: IntersectionObserverCallback) { notify = callback } + observe() {} + disconnect() {} + }) + const account = makeAccount({ id: 98401, platform, extra: {} }) + getUsage.mockResolvedValue({ five_hour: { utilization: 44 }, gemini_shared_daily: { utilization: 44 } }) + const wrapper = mount(AccountUsageCell, { props: { account } }) + try { + await flushPromises() + await wrapper.setProps({ account: { ...account, last_used_at: '2026-11-16T10:00:00Z' } }) + expect(getUsage).not.toHaveBeenCalled() + notify([{ isIntersecting: true }] as IntersectionObserverEntry[], {} as IntersectionObserver) + await flushPromises() + expect(getUsage).toHaveBeenCalledTimes(1) + expect(getUsage).toHaveBeenLastCalledWith(...(platform === 'anthropic' ? [account.id, 'passive', false] : [account.id])) + await wrapper.setProps({ account: { ...account, last_used_at: '2026-11-16T10:01:00Z' } }) + await flushPromises() + expect(getUsage).toHaveBeenCalledTimes(2) + } finally { + wrapper.unmount() + vi.unstubAllGlobals() + } + }) + beforeEach(() => { getUsage.mockReset() Object.defineProperty(window, 'matchMedia', { diff --git a/frontend/src/utils/__tests__/accountUsageRefresh.spec.ts b/frontend/src/utils/__tests__/accountUsageRefresh.spec.ts index f9559697e1..f2d21a4212 100644 --- a/frontend/src/utils/__tests__/accountUsageRefresh.spec.ts +++ b/frontend/src/utils/__tests__/accountUsageRefresh.spec.ts @@ -1,5 +1,30 @@ import { describe, expect, it } from 'vitest' -import { buildGrokUsageRefreshKey, buildOpenAIUsageRefreshKey } from '../accountUsageRefresh' +import { buildAccountUsageRefreshKey, buildGrokUsageRefreshKey, buildOpenAIUsageRefreshKey } from '../accountUsageRefresh' + +describe('buildAccountUsageRefreshKey', () => { + it.each(['oauth', 'setup-token'])('tracks every Claude %s passive snapshot input', (type) => { + const base = { id: 1, platform: 'anthropic', type, extra: {} } as any + for (const field of ['last_used_at', 'session_window_start', 'session_window_end', 'session_window_status']) { + expect(buildAccountUsageRefreshKey({ ...base, [field]: 'new' })).not.toBe(buildAccountUsageRefreshKey(base)) + } + for (const field of ['session_window_utilization', 'passive_usage_sampled_at', 'passive_usage_7d_utilization', 'passive_usage_7d_reset', 'passive_usage_7d_oi_utilization', 'passive_usage_7d_oi_reset']) { + expect(buildAccountUsageRefreshKey({ ...base, extra: { [field]: 1 } })).not.toBe(buildAccountUsageRefreshKey(base)) + } + }) + + it.each(['anthropic', 'gemini'])('ignores unrelated %s changes and extra key ordering', (platform) => { + const base = { id: 1, platform, type: 'oauth', extra: { session_window_utilization: 0, other: 1 } } as any + expect(buildAccountUsageRefreshKey({ ...base, updated_at: 'new', current_concurrency: 5, extra: { other: 2, session_window_utilization: 0 } } as any)).toBe(buildAccountUsageRefreshKey(base)) + expect(buildAccountUsageRefreshKey({ ...base, last_used_at: 'new' })).not.toBe(buildAccountUsageRefreshKey(base)) + }) + + it('retains OpenAI keys and excludes unsupported platforms/types', () => { + const base = { id: 1, platform: 'openai', type: 'oauth', extra: {} } as any + expect(buildAccountUsageRefreshKey(base)).toBe(buildOpenAIUsageRefreshKey(base)) + expect(buildAccountUsageRefreshKey({ ...base, platform: 'anthropic', type: 'apikey' })).toBe('') + expect(buildAccountUsageRefreshKey({ ...base, platform: 'antigravity' })).toBe('') + }) +}) describe('buildOpenAIUsageRefreshKey', () => { it('会在 codex 快照变化时生成不同 key', () => { diff --git a/frontend/src/utils/accountUsageRefresh.ts b/frontend/src/utils/accountUsageRefresh.ts index 121dae253a..4d64ee7899 100644 --- a/frontend/src/utils/accountUsageRefresh.ts +++ b/frontend/src/utils/accountUsageRefresh.ts @@ -69,3 +69,29 @@ export const buildGrokUsageRefreshKey = (account: Pick): string => { + if (account.platform === 'openai') return buildOpenAIUsageRefreshKey(account) + + const isClaude = account.platform === 'anthropic' && (account.type === 'oauth' || account.type === 'setup-token') + if (!isClaude && account.platform !== 'gemini') return '' + + const extra = account.extra ?? {} + return serializeSnapshotRefreshValue([ + account.id, + account.platform, + account.type, + account.last_used_at ?? null, + account.session_window_start ?? null, + account.session_window_end ?? null, + ...(isClaude ? [ + account.session_window_status ?? null, + extra.session_window_utilization ?? null, + extra.passive_usage_sampled_at ?? null, + extra.passive_usage_7d_utilization ?? null, + extra.passive_usage_7d_reset ?? null, + extra.passive_usage_7d_oi_utilization ?? null, + extra.passive_usage_7d_oi_reset ?? null + ] : []) + ]) +} diff --git a/frontend/src/views/admin/AccountsView.vue b/frontend/src/views/admin/AccountsView.vue index 7384e4858b..cb650f7060 100644 --- a/frontend/src/views/admin/AccountsView.vue +++ b/frontend/src/views/admin/AccountsView.vue @@ -531,7 +531,7 @@ import Icon from '@/components/icons/Icon.vue' import ErrorPassthroughRulesModal from '@/components/admin/ErrorPassthroughRulesModal.vue' import TLSFingerprintProfilesModal from '@/components/admin/TLSFingerprintProfilesModal.vue' import { fetchAllAccountIds } from '@/utils/accountSelection' -import { buildGrokUsageRefreshKey, buildOpenAIUsageRefreshKey } from '@/utils/accountUsageRefresh' +import { buildGrokUsageRefreshKey, buildAccountUsageRefreshKey } from '@/utils/accountUsageRefresh' import { formatDateTime, formatRelativeTime } from '@/utils/format' import { proxyExpiryBadgeClass, proxyExpiryLabelKey } from '@/utils/proxyExpiry' import { extractApiErrorMessage } from '@/utils/apiError' @@ -747,7 +747,7 @@ const usageBatchByAccountId = ref>({}) const usageBatchErrorByAccountId = ref>({}) const usageBatchLoadingByAccountId = ref>({}) const usageBatchRequestTokenByAccountId = ref>({}) -const usageBatchCache = new Map() +const usageBatchCache = new Map() const USAGE_BATCH_CACHE_TTL = 5 * 60 * 1000 const pendingUsageBatchIds = new Set() let usageBatchFlushTimer: ReturnType | null = null @@ -801,6 +801,7 @@ const flushQueuedUsageBatch = async () => { usageBatchFlushTimer = null const accountIDs = Array.from(pendingUsageBatchIds) const force = queuedUsageBatchForce + const refreshKeys = new Map(accounts.value.map(account => [account.id, buildAccountUsageRefreshKey(account)])) pendingUsageBatchIds.clear() queuedUsageBatchForce = false @@ -831,7 +832,7 @@ const flushQueuedUsageBatch = async () => { nextErrors[key] = errorMap[key] ?? null nextLoading[key] = false if (usage) { - usageBatchCache.set(accountID, { data: usage, ts: now }) + usageBatchCache.set(accountID, { data: usage, ts: now, refreshKey: refreshKeys.get(accountID) ?? '' }) } else { usageBatchCache.delete(accountID) } @@ -869,7 +870,7 @@ const queueBatchedUsage = (account: Account, options?: { force?: boolean }) => { usageBatchCache.delete(cacheKey) } else { const cached = usageBatchCache.get(cacheKey) - if (cached && Date.now() - cached.ts < USAGE_BATCH_CACHE_TTL) { + if (cached && cached.refreshKey === buildAccountUsageRefreshKey(account) && Date.now() - cached.ts < USAGE_BATCH_CACHE_TTL) { setUsageBatchState(cacheKey, cached.data, null) setUsageBatchLoading(cacheKey, false) return @@ -1435,7 +1436,7 @@ const shouldReplaceAutoRefreshRow = (current: Account, next: Account) => { current.rate_limit_reset_at !== next.rate_limit_reset_at || current.overload_until !== next.overload_until || current.temp_unschedulable_until !== next.temp_unschedulable_until || - buildOpenAIUsageRefreshKey(current) !== buildOpenAIUsageRefreshKey(next) || + buildAccountUsageRefreshKey(current) !== buildAccountUsageRefreshKey(next) || buildGrokUsageRefreshKey(current) !== buildGrokUsageRefreshKey(next) ) } diff --git a/frontend/src/views/admin/__tests__/AccountsView.lite.spec.ts b/frontend/src/views/admin/__tests__/AccountsView.lite.spec.ts index 9d8d7266e5..64115c43f5 100644 --- a/frontend/src/views/admin/__tests__/AccountsView.lite.spec.ts +++ b/frontend/src/views/admin/__tests__/AccountsView.lite.spec.ts @@ -10,6 +10,7 @@ const { listWithEtag, getById, getBatchTodayStats, + getBatchUsage, getUpstreamBillingProbeSettings, getAllProxies, getAllGroups, @@ -21,6 +22,7 @@ const { listWithEtag: vi.fn(), getById: vi.fn(), getBatchTodayStats: vi.fn(), + getBatchUsage: vi.fn(), getUpstreamBillingProbeSettings: vi.fn(), getAllProxies: vi.fn(), getAllGroups: vi.fn(), @@ -36,6 +38,7 @@ vi.mock('@/api/admin', () => ({ getById, listWithEtag, getBatchTodayStats, + getBatchUsage, getUpstreamBillingProbeSettings, delete: vi.fn(), batchClearError: vi.fn(), @@ -67,6 +70,7 @@ const DataTableStub = defineComponent({
@@ -93,7 +97,7 @@ const AccountStatsModalStub = defineComponent({ template: '
{{ show ? account?.name : "" }}
' }) -function mountView(stubActionMenu = true) { +function mountView(stubActionMenu = true, realUsageCell = false) { return mount(AccountsView, { attachTo: document.body, global: { @@ -124,7 +128,7 @@ function mountView(stubActionMenu = true) { AccountStatusIndicator: true, AccountTodayStatsCell: true, AccountGroupsCell: AccountGroupsCellStub, - AccountUsageCell: true, + AccountUsageCell: !realUsageCell, UpstreamBillingRateCell: true, HelpTooltip: true, Icon: true, @@ -163,6 +167,7 @@ describe('admin AccountsView lite account list', () => { listWithEtag.mockReset().mockResolvedValue({ notModified: true, etag: 'compact-etag', data: null }) getById.mockReset().mockResolvedValue(fullAccount) getBatchTodayStats.mockReset().mockResolvedValue({ stats: {} }) + getBatchUsage.mockReset().mockResolvedValue({ usage: { '42': { five_hour: { utilization: 21 }, seven_day: { utilization: 31 } } }, errors: {} }) getUpstreamBillingProbeSettings.mockReset().mockResolvedValue({ enabled: true }) getAllProxies.mockReset().mockResolvedValue([]) getAllGroups.mockReset().mockResolvedValue([{ id: 7, name: 'codex', platform: 'openai' }]) @@ -176,6 +181,45 @@ describe('admin AccountsView lite account list', () => { vi.restoreAllMocks() }) + it.each([ + ['anthropic', 'oauth'], ['anthropic', 'setup-token'], ['gemini', 'oauth'] + ])('updates %s %s usage on auto-refresh without force or unrelated probes', async (platform, type) => { + vi.useFakeTimers() + vi.spyOn(document, 'hidden', 'get').mockReturnValue(false) + vi.spyOn(window, 'matchMedia').mockImplementation(() => ({ + matches: true, addEventListener: vi.fn(), removeEventListener: vi.fn() + }) as unknown as MediaQueryList) + localStorage.setItem('account-auto-refresh', JSON.stringify({ enabled: true, interval_seconds: 5 })) + const account = { ...listRow, platform, type } + listAccounts.mockResolvedValue({ items: [account], total: 1, page: 1, page_size: 20, pages: 1 }) + const wrapper = mountView(true, true) + await flushPromises() + await vi.advanceTimersByTimeAsync(1) + await flushPromises() + expect(getBatchUsage).toHaveBeenCalledTimes(1) + expect(getBatchUsage).toHaveBeenCalledWith([42], false) + + const next = { ...account, extra: { session_window_utilization: 0.44, passive_usage_7d_utilization: 0.54 }, last_used_at: platform === 'gemini' ? '2026-11-16T10:00:00Z' : null } + getBatchUsage.mockResolvedValue({ usage: { '42': { five_hour: { utilization: 44 }, seven_day: { utilization: 54 } } }, errors: {} }) + listWithEtag.mockResolvedValue({ notModified: false, etag: 'new', data: { items: [next], total: 1, pages: 1 } }) + await vi.advanceTimersByTimeAsync(6000) + await flushPromises() + expect(getBatchUsage).toHaveBeenCalledTimes(2) + expect(getBatchUsage).toHaveBeenLastCalledWith([42], false) + const cell = wrapper.findComponent({ name: 'AccountUsageCell' }) + expect(cell.props('account').last_used_at).toBe(next.last_used_at) + expect(cell.props('batchedUsage').seven_day.utilization).toBe(54) + cell.props('requestBatchedUsage')(cell.props('account')) + await vi.advanceTimersByTimeAsync(1) + expect(getBatchUsage).toHaveBeenCalledTimes(2) + + listWithEtag.mockResolvedValue({ notModified: false, etag: 'unrelated', data: { items: [{ ...next, updated_at: 'new', current_concurrency: 2, extra: { ...next.extra, unrelated: true } }], total: 1, pages: 1 } }) + await vi.advanceTimersByTimeAsync(6000) + await flushPromises() + expect(getBatchUsage).toHaveBeenCalledTimes(2) + wrapper.unmount() + }) + it('keeps lite=1 on the initial list request', async () => { const wrapper = mountView() await flushPromises() From 833cfcc2fb49ea35f2191b009cd2dc35a2784234 Mon Sep 17 00:00:00 2001 From: lishuangqiang <142634204+lishuangqiang@users.noreply.github.com> Date: Mon, 16 Nov 2026 21:30:06 +0800 Subject: [PATCH 26/85] perf(gateway): skip the cache_control TTL walk when no 1h breakpoint exists The byte-level precheck added for #8668 still runs both cache_control walks for any body containing a "thinking" literal, because the thinking-block cleanup cannot be skipped by that check alone. Claude Code enables extended thinking by default, so that is the dominant shape: the precheck pays its own scan and then falls through to the unconditional normalizeCacheControlTTLOrder(enforceCacheControlBlockLimit(body)). On the 32KB Claude Code benchmark body with thinking, this made the optimized path slightly slower than the pre-fix code (112us vs 104us). Skip the second collectCacheControlPaths pass when the body has no "1h" literal. The walk is provably a no-op there: last1h stays -1 and nothing is rewritten. Escaped bodies returned earlier, so the byte check is exact, and the block-limit deletions only remove cache_control keys, which cannot introduce a 1h breakpoint. Benchmark (Apple M5 Pro, -benchtime 2s -count 3): thinking, no 1h: 112us / 21 allocs -> 52us / 8 allocs common, no 1h: 21.6us / 0 allocs -> 21.3us / 0 allocs 1h bodies: unchanged (within noise) The benchmark gains two thinking cases so future work cannot regress this shape unnoticed. Equivalence tests compare against the verbatim legacy implementation. Fixes #8861 Refs #8668 --- .../service/gateway_claude_oauth_body.go | 10 +++++- .../gateway_request_json_bench_test.go | 34 +++++++++++++++++-- 2 files changed, 41 insertions(+), 3 deletions(-) diff --git a/backend/internal/service/gateway_claude_oauth_body.go b/backend/internal/service/gateway_claude_oauth_body.go index eb4faac461..c67143c66a 100644 --- a/backend/internal/service/gateway_claude_oauth_body.go +++ b/backend/internal/service/gateway_claude_oauth_body.go @@ -1091,7 +1091,15 @@ func enforceCacheControlLimit(body []byte) []byte { } return normalizeCacheControlTTLOrder(body) } - return normalizeCacheControlTTLOrder(enforceCacheControlBlockLimit(body)) + out := enforceCacheControlBlockLimit(body) + // Escaped bodies returned earlier, so a missing "1h" literal here is exact: + // the TTL walk would find no 1h breakpoint and rewrite nothing, yet it still + // costs a full collectCacheControlPaths pass over the body. Deletions above + // only remove cache_control keys, so they cannot introduce a 1h breakpoint. + if !bytes.Contains(body, cacheTTL1hJSONBytes) { + return out + } + return normalizeCacheControlTTLOrder(out) } // enforceCacheControlBlockLimit 强制执行 cache_control 块数量限制(最多 4 个) diff --git a/backend/internal/service/gateway_request_json_bench_test.go b/backend/internal/service/gateway_request_json_bench_test.go index d56064a09c..2eca1091a7 100644 --- a/backend/internal/service/gateway_request_json_bench_test.go +++ b/backend/internal/service/gateway_request_json_bench_test.go @@ -10,8 +10,32 @@ import ( // claudeCodeLikeBody builds a ~32KB request shaped like a Claude Code turn: // 20 tools, a system prompt, and 40 messages with 4 content blocks each. func claudeCodeLikeBody(cacheControls int, with1h bool) []byte { + return claudeCodeLikeBodyWith(claudeCodeLikeBodyOptions{cacheControls: cacheControls, with1h: with1h}) +} + +// claudeCodeLikeBodyWithThinking builds the same shape with extended thinking +// enabled: the top-level thinking config plus a thinking block in the last +// assistant turn. Either occurrence makes the byte-level precheck in +// enforceCacheControlLimit inapplicable, so this is the shape that decides +// whether the cache_control walks can be skipped for real Claude Code traffic. +func claudeCodeLikeBodyWithThinking(with1h bool) []byte { + return claudeCodeLikeBodyWith(claudeCodeLikeBodyOptions{cacheControls: 4, with1h: with1h, thinking: true}) +} + +type claudeCodeLikeBodyOptions struct { + cacheControls int + with1h bool + thinking bool +} + +func claudeCodeLikeBodyWith(opts claudeCodeLikeBodyOptions) []byte { + cacheControls := opts.cacheControls var b strings.Builder - _, _ = b.WriteString(`{"model":"claude-sonnet-5-5","max_tokens":32000,"stream":true,"tools":[`) + _, _ = b.WriteString(`{"model":"claude-sonnet-5-5","max_tokens":32000,"stream":true`) + if opts.thinking { + _, _ = b.WriteString(`,"thinking":{"type":"enabled","budget_tokens":31999}`) + } + _, _ = b.WriteString(`,"tools":[`) for i := 0; i < 20; i++ { if i > 0 { _ = b.WriteByte(',') @@ -42,10 +66,14 @@ func claudeCodeLikeBody(cacheControls int, with1h bool) []byte { if c > 0 { _ = b.WriteByte(',') } + if opts.thinking && m == 39 && c == 0 { + _, _ = b.WriteString(`{"type":"thinking","thinking":"` + strings.Repeat("t", 80) + `","signature":"` + strings.Repeat("s", 64) + `"}`) + continue + } fmt.Fprintf(&b, `{"type":"text","text":"%s"`, strings.Repeat("x", 120)) if m >= 38 && c == 3 && cacheControls > 0 { ttl := "" - if with1h && m == 39 { + if opts.with1h && m == 39 { ttl = `,"ttl":"1h"` } fmt.Fprintf(&b, `,"cache_control":{"type":"ephemeral"%s}`, ttl) @@ -66,6 +94,8 @@ func BenchmarkEnforceCacheControlLimit(b *testing.B) { }{ {"common_4cc_no1h", claudeCodeLikeBody(4, false)}, {"with_1h", claudeCodeLikeBody(4, true)}, + {"thinking_4cc_no1h", claudeCodeLikeBodyWithThinking(false)}, + {"thinking_4cc_1h", claudeCodeLikeBodyWithThinking(true)}, } for _, tc := range cases { b.Run(tc.name+"/legacy", func(b *testing.B) { From f42dad9b7113ad26dfcfc59b4ce1bfe3352c9493 Mon Sep 17 00:00:00 2001 From: Anankke Date: Mon, 16 Nov 2026 01:28:35 -0800 Subject: [PATCH 27/85] fix(composite): adapt thinking to the Claude 5.5 model a route rewrites to A composite route that rewrites the request model left the client's thinking untouched, so a route from claude-sonnet-5 to claude-opus-5-5 forwarded thinking.type=enabled with budget_tokens and validateClaude55Request answered 400 before the request reached the upstream. The route middleware now rewrites the model through RewriteCompositeRequestModel, which replaces a thinking mode that validateClaude55Request rejects for the new model with the nearest mode it accepts: enabled becomes adaptive without budget_tokens, and disabled becomes between_tools on Sonnet 5.5. The mapping is shared with the Bedrock Sonnet 5.5 sanitizer, whose behavior is unchanged. Modes the target still rejects stay with validateClaude55Request, and a request whose model the route does not rewrite keeps its thinking as sent. --- .../server/routes/composite_platform_test.go | 80 ++++++++++++++++++ backend/internal/server/routes/gateway.go | 5 +- backend/internal/service/bedrock_request.go | 9 +- backend/internal/service/claude55_thinking.go | 27 ++++++ .../internal/service/composite_platform.go | 12 +++ .../composite_platform_thinking_test.go | 82 +++++++++++++++++++ 6 files changed, 203 insertions(+), 12 deletions(-) create mode 100644 backend/internal/service/claude55_thinking.go create mode 100644 backend/internal/service/composite_platform_thinking_test.go diff --git a/backend/internal/server/routes/composite_platform_test.go b/backend/internal/server/routes/composite_platform_test.go index 9841b243c5..262e4ec987 100644 --- a/backend/internal/server/routes/composite_platform_test.go +++ b/backend/internal/server/routes/composite_platform_test.go @@ -415,3 +415,83 @@ func TestCompositeLiveRouteDispatchesBySessionModelNotTopLevelAlias(t *testing.T require.Equal(t, http.StatusNoContent, w.Code) } + +// A route that rewrites the model to a Claude 5.5 model also rewrites a +// thinking mode that model rejects into the nearest one it accepts; a route +// that keeps the client's model leaves thinking as the client sent it. +func TestCompositeTargetPlatformMiddlewareAdaptsThinkingToRewrittenModel(t *testing.T) { + cases := []struct { + name string + publicModel string + upstreamModel string + thinking string + wantThinking string + }{ + { + name: "enabled becomes adaptive on opus 5.5", + publicModel: "claude-sonnet-5", + upstreamModel: "claude-opus-5-5", + thinking: `{"type":"enabled","budget_tokens":4096}`, + wantThinking: `{"type":"adaptive"}`, + }, + { + name: "disabled becomes between_tools on sonnet 5.5", + publicModel: "claude-sonnet-5", + upstreamModel: "claude-sonnet-5-5", + thinking: `{"type":"disabled"}`, + wantThinking: `{"type":"between_tools"}`, + }, + { + name: "model not rewritten keeps enabled", + publicModel: "claude-opus-5-5", + upstreamModel: "claude-opus-5-5", + thinking: `{"type":"enabled","budget_tokens":4096}`, + wantThinking: `{"type":"enabled","budget_tokens":4096}`, + }, + } + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + gin.SetMode(gin.TestMode) + router := gin.New() + resolver := service.NewCompositeRouteResolver(compositeRouteRepoStub{ + routes: []service.CompositeModelRoute{{ + ID: 1, + GroupID: 1, + PublicModel: tc.publicModel, + MatchType: service.CompositeRouteMatchExact, + TargetPlatform: service.PlatformAnthropic, + UpstreamModel: tc.upstreamModel, + Endpoint: service.CompositeRouteEndpointAny, + Priority: 100, + Enabled: true, + }}, + }) + router.Use(gin.HandlerFunc(servermiddleware.APIKeyAuthMiddleware(func(c *gin.Context) { + groupID := int64(1) + c.Set(string(servermiddleware.ContextKeyAPIKey), &service.APIKey{ + GroupID: &groupID, + Group: &service.Group{ID: groupID, Platform: service.PlatformComposite}, + }) + c.Next() + }))) + router.Use(compositeTargetPlatformMiddleware(resolver)) + router.POST("/v1/messages", func(c *gin.Context) { + body, err := io.ReadAll(c.Request.Body) + require.NoError(t, err) + require.JSONEq(t, + `{"model":"`+tc.upstreamModel+`","max_tokens":64,"thinking":`+tc.wantThinking+`,"messages":[]}`, + string(body)) + c.Status(http.StatusNoContent) + }) + + req := httptest.NewRequest(http.MethodPost, "/v1/messages", strings.NewReader( + `{"model":"`+tc.publicModel+`","max_tokens":64,"thinking":`+tc.thinking+`,"messages":[]}`)) + req.Header.Set("Content-Type", "application/json") + w := httptest.NewRecorder() + + router.ServeHTTP(w, req) + + require.Equal(t, http.StatusNoContent, w.Code) + }) + } +} diff --git a/backend/internal/server/routes/gateway.go b/backend/internal/server/routes/gateway.go index 0e7dbef05a..d4ce231013 100644 --- a/backend/internal/server/routes/gateway.go +++ b/backend/internal/server/routes/gateway.go @@ -14,7 +14,6 @@ import ( "github.com/gin-gonic/gin" "github.com/tidwall/gjson" - "github.com/tidwall/sjson" ) // RegisterGatewayRoutes 注册 API 网关路由(Claude/OpenAI/Gemini 兼容) @@ -593,9 +592,7 @@ func compositeTargetPlatformMiddleware(resolver *service.CompositeRouteResolver) c.Request = c.Request.WithContext(service.WithCompositeRouteDecision(c.Request.Context(), decision)) if upstreamModel := strings.TrimSpace(decision.UpstreamModel); upstreamModel != "" && upstreamModel != model && gjson.ValidBytes(body) { if _, modelPath := requestmodel.JSONModelPathForRoute(routePath, body); modelPath != "" { - if rewritten, rewriteErr := sjson.SetBytes(body, modelPath, upstreamModel); rewriteErr == nil { - body = rewritten - } + body = service.RewriteCompositeRequestModel(body, modelPath, upstreamModel) } } } diff --git a/backend/internal/service/bedrock_request.go b/backend/internal/service/bedrock_request.go index 4fc7fd7213..fb26686d28 100644 --- a/backend/internal/service/bedrock_request.go +++ b/backend/internal/service/bedrock_request.go @@ -756,14 +756,7 @@ func sanitizeBedrockThinking(body []byte, modelID string) []byte { } if claude.IsSonnet55(modelID) { - switch thinkingType { - case "enabled": - body, _ = sjson.SetBytes(body, "thinking.type", "adaptive") - body, _ = sjson.DeleteBytes(body, "thinking.budget_tokens") - case "disabled": - body, _ = sjson.SetBytes(body, "thinking.type", "between_tools") - } - return body + return adaptThinkingToClaude55(body, modelID) } if isBedrockOpus47OrNewer(modelID) { diff --git a/backend/internal/service/claude55_thinking.go b/backend/internal/service/claude55_thinking.go new file mode 100644 index 0000000000..b74a05420e --- /dev/null +++ b/backend/internal/service/claude55_thinking.go @@ -0,0 +1,27 @@ +package service + +import ( + "github.com/Wei-Shaw/sub2api/internal/pkg/claude" + "github.com/tidwall/gjson" + "github.com/tidwall/sjson" +) + +// adaptThinkingToClaude55 replaces a thinking mode that a Claude 5.5 model +// rejects with the nearest mode it accepts: enabled becomes adaptive without +// budget_tokens, and on Sonnet 5.5 disabled becomes between_tools. Other modes +// are left for validateClaude55Request to judge. +func adaptThinkingToClaude55(body []byte, model string) []byte { + if !isClaude55SignedThinkingModel(model) { + return body + } + switch gjson.GetBytes(body, "thinking.type").String() { + case "enabled": + body, _ = sjson.SetBytes(body, "thinking.type", "adaptive") + body, _ = sjson.DeleteBytes(body, "thinking.budget_tokens") + case "disabled": + if claude.IsSonnet55(model) { + body, _ = sjson.SetBytes(body, "thinking.type", "between_tools") + } + } + return body +} diff --git a/backend/internal/service/composite_platform.go b/backend/internal/service/composite_platform.go index ddaf2d83ad..5b65a36040 100644 --- a/backend/internal/service/composite_platform.go +++ b/backend/internal/service/composite_platform.go @@ -51,6 +51,18 @@ func WithCompositeRouteDecision(ctx context.Context, decision CompositeRouteDeci return ctx } +// RewriteCompositeRequestModel puts a composite route's upstream model into the +// request body at modelPath. The client chose its thinking mode for the model +// it asked for, so a mode the upstream model rejects becomes the nearest mode +// it accepts. The body is returned unchanged when it cannot be rewritten. +func RewriteCompositeRequestModel(body []byte, modelPath, upstreamModel string) []byte { + rewritten, err := sjson.SetBytes(body, modelPath, upstreamModel) + if err != nil { + return body + } + return adaptThinkingToClaude55(rewritten, upstreamModel) +} + func ResolvedUpstreamModelFromContext(ctx context.Context) (string, bool) { if ctx == nil { return "", false diff --git a/backend/internal/service/composite_platform_thinking_test.go b/backend/internal/service/composite_platform_thinking_test.go new file mode 100644 index 0000000000..b7c2f315e7 --- /dev/null +++ b/backend/internal/service/composite_platform_thinking_test.go @@ -0,0 +1,82 @@ +//go:build unit + +package service + +import ( + "context" + "io" + "net/http" + "net/http/httptest" + "strings" + "testing" + + "github.com/gin-gonic/gin" + "github.com/stretchr/testify/require" + "github.com/tidwall/gjson" +) + +func forwardCompositeThinkingRequest(t *testing.T, publicModel, upstreamModel, clientBody string) (*httptest.ResponseRecorder, *anthropicHTTPUpstreamRecorder, error) { + t.Helper() + gin.SetMode(gin.TestMode) + rec := httptest.NewRecorder() + c, _ := gin.CreateTestContext(rec) + c.Request = httptest.NewRequest(http.MethodPost, "/v1/messages", nil) + + body := []byte(clientBody) + ctx := context.Background() + if upstreamModel != publicModel { + body = RewriteCompositeRequestModel(body, "model", upstreamModel) + ctx = WithCompositeRouteDecision(ctx, CompositeRouteDecision{ + Matched: true, Source: CompositeRouteSourceExplicit, + PublicModel: publicModel, TargetPlatform: PlatformAnthropic, UpstreamModel: upstreamModel, + }) + } + c.Request = c.Request.WithContext(ctx) + parsed, err := ParseGatewayRequest(NewRequestBodyRef(body), PlatformAnthropic) + require.NoError(t, err) + + upstream := &anthropicHTTPUpstreamRecorder{resp: &http.Response{ + StatusCode: http.StatusOK, + Header: http.Header{"Content-Type": []string{"application/json"}}, + Body: io.NopCloser(strings.NewReader(`{"id":"msg_1","type":"message","role":"assistant","model":"` + upstreamModel + `","content":[{"type":"text","text":"ok"}],"usage":{"input_tokens":1,"output_tokens":1}}`)), + }} + svc := newForwardPartialUsageServiceForTest(upstream) + _, err = svc.Forward(ctx, c, newAnthropicOAuthAccountForPartialUsageTest(), parsed) + return rec, upstream, err +} + +// A composite route that rewrites claude-sonnet-5 to claude-opus-5-5 sends the +// client's budget thinking upstream as adaptive thinking instead of failing +// Opus 5.5 validation. +func TestCompositeRewriteToOpus55SendsEnabledThinkingAsAdaptive(t *testing.T) { + rec, upstream, err := forwardCompositeThinkingRequest(t, "claude-sonnet-5", "claude-opus-5-5", + `{"model":"claude-sonnet-5","max_tokens":64,"stream":false,"thinking":{"type":"enabled","budget_tokens":4096},"messages":[{"role":"user","content":"hi"}]}`) + + require.NoError(t, err) + require.NotEqual(t, http.StatusBadRequest, rec.Code) + require.NotNil(t, upstream.lastReq, "request must reach the upstream") + require.Equal(t, "claude-opus-5-5", gjson.GetBytes(upstream.lastBody, "model").String()) + require.Equal(t, "adaptive", gjson.GetBytes(upstream.lastBody, "thinking.type").String()) + require.False(t, gjson.GetBytes(upstream.lastBody, "thinking.budget_tokens").Exists()) +} + +func TestCompositeRewriteToSonnet55SendsDisabledThinkingAsBetweenTools(t *testing.T) { + rec, upstream, err := forwardCompositeThinkingRequest(t, "claude-sonnet-5", "claude-sonnet-5-5", + `{"model":"claude-sonnet-5","max_tokens":64,"stream":false,"thinking":{"type":"disabled"},"messages":[{"role":"user","content":"hi"}]}`) + + require.NoError(t, err) + require.NotEqual(t, http.StatusBadRequest, rec.Code) + require.NotNil(t, upstream.lastReq, "request must reach the upstream") + require.Equal(t, "between_tools", gjson.GetBytes(upstream.lastBody, "thinking.type").String()) +} + +// Without a model rewrite the client's own invalid thinking mode is still +// rejected. +func TestDirectOpus55RequestWithEnabledThinkingIsStillRejected(t *testing.T) { + rec, upstream, err := forwardCompositeThinkingRequest(t, "claude-opus-5-5", "claude-opus-5-5", + `{"model":"claude-opus-5-5","max_tokens":64,"stream":false,"thinking":{"type":"enabled","budget_tokens":4096},"messages":[{"role":"user","content":"hi"}]}`) + + require.ErrorContains(t, err, "claude-opus-5-5 requires adaptive thinking") + require.Equal(t, http.StatusBadRequest, rec.Code) + require.Nil(t, upstream.lastReq) +} From 59645b7bea035d4f43072a2c0b62360eaa6e45fe Mon Sep 17 00:00:00 2001 From: lishuangqiang <142634204+lishuangqiang@users.noreply.github.com> Date: Mon, 16 Nov 2026 22:52:36 +0800 Subject: [PATCH 28/85] perf(openai): skip the image-intent body scan when a request cannot declare one Every /v1/responses request runs IsImageGenerationIntentForPlatform to decide whether to mark the context as image generation (capability routing and image billing). After the two O(1) checks (dedicated image endpoint, image model) the function unconditionally runs gjson.ValidBytes over the whole body and then walks the root object with a ForEach. Both steps are pure overhead for requests that cannot match. Every branch that can set the intent requires one of two things in the body: the literal "image_gen" (image_generation tools carry that prefix, and the namespace, tool_choice and function-reference checks all use image_gen), or an image model name (gpt-image-*, grok-imagine*) as the "model" value. The same body is also validated by the handler and again by ParseGatewayRequest, so this pass is a third redundant validation of the same bytes. Add a byte-level necessary condition ahead of gjson.ValidBytes: bytes.Contains(body, "image_gen") || containsASCIIFold(body, "imag") // image model names || bytes.Contains(body, "\\u") // unicode-escaped literal All three are required: - "image_gen" alone misses the model branch. {"model":"gpt-image-2"} returns true today and does not contain "image_gen"; dropping it would let image model requests bypass the group image-generation gate and image billing. - isOpenAIImageGenerationModel lowercases its argument while bytes.Contains does not, so the model token is matched case-insensitively. - JSON strings may spell any byte as a unicode escape, so a body containing "image_generation" only reveals the literal after decoding. Escaped bodies therefore fall back to the full scan. None of the target literals contain a character JSON escapes, so a "\u" probe is exhaustive. containsASCIIFold had to be rewritten as well. It compared byte by byte, which is a full body scan on its own, and a first-byte memchr variant that re-probes both cases of the first byte per candidate degrades quadratically. The new implementation keeps one cursor per case and advances only the cursor it just consumed, so it stays linear. Without this the precheck would cost more than the scan it replaces (~930us vs 783us on a 1MiB body). The three scan bodies collapse into two root walkers plus one entry point; the grok and explicit rules were byte-identical copies. Codex clients advertise the image_gen namespace on ordinary requests, so those bodies still take the full scan. Skipping the duplicate validation for callers that already validated the same bytes is a separate change. Benchmark (Apple M5 Pro, 1MiB body, 0 allocs): no image declarations 783us -> 48us codex namespace 560us -> 564us (gate cannot fire, unchanged) Fixes #8865 --- .../service/image_generation_intent.go | 158 ++++++++++-------- ...eration_intent_prefilter_benchmark_test.go | 92 ++++++++++ .../image_generation_intent_prefilter_test.go | 140 ++++++++++++++++ .../service/openai_codex_tool_names.go | 55 ++++-- 4 files changed, 359 insertions(+), 86 deletions(-) create mode 100644 backend/internal/service/image_generation_intent_prefilter_benchmark_test.go create mode 100644 backend/internal/service/image_generation_intent_prefilter_test.go diff --git a/backend/internal/service/image_generation_intent.go b/backend/internal/service/image_generation_intent.go index 927fd08765..47f59a3ec6 100644 --- a/backend/internal/service/image_generation_intent.go +++ b/backend/internal/service/image_generation_intent.go @@ -1,6 +1,7 @@ package service import ( + "bytes" "strings" "github.com/tidwall/gjson" @@ -36,21 +37,93 @@ func GroupAllowsImageGeneration(group *Group) bool { return group == nil || group.AllowImageGeneration } -// IsImageGenerationIntent classifies requests that can produce generated images. -func IsImageGenerationIntent(endpoint string, requestedModel string, body []byte) bool { - if IsImageGenerationEndpoint(endpoint) { - return true - } - if isOpenAIImageGenerationModel(requestedModel) { - return true - } - if len(body) == 0 || !gjson.ValidBytes(body) { +var ( + // imageGenLiteralBytes 覆盖扫描侧的全部非模型分支:tool type image_generation + // 自带该前缀,namespace / tool_choice / 函数引用的名字都是 image_gen。 + imageGenLiteralBytes = []byte("image_gen") + // imageModelFoldBytes 覆盖 model 分支:gpt-image-* 与 grok-imagine* 都含 imag, + // 模型名按 ToLower 比较,这里做 ASCII 折叠匹配。 + imageModelFoldBytes = []byte("imag") +) + +// openAIBodyMayDeclareImageGeneration 是生图意图扫描的字节级必要条件。 +// +// 扫描侧每个能让意图成立的取值都要求 body 里出现 image_gen 字面量,或 model 值本身 +// 是图片模型;因此不满足本判定的 body 一定不会命中扫描,可以整段跳过 +// gjson.ValidBytes 全量校验与根对象遍历(大 body 上这两步各占数百微秒)。 +// 只做字节级预检查,宁多算不漏判:含 \u 转义时交给完整扫描兜底,因为 JSON 字符串 +// 允许把 image_gen 的任意字节写成 unicode 转义。 +// +// 唯一的理论缺口:模型名比较走 strings.ToLower(Unicode 简易映射),把非 ASCII +// 字母折叠成 ASCII 的拼写(如 İ→i)不在字节折叠覆盖内;这类拼写不是真实模型 id, +// 且以 \u 形式出现时仍由上面的转义兜底放行。 +func openAIBodyMayDeclareImageGeneration(body []byte) bool { + if len(body) == 0 { return false } + if bytes.Contains(body, imageGenLiteralBytes) { + return true + } + if containsASCIIFold(body, imageModelFoldBytes) { + return true + } + return bytes.Contains(body, jsonUnicodeEscapeBytes) +} +// IsImageGenerationIntent classifies requests that can produce generated images. +func IsImageGenerationIntent(endpoint string, requestedModel string, body []byte) bool { + return openAIImageGenerationIntent(endpoint, requestedModel, body, false) +} + +// IsExplicitImageGenerationIntent 仅检测原生 image_generation 工具、图片模型和显式 tool_choice, +// 不检测被动的 image_gen namespace 声明。用于 capability 路由决策——被动 namespace 不应 +// 强制要求原生 Responses 能力,否则 Chat Completions-only 账号会被误过滤(#4476)。 +func IsExplicitImageGenerationIntent(endpoint string, requestedModel string, body []byte) bool { + return openAIImageGenerationIntent(endpoint, requestedModel, body, true) +} + +// IsImageGenerationIntentForPlatform applies platform-specific intent rules. +// +// Codex advertises the image_gen namespace on ordinary Responses requests so +// that it is available if the model needs it. Grok strips namespace and +// Responses Lite additional_tools declarations before forwarding, so those +// declarations alone must not turn every Codex request into an image request. +// Native image_generation tools, explicit image selection and image models +// remain image intent. Other platforms retain the original declaration rule. +func IsImageGenerationIntentForPlatform(endpoint string, requestedModel string, body []byte, platform string) bool { + if !strings.EqualFold(strings.TrimSpace(platform), PlatformGrok) { + return openAIImageGenerationIntent(endpoint, requestedModel, body, false) + } + // Grok removes namespace catalogs before forwarding. Native image_generation + // remains an explicit capability request. + return openAIImageGenerationIntent(endpoint, requestedModel, body, true) +} + +// openAIImageGenerationIntent 统一入口:先做 O(1) 端点/模型判断,再用字节级预检查 +// 挡住不可能命中扫描的 body,最后才校验并遍历根对象。 +func openAIImageGenerationIntent(endpoint string, requestedModel string, body []byte, explicit bool) bool { + if IsImageGenerationEndpoint(endpoint) || isOpenAIImageGenerationModel(requestedModel) { + return true + } + if !openAIBodyMayDeclareImageGeneration(body) { + return false + } + if !gjson.ValidBytes(body) { + return false + } + root := parseRawJSONView(body) + if explicit { + return explicitImageGenerationDeclarationsFromRoot(root) + } + return imageGenerationDeclarationsFromRoot(root) +} + +// imageGenerationDeclarationsFromRoot 走一遍根对象,保留「重复键取第一个」语义, +// 覆盖 model、tools、input.additional_tools 与 tool_choice。调用方负责 JSON 合法性。 +func imageGenerationDeclarationsFromRoot(root gjson.Result) bool { var modelSeen, toolsSeen, inputSeen, toolChoiceSeen bool imageIntent := false - parseRawJSONView(body).ForEach(func(key, value gjson.Result) bool { + root.ForEach(func(key, value gjson.Result) bool { // GetBytes returns the first duplicate key; retain that behavior while walking the root once. switch key.Str { case "model": @@ -79,19 +152,12 @@ func IsImageGenerationIntent(endpoint string, requestedModel string, body []byte return imageIntent } -// IsExplicitImageGenerationIntent 仅检测原生 image_generation 工具、图片模型和显式 tool_choice, -// 不检测被动的 image_gen namespace 声明。用于 capability 路由决策——被动 namespace 不应 -// 强制要求原生 Responses 能力,否则 Chat Completions-only 账号会被误过滤(#4476)。 -func IsExplicitImageGenerationIntent(endpoint string, requestedModel string, body []byte) bool { - if IsImageGenerationEndpoint(endpoint) || isOpenAIImageGenerationModel(requestedModel) { - return true - } - if len(body) == 0 || !gjson.ValidBytes(body) { - return false - } +// explicitImageGenerationDeclarationsFromRoot 只认原生 image_generation 工具、图片模型 +// 与显式 tool_choice,不认被动的 image_gen namespace 声明。 +func explicitImageGenerationDeclarationsFromRoot(root gjson.Result) bool { var modelSeen, toolsSeen, toolChoiceSeen bool imageIntent := false - parseRawJSONView(body).ForEach(func(key, value gjson.Result) bool { + root.ForEach(func(key, value gjson.Result) bool { switch key.Str { case "model": if !modelSeen { @@ -114,56 +180,6 @@ func IsExplicitImageGenerationIntent(endpoint string, requestedModel string, bod return imageIntent } -// IsImageGenerationIntentForPlatform applies platform-specific intent rules. -// -// Codex advertises the image_gen namespace on ordinary Responses requests so -// that it is available if the model needs it. Grok strips namespace and -// Responses Lite additional_tools declarations before forwarding, so those -// declarations alone must not turn every Codex request into an image request. -// Native image_generation tools, explicit image selection and image models -// remain image intent. Other platforms retain the original declaration rule. -func IsImageGenerationIntentForPlatform(endpoint string, requestedModel string, body []byte, platform string) bool { - if !strings.EqualFold(strings.TrimSpace(platform), PlatformGrok) { - return IsImageGenerationIntent(endpoint, requestedModel, body) - } - return isExplicitGrokImageGenerationIntent(endpoint, requestedModel, body) -} - -func isExplicitGrokImageGenerationIntent(endpoint string, requestedModel string, body []byte) bool { - if IsImageGenerationEndpoint(endpoint) || isOpenAIImageGenerationModel(requestedModel) { - return true - } - if len(body) == 0 || !gjson.ValidBytes(body) { - return false - } - - var modelSeen, toolsSeen, toolChoiceSeen bool - imageIntent := false - parseRawJSONView(body).ForEach(func(key, value gjson.Result) bool { - switch key.Str { - case "model": - if !modelSeen { - modelSeen = true - imageIntent = isOpenAIImageGenerationModel(strings.TrimSpace(value.String())) - } - case "tools": - if !toolsSeen { - toolsSeen = true - // Grok removes namespace catalogs before forwarding. Native - // image_generation remains an explicit capability request. - imageIntent = openAIJSONToolsContainNativeImageGeneration(value) - } - case "tool_choice": - if !toolChoiceSeen { - toolChoiceSeen = true - imageIntent = openAIJSONToolChoiceSelectsExplicitImageGeneration(value) - } - } - return !imageIntent && (!modelSeen || !toolsSeen || !toolChoiceSeen) - }) - return imageIntent -} - // IsImageGenerationIntentMap is the map-backed variant used after service-side request mutation. func IsImageGenerationIntentMap(endpoint string, requestedModel string, reqBody map[string]any) bool { if IsImageGenerationEndpoint(endpoint) { diff --git a/backend/internal/service/image_generation_intent_prefilter_benchmark_test.go b/backend/internal/service/image_generation_intent_prefilter_benchmark_test.go new file mode 100644 index 0000000000..8658bda1b0 --- /dev/null +++ b/backend/internal/service/image_generation_intent_prefilter_benchmark_test.go @@ -0,0 +1,92 @@ +package service + +import ( + "strings" + "testing" +) + +// buildImageIntentPrefilterBenchmarkBody 生成形状接近 Codex 客户端的大请求体: +// tools 在 input 之前、input 内含大量 items;withImageGen 控制是否带上 Codex +// 默认注入的 image_gen namespace 声明。 +func buildImageIntentPrefilterBenchmarkBody(targetBytes int, withImageGen bool) []byte { + var builder strings.Builder + builder.Grow(targetBytes + 512) + _, _ = builder.WriteString(`{"model":"gpt-5.5","instructions":"`) + _, _ = builder.WriteString(strings.Repeat("z", targetBytes/8)) + _, _ = builder.WriteString(`","tools":[{"type":"function","name":"shell","description":"`) + _, _ = builder.WriteString(strings.Repeat("y", targetBytes/16)) + _, _ = builder.WriteString(`"}`) + if withImageGen { + _, _ = builder.WriteString(`,{"type":"namespace","name":"image_gen"}`) + } + _, _ = builder.WriteString(`],"input":[`) + item := `{"type":"message","role":"user","content":[{"type":"input_text","text":"` + strings.Repeat("x", 4000) + `"}]}` + for i := 0; builder.Len() < targetBytes; i++ { + if i > 0 { + _, _ = builder.WriteString(`,`) + } + _, _ = builder.WriteString(item) + } + _, _ = builder.WriteString(`]}`) + return []byte(builder.String()) +} + +// 字节级预检查把「没有生图声明」的请求整段跳过校验与根对象遍历; +// scan_without_prefilter 是修复前的等价路径,两者同一次运行即可对比。 +func BenchmarkImageGenerationIntentPrefilter(b *testing.B) { + const targetBytes = 1 << 20 + plain := buildImageIntentPrefilterBenchmarkBody(targetBytes, false) + codex := buildImageIntentPrefilterBenchmarkBody(targetBytes, true) + + b.Run("prefilter_only/plain", func(b *testing.B) { + b.SetBytes(int64(len(plain))) + b.ReportAllocs() + for range b.N { + if openAIBodyMayDeclareImageGeneration(plain) { + b.Fatal("plain body must not declare image generation") + } + } + }) + + b.Run("scan_without_prefilter/plain", func(b *testing.B) { + b.SetBytes(int64(len(plain))) + b.ReportAllocs() + for range b.N { + if referenceImageGenerationIntent(plain) { + b.Fatal("plain body must not have image intent") + } + } + }) + + b.Run("intent/plain", func(b *testing.B) { + b.SetBytes(int64(len(plain))) + b.ReportAllocs() + for range b.N { + if IsImageGenerationIntent(openAIResponsesEndpoint, "gpt-5.5", plain) { + b.Fatal("plain body must not have image intent") + } + } + }) + + b.Run("scan_without_prefilter/codex", func(b *testing.B) { + b.SetBytes(int64(len(codex))) + b.ReportAllocs() + for range b.N { + if !referenceImageGenerationIntent(codex) { + b.Fatal("codex namespace body must have image intent") + } + } + }) + + // Codex 在普通请求里就带 image_gen namespace(见 IsImageGenerationIntentForPlatform + // 注释),预检查必然放行,这类流量仍需完整扫描,本项用于跟踪它的成本。 + b.Run("intent/codex_namespace", func(b *testing.B) { + b.SetBytes(int64(len(codex))) + b.ReportAllocs() + for range b.N { + if !IsImageGenerationIntent(openAIResponsesEndpoint, "gpt-5.5", codex) { + b.Fatal("codex namespace body must have image intent") + } + } + }) +} diff --git a/backend/internal/service/image_generation_intent_prefilter_test.go b/backend/internal/service/image_generation_intent_prefilter_test.go new file mode 100644 index 0000000000..beb12d259f --- /dev/null +++ b/backend/internal/service/image_generation_intent_prefilter_test.go @@ -0,0 +1,140 @@ +package service + +import ( + "strings" + "testing" + + "github.com/stretchr/testify/require" + "github.com/tidwall/gjson" +) + +// 生图意图的字节级预检查只能少算、不能漏判:任何能让扫描成立的 body, +// openAIBodyMayDeclareImageGeneration 都必须放行。下面用扫描函数本身作为基准, +// 逐个语料核对「带预检查」与「不带预检查」的结果完全一致。 +func TestImageGenerationIntentPrefilterPreservesScanOutcomes(t *testing.T) { + escape := string(rune(92)) + "u005f" // _ + bodies := map[string]string{ + "no image declarations": `{"model":"gpt-5.5","input":"hello"}`, + "empty body": ``, + "invalid json": `{"tools":[{"type":"image_generation"}]`, + "native tool": `{"model":"gpt-5.5","tools":[{"type":"image_generation"}]}`, + "namespace tool": `{"model":"gpt-5.5","tools":[{"type":"namespace","name":"image_gen"}]}`, + "tool choice string": `{"model":"gpt-5.5","tool_choice":"image_generation"}`, + "tool choice namespace": `{"model":"gpt-5.5","tool_choice":{"type":"namespace","name":"image_gen"}}`, + "tool choice function": `{"model":"gpt-5.5","tool_choice":{"type":"function","function":{"name":"image_gen.imagegen"}}}`, + "input additional": `{"input":[{"type":"additional_tools","tools":[{"type":"image_generation"}]}]}`, + "escaped key": `{"tool_` + string(rune(92)) + `u0063hoice":{"type":"image_generation"}}`, + "escaped tool type": `{"tools":[{"type":"image` + escape + `generation"}]}`, + "escaped namespace": `{"tools":[{"type":"namespace","name":"image` + escape + `gen"}]}`, + "uppercase model": `{"model":"GPT-Image-2"}`, + "grok model": `{"model":"grok-imagine"}`, + "uppercase grok model": `{"model":"Grok-Imagine"}`, + "duplicate model": `{"model":"gpt-5.5","model":"gpt-image-2"}`, + "model only": `{"model":"gpt-image-2"}`, + "prose mentions image": `{"model":"gpt-5.5","input":"please imagine a cat"}`, + "namespace value": `{"tools":[{"type":"namespace","name":"image_gen","tools":[]}]}`, + } + for name, raw := range bodies { + body := []byte(raw) + t.Run(name, func(t *testing.T) { + // endpoint 与 requestedModel 都取非图片值,预检查才会真正生效。 + require.Equal(t, + referenceImageGenerationIntent(body), + IsImageGenerationIntent("/v1/responses", "gpt-5.5", body), + "declaration rule must not change with the prefilter") + require.Equal(t, + referenceExplicitImageGenerationIntent(body), + IsExplicitImageGenerationIntent("/v1/responses", "gpt-5.5", body), + "explicit rule must not change with the prefilter") + require.Equal(t, + referenceExplicitImageGenerationIntent(body), + IsImageGenerationIntentForPlatform("/v1/responses", "gpt-5.5", body, PlatformGrok), + "grok rule must not change with the prefilter") + require.Equal(t, + referenceImageGenerationIntent(body), + IsImageGenerationIntentForPlatform("/v1/responses", "gpt-5.5", body, PlatformOpenAI), + "platform rule must not change with the prefilter") + }) + } +} + +// 下面两个参考实现就是修复前的完整扫描:校验 + 根对象遍历,不带字节级预检查。 +func referenceImageGenerationIntent(body []byte) bool { + if len(body) == 0 || !gjson.ValidBytes(body) { + return false + } + return imageGenerationDeclarationsFromRoot(parseRawJSONView(body)) +} + +func referenceExplicitImageGenerationIntent(body []byte) bool { + if len(body) == 0 || !gjson.ValidBytes(body) { + return false + } + return explicitImageGenerationDeclarationsFromRoot(parseRawJSONView(body)) +} + +// 预检查的健全性:扫描能成立的 body 一定被放行。语料之外由 fuzz 继续探索。 +func TestImageGenerationIntentPrefilterIsNecessary(t *testing.T) { + seeds := []string{ + `{"model":"gpt-image-2"}`, + `{"tools":[{"type":"image_generation"}]}`, + `{"tools":[{"type":"namespace","name":"image_gen"}]}`, + `{"tool_choice":{"type":"namespace","name":"image_gen"}}`, + `{"input":[{"type":"additional_tools","tools":[{"type":"image_generation"}]}]}`, + `{"model":"grok-imagine"}`, + `{"model":"gpt-5.5","input":"nothing here"}`, + } + for _, seed := range seeds { + body := []byte(seed) + if referenceImageGenerationIntent(body) { + require.True(t, openAIBodyMayDeclareImageGeneration(body), "prefilter must not hide a detected body: %s", seed) + } + } +} + +func FuzzImageGenerationIntentPrefilter(f *testing.F) { + f.Add([]byte(`{"model":"gpt-image-2"}`)) + f.Add([]byte(`{"tools":[{"type":"namespace","name":"image_gen"}]}`)) + f.Add([]byte(`{"model":"gpt-5.5"}`)) + f.Add([]byte(`{"tools":[{"type":"image` + string(rune(92)) + `u005fgeneration"}]}`)) + f.Fuzz(func(t *testing.T, body []byte) { + if referenceImageGenerationIntent(body) && !openAIBodyMayDeclareImageGeneration(body) { + t.Fatalf("prefilter hid a detected body: %q", body) + } + if referenceExplicitImageGenerationIntent(body) && !openAIBodyMayDeclareImageGeneration(body) { + t.Fatalf("prefilter hid a detected body: %q", body) + } + }) +} + +func TestContainsASCIIFold(t *testing.T) { + cases := []struct { + name string + haystack string + needle string + want bool + }{ + {"exact", "gpt-image-2", "imag", true}, + {"upper", "GPT-IMAGE-2", "imag", true}, + {"mixed", "Gpt-ImAgE-2", "imag", true}, + {"grok", "grok-imagine", "imag", true}, + {"absent", "gpt-5.5", "imag", false}, + {"needle longer", "img", "imag", false}, + {"empty haystack", "", "imag", false}, + {"partial at end", "xxIma", "imag", false}, + {"second candidate matches", "iaaiimag", "imag", true}, + } + for _, tt := range cases { + t.Run(tt.name, func(t *testing.T) { + require.Equal(t, tt.want, containsASCIIFold([]byte(tt.haystack), []byte(tt.needle))) + }) + } + require.False(t, containsASCIIFold(nil, []byte("imag"))) + + // 与 strings.Contains(strings.ToLower(...)) 对拍一段混合大小写文本。 + haystack := []byte(`{"model":"Gpt-Image-2","input":"IMAGINE this, Image and IMAGE"}`) + require.True(t, containsASCIIFold(haystack, []byte("imag"))) + require.Equal(t, + strings.Contains(strings.ToLower(string(haystack)), "imag"), + containsASCIIFold(haystack, []byte("imag"))) +} diff --git a/backend/internal/service/openai_codex_tool_names.go b/backend/internal/service/openai_codex_tool_names.go index 849a45e417..ffc4b50f56 100644 --- a/backend/internal/service/openai_codex_tool_names.go +++ b/backend/internal/service/openai_codex_tool_names.go @@ -1,6 +1,7 @@ package service import ( + "bytes" "encoding/json" "fmt" "strings" @@ -165,28 +166,52 @@ func aliasOpenAIOAuthReservedToolNamesBody(body []byte) ([]byte, map[string]stri return normalized, reverse, true, nil } +// containsASCIIFold reports whether haystack contains needle under ASCII case +// folding. +// +// 逐字节比较在 1MiB 级请求体上等于整段扫描;只按首字节 memchr 又会为每个候选 +// 重新探测「大小写两种首字节」各自的整段尾部,候选一多就退化成平方级。这里给 +// 大小写两条候选游标,每条只在自身未消费的区间上前进,整体保持线性, +// 结果与逐字节折叠比较完全一致。 func containsASCIIFold(haystack, needle []byte) bool { if len(needle) == 0 || len(haystack) < len(needle) { return false } - for i := 0; i <= len(haystack)-len(needle); i++ { - matched := true - for j := range needle { - a, b := haystack[i+j], needle[j] - if a >= 'A' && a <= 'Z' { - a += 'a' - 'A' - } - if b >= 'A' && b <= 'Z' { - b += 'a' - 'A' - } - if a != b { - matched = false - break - } + first := needle[0] + upper := first + if 'a' <= first && first <= 'z' { + upper = first - ('a' - 'A') + } + last := len(haystack) - len(needle) + + lowerPos := bytes.IndexByte(haystack, first) + upperPos := -1 + if upper != first { + upperPos = bytes.IndexByte(haystack, upper) + } + for lowerPos >= 0 || upperPos >= 0 { + pos := lowerPos + if pos < 0 || (upperPos >= 0 && upperPos < pos) { + pos = upperPos } - if matched { + if pos > last { + return false + } + if bytes.EqualFold(haystack[pos:pos+len(needle)], needle) { return true } + // 只推进刚刚消费掉的那条游标。 + if pos == lowerPos { + lowerPos = -1 + if next := bytes.IndexByte(haystack[pos+1:], first); next >= 0 { + lowerPos = pos + 1 + next + } + continue + } + upperPos = -1 + if next := bytes.IndexByte(haystack[pos+1:], upper); next >= 0 { + upperPos = pos + 1 + next + } } return false } From 487d42c9645d3e259e42a99a29edc9d1a9311e4c Mon Sep 17 00:00:00 2001 From: lishuangqiang <142634204+lishuangqiang@users.noreply.github.com> Date: Mon, 16 Nov 2026 23:02:17 +0800 Subject: [PATCH 29/85] perf(openai): reuse an already-validated body when classifying image intent The handler validates the request body at gateway_handler_responses.go:66 and ParseGatewayRequest validates it again at gateway_request.go:240. For bodies that do carry image declarations the byte-level precheck cannot fire, so the intent classifier still ran gjson.ValidBytes over the same bytes a third time. That is the dominant remaining cost for Codex traffic, because Codex advertises the image_gen namespace on ordinary responses requests. Add IsImageGenerationIntentForPlatformValidated for callers that have already established the body is valid JSON, and use it at the two call sites where that holds: - gateway_handler_responses.go: the body is validated at the top of the handler, and afterwards it is only rewritten through sjson (applyOpenAIReasoningEffortPolicyForRequest), which preserves validity. - openai_ws_forwarder_ingress.go: the payload is validated in parseClientPayload, and every later rewrite is sjson, a decode/re-marshal round trip, or a no-op. Both call sites carry the reasoning in a comment. The validating entry points are unchanged, so invalid-JSON semantics stay exactly as they were for every other caller. Benchmark (Apple M5 Pro, 1MiB Codex body, 0 allocs): intent classifier: 562us -> 50us Refs #8865 --- .../handler/gateway_handler_responses.go | 5 +++- .../service/image_generation_intent.go | 26 ++++++++++++++----- ...eration_intent_prefilter_benchmark_test.go | 14 ++++++++-- .../image_generation_intent_prefilter_test.go | 7 +++++ .../service/openai_ws_forwarder_ingress.go | 4 ++- 5 files changed, 45 insertions(+), 11 deletions(-) diff --git a/backend/internal/handler/gateway_handler_responses.go b/backend/internal/handler/gateway_handler_responses.go index 165b57867d..9cabe3df67 100644 --- a/backend/internal/handler/gateway_handler_responses.go +++ b/backend/internal/handler/gateway_handler_responses.go @@ -106,7 +106,10 @@ func (h *GatewayHandler) Responses(c *gin.Context) { // 里的任何工具声明(含 Codex 被动 image_gen namespace)而关闭。生图意图 // 仅用于能力路由与图片计费;独立图片/视频端点才在利润门范围之外。 requestCtx, pricingAt := service.WithGatewayTokenRequestPricing(requestCtx) - if service.IsImageGenerationIntentForPlatform("/v1/responses", reqModel, body, openAICompatibleRequestPlatform(c.Request.Context(), apiKey)) { + // body 已在本函数开头用 gjson.ValidBytes 校验过,之后只经过 sjson 改写 + // (applyOpenAIReasoningEffortPolicyForRequest),合法性保持,因此走跳过校验的 + // 变体,避免对同一份字节再全量校验一次。 + if service.IsImageGenerationIntentForPlatformValidated("/v1/responses", reqModel, body, openAICompatibleRequestPlatform(c.Request.Context(), apiKey)) { requestCtx = service.WithOpenAIImageGenerationIntent(requestCtx) } c.Request = c.Request.WithContext(requestCtx) diff --git a/backend/internal/service/image_generation_intent.go b/backend/internal/service/image_generation_intent.go index 47f59a3ec6..630ed3b229 100644 --- a/backend/internal/service/image_generation_intent.go +++ b/backend/internal/service/image_generation_intent.go @@ -72,14 +72,14 @@ func openAIBodyMayDeclareImageGeneration(body []byte) bool { // IsImageGenerationIntent classifies requests that can produce generated images. func IsImageGenerationIntent(endpoint string, requestedModel string, body []byte) bool { - return openAIImageGenerationIntent(endpoint, requestedModel, body, false) + return openAIImageGenerationIntent(endpoint, requestedModel, body, false, true) } // IsExplicitImageGenerationIntent 仅检测原生 image_generation 工具、图片模型和显式 tool_choice, // 不检测被动的 image_gen namespace 声明。用于 capability 路由决策——被动 namespace 不应 // 强制要求原生 Responses 能力,否则 Chat Completions-only 账号会被误过滤(#4476)。 func IsExplicitImageGenerationIntent(endpoint string, requestedModel string, body []byte) bool { - return openAIImageGenerationIntent(endpoint, requestedModel, body, true) + return openAIImageGenerationIntent(endpoint, requestedModel, body, true, true) } // IsImageGenerationIntentForPlatform applies platform-specific intent rules. @@ -91,24 +91,36 @@ func IsExplicitImageGenerationIntent(endpoint string, requestedModel string, bod // Native image_generation tools, explicit image selection and image models // remain image intent. Other platforms retain the original declaration rule. func IsImageGenerationIntentForPlatform(endpoint string, requestedModel string, body []byte, platform string) bool { + return openAIImageGenerationIntentForPlatform(endpoint, requestedModel, body, platform, true) +} + +// IsImageGenerationIntentForPlatformValidated 与 IsImageGenerationIntentForPlatform 判定相同, +// 但要求调用方已经确认 body 是合法 JSON(例如 handler 已对同一份字节做过 gjson.ValidBytes)。 +// 它跳过这次全量校验——大 body 上这一项占判定耗时的六成以上。非法 JSON 的语义与未校验 +// 版本不同,只允许在校验过同一份字节、且后续改写只经由 sjson / json.Marshal 的调用点使用。 +func IsImageGenerationIntentForPlatformValidated(endpoint string, requestedModel string, body []byte, platform string) bool { + return openAIImageGenerationIntentForPlatform(endpoint, requestedModel, body, platform, false) +} + +func openAIImageGenerationIntentForPlatform(endpoint string, requestedModel string, body []byte, platform string, validate bool) bool { if !strings.EqualFold(strings.TrimSpace(platform), PlatformGrok) { - return openAIImageGenerationIntent(endpoint, requestedModel, body, false) + return openAIImageGenerationIntent(endpoint, requestedModel, body, false, validate) } // Grok removes namespace catalogs before forwarding. Native image_generation // remains an explicit capability request. - return openAIImageGenerationIntent(endpoint, requestedModel, body, true) + return openAIImageGenerationIntent(endpoint, requestedModel, body, true, validate) } // openAIImageGenerationIntent 统一入口:先做 O(1) 端点/模型判断,再用字节级预检查 -// 挡住不可能命中扫描的 body,最后才校验并遍历根对象。 -func openAIImageGenerationIntent(endpoint string, requestedModel string, body []byte, explicit bool) bool { +// 挡住不可能命中扫描的 body,最后才按需校验并遍历根对象。 +func openAIImageGenerationIntent(endpoint string, requestedModel string, body []byte, explicit bool, validate bool) bool { if IsImageGenerationEndpoint(endpoint) || isOpenAIImageGenerationModel(requestedModel) { return true } if !openAIBodyMayDeclareImageGeneration(body) { return false } - if !gjson.ValidBytes(body) { + if validate && !gjson.ValidBytes(body) { return false } root := parseRawJSONView(body) diff --git a/backend/internal/service/image_generation_intent_prefilter_benchmark_test.go b/backend/internal/service/image_generation_intent_prefilter_benchmark_test.go index 8658bda1b0..3136faab97 100644 --- a/backend/internal/service/image_generation_intent_prefilter_benchmark_test.go +++ b/backend/internal/service/image_generation_intent_prefilter_benchmark_test.go @@ -78,8 +78,8 @@ func BenchmarkImageGenerationIntentPrefilter(b *testing.B) { } }) - // Codex 在普通请求里就带 image_gen namespace(见 IsImageGenerationIntentForPlatform - // 注释),预检查必然放行,这类流量仍需完整扫描,本项用于跟踪它的成本。 + // Codex 在普通请求里就带 image_gen namespace,预检查必然放行, + // 这类流量只能靠「已校验」变体省掉重复的全量校验。 b.Run("intent/codex_namespace", func(b *testing.B) { b.SetBytes(int64(len(codex))) b.ReportAllocs() @@ -89,4 +89,14 @@ func BenchmarkImageGenerationIntentPrefilter(b *testing.B) { } } }) + + b.Run("validated_intent/codex_namespace", func(b *testing.B) { + b.SetBytes(int64(len(codex))) + b.ReportAllocs() + for range b.N { + if !IsImageGenerationIntentForPlatformValidated(openAIResponsesEndpoint, "gpt-5.5", codex, PlatformOpenAI) { + b.Fatal("codex namespace body must have image intent") + } + } + }) } diff --git a/backend/internal/service/image_generation_intent_prefilter_test.go b/backend/internal/service/image_generation_intent_prefilter_test.go index beb12d259f..0b9b8413c0 100644 --- a/backend/internal/service/image_generation_intent_prefilter_test.go +++ b/backend/internal/service/image_generation_intent_prefilter_test.go @@ -104,6 +104,13 @@ func FuzzImageGenerationIntentPrefilter(f *testing.F) { if referenceExplicitImageGenerationIntent(body) && !openAIBodyMayDeclareImageGeneration(body) { t.Fatalf("prefilter hid a detected body: %q", body) } + // 已校验分支不得与校验分支结论不同:同一份合法 JSON 上两者必须一致。 + if gjson.ValidBytes(body) { + require.Equal(t, + referenceImageGenerationIntent(body), + IsImageGenerationIntentForPlatformValidated(openAIResponsesEndpoint, "gpt-5.5", body, PlatformOpenAI), + "validated variant must agree with the reference scan: %q", body) + } }) } diff --git a/backend/internal/service/openai_ws_forwarder_ingress.go b/backend/internal/service/openai_ws_forwarder_ingress.go index c3994e3540..0366a2a929 100644 --- a/backend/internal/service/openai_ws_forwarder_ingress.go +++ b/backend/internal/service/openai_ws_forwarder_ingress.go @@ -411,7 +411,9 @@ func (s *OpenAIGatewayService) ProxyResponsesWebSocketFromClient( normalized = stripped logOpenAIWSModeInfo("ingress_ws_codex_spark_image_tool_stripped account_id=%d", account.ID) } - imageIntent := IsImageGenerationIntentForPlatform(openAIResponsesEndpoint, originalModel, normalized, account.Platform) + // normalized 由 parseClientPayload 中已通过 gjson.ValidBytes 校验的字节派生, + // 后续改写只走 sjson 或 decode→json.Marshal,合法性保持,因此跳过重复校验。 + imageIntent := IsImageGenerationIntentForPlatformValidated(openAIResponsesEndpoint, originalModel, normalized, account.Platform) if imageIntent && !imageGenerationAllowed { return openAIWSClientPayload{}, NewOpenAIWSClientCloseError(coderws.StatusPolicyViolation, ImageGenerationPermissionMessage(), nil) } From 62765bb4e761ec89f91aa7d409d4103f7075154e Mon Sep 17 00:00:00 2001 From: lishuangqiang <142634204+lishuangqiang@users.noreply.github.com> Date: Mon, 16 Nov 2026 23:03:38 +0800 Subject: [PATCH 30/85] perf(openai): apply the image-intent precheck to the declaration scanners openAIRequestBodyHasImageGenerationDeclaration and openAIRequestBodyImageGenerationToolNeedsNormalization each validate the whole body up front before looking at tools/input/tool_choice. Both branches only match image_gen literals, so the same byte-level necessary condition applies and lets them skip the validation for bodies that cannot match. Refs #8865 --- backend/internal/service/image_generation_intent.go | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/backend/internal/service/image_generation_intent.go b/backend/internal/service/image_generation_intent.go index 630ed3b229..9593213da3 100644 --- a/backend/internal/service/image_generation_intent.go +++ b/backend/internal/service/image_generation_intent.go @@ -300,7 +300,7 @@ func openAIJSONInputContainsImageGenTool(input gjson.Result) bool { } func openAIRequestBodyHasImageGenerationDeclaration(body []byte) bool { - if len(body) == 0 || !gjson.ValidBytes(body) { + if len(body) == 0 || !openAIBodyMayDeclareImageGeneration(body) || !gjson.ValidBytes(body) { return false } return openAIJSONToolsContainImageGeneration(gjson.GetBytes(body, "tools")) || @@ -309,7 +309,7 @@ func openAIRequestBodyHasImageGenerationDeclaration(body []byte) bool { } func openAIRequestBodyImageGenerationToolNeedsNormalization(body []byte) bool { - if len(body) == 0 || !gjson.ValidBytes(body) { + if len(body) == 0 || !openAIBodyMayDeclareImageGeneration(body) || !gjson.ValidBytes(body) { return false } tools := gjson.GetBytes(body, "tools") From 0c571e9e271ebc295e505424700e9213d2401388 Mon Sep 17 00:00:00 2001 From: lishuangqiang <142634204+lishuangqiang@users.noreply.github.com> Date: Mon, 16 Nov 2026 23:23:13 +0800 Subject: [PATCH 31/85] perf(service): parse the gateway request body with a single root walk parseGatewayRequestCurrentBody looked up eight fields with separate gjson.Get calls. A lookup for a key that is not present still has to scan the whole body to prove absence, and for a typical Responses request six of those keys are absent (metadata.user_id, thinking.type, output_config.effort, max_tokens, system, messages). On a 1MiB body that is six full passes at about 142us each, while a single root walk over the same body costs about 220us. Collect every field the parser needs in one ForEach over the root and derive the raw ranges from the same results. Nested paths keep gjson semantics: each path segment resolves to the first duplicate key that actually yields the child, not simply the first key with that name. {"metadata":"x","metadata":{"user_id":"u"}} resolves to "u", and the walk reproduces that by retrying while the collected child does not exist. Duplicate scalar keys keep first-occurrence-wins. The Anthropic [1m] model normalization rewrites the body mid-parse, so the walk is repeated after the rewrite. That path only runs when the client leaks the suffix. Benchmark (Apple M5 Pro, 3 allocs unchanged): responses 128KiB: 208us -> 96us responses 1MiB: 1.59ms -> 735us anthropic 1MiB: 1.43ms -> 723us Equivalence tests keep a verbatim copy of the previous implementation as legacy* and compare every field (model, stream, metadata user id, thinking, effort, speed, max tokens, system/messages/input ranges, protocol, body after parsing) across 4 protocols and 44 bodies, plus 3000 deterministic random combinations. A fuzz target does the same for arbitrary input. --- backend/internal/service/gateway_request.go | 151 +++++++-- .../gateway_request_scan_benchmark_test.go | 81 +++++ .../gateway_request_scan_equivalence_test.go | 293 ++++++++++++++++++ 3 files changed, 492 insertions(+), 33 deletions(-) create mode 100644 backend/internal/service/gateway_request_scan_benchmark_test.go create mode 100644 backend/internal/service/gateway_request_scan_equivalence_test.go diff --git a/backend/internal/service/gateway_request.go b/backend/internal/service/gateway_request.go index 2abbe5e1a8..1ec3209250 100644 --- a/backend/internal/service/gateway_request.go +++ b/backend/internal/service/gateway_request.go @@ -189,29 +189,115 @@ func clearGatewayRequestRanges(parsed *ParsedRequest) { parsed.inputRange = missingJSONRange() } -func setGatewayRequestRanges(parsed *ParsedRequest, protocol string, jsonStr string) { +// gatewayRequestRootFields 保存一次根对象遍历取到的原始值视图。全部零拷贝, +// 只在本次解析内使用,body 被改写后必须重新扫描。 +// +// 嵌套字段按 gjson.Get 的语义取值:路径的每一段都取「第一个能解析出子键的同名键」, +// 而不是简单取第一个同名键。例如 {"metadata":"x","metadata":{"user_id":"u"}} 在 +// gjson.Get("metadata.user_id") 下取到 "u",这里以 Exists() 作为「还没取到」的判据 +// 复现该重试行为。 +type gatewayRequestRootFields struct { + model gjson.Result + stream gjson.Result + maxTokens gjson.Result + metadataUID gjson.Result + thinkingType gjson.Result + outputEffort gjson.Result + speed gjson.Result + system gjson.Result + messages gjson.Result + input gjson.Result + contents gjson.Result + geminiSysParts gjson.Result +} + +// scanGatewayRequestRoot 用一次根对象遍历取出解析需要的全部字段。 +// +// 逐字段 gjson.Get 的问题在于「键不存在」也要把整份 body 扫一遍才能返回不存在: +// 1 MiB body 上每个缺失键约 142µs,而一次完整遍历约 220µs——解析一次要做 7 次查找, +// 其中 6 个键(metadata.user_id / thinking.type / output_config.effort / max_tokens / +// system / messages)在典型 Responses 请求里都不存在。 +func scanGatewayRequestRoot(body []byte) gatewayRequestRootFields { + var f gatewayRequestRootFields + parseRawJSONView(body).ForEach(func(key, value gjson.Result) bool { + switch key.Str { + case "model": + if !f.model.Exists() { + f.model = value + } + case "stream": + if !f.stream.Exists() { + f.stream = value + } + case "max_tokens": + if !f.maxTokens.Exists() { + f.maxTokens = value + } + case "metadata": + if !f.metadataUID.Exists() { + f.metadataUID = value.Get("user_id") + } + case "thinking": + if !f.thinkingType.Exists() { + f.thinkingType = value.Get("type") + } + case "output_config": + if !f.outputEffort.Exists() { + f.outputEffort = value.Get("effort") + } + case "speed": + if !f.speed.Exists() { + f.speed = value + } + case "system": + if !f.system.Exists() { + f.system = value + } + case "messages": + if !f.messages.Exists() { + f.messages = value + } + case "input": + if !f.input.Exists() { + f.input = value + } + case "contents": + if !f.contents.Exists() { + f.contents = value + } + case "systemInstruction": + if !f.geminiSysParts.Exists() { + f.geminiSysParts = value.Get("parts") + } + } + return true + }) + return f +} + +func setGatewayRequestRangesFromFields(parsed *ParsedRequest, protocol string, fields gatewayRequestRootFields) { if parsed == nil { return } switch protocol { case domain.PlatformGemini: - if sysParts := gjson.Get(jsonStr, "systemInstruction.parts"); sysParts.Exists() && sysParts.IsArray() { - parsed.systemRange = rangeFromResult(sysParts) + if fields.geminiSysParts.Exists() && fields.geminiSysParts.IsArray() { + parsed.systemRange = rangeFromResult(fields.geminiSysParts) } - if contents := gjson.Get(jsonStr, "contents"); contents.Exists() && contents.IsArray() { - parsed.messagesRange = rangeFromResult(contents) + if fields.contents.Exists() && fields.contents.IsArray() { + parsed.messagesRange = rangeFromResult(fields.contents) } default: - if sys := gjson.Get(jsonStr, "system"); sys.Exists() { + if fields.system.Exists() { parsed.HasSystem = true - parsed.systemRange = rangeFromResult(sys) + parsed.systemRange = rangeFromResult(fields.system) } - if msgs := gjson.Get(jsonStr, "messages"); msgs.Exists() && msgs.IsArray() { - parsed.messagesRange = rangeFromResult(msgs) + if fields.messages.Exists() && fields.messages.IsArray() { + parsed.messagesRange = rangeFromResult(fields.messages) } if protocol == "responses" { - if input := gjson.Get(jsonStr, "input"); input.Exists() { - parsed.inputRange = rangeFromResult(input) + if fields.input.Exists() { + parsed.inputRange = rangeFromResult(fields.input) } } } @@ -229,8 +315,8 @@ func normalizeClaudeCodeLongContextModel(model string) string { return model } -// parseGatewayRequestCurrentBody 只做标量和 raw range 轻量解析,不恢复 system/messages 对象图。 -func parseGatewayRequestCurrentBody(parsed *ParsedRequest, protocol string) error { +// parseGatewayRequestBody 只做标量和 raw range 轻量解析,不恢复 system/messages 对象图。 +func parseGatewayRequestBody(parsed *ParsedRequest, protocol string) error { if parsed == nil || parsed.Body == nil { return fmt.Errorf("empty request body") } @@ -244,16 +330,16 @@ func parseGatewayRequestCurrentBody(parsed *ParsedRequest, protocol string) erro // Zero-copy JSON reads stay local to parsing. Persisted scalar strings must // own their storage: an unescaped gjson string otherwise retains the complete // request buffer when copied into queued billing work. Raw ranges stay zero-copy. - jsonStr := *(*string)(unsafe.Pointer(&bodyBytes)) clearGatewayRequestDerivedState(parsed) parsed.protocol = protocol - modelResult := gjson.Get(jsonStr, "model") - if modelResult.Exists() { - if modelResult.Type != gjson.String { + fields := scanGatewayRequestRoot(bodyBytes) + + if fields.model.Exists() { + if fields.model.Type != gjson.String { return fmt.Errorf("invalid model field type") } - parsed.Model = strings.Clone(modelResult.String()) + parsed.Model = strings.Clone(fields.model.String()) if protocol == domain.PlatformAnthropic { normalizedModel := normalizeClaudeCodeLongContextModel(parsed.Model) if normalizedModel != parsed.Model { @@ -263,47 +349,46 @@ func parseGatewayRequestCurrentBody(parsed *ParsedRequest, protocol string) erro } parsed.Body.Replace(normalizedBody) bodyBytes = normalizedBody - jsonStr = *(*string)(unsafe.Pointer(&bodyBytes)) + // 改写后旧的值视图指向已失效的字节,重新遍历一次(仅 [1m] 规范化这条罕见路径)。 + fields = scanGatewayRequestRoot(bodyBytes) parsed.Model = normalizedModel } } } - streamResult := gjson.Get(jsonStr, "stream") - if streamResult.Exists() { - if streamResult.Type != gjson.True && streamResult.Type != gjson.False { + if fields.stream.Exists() { + if fields.stream.Type != gjson.True && fields.stream.Type != gjson.False { return fmt.Errorf("invalid stream field type") } - parsed.Stream = streamResult.Bool() + parsed.Stream = fields.stream.Bool() } - parsed.MetadataUserID = strings.Clone(gjson.Get(jsonStr, "metadata.user_id").String()) + parsed.MetadataUserID = strings.Clone(fields.metadataUID.String()) - thinkingType := gjson.Get(jsonStr, "thinking.type").String() + thinkingType := fields.thinkingType.String() parsed.ThinkingEnabled = thinkingType == "enabled" || thinkingType == "adaptive" || thinkingType == "between_tools" || (protocol == domain.PlatformAnthropic && isClaude55SignedThinkingModel(parsed.Model)) - parsed.OutputEffort = strings.Clone(strings.TrimSpace(gjson.Get(jsonStr, "output_config.effort").String())) + parsed.OutputEffort = strings.Clone(strings.TrimSpace(fields.outputEffort.String())) if protocol == domain.PlatformAnthropic { - parsed.Speed = strings.Clone(strings.ToLower(strings.TrimSpace(gjson.Get(jsonStr, "speed").String()))) + parsed.Speed = strings.Clone(strings.ToLower(strings.TrimSpace(fields.speed.String()))) } - maxTokensResult := gjson.Get(jsonStr, "max_tokens") - if maxTokensResult.Exists() && maxTokensResult.Type == gjson.Number { - f := maxTokensResult.Float() + if fields.maxTokens.Exists() && fields.maxTokens.Type == gjson.Number { + f := fields.maxTokens.Float() if !math.IsNaN(f) && !math.IsInf(f, 0) && f == math.Trunc(f) && f <= float64(math.MaxInt) && f >= float64(math.MinInt) { parsed.MaxTokens = int(f) } } - setGatewayRequestRanges(parsed, protocol, jsonStr) + setGatewayRequestRangesFromFields(parsed, protocol, fields) parsed.saveBodyState() return nil } func refreshGatewayRequestRanges(parsed *ParsedRequest, protocol string) error { - return parseGatewayRequestCurrentBody(parsed, protocol) + return parseGatewayRequestBody(parsed, protocol) } // DescribeInvalidJSON returns a diagnostic error for a request body that @@ -411,7 +496,7 @@ func normalizeSessionUserAgentFallback(raw string) string { // 不同协议使用不同的 system/messages 字段名。 func ParseGatewayRequest(body *RequestBodyRef, protocol string) (*ParsedRequest, error) { parsed := &ParsedRequest{Body: body} - if err := parseGatewayRequestCurrentBody(parsed, protocol); err != nil { + if err := parseGatewayRequestBody(parsed, protocol); err != nil { return nil, err } return parsed, nil diff --git a/backend/internal/service/gateway_request_scan_benchmark_test.go b/backend/internal/service/gateway_request_scan_benchmark_test.go new file mode 100644 index 0000000000..0b09668d70 --- /dev/null +++ b/backend/internal/service/gateway_request_scan_benchmark_test.go @@ -0,0 +1,81 @@ +package service + +import ( + "strings" + "testing" + + "github.com/Wei-Shaw/sub2api/internal/domain" +) + +// buildGatewayRequestBenchmarkBody 生成 Codex / Claude Code 两种形态的大请求体。 +func buildGatewayRequestBenchmarkBody(targetBytes int, anthropic bool) []byte { + var sb strings.Builder + sb.Grow(targetBytes + 1024) + item := `{"type":"message","role":"user","content":[{"type":"input_text","text":"` + strings.Repeat("x", 4000) + `"}]}` + if anthropic { + sb.WriteString(`{"model":"claude-sonnet-5-5","stream":true,"system":[{"type":"text","text":"`) + sb.WriteString(strings.Repeat("z", targetBytes/8)) + sb.WriteString(`"}],"tools":[{"name":"shell","description":"`) + sb.WriteString(strings.Repeat("y", targetBytes/16)) + sb.WriteString(`"}],"messages":[`) + msg := `{"role":"user","content":[{"type":"text","text":"` + strings.Repeat("x", 4000) + `"}]}` + for i := 0; sb.Len() < targetBytes; i++ { + if i > 0 { + sb.WriteString(`,`) + } + sb.WriteString(msg) + } + sb.WriteString(`]}`) + return []byte(sb.String()) + } + sb.WriteString(`{"model":"gpt-5.5","stream":true,"instructions":"`) + sb.WriteString(strings.Repeat("z", targetBytes/8)) + sb.WriteString(`","tools":[{"type":"function","name":"shell","description":"`) + sb.WriteString(strings.Repeat("y", targetBytes/16)) + sb.WriteString(`"}],"input":[`) + for i := 0; sb.Len() < targetBytes; i++ { + if i > 0 { + sb.WriteString(`,`) + } + sb.WriteString(item) + } + sb.WriteString(`]}`) + return []byte(sb.String()) +} + +func BenchmarkParseGatewayRequestScan(b *testing.B) { + cases := []struct { + name string + size int + protocol string + anthropic bool + }{ + {"responses_128KiB", 128 << 10, "responses", false}, + {"responses_1MiB", 1 << 20, "responses", false}, + {"anthropic_1MiB", 1 << 20, domain.PlatformAnthropic, true}, + } + + for _, tc := range cases { + body := buildGatewayRequestBenchmarkBody(tc.size, tc.anthropic) + b.Run(tc.name+"/legacy", func(b *testing.B) { + b.SetBytes(int64(len(body))) + b.ReportAllocs() + for range b.N { + parsed := &ParsedRequest{Body: NewRequestBodyRef(body)} + if err := legacyParseGatewayRequestCurrentBody(parsed, tc.protocol); err != nil { + b.Fatal(err) + } + } + }) + b.Run(tc.name+"/scan", func(b *testing.B) { + b.SetBytes(int64(len(body))) + b.ReportAllocs() + for range b.N { + parsed := &ParsedRequest{Body: NewRequestBodyRef(body)} + if err := parseGatewayRequestBody(parsed, tc.protocol); err != nil { + b.Fatal(err) + } + } + }) + } +} diff --git a/backend/internal/service/gateway_request_scan_equivalence_test.go b/backend/internal/service/gateway_request_scan_equivalence_test.go new file mode 100644 index 0000000000..ca35784c0c --- /dev/null +++ b/backend/internal/service/gateway_request_scan_equivalence_test.go @@ -0,0 +1,293 @@ +package service + +import ( + "fmt" + "math" + "strings" + "testing" + "unsafe" + + "github.com/Wei-Shaw/sub2api/internal/domain" + "github.com/stretchr/testify/require" + "github.com/tidwall/gjson" + "github.com/tidwall/sjson" +) + +// 下面两个函数是重构前的 parseGatewayRequestCurrentBody / setGatewayRequestRanges +// 的逐字副本,作为差分测试的基准。任何一处语义变化都会在下面的对比里暴露。 +func legacyParseGatewayRequestCurrentBody(parsed *ParsedRequest, protocol string) error { + if parsed == nil || parsed.Body == nil { + return fmt.Errorf("empty request body") + } + parsed.Body.parsed = nil + + bodyBytes := parsed.Body.Bytes() + if !gjson.ValidBytes(bodyBytes) { + return DescribeInvalidJSON(bodyBytes) + } + + jsonStr := *(*string)(unsafe.Pointer(&bodyBytes)) + clearGatewayRequestDerivedState(parsed) + parsed.protocol = protocol + + modelResult := gjson.Get(jsonStr, "model") + if modelResult.Exists() { + if modelResult.Type != gjson.String { + return fmt.Errorf("invalid model field type") + } + parsed.Model = strings.Clone(modelResult.String()) + if protocol == domain.PlatformAnthropic { + normalizedModel := normalizeClaudeCodeLongContextModel(parsed.Model) + if normalizedModel != parsed.Model { + normalizedBody, err := sjson.SetBytes(bodyBytes, "model", normalizedModel) + if err != nil { + return fmt.Errorf("normalize model field: %w", err) + } + parsed.Body.Replace(normalizedBody) + bodyBytes = normalizedBody + jsonStr = *(*string)(unsafe.Pointer(&bodyBytes)) + parsed.Model = normalizedModel + } + } + } + + streamResult := gjson.Get(jsonStr, "stream") + if streamResult.Exists() { + if streamResult.Type != gjson.True && streamResult.Type != gjson.False { + return fmt.Errorf("invalid stream field type") + } + parsed.Stream = streamResult.Bool() + } + + parsed.MetadataUserID = strings.Clone(gjson.Get(jsonStr, "metadata.user_id").String()) + + thinkingType := gjson.Get(jsonStr, "thinking.type").String() + parsed.ThinkingEnabled = thinkingType == "enabled" || thinkingType == "adaptive" || thinkingType == "between_tools" || + (protocol == domain.PlatformAnthropic && isClaude55SignedThinkingModel(parsed.Model)) + + parsed.OutputEffort = strings.Clone(strings.TrimSpace(gjson.Get(jsonStr, "output_config.effort").String())) + if protocol == domain.PlatformAnthropic { + parsed.Speed = strings.Clone(strings.ToLower(strings.TrimSpace(gjson.Get(jsonStr, "speed").String()))) + } + + maxTokensResult := gjson.Get(jsonStr, "max_tokens") + if maxTokensResult.Exists() && maxTokensResult.Type == gjson.Number { + f := maxTokensResult.Float() + if !math.IsNaN(f) && !math.IsInf(f, 0) && f == math.Trunc(f) && + f <= float64(math.MaxInt) && f >= float64(math.MinInt) { + parsed.MaxTokens = int(f) + } + } + + legacySetGatewayRequestRanges(parsed, protocol, jsonStr) + parsed.saveBodyState() + return nil +} + +func legacySetGatewayRequestRanges(parsed *ParsedRequest, protocol string, jsonStr string) { + if parsed == nil { + return + } + switch protocol { + case domain.PlatformGemini: + if sysParts := gjson.Get(jsonStr, "systemInstruction.parts"); sysParts.Exists() && sysParts.IsArray() { + parsed.systemRange = rangeFromResult(sysParts) + } + if contents := gjson.Get(jsonStr, "contents"); contents.Exists() && contents.IsArray() { + parsed.messagesRange = rangeFromResult(contents) + } + default: + if sys := gjson.Get(jsonStr, "system"); sys.Exists() { + parsed.HasSystem = true + parsed.systemRange = rangeFromResult(sys) + } + if msgs := gjson.Get(jsonStr, "messages"); msgs.Exists() && msgs.IsArray() { + parsed.messagesRange = rangeFromResult(msgs) + } + if protocol == "responses" { + if input := gjson.Get(jsonStr, "input"); input.Exists() { + parsed.inputRange = rangeFromResult(input) + } + } + } +} + +// parsedSnapshot 只记录解析产出的可观测结果,避免比较实现内部的缓存指针。 +type parsedSnapshot struct { + err string + model string + stream bool + metadataUserID string + thinkingOn bool + outputEffort string + speed string + maxTokens int + hasSystem bool + systemRange jsonRange + messagesRange jsonRange + inputRange jsonRange + protocol string + bodyAfter string +} + +func snapshotOf(parsed *ParsedRequest, err error) parsedSnapshot { + snap := parsedSnapshot{} + if err != nil { + snap.err = err.Error() + } + if parsed == nil { + return snap + } + snap.model = parsed.Model + snap.stream = parsed.Stream + snap.metadataUserID = parsed.MetadataUserID + snap.thinkingOn = parsed.ThinkingEnabled + snap.outputEffort = parsed.OutputEffort + snap.speed = parsed.Speed + snap.maxTokens = parsed.MaxTokens + snap.hasSystem = parsed.HasSystem + snap.systemRange = parsed.systemRange + snap.messagesRange = parsed.messagesRange + snap.inputRange = parsed.inputRange + snap.protocol = parsed.protocol + if parsed.Body != nil { + snap.bodyAfter = string(parsed.Body.Bytes()) + } + return snap +} + +func parseBoth(t *testing.T, protocol string, body []byte) (parsedSnapshot, parsedSnapshot) { + t.Helper() + legacyBody := NewRequestBodyRef(append([]byte(nil), body...)) + legacyParsed := &ParsedRequest{Body: legacyBody} + legacyErr := legacyParseGatewayRequestCurrentBody(legacyParsed, protocol) + + // 直接调被重构的这一步:ParseGatewayRequest 在失败时返回 nil,无法比较错误路径上的中间状态。 + newBody := NewRequestBodyRef(append([]byte(nil), body...)) + newParsed := &ParsedRequest{Body: newBody} + newErr := parseGatewayRequestBody(newParsed, protocol) + + return snapshotOf(legacyParsed, legacyErr), snapshotOf(newParsed, newErr) +} + +func TestParseGatewayRequestMatchesLegacy(t *testing.T) { + escape := string(rune(92)) + cases := []struct { + name string + body string + }{ + {"typical responses", `{"model":"gpt-5.5","stream":true,"input":[{"type":"message"}]}`}, + {"typical anthropic", `{"model":"claude-sonnet-5-5","stream":true,"system":"s","messages":[{"role":"user","content":"hi"}],"max_tokens":1024,"thinking":{"type":"enabled"},"output_config":{"effort":" high "},"speed":"Fast"}`}, + {"typical gemini", `{"contents":[{"parts":[{"text":"hi"}]}],"systemInstruction":{"parts":[{"text":"sys"}]},"generationConfig":{"maxOutputTokens":32}}`}, + {"empty object", `{}`}, + {"empty string", ``}, + {"invalid json", `{"model":`}, + {"invalid json with image tool", `{"tools":[{"type":"image_generation"}]`}, + {"model wrong type", `{"model":123}`}, + {"model null", `{"model":null}`}, + {"stream wrong type", `{"model":"m","stream":"yes"}`}, + {"stream null", `{"model":"m","stream":null}`}, + {"stream false", `{"model":"m","stream":false}`}, + {"max_tokens float", `{"model":"m","max_tokens":1024.5}`}, + {"max_tokens negative", `{"model":"m","max_tokens":-8}`}, + {"max_tokens huge", `{"model":"m","max_tokens":1e30}`}, + {"max_tokens string", `{"model":"m","max_tokens":"1024"}`}, + {"metadata nested", `{"metadata":{"user_id":"u1"}}`}, + {"metadata string first", `{"metadata":"x","metadata":{"user_id":"u2"}}`}, + {"metadata null child", `{"metadata":{"user_id":null},"metadata":{"user_id":"u3"}}`}, + {"metadata wrong shape", `{"metadata":[],"metadata":{"user_id":"u4"}}`}, + {"thinking string first", `{"thinking":"x","thinking":{"type":"enabled"}}`}, + {"thinking adaptive", `{"thinking":{"type":"adaptive"}}`}, + {"thinking between tools", `{"thinking":{"type":"between_tools"}}`}, + {"effort with spaces", `{"output_config":{"effort":" medium "}}`}, + {"effort first empty", `{"output_config":{"effort":""},"output_config":{"effort":"high"}}`}, + {"speed uppercase", `{"speed":" FAST "}`}, + {"system string", `{"system":"sys","messages":[{"role":"user"}]}`}, + {"system object", `{"system":{"type":"text"},"messages":[]}`}, + {"system wrong shape", `{"system":123}`}, + {"messages not array", `{"messages":"x"}`}, + {"input present", `{"input":[{"a":1}]}`}, + {"contents not array", `{"contents":"x"}`}, + {"gemini parts not array", `{"systemInstruction":{"parts":"x"}}`}, + {"gemini parts retry", `{"systemInstruction":{"parts":"x"},"systemInstruction":{"parts":[{"a":1}]}}`}, + {"duplicate model", `{"model":"m1","model":"m2"}`}, + {"duplicate stream", `{"stream":true,"stream":false}`}, + {"long context suffix", `{"model":"claude-sonnet-5-5[1m]","messages":[]}`}, + {"long context suffix duplicated", `{"model":"claude-sonnet-5-5[1m][1m]","messages":[]}`}, + {"escaped system key", `{"` + escape + `u0073ystem":"s","messages":[]}`}, + {"escaped model key", `{"` + escape + `u006dodel":"m"}`}, + {"root array", `[1,2,3]`}, + {"root scalar", `"just a string"`}, + {"nested nulls", `{"model":"m","system":null,"messages":[{"a":1}],"input":null}`}, + {"unicode content", `{"model":"m","messages":[{"content":"中文 😀"}]}`}, + } + + protocols := []string{"responses", "chat_completions", domain.PlatformAnthropic, domain.PlatformGemini} + + for _, tc := range cases { + for _, protocol := range protocols { + t.Run(tc.name+"/"+protocol, func(t *testing.T) { + want, got := parseBoth(t, protocol, []byte(tc.body)) + require.Equal(t, want, got, "body=%s", tc.body) + }) + } + } +} + +// deterministic 随机组合,覆盖键顺序、重复键、类型混杂的组合空间。 +func TestParseGatewayRequestMatchesLegacyRandomized(t *testing.T) { + pieces := []string{ + `"model":"m"`, `"model":"claude-x[1m]"`, `"model":null`, `"model":1`, + `"stream":true`, `"stream":"x"`, `"stream":null`, + `"max_tokens":16`, `"max_tokens":16.5`, `"max_tokens":"16"`, + `"metadata":{"user_id":"u"}`, `"metadata":"s"`, `"metadata":null`, + `"thinking":{"type":"enabled"}`, `"thinking":{"type":"adaptive"}`, `"thinking":"x"`, + `"output_config":{"effort":" low "}`, `"output_config":null`, + `"speed":" FAST "`, `"speed":null`, + `"system":"sys"`, `"system":[{"type":"text"}]`, `"system":null`, + `"messages":[]`, `"messages":[{"role":"user"}]`, `"messages":"x"`, + `"input":[]`, `"input":[{"a":1}]`, `"input":null`, + `"contents":[]`, `"contents":"x"`, + `"systemInstruction":{"parts":[]}`, `"systemInstruction":{"parts":"x"}`, + `"unknown":1`, `"unknown":{"nested":true}`, + } + protocols := []string{"responses", "chat_completions", domain.PlatformAnthropic, domain.PlatformGemini} + + seed := uint64(0x9e3779b97f4a7c15) + next := func() uint64 { + seed ^= seed << 13 + seed ^= seed >> 7 + seed ^= seed << 17 + return seed + } + + for i := 0; i < 3000; i++ { + n := int(next()%6) + 1 + parts := make([]string, 0, n) + for j := 0; j < n; j++ { + parts = append(parts, pieces[int(next()%uint64(len(pieces)))]) + } + body := []byte("{" + strings.Join(parts, ",") + "}") + protocol := protocols[int(next()%uint64(len(protocols)))] + + want, got := parseBoth(t, protocol, body) + require.Equal(t, want, got, "iteration=%d protocol=%s body=%s", i, protocol, body) + } +} + +func FuzzParseGatewayRequestMatchesLegacy(f *testing.F) { + f.Add([]byte(`{"model":"m","stream":true,"input":[]}`), "responses") + f.Add([]byte(`{"model":"claude-x[1m]","messages":[],"system":"s"}`), domain.PlatformAnthropic) + f.Add([]byte(`{"metadata":{"user_id":"u"},"thinking":{"type":"enabled"}}`), "chat_completions") + f.Add([]byte(`{"contents":[],"systemInstruction":{"parts":[]}}`), domain.PlatformGemini) + f.Fuzz(func(t *testing.T, body []byte, protocol string) { + switch protocol { + case "responses", "chat_completions", domain.PlatformAnthropic, domain.PlatformGemini: + default: + return + } + want, got := parseBoth(t, protocol, body) + require.Equal(t, want, got, "body=%q protocol=%s", body, protocol) + + }) +} From 844459e78595acb63dc4d97e0394106cfd9dbfa1 Mon Sep 17 00:00:00 2001 From: lishuangqiang <142634204+lishuangqiang@users.noreply.github.com> Date: Mon, 16 Nov 2026 23:24:26 +0800 Subject: [PATCH 32/85] perf(openai): skip the redundant body validation when parsing responses requests The /v1/responses handler validates the request body with gjson.ValidBytes before doing anything else, then hands the same bytes to ParseGatewayRequest, which validates them a second time. After the single-root-walk change the validation is the majority of what that call does: at 1MiB it is about 510us of the remaining 730us. Add ParseGatewayRequestValidated for callers that have already established the body is valid JSON, and use it in the handler, where the only rewrite between the two points is applyOpenAIReasoningEffortPolicyForRequest (sjson, which preserves validity). The validating entry point is unchanged, so invalid JSON keeps producing a clean error everywhere else. ReplaceBody / CloneForBody keep validating as well, because their bytes can differ from the ones a caller validated. Equivalence tests assert the trusted variant produces identical results to the validating one on valid JSON, and the fuzz target checks the same for every input that parses. Benchmark (Apple M5 Pro, 3 allocs unchanged): responses 1MiB: 735us -> 239us anthropic 1MiB: 723us -> 207us (not yet wired: that handler has no earlier validation, so it keeps the validating path) --- .../handler/gateway_handler_responses.go | 4 ++- backend/internal/service/gateway_request.go | 21 ++++++++--- .../gateway_request_scan_benchmark_test.go | 13 ++++++- .../gateway_request_scan_equivalence_test.go | 35 ++++++++++++++++++- 4 files changed, 66 insertions(+), 7 deletions(-) diff --git a/backend/internal/handler/gateway_handler_responses.go b/backend/internal/handler/gateway_handler_responses.go index 165b57867d..f499dba5e8 100644 --- a/backend/internal/handler/gateway_handler_responses.go +++ b/backend/internal/handler/gateway_handler_responses.go @@ -178,8 +178,10 @@ func (h *GatewayHandler) Responses(c *gin.Context) { defer inflightRelease() // Parse request for session hash + // body 已在本函数开头用 gjson.ValidBytes 校验过,之后只经过 sjson 改写 + // (applyOpenAIReasoningEffortPolicyForRequest),合法性保持,因此跳过重复校验。 bodyRef := service.NewRequestBodyRef(body) - parsedReq, _ := service.ParseGatewayRequest(bodyRef, "responses") + parsedReq, _ := service.ParseGatewayRequestValidated(bodyRef, "responses") if parsedReq == nil { parsedReq = &service.ParsedRequest{Model: reqModel, Stream: reqStream, Body: bodyRef} } diff --git a/backend/internal/service/gateway_request.go b/backend/internal/service/gateway_request.go index 1ec3209250..deb11fae90 100644 --- a/backend/internal/service/gateway_request.go +++ b/backend/internal/service/gateway_request.go @@ -316,14 +316,15 @@ func normalizeClaudeCodeLongContextModel(model string) string { } // parseGatewayRequestBody 只做标量和 raw range 轻量解析,不恢复 system/messages 对象图。 -func parseGatewayRequestBody(parsed *ParsedRequest, protocol string) error { +// validate 为 false 时要求调用方已经确认 body 是合法 JSON(见 ParseGatewayRequestValidated)。 +func parseGatewayRequestBody(parsed *ParsedRequest, protocol string, validate bool) error { if parsed == nil || parsed.Body == nil { return fmt.Errorf("empty request body") } parsed.Body.parsed = nil bodyBytes := parsed.Body.Bytes() - if !gjson.ValidBytes(bodyBytes) { + if validate && !gjson.ValidBytes(bodyBytes) { return DescribeInvalidJSON(bodyBytes) } @@ -388,7 +389,7 @@ func parseGatewayRequestBody(parsed *ParsedRequest, protocol string) error { } func refreshGatewayRequestRanges(parsed *ParsedRequest, protocol string) error { - return parseGatewayRequestBody(parsed, protocol) + return parseGatewayRequestBody(parsed, protocol, true) } // DescribeInvalidJSON returns a diagnostic error for a request body that @@ -495,8 +496,20 @@ func normalizeSessionUserAgentFallback(raw string) string { // protocol 指定请求协议格式(domain.PlatformAnthropic / domain.PlatformGemini), // 不同协议使用不同的 system/messages 字段名。 func ParseGatewayRequest(body *RequestBodyRef, protocol string) (*ParsedRequest, error) { + return parseGatewayRequest(body, protocol, true) +} + +// ParseGatewayRequestValidated 与 ParseGatewayRequest 结果相同,但要求调用方已经确认 +// body 是合法 JSON(例如 handler 已对同一份字节做过 gjson.ValidBytes,且此后的改写只 +// 经过 sjson)。它跳过这次全量校验——1 MiB body 上约 510µs,占解析耗时的七成。 +// 非法 JSON 的语义与未校验版本不同,只允许在校验过同一份字节的调用点使用。 +func ParseGatewayRequestValidated(body *RequestBodyRef, protocol string) (*ParsedRequest, error) { + return parseGatewayRequest(body, protocol, false) +} + +func parseGatewayRequest(body *RequestBodyRef, protocol string, validate bool) (*ParsedRequest, error) { parsed := &ParsedRequest{Body: body} - if err := parseGatewayRequestBody(parsed, protocol); err != nil { + if err := parseGatewayRequestBody(parsed, protocol, validate); err != nil { return nil, err } return parsed, nil diff --git a/backend/internal/service/gateway_request_scan_benchmark_test.go b/backend/internal/service/gateway_request_scan_benchmark_test.go index 0b09668d70..82e5634ccc 100644 --- a/backend/internal/service/gateway_request_scan_benchmark_test.go +++ b/backend/internal/service/gateway_request_scan_benchmark_test.go @@ -72,7 +72,18 @@ func BenchmarkParseGatewayRequestScan(b *testing.B) { b.ReportAllocs() for range b.N { parsed := &ParsedRequest{Body: NewRequestBodyRef(body)} - if err := parseGatewayRequestBody(parsed, tc.protocol); err != nil { + if err := parseGatewayRequestBody(parsed, tc.protocol, true); err != nil { + b.Fatal(err) + } + } + }) + // 调用方已经校验过同一份字节时(handler 已做 gjson.ValidBytes,且之后只经 sjson 改写)。 + b.Run(tc.name+"/scan_validated", func(b *testing.B) { + b.SetBytes(int64(len(body))) + b.ReportAllocs() + for range b.N { + parsed := &ParsedRequest{Body: NewRequestBodyRef(body)} + if err := parseGatewayRequestBody(parsed, tc.protocol, false); err != nil { b.Fatal(err) } } diff --git a/backend/internal/service/gateway_request_scan_equivalence_test.go b/backend/internal/service/gateway_request_scan_equivalence_test.go index ca35784c0c..ffe43ec9e9 100644 --- a/backend/internal/service/gateway_request_scan_equivalence_test.go +++ b/backend/internal/service/gateway_request_scan_equivalence_test.go @@ -165,7 +165,7 @@ func parseBoth(t *testing.T, protocol string, body []byte) (parsedSnapshot, pars // 直接调被重构的这一步:ParseGatewayRequest 在失败时返回 nil,无法比较错误路径上的中间状态。 newBody := NewRequestBodyRef(append([]byte(nil), body...)) newParsed := &ParsedRequest{Body: newBody} - newErr := parseGatewayRequestBody(newParsed, protocol) + newErr := parseGatewayRequestBody(newParsed, protocol, true) return snapshotOf(legacyParsed, legacyErr), snapshotOf(newParsed, newErr) } @@ -275,6 +275,30 @@ func TestParseGatewayRequestMatchesLegacyRandomized(t *testing.T) { } } +// 已校验变体只允许在「body 合法」的前提下使用;合法 JSON 上两者必须产出完全相同的结果。 +func TestParseGatewayRequestValidatedMatchesValidatingPath(t *testing.T) { + bodies := []string{ + `{"model":"gpt-5.5","stream":true,"input":[{"type":"message"}]}`, + `{"model":"claude-x[1m]","messages":[],"system":"s","max_tokens":8}`, + `{"metadata":{"user_id":"u"},"thinking":{"type":"enabled"},"output_config":{"effort":" high "}}`, + `{"contents":[],"systemInstruction":{"parts":[]}}`, + `{}`, + } + protocols := []string{"responses", "chat_completions", domain.PlatformAnthropic, domain.PlatformGemini} + for _, body := range bodies { + for _, protocol := range protocols { + validating := &ParsedRequest{Body: NewRequestBodyRef([]byte(body))} + validatingErr := parseGatewayRequestBody(validating, protocol, true) + + trusted := &ParsedRequest{Body: NewRequestBodyRef([]byte(body))} + trustedErr := parseGatewayRequestBody(trusted, protocol, false) + + require.Equal(t, snapshotOf(validating, validatingErr), snapshotOf(trusted, trustedErr), + "body=%s protocol=%s", body, protocol) + } + } +} + func FuzzParseGatewayRequestMatchesLegacy(f *testing.F) { f.Add([]byte(`{"model":"m","stream":true,"input":[]}`), "responses") f.Add([]byte(`{"model":"claude-x[1m]","messages":[],"system":"s"}`), domain.PlatformAnthropic) @@ -289,5 +313,14 @@ func FuzzParseGatewayRequestMatchesLegacy(f *testing.F) { want, got := parseBoth(t, protocol, body) require.Equal(t, want, got, "body=%q protocol=%s", body, protocol) + // 合法 JSON 上,跳过校验不得改变结果。 + if gjson.ValidBytes(body) { + validating := &ParsedRequest{Body: NewRequestBodyRef(append([]byte(nil), body...))} + validatingErr := parseGatewayRequestBody(validating, protocol, true) + trusted := &ParsedRequest{Body: NewRequestBodyRef(append([]byte(nil), body...))} + trustedErr := parseGatewayRequestBody(trusted, protocol, false) + require.Equal(t, snapshotOf(validating, validatingErr), snapshotOf(trusted, trustedErr), + "validated path diverged: body=%q protocol=%s", body, protocol) + } }) } From 8d962ba494ae0adcd745629b1e4bcec1dc839b0e Mon Sep 17 00:00:00 2001 From: lishuangqiang <142634204+lishuangqiang@users.noreply.github.com> Date: Mon, 16 Nov 2026 23:34:25 +0800 Subject: [PATCH 33/85] perf(openai): use the validated parse path for chat completions too Same shape as the responses handler: the body is validated at the top of ChatCompletions, the only later rewrite is applyOpenAIReasoningEffortPolicyForRequest (sjson), and the parse error was already being ignored. Nothing between the two points mutates the bytes: parseOpenAICompatibleStream, checkSecurityAudit and tokenInflightEstimate only read them. --- backend/internal/handler/gateway_handler_chat_completions.go | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/backend/internal/handler/gateway_handler_chat_completions.go b/backend/internal/handler/gateway_handler_chat_completions.go index 0b982a961b..ef54220177 100644 --- a/backend/internal/handler/gateway_handler_chat_completions.go +++ b/backend/internal/handler/gateway_handler_chat_completions.go @@ -174,8 +174,10 @@ func (h *GatewayHandler) ChatCompletions(c *gin.Context) { defer inflightRelease() // Parse request for session hash + // body 已在本函数开头用 gjson.ValidBytes 校验过,之后只经过 sjson 改写 + // (applyOpenAIReasoningEffortPolicyForRequest),合法性保持,因此跳过重复校验。 bodyRef := service.NewRequestBodyRef(body) - parsedReq, _ := service.ParseGatewayRequest(bodyRef, "chat_completions") + parsedReq, _ := service.ParseGatewayRequestValidated(bodyRef, "chat_completions") if parsedReq == nil { parsedReq = &service.ParsedRequest{Model: reqModel, Stream: reqStream, Body: bodyRef} } From fb52c6e136a9401d5c078bade0533b32715706f7 Mon Sep 17 00:00:00 2001 From: xuemk <19485593+xuemk@users.noreply.github.com> Date: Wed, 11 Nov 2026 15:21:18 +0800 Subject: [PATCH 34/85] fix(openai): protect rotated oauth credentials from enrichment timeout and race conditions --- backend/internal/repository/account_repo.go | 26 +- .../account_repo_temp_unsched_test.go | 75 +++++ backend/internal/service/oauth_refresh_api.go | 99 ++++++ .../service/oauth_refresh_api_test.go | 281 +++++++++++++++++- .../internal/service/token_refresh_service.go | 15 +- .../token_refresh_service_candidates_test.go | 38 +++ .../service/token_refresh_service_test.go | 151 ++++++++++ 7 files changed, 672 insertions(+), 13 deletions(-) diff --git a/backend/internal/repository/account_repo.go b/backend/internal/repository/account_repo.go index 468a82a0e7..80bebe8314 100644 --- a/backend/internal/repository/account_repo.go +++ b/backend/internal/repository/account_repo.go @@ -1657,6 +1657,29 @@ func (r *accountRepository) UpdateGrokOAuthCredentialsIfUnchanged( expectedCredentials map[string]any, expectedProxyID *int64, credentials map[string]any, +) (bool, error) { + return r.updateOAuthCredentialsIfUnchanged(ctx, id, service.PlatformGrok, expectedCredentials, expectedProxyID, credentials) +} + +// UpdateOpenAIOAuthCredentialsIfUnchanged preserves a completed token rotation +// without overwriting concurrent reauthorization or writing to a credential shadow. +func (r *accountRepository) UpdateOpenAIOAuthCredentialsIfUnchanged( + ctx context.Context, + id int64, + expectedCredentials map[string]any, + expectedProxyID *int64, + credentials map[string]any, +) (bool, error) { + return r.updateOAuthCredentialsIfUnchanged(ctx, id, service.PlatformOpenAI, expectedCredentials, expectedProxyID, credentials) +} + +func (r *accountRepository) updateOAuthCredentialsIfUnchanged( + ctx context.Context, + id int64, + platform string, + expectedCredentials map[string]any, + expectedProxyID *int64, + credentials map[string]any, ) (bool, error) { if r == nil || r.sql == nil { return false, errors.New("account repository SQL executor is not configured") @@ -1680,6 +1703,7 @@ func (r *accountRepository) UpdateGrokOAuthCredentialsIfUnchanged( AND a.type = $4 AND a.credentials = $5::jsonb AND a.proxy_id IS NOT DISTINCT FROM $6 + AND ($3 <> 'openai' OR a.parent_account_id IS NULL) RETURNING a.id ) INSERT INTO scheduler_outbox (event_type, account_id, group_id, payload) @@ -1687,7 +1711,7 @@ func (r *accountRepository) UpdateGrokOAuthCredentialsIfUnchanged( `, string(credentialsJSON), id, - service.PlatformGrok, + platform, service.AccountTypeOAuth, string(expectedJSON), expectedProxyID, diff --git a/backend/internal/repository/account_repo_temp_unsched_test.go b/backend/internal/repository/account_repo_temp_unsched_test.go index 9853e272ba..df226b1cb3 100644 --- a/backend/internal/repository/account_repo_temp_unsched_test.go +++ b/backend/internal/repository/account_repo_temp_unsched_test.go @@ -4,6 +4,7 @@ import ( "context" "database/sql" "database/sql/driver" + "errors" "regexp" "strings" "testing" @@ -258,9 +259,83 @@ func TestAccountRepository_UpdateGrokOAuthCredentialsIfUnchanged_UsesExactAttemp require.Contains(t, normalized, "proxy_id IS NOT DISTINCT FROM $6") require.Contains(t, normalized, "INSERT INTO scheduler_outbox") require.Len(t, exec.execArgs[0], 7) + require.Equal(t, service.PlatformGrok, exec.execArgs[0][2]) require.Equal(t, &proxyID, exec.execArgs[0][5]) } +func TestAccountRepository_UpdateOpenAIOAuthCredentialsIfUnchanged_UsesExactAttemptStateAndAtomicOutbox(t *testing.T) { + exec := &recordingSQLExecutor{result: rowsAffectedResult(1)} + repo := newAccountRepositoryWithSQL(nil, exec, nil) + proxyID := int64(29) + + applied, err := repo.UpdateOpenAIOAuthCredentialsIfUnchanged( + context.Background(), + 42, + map[string]any{"refresh_token": "attempted", "_token_version": int64(9)}, + &proxyID, + map[string]any{"refresh_token": "rotated", "_token_version": int64(10)}, + ) + + require.NoError(t, err) + require.True(t, applied) + require.Len(t, exec.execQueries, 1, "credential update and outbox insertion must share one SQL statement") + normalized := normalizeSQLWhitespace(exec.execQueries[0]) + require.Contains(t, normalized, "WITH updated AS ( UPDATE accounts AS a SET credentials = $1::jsonb") + require.Contains(t, normalized, "a.deleted_at IS NULL") + require.Contains(t, normalized, "a.platform = $3") + require.Contains(t, normalized, "a.type = $4") + require.Contains(t, normalized, "a.credentials = $5::jsonb") + require.Contains(t, normalized, "a.proxy_id IS NOT DISTINCT FROM $6") + require.Contains(t, normalized, "($3 <> 'openai' OR a.parent_account_id IS NULL)") + require.Contains(t, normalized, "RETURNING a.id ) INSERT INTO scheduler_outbox") + require.Contains(t, normalized, "SELECT $7, updated.id, NULL, NULL FROM updated") + require.Len(t, exec.execArgs[0], 7) + arg0, ok := exec.execArgs[0][0].(string) + require.True(t, ok) + require.JSONEq(t, `{"refresh_token":"rotated","_token_version":10}`, arg0) + require.Equal(t, int64(42), exec.execArgs[0][1]) + require.Equal(t, service.PlatformOpenAI, exec.execArgs[0][2]) + require.Equal(t, service.AccountTypeOAuth, exec.execArgs[0][3]) + arg4, ok := exec.execArgs[0][4].(string) + require.True(t, ok) + require.JSONEq(t, `{"refresh_token":"attempted","_token_version":9}`, arg4) + require.Equal(t, &proxyID, exec.execArgs[0][5]) + require.Equal(t, service.SchedulerOutboxEventAccountChanged, exec.execArgs[0][6]) +} + +func TestAccountRepository_UpdateOpenAIOAuthCredentialsIfUnchanged_NoMatchDoesNotApply(t *testing.T) { + exec := &recordingSQLExecutor{result: rowsAffectedResult(0)} + repo := newAccountRepositoryWithSQL(nil, exec, nil) + + applied, err := repo.UpdateOpenAIOAuthCredentialsIfUnchanged( + context.Background(), 42, map[string]any{"refresh_token": "attempted"}, nil, + map[string]any{"refresh_token": "rotated"}, + ) + + require.NoError(t, err) + require.False(t, applied) + require.Len(t, exec.execQueries, 1) + require.Nil(t, exec.execArgs[0][5], "a nil proxy must match only a database NULL proxy") + require.Contains(t, normalizeSQLWhitespace(exec.execQueries[0]), "SELECT $7, updated.id, NULL, NULL FROM updated", + "a CAS miss must not insert an independent invalidation event") +} + +func TestAccountRepository_UpdateOpenAIOAuthCredentialsIfUnchanged_OutboxFailureDoesNotReportSuccess(t *testing.T) { + outboxErr := errors.New("scheduler outbox insert failed") + exec := &recordingSQLExecutor{err: outboxErr} + repo := newAccountRepositoryWithSQL(nil, exec, nil) + + applied, err := repo.UpdateOpenAIOAuthCredentialsIfUnchanged( + context.Background(), 42, map[string]any{"refresh_token": "attempted"}, nil, + map[string]any{"refresh_token": "rotated"}, + ) + + require.ErrorIs(t, err, outboxErr) + require.False(t, applied) + require.Len(t, exec.execQueries, 1) + require.Contains(t, normalizeSQLWhitespace(exec.execQueries[0]), "INSERT INTO scheduler_outbox") +} + func TestAccountRepository_ListOAuthRefreshCandidatePage_SQLFilter(t *testing.T) { db, mock, err := sqlmock.New(sqlmock.QueryMatcherOption(sqlmock.QueryMatcherRegexp)) require.NoError(t, err) diff --git a/backend/internal/service/oauth_refresh_api.go b/backend/internal/service/oauth_refresh_api.go index c940bd335a..af7126eebb 100644 --- a/backend/internal/service/oauth_refresh_api.go +++ b/backend/internal/service/oauth_refresh_api.go @@ -5,6 +5,7 @@ import ( "errors" "fmt" "log/slog" + "reflect" "strconv" "strings" "sync" @@ -34,10 +35,17 @@ type GrokOAuthRefreshSuccessRepository interface { ) (bool, error) } +type OpenAIOAuthRefreshSuccessRepository interface { + UpdateOpenAIOAuthCredentialsIfUnchanged(ctx context.Context, id int64, expectedCredentials map[string]any, expectedProxyID *int64, credentials map[string]any) (bool, error) +} + const ( defaultRefreshLockTTL = 60 * time.Second defaultRefreshLockReleaseTimeout = 2 * time.Second defaultRefreshPostPersistCleanupTimeout = 2 * time.Second + defaultOpenAIRefreshPersistTimeout = 10 * time.Second + // Repository snapshot propagation uses its own detached timeout after CAS. + defaultRefreshRepositorySyncTimeout = 2 * time.Second ) var ( @@ -205,6 +213,17 @@ func (api *OAuthRefreshAPI) RefreshIfNeeded( return &OAuthRefreshResult{LockHeld: true}, nil } else { defer api.releaseRefreshLock(ctx, cacheKey) + if account.Platform == PlatformOpenAI && account.Type == AccountTypeOAuth { + // Reserve lease time for the irreversible rotation's detached save, + // cache invalidation and lock release, including request-path calls. + budget := api.lockTTL - defaultOpenAIRefreshPersistTimeout - defaultRefreshRepositorySyncTimeout - defaultRefreshPostPersistCleanupTimeout - defaultRefreshLockReleaseTimeout - maxTokenRefreshLockSafetyMargin + if budget <= 0 { + return nil, &providerConfigurationRefreshError{err: errors.New("OpenAI OAuth refresh lock lease is too short for credential persistence")} + } + var cancel context.CancelFunc + ctx, cancel = context.WithTimeout(ctx, budget) + defer cancel() + } } } @@ -256,6 +275,26 @@ func (api *OAuthRefreshAPI) RefreshIfNeeded( // 4. 执行平台特定刷新逻辑 attemptedAccount := snapshotOAuthRefreshAccount(freshAccount) newCredentials, refreshErr := executor.Refresh(ctx, freshAccount) + if refreshErr == nil && hasOpenAIRefreshCredentials(attemptedAccount, newCredentials) { + // The upstream rotation is irreversible. Cancellation of optional + // enrichment must not discard its result or cause an old-token retry. + durableAccount, applied, persistErr := persistOpenAIRefreshCredentials(ctx, api.accountRepo, attemptedAccount, newCredentials) + if applied && api.tokenCache != nil { + cleanupCtx, cancel := context.WithTimeout(context.WithoutCancel(ctx), defaultRefreshPostPersistCleanupTimeout) + defer cancel() + if err := api.tokenCache.DeleteAccessToken(cleanupCtx, cacheKey); err != nil { + slog.Warn("oauth_refresh_post_persist_cache_delete_failed", "account_id", account.ID, "error", err) + } + } + if persistErr != nil { + return nil, persistErr + } + result := &OAuthRefreshResult{Refreshed: applied, Account: durableAccount} + if applied { + result.NewCredentials = newCredentials + } + return result, nil + } if ctxErr := ctx.Err(); ctxErr != nil { // A provider implementation may ignore cancellation and return late // credentials. Never persist them after the attempt/cycle boundary. @@ -372,6 +411,66 @@ func (api *OAuthRefreshAPI) RefreshIfNeeded( }, nil } +func hasOpenAIRefreshCredentials(account *Account, credentials map[string]any) bool { + if account == nil || account.Platform != PlatformOpenAI || account.Type != AccountTypeOAuth || + account.IsCredentialShadow() || account.IsOpenAIPersonalAccessToken() { + return false + } + accessToken, _ := credentials["access_token"].(string) + refreshToken, _ := credentials["refresh_token"].(string) + return strings.TrimSpace(accessToken) != "" && strings.TrimSpace(refreshToken) != "" +} + +func persistOpenAIRefreshCredentials(parent context.Context, repo AccountRepository, attempted *Account, credentials map[string]any) (*Account, bool, error) { + conditionalRepo, ok := repo.(OpenAIOAuthRefreshSuccessRepository) + if !ok { + return nil, false, &providerConfigurationRefreshError{err: errors.New("OpenAI OAuth refresh success CAS repository is not configured")} + } + ctx, cancel := context.WithTimeout(context.WithoutCancel(parent), defaultOpenAIRefreshPersistTimeout) + defer cancel() + credentials["_token_version"] = time.Now().UnixMilli() + expected := attempted + replacement := credentials + for saveAttempt := 0; saveAttempt < 3; saveAttempt++ { + applied, err := conditionalRepo.UpdateOpenAIOAuthCredentialsIfUnchanged(ctx, attempted.ID, expected.Credentials, expected.ProxyID, replacement) + if err != nil { + return nil, false, &providerCycleContainmentRefreshError{err: fmt.Errorf("%w: %v", errOAuthRefreshCredentialPersist, err)} + } + // Read the durable row rather than publishing the pre-refresh scheduling + // snapshot; an administrator may have changed the account while we waited. + current, err := repo.GetByID(ctx, attempted.ID) + if err != nil || current == nil || current.ID != attempted.ID { + return nil, applied, &providerCycleContainmentRefreshError{err: fmt.Errorf("%w: durable account unavailable after OpenAI refresh", errOAuthRefreshCredentialPersist)} + } + if applied { + return current, true, nil + } + if current.Platform != PlatformOpenAI || current.Type != AccountTypeOAuth || + current.IsCredentialShadow() || current.IsOpenAIPersonalAccessToken() || + current.GetCredential("refresh_token") != attempted.GetCredential("refresh_token") || + current.GetCredential("access_token") != attempted.GetCredential("access_token") || + current.GetCredentialAsInt64("_token_version") != attempted.GetCredentialAsInt64("_token_version") { + return current, false, nil + } + // A proxy or non-token setting edit must not discard a completed rotation. + // Reapply only this refresh's credential changes to the newest snapshot. + expected = snapshotOAuthRefreshAccount(current) + replacement = shallowCopyMap(current.Credentials) + for key, value := range credentials { + previous, exists := attempted.Credentials[key] + if !exists || !reflect.DeepEqual(previous, value) { + replacement[key] = value + } + } + for key := range attempted.Credentials { + if _, exists := credentials[key]; !exists { + delete(replacement, key) + } + } + } + return nil, false, &providerCycleContainmentRefreshError{err: fmt.Errorf("%w: OpenAI credentials changed repeatedly during persistence", errOAuthRefreshCredentialPersist)} +} + func (api *OAuthRefreshAPI) releaseRefreshLock(parent context.Context, cacheKey string) { cleanupParent := context.Background() if parent != nil { diff --git a/backend/internal/service/oauth_refresh_api_test.go b/backend/internal/service/oauth_refresh_api_test.go index e92bd99f02..9319ed6b8f 100644 --- a/backend/internal/service/oauth_refresh_api_test.go +++ b/backend/internal/service/oauth_refresh_api_test.go @@ -5,11 +5,14 @@ package service import ( "context" "errors" + "fmt" "reflect" "sync" "testing" "time" + "github.com/Wei-Shaw/sub2api/internal/pkg/openai" + "github.com/imroc/req/v3" "github.com/stretchr/testify/require" ) @@ -30,9 +33,16 @@ type refreshAPIAccountRepo struct { beforeSuccessCAS func(*refreshAPIAccountRepo) lastExpectedCredentials map[string]any lastExpectedProxyID *int64 + openAISuccessCASCalls int + openAIPersistCtxErr error + openAIPersistDeadline time.Time + respectReadContext bool } -func (r *refreshAPIAccountRepo) GetByID(_ context.Context, _ int64) (*Account, error) { +func (r *refreshAPIAccountRepo) GetByID(ctx context.Context, _ int64) (*Account, error) { + if r.respectReadContext && ctx.Err() != nil { + return nil, ctx.Err() + } r.getByIDCalls++ if r.getByIDErrAfterCall > 0 && r.getByIDCalls >= r.getByIDErrAfterCall { return nil, r.getByIDErrAfterCallErr @@ -103,16 +113,50 @@ func (r *refreshAPIAccountRepo) UpdateGrokOAuthCredentialsIfUnchanged( return true, nil } +func (r *refreshAPIAccountRepo) UpdateOpenAIOAuthCredentialsIfUnchanged( + ctx context.Context, + id int64, + expectedCredentials map[string]any, + expectedProxyID *int64, + credentials map[string]any, +) (bool, error) { + r.openAISuccessCASCalls++ + r.openAIPersistCtxErr = ctx.Err() + r.openAIPersistDeadline, _ = ctx.Deadline() + if err := ctx.Err(); err != nil { + return false, err + } + r.lastExpectedCredentials = shallowCopyMap(expectedCredentials) + r.lastExpectedProxyID = expectedProxyID + if r.beforeSuccessCAS != nil { + r.beforeSuccessCAS(r) + } + if r.updateErr != nil { + return false, r.updateErr + } + if r.account == nil || r.account.ID != id || r.account.Platform != PlatformOpenAI || + r.account.Type != AccountTypeOAuth || r.account.IsCredentialShadow() || + !reflect.DeepEqual(r.account.Credentials, expectedCredentials) || + !reflect.DeepEqual(r.account.ProxyID, expectedProxyID) { + return false, nil + } + r.updateCalls++ + r.updateCredentialsCalls++ + r.account.Credentials = shallowCopyMap(credentials) + return true, nil +} + // refreshAPIExecutorStub implements OAuthRefreshExecutor for tests. type refreshAPIExecutorStub struct { - needsRefresh bool - cannotRefresh bool - credentials map[string]any - err error - refreshCalls int - canRefresh func(*Account) bool - onRefresh func() - delay time.Duration + needsRefresh bool + cannotRefresh bool + credentials map[string]any + err error + refreshCalls int + canRefresh func(*Account) bool + onRefresh func() + onRefreshContext func(context.Context) + delay time.Duration } func (e *refreshAPIExecutorStub) CanRefresh(account *Account) bool { @@ -129,7 +173,7 @@ func (e *refreshAPIExecutorStub) NeedsRefresh(_ *Account, _ time.Duration) bool return e.needsRefresh } -func (e *refreshAPIExecutorStub) Refresh(_ context.Context, _ *Account) (map[string]any, error) { +func (e *refreshAPIExecutorStub) Refresh(ctx context.Context, _ *Account) (map[string]any, error) { e.refreshCalls++ if e.delay > 0 { time.Sleep(e.delay) @@ -137,6 +181,9 @@ func (e *refreshAPIExecutorStub) Refresh(_ context.Context, _ *Account) (map[str if e.onRefresh != nil { e.onRefresh() } + if e.onRefreshContext != nil { + e.onRefreshContext(ctx) + } if e.err != nil { return nil, e.err } @@ -652,6 +699,220 @@ func TestRefreshIfNeeded_LateSuccessAfterDeadlineDoesNotPersist(t *testing.T) { require.Zero(t, repo.updateCredentialsCalls, "late credentials must not cross the unified API persistence boundary") } +type openAIRotationClientStub struct { + openaiOAuthClientRefreshStub + rotationCalls int +} + +func (c *openAIRotationClientStub) RefreshTokenWithClientID(context.Context, string, string, string) (*openai.TokenResponse, error) { + c.rotationCalls++ + return &openai.TokenResponse{ + AccessToken: "rotated-access", RefreshToken: "rotated-refresh", ExpiresIn: 3600, + }, nil +} + +func TestRefreshIfNeeded_OpenAIEnrichmentTimeoutKeepsRotatedCredentials(t *testing.T) { + account := openAIRefreshTestAccount() + account.Credentials["expires_at"] = time.Now().Add(-time.Minute).UTC().Format(time.RFC3339) + repo := &refreshAPIAccountRepo{account: account, respectReadContext: true} + client := &openAIRotationClientStub{} + oauthService := NewOpenAIOAuthService(nil, client) + defer oauthService.Stop() + privacyCalls := 0 + oauthService.SetPrivacyClientFactory(func(string) (*req.Client, error) { + return req.C().WrapRoundTripFunc(func(req.RoundTripper) req.RoundTripFunc { + return func(request *req.Request) (*req.Response, error) { + privacyCalls++ + <-request.Context().Done() + return nil, request.Context().Err() + } + }), nil + }) + ctx, cancel := context.WithTimeout(context.Background(), 20*time.Millisecond) + defer cancel() + executor := NewOpenAITokenRefresher(oauthService, repo) + + result, err := NewOAuthRefreshAPI(repo, nil).RefreshIfNeeded(ctx, account, executor, time.Hour) + + require.NoError(t, err) + require.ErrorIs(t, ctx.Err(), context.DeadlineExceeded) + require.Positive(t, privacyCalls, "optional enrichment must be the operation that exhausts the context") + require.Equal(t, 1, client.rotationCalls) + require.True(t, result.Refreshed) + require.Equal(t, "rotated-refresh", result.Account.GetOpenAIRefreshToken()) + require.Equal(t, "rotated-refresh", repo.account.GetOpenAIRefreshToken()) + require.Equal(t, 1, repo.openAISuccessCASCalls) + require.NoError(t, repo.openAIPersistCtxErr) +} + +func TestRefreshIfNeeded_OpenAILockLeaseReservesPersistenceBudget(t *testing.T) { + account := openAIRefreshTestAccount() + repo := &refreshAPIAccountRepo{account: account} + cache := &refreshAPICacheStub{lockResult: true} + var executorBudget time.Duration + executor := &refreshAPIExecutorStub{ + needsRefresh: true, + credentials: map[string]any{"access_token": "rotated-access", "refresh_token": "rotated-refresh"}, + onRefreshContext: func(ctx context.Context) { + deadline, ok := ctx.Deadline() + require.True(t, ok) + executorBudget = time.Until(deadline) + }, + } + + _, err := NewOAuthRefreshAPI(repo, cache).RefreshIfNeeded(context.Background(), account, executor, time.Hour) + + require.NoError(t, err) + require.Positive(t, executorBudget) + require.LessOrEqual(t, executorBudget, 41*time.Second, "60-second lease must reserve 19 seconds for persistence and cleanup") + require.Equal(t, 1, executor.refreshCalls) + require.Equal(t, 1, cache.releaseCalls) +} + +func TestRefreshIfNeeded_OpenAIShortLockLeaseDoesNotConsumeRefreshToken(t *testing.T) { + for _, lease := range []time.Duration{time.Second, 19 * time.Second} { + t.Run(lease.String(), func(t *testing.T) { + account := openAIRefreshTestAccount() + repo := &refreshAPIAccountRepo{account: account} + cache := &refreshAPICacheStub{lockResult: true} + executor := &refreshAPIExecutorStub{ + needsRefresh: true, + credentials: map[string]any{"access_token": "rotated-access", "refresh_token": "rotated-refresh"}, + } + + _, err := NewOAuthRefreshAPI(repo, cache, lease).RefreshIfNeeded(context.Background(), account, executor, time.Hour) + + var configuration *providerConfigurationRefreshError + require.ErrorAs(t, err, &configuration) + require.Zero(t, executor.refreshCalls) + require.Zero(t, repo.openAISuccessCASCalls) + require.Equal(t, "old-refresh", repo.account.GetOpenAIRefreshToken()) + require.Equal(t, 1, cache.releaseCalls) + }) + } +} + +func TestRefreshIfNeeded_OpenAILateSuccessPersistsWithBoundedContext(t *testing.T) { + for _, cancellation := range []string{"deadline", "parent cancellation"} { + t.Run(cancellation, func(t *testing.T) { + account := openAIRefreshTestAccount() + expected := shallowCopyMap(account.Credentials) + repo := &refreshAPIAccountRepo{account: account, respectReadContext: true} + cache := &refreshAPICacheStub{lockResult: true} + ctx, cancel := context.WithCancel(context.Background()) + if cancellation == "deadline" { + cancel() + ctx, cancel = context.WithTimeout(context.Background(), 10*time.Millisecond) + } + defer cancel() + executor := &refreshAPIExecutorStub{ + needsRefresh: true, + credentials: map[string]any{"access_token": "rotated-access", "refresh_token": "rotated-refresh"}, + onRefresh: func() { + if cancellation == "parent cancellation" { + cancel() + } + <-ctx.Done() + }, + } + + result, err := NewOAuthRefreshAPI(repo, cache).RefreshIfNeeded(ctx, account, executor, time.Hour) + + require.NoError(t, err) + require.True(t, result.Refreshed) + require.Equal(t, "rotated-refresh", result.Account.GetOpenAIRefreshToken()) + require.Equal(t, "rotated-refresh", repo.account.GetOpenAIRefreshToken()) + require.Equal(t, expected, repo.lastExpectedCredentials) + require.Equal(t, 1, executor.refreshCalls) + require.Equal(t, 1, repo.openAISuccessCASCalls) + require.NoError(t, repo.openAIPersistCtxErr) + require.False(t, repo.openAIPersistDeadline.IsZero(), "detached persistence must remain bounded") + require.LessOrEqual(t, time.Until(repo.openAIPersistDeadline), 10*time.Second) + require.Equal(t, 1, cache.releaseCalls) + require.NoError(t, cache.releaseCtxErr) + }) + } +} + +func openAIRefreshTestAccount() *Account { + return &Account{ + ID: 154, Platform: PlatformOpenAI, Type: AccountTypeOAuth, Status: StatusActive, + Credentials: map[string]any{ + "access_token": "old-access", "refresh_token": "old-refresh", "_token_version": int64(1), + }, + } +} + +func TestRefreshIfNeeded_OpenAICASKeepsConcurrentReauthorization(t *testing.T) { + account := openAIRefreshTestAccount() + expected := shallowCopyMap(account.Credentials) + repo := &refreshAPIAccountRepo{account: account} + repo.beforeSuccessCAS = func(repo *refreshAPIAccountRepo) { + repo.account.Credentials = map[string]any{ + "access_token": "reauthorized-access", "refresh_token": "reauthorized-refresh", "_token_version": int64(2), + } + } + executor := &refreshAPIExecutorStub{ + needsRefresh: true, + credentials: map[string]any{"access_token": "rotated-access", "refresh_token": "rotated-refresh"}, + } + + result, err := NewOAuthRefreshAPI(repo, nil).RefreshIfNeeded(context.Background(), account, executor, time.Hour) + + require.NoError(t, err) + require.False(t, result.Refreshed) + require.Equal(t, "reauthorized-refresh", result.Account.GetOpenAIRefreshToken()) + require.Equal(t, expected, repo.lastExpectedCredentials) + require.Zero(t, repo.updateCalls) +} + +func TestRefreshIfNeeded_OpenAIPersistenceFailureContainsProvider(t *testing.T) { + for _, failure := range []string{"CAS write", "durable reread"} { + t.Run(failure, func(t *testing.T) { + account := openAIRefreshTestAccount() + repo := &refreshAPIAccountRepo{account: account} + if failure == "CAS write" { + repo.updateErr = errors.New("database unavailable") + } else { + repo.getByIDErrAfterCall = 2 + repo.getByIDErrAfterCallErr = errors.New("database reread unavailable") + } + executor := &refreshAPIExecutorStub{ + needsRefresh: true, + credentials: map[string]any{"access_token": "rotated-access", "refresh_token": "rotated-refresh"}, + } + + _, err := NewOAuthRefreshAPI(repo, nil).RefreshIfNeeded(context.Background(), account, executor, time.Hour) + + var containment *providerCycleContainmentRefreshError + require.ErrorAs(t, err, &containment) + require.Equal(t, 1, executor.refreshCalls) + require.Equal(t, 1, repo.openAISuccessCASCalls) + if failure == "CAS write" { + require.Equal(t, "old-refresh", account.GetOpenAIRefreshToken(), "failed persistence must not publish in-memory credentials") + } + }) + } +} + +func TestRefreshIfNeeded_OpenAICanceledWithoutSuccessfulCredentialsDoesNotPersist(t *testing.T) { + for _, refreshErr := range []error{nil, errors.New("token endpoint failed")} { + t.Run(fmt.Sprint(refreshErr), func(t *testing.T) { + account := openAIRefreshTestAccount() + repo := &refreshAPIAccountRepo{account: account} + ctx, cancel := context.WithCancel(context.Background()) + defer cancel() + executor := &refreshAPIExecutorStub{needsRefresh: true, err: refreshErr, onRefresh: cancel} + + _, err := NewOAuthRefreshAPI(repo, nil).RefreshIfNeeded(ctx, account, executor, time.Hour) + + require.Error(t, err) + require.Zero(t, repo.openAISuccessCASCalls) + require.Zero(t, repo.updateCalls) + }) + } +} + func TestRefreshIfNeeded_NilCredentials(t *testing.T) { account := &Account{ID: 9, Platform: PlatformGemini, Type: AccountTypeOAuth, Status: StatusActive} repo := &refreshAPIAccountRepo{account: account} diff --git a/backend/internal/service/token_refresh_service.go b/backend/internal/service/token_refresh_service.go index bbf1e8655e..0e3b767c18 100644 --- a/backend/internal/service/token_refresh_service.go +++ b/backend/internal/service/token_refresh_service.go @@ -894,6 +894,7 @@ func (s *TokenRefreshService) refreshWithRetryWithRateGate( } } else { // 降级:直接调用 refresher(兼容旧路径) + attemptedAccount := snapshotOAuthRefreshAccount(account) releaseRate := func() {} if acquireRate != nil { releaseRate, err = acquireRate(attemptCtx) @@ -905,7 +906,17 @@ func (s *TokenRefreshService) refreshWithRetryWithRateGate( releaseRate() } attemptTimedOut := errors.Is(attemptCtx.Err(), context.DeadlineExceeded) && ctx.Err() == nil - if err == nil && newCredentials != nil && !attemptTimedOut { + if err == nil && hasOpenAIRefreshCredentials(attemptedAccount, newCredentials) { + var durableAccount *Account + durableAccount, credentialsPersisted, err = persistOpenAIRefreshCredentials(attemptCtx, s.accountRepo, attemptedAccount, newCredentials) + if err == nil { + account = durableAccount + if !credentialsPersisted { + err = errRefreshSkipped + shortCircuit = true + } + } + } else if err == nil && newCredentials != nil && !attemptTimedOut { newCredentials["_token_version"] = time.Now().UnixMilli() if saveErr := persistAccountCredentials(attemptCtx, s.accountRepo, account, newCredentials); saveErr != nil { err = fmt.Errorf("failed to save credentials: %w", saveErr) @@ -918,7 +929,7 @@ func (s *TokenRefreshService) refreshWithRetryWithRateGate( cancelAttempt() releaseAttempt() persistedAfterAttemptDeadline := attemptTimedOut && credentialsPersisted && err == nil - if attemptTimedOut && !persistedAfterAttemptDeadline && !isProviderScopedTerminalRefreshError(err) { + if attemptTimedOut && !shortCircuit && !persistedAfterAttemptDeadline && !isProviderScopedTerminalRefreshError(err) { cause := err if cause == nil { cause = context.DeadlineExceeded diff --git a/backend/internal/service/token_refresh_service_candidates_test.go b/backend/internal/service/token_refresh_service_candidates_test.go index ba382bd2dc..46b3dacc53 100644 --- a/backend/internal/service/token_refresh_service_candidates_test.go +++ b/backend/internal/service/token_refresh_service_candidates_test.go @@ -3,6 +3,7 @@ package service import ( "context" "errors" + "reflect" "strings" "sync" "testing" @@ -69,6 +70,17 @@ func (r *tokenRefreshCandidateRepo) ListOAuthRefreshCandidatePage(_ context.Cont return page, nil } +func (r *tokenRefreshCandidateRepo) GetByID(_ context.Context, id int64) (*Account, error) { + r.mu.Lock() + defer r.mu.Unlock() + for i := range r.accounts { + if r.accounts[i].ID == id { + return snapshotOAuthRefreshAccount(&r.accounts[i]), nil + } + } + return nil, errors.New("account not found") +} + func (r *tokenRefreshCandidateRepo) UpdateCredentials(_ context.Context, id int64, _ map[string]any) error { r.mu.Lock() defer r.mu.Unlock() @@ -76,6 +88,32 @@ func (r *tokenRefreshCandidateRepo) UpdateCredentials(_ context.Context, id int6 return nil } +func (r *tokenRefreshCandidateRepo) UpdateOpenAIOAuthCredentialsIfUnchanged( + _ context.Context, + id int64, + expectedCredentials map[string]any, + expectedProxyID *int64, + credentials map[string]any, +) (bool, error) { + r.mu.Lock() + defer r.mu.Unlock() + for i := range r.accounts { + account := &r.accounts[i] + if account.ID != id { + continue + } + if account.Platform != PlatformOpenAI || account.Type != AccountTypeOAuth || + account.IsCredentialShadow() || !reflect.DeepEqual(account.Credentials, expectedCredentials) || + !reflect.DeepEqual(account.ProxyID, expectedProxyID) { + return false, nil + } + account.Credentials = shallowCopyMap(credentials) + r.updatedCredentialIDs = append(r.updatedCredentialIDs, id) + return true, nil + } + return false, nil +} + func (r *tokenRefreshCandidateRepo) SetError(context.Context, int64, string) error { r.mu.Lock() defer r.mu.Unlock() diff --git a/backend/internal/service/token_refresh_service_test.go b/backend/internal/service/token_refresh_service_test.go index 75a84bfbcc..37911d8ac7 100644 --- a/backend/internal/service/token_refresh_service_test.go +++ b/backend/internal/service/token_refresh_service_test.go @@ -5,6 +5,7 @@ package service import ( "context" "errors" + "fmt" "reflect" "testing" "time" @@ -46,6 +47,9 @@ type tokenRefreshAccountRepo struct { setErrorErr error setTempUnschedErr error beforeConditionalState func() + openAISuccessCASCalls int + openAIPersistCtxErr error + openAIPersistDeadline time.Time } func (r *tokenRefreshAccountRepo) Update(ctx context.Context, account *Account) error { @@ -252,6 +256,35 @@ func (r *tokenRefreshAccountRepo) UpdateGrokOAuthCredentialsIfUnchanged( return true, nil } +func (r *tokenRefreshAccountRepo) UpdateOpenAIOAuthCredentialsIfUnchanged( + ctx context.Context, + id int64, + expectedCredentials map[string]any, + expectedProxyID *int64, + credentials map[string]any, +) (bool, error) { + r.openAISuccessCASCalls++ + r.openAIPersistCtxErr = ctx.Err() + r.openAIPersistDeadline, _ = ctx.Deadline() + if err := ctx.Err(); err != nil { + return false, err + } + if r.conditionalSuccessErr != nil { + return false, r.conditionalSuccessErr + } + account := r.accountsByID[id] + if account == nil || account.Platform != PlatformOpenAI || account.Type != AccountTypeOAuth || + account.IsCredentialShadow() || !reflect.DeepEqual(account.Credentials, expectedCredentials) || + !reflect.DeepEqual(account.ProxyID, expectedProxyID) { + return false, nil + } + r.updateCalls++ + r.updateCredentialsCalls++ + account.Credentials = shallowCopyMap(credentials) + r.lastAccount = account + return true, nil +} + func (r *tokenRefreshAccountRepo) SetGrokOAuthRefreshTempUnschedulableIfCredentialsUnchanged( _ context.Context, id int64, @@ -1210,6 +1243,124 @@ func TestTokenRefreshService_PersistedSuccessCrossingAttemptDeadlineStaysSuccess require.Equal(t, 1, scheduler.setAccountCalls) } +func TestTokenRefreshService_OpenAIRotationSurvivesAttemptDeadline(t *testing.T) { + for _, unified := range []bool{false, true} { + name := "fallback" + if unified { + name = "unified" + } + t.Run(name, func(t *testing.T) { + account := openAIRefreshTestAccount() + repo := &tokenRefreshAccountRepo{snapshotReads: true, respectReadContext: true} + repo.accountsByID = map[int64]*Account{account.ID: account} + invalidator := &tokenCacheInvalidatorStub{} + svc := &TokenRefreshService{ + accountRepo: repo, + cfg: &config.TokenRefreshConfig{MaxRetries: 3}, + refreshPolicy: DefaultBackgroundRefreshPolicy(), + cacheInvalidator: invalidator, + attemptTimeoutOverride: 10 * time.Millisecond, + } + if unified { + svc.refreshAPI = NewOAuthRefreshAPI(repo, nil) + } + executor := &refreshAPIExecutorStub{ + needsRefresh: true, + credentials: map[string]any{"access_token": "rotated-access", "refresh_token": "rotated-refresh"}, + onRefreshContext: func(ctx context.Context) { <-ctx.Done() }, + } + + err := svc.refreshWithRetry(context.Background(), account, executor, executor, time.Hour) + + require.NoError(t, err) + require.Equal(t, 1, executor.refreshCalls, "received rotation must not be retried after the attempt deadline") + require.Equal(t, 1, repo.openAISuccessCASCalls) + require.NoError(t, repo.openAIPersistCtxErr) + require.False(t, repo.openAIPersistDeadline.IsZero()) + require.LessOrEqual(t, time.Until(repo.openAIPersistDeadline), 10*time.Second) + require.Equal(t, "rotated-refresh", repo.accountsByID[account.ID].GetOpenAIRefreshToken()) + require.Equal(t, 1, invalidator.calls) + require.NoError(t, invalidator.ctxErr) + require.Zero(t, repo.setErrorCalls) + require.Zero(t, repo.setTempUnschedCalls) + }) + } +} + +func TestTokenRefreshService_OpenAIPersistenceFailureDoesNotRetryUpstream(t *testing.T) { + for _, unified := range []bool{false, true} { + for _, expireAttempt := range []bool{false, true} { + name := fmt.Sprintf("unified=%t/expired=%t", unified, expireAttempt) + t.Run(name, func(t *testing.T) { + account := openAIRefreshTestAccount() + repo := &tokenRefreshAccountRepo{snapshotReads: true, respectReadContext: true, conditionalSuccessErr: errors.New("database unavailable")} + repo.accountsByID = map[int64]*Account{account.ID: account} + svc := &TokenRefreshService{ + accountRepo: repo, + cfg: &config.TokenRefreshConfig{MaxRetries: 3}, + refreshPolicy: DefaultBackgroundRefreshPolicy(), + attemptTimeoutOverride: 10 * time.Millisecond, + } + if unified { + svc.refreshAPI = NewOAuthRefreshAPI(repo, nil) + } + executor := &refreshAPIExecutorStub{ + needsRefresh: true, + credentials: map[string]any{"access_token": "rotated-access", "refresh_token": "rotated-refresh"}, + } + if expireAttempt { + executor.onRefreshContext = func(ctx context.Context) { <-ctx.Done() } + } + + err := svc.refreshWithRetry(context.Background(), account, executor, executor, time.Hour) + + var containment *providerCycleContainmentRefreshError + require.ErrorAs(t, err, &containment) + require.Equal(t, 1, executor.refreshCalls, "a failed save must not reuse the consumed refresh token") + require.Equal(t, 1, repo.openAISuccessCASCalls) + require.NoError(t, repo.openAIPersistCtxErr) + require.Equal(t, "old-refresh", account.GetOpenAIRefreshToken()) + require.Zero(t, repo.setErrorCalls) + require.Zero(t, repo.setTempUnschedCalls) + }) + } + } +} + +func TestTokenRefreshService_OpenAIParentCancellationStillPersists(t *testing.T) { + for _, unified := range []bool{false, true} { + t.Run(fmt.Sprintf("unified=%t", unified), func(t *testing.T) { + account := openAIRefreshTestAccount() + repo := &tokenRefreshAccountRepo{snapshotReads: true, respectReadContext: true} + repo.accountsByID = map[int64]*Account{account.ID: account} + invalidator := &tokenCacheInvalidatorStub{} + svc := &TokenRefreshService{ + accountRepo: repo, cfg: &config.TokenRefreshConfig{MaxRetries: 3}, + refreshPolicy: DefaultBackgroundRefreshPolicy(), cacheInvalidator: invalidator, + } + if unified { + svc.refreshAPI = NewOAuthRefreshAPI(repo, nil) + } + ctx, cancel := context.WithCancel(context.Background()) + defer cancel() + executor := &refreshAPIExecutorStub{ + needsRefresh: true, onRefresh: cancel, + credentials: map[string]any{"access_token": "rotated-access", "refresh_token": "rotated-refresh"}, + } + + err := svc.refreshWithRetry(ctx, account, executor, executor, time.Hour) + + require.ErrorIs(t, err, context.Canceled) + require.Equal(t, 1, executor.refreshCalls) + require.Equal(t, 1, repo.openAISuccessCASCalls) + require.NoError(t, repo.openAIPersistCtxErr) + require.Equal(t, "rotated-refresh", repo.accountsByID[account.ID].GetOpenAIRefreshToken()) + require.Equal(t, 1, invalidator.calls) + require.NoError(t, invalidator.ctxErr) + }) + } +} + func TestPathA_ParentCancellationAfterPersistStillSynchronizesCacheState(t *testing.T) { account := &Account{ ID: 109, From 049e0f41b863b0e81527de088fb144db0a60e5d3 Mon Sep 17 00:00:00 2001 From: lishuangqiang <142634204+lishuangqiang@users.noreply.github.com> Date: Tue, 17 Nov 2026 00:10:26 +0800 Subject: [PATCH 35/85] perf(openai): stop copying the whole input array when stripping namespaces stripOpenAIResponsesInputNamespaces runs on every OpenAI OAuth / API-key HTTP forward attempt. Its entry check only proves that the *body* contains a namespace literal, and Codex clients advertise the image_gen namespace tool on ordinary requests, so the check passes for most traffic and the function runs even when there is nothing to strip. Three avoidable copies showed up in that path: 1. gjson.GetBytes(body, "input") materialises the input array. On a 1MiB body that is a 1MiB allocation on every request, including the no-op case. Use the zero-copy parse view (parseRawJSONView) instead. 2. The rewrite built the new input array in a buffer and then handed it to sjson.SetRawBytes, which allocates a second full body copy. Assemble the output directly instead: prefix + rewritten array + suffix in one buffer sized to the body. 3. sjson.DeleteBytes([]byte(item.Raw), ...) converted each changed item to a byte slice first. Use the string form. hasOpenAIResponsesNamespaceToolDeclaration reads input the same way and gets the same treatment; it runs for API-key accounts on every request. Benchmark (Apple M5 Pro, -benchmem), legacy = the previous implementation: 1MiB tools_only 545us / 1056768 B / 1 alloc -> 495us / 0 B / 0 alloc 1MiB strip_first 882us / 3170624 B / 8 allocs -> 548us / 1056936 B / 4 1MiB strip_last 841us / 3170624 B / 8 allocs -> 556us / 1056928 B / 4 8MiB strip_first 5.95ms / 25190720 B / 8 -> 4.30ms / 8396960 B / 4 So the no-op path stops allocating entirely and the rewriting path copies one body instead of three. Behaviour is unchanged for valid JSON: equivalence tests keep the previous implementation as legacy* and compare output bytes, errors and whether the input slice was returned untouched, across 36 bodies (duplicate keys, escaped keys, nested namespace fields, non-object items, keep-tool-call mode, missing or non-array input) plus 3000 randomized combinations and a fuzz target. One deliberate difference, pinned by a test: on input that is not valid JSON, gjson.GetBytes and gjson.Parse return different spans for the same key, and the new implementation refuses to rewrite an unparseable fragment instead of truncating it. The only caller forwards a body that the handler has already validated, so this path is not reachable in production. --- .../service/openai_responses_namespace.go | 49 ++-- ...enai_responses_namespace_benchmark_test.go | 19 +- ...ai_responses_namespace_equivalence_test.go | 241 ++++++++++++++++++ 3 files changed, 284 insertions(+), 25 deletions(-) create mode 100644 backend/internal/service/openai_responses_namespace_equivalence_test.go diff --git a/backend/internal/service/openai_responses_namespace.go b/backend/internal/service/openai_responses_namespace.go index 3978518ed9..99276eccb4 100644 --- a/backend/internal/service/openai_responses_namespace.go +++ b/backend/internal/service/openai_responses_namespace.go @@ -14,6 +14,11 @@ import ( const openAIResponsesNamespaceNamesContextKey = "openai_responses_namespace_names" +// openAIResponsesNamespaceFieldBytes 是入口预检查用的字面量。带引号可避免匹配到 +// 正文里的普通单词;键写成 unicode 转义时无法字节匹配,那条路径不会进入清理逻辑, +// 与改动前一致。 +var openAIResponsesNamespaceFieldBytes = []byte(`"namespace"`) + // shouldFlattenOpenAIResponsesNamespaces 判定原生 Responses 转发前是否摊平 // Codex namespace 工具。 // @@ -120,6 +125,7 @@ func hasOpenAIResponsesNamespaceToolDeclaration(body []byte) bool { return found } + // 与 stripOpenAIResponsesInputNamespaces 同理:input 可能很大,用零拷贝视图取值。 root := parseRawJSONView(body) if hasNamespaceTool(root.Get("tools")) { return true @@ -163,7 +169,7 @@ func isOpenAIResponsesToolCallItemType(itemType string) bool { } func flattenOpenAIResponsesNamespaces(c *gin.Context, body []byte) ([]byte, error) { - if !bytes.Contains(body, []byte(`"namespace"`)) { + if !bytes.Contains(body, openAIResponsesNamespaceFieldBytes) { return body, nil } var requestBody map[string]any @@ -190,22 +196,28 @@ func flattenOpenAIResponsesNamespaces(c *gin.Context, body []byte) ([]byte, erro // untouched. Rebuilding the input array once keeps this linear for long // histories and avoids decoding JSON numbers through float64. // +// 读取走 parseRawJSONView(零拷贝 string 视图)而不是 gjson.GetBytes:后者会把 +// input 数组物化成一份拷贝,而这个函数在 Codex 流量上几乎每个请求都会进来 +// (tools 里就有 namespace 声明,入口预检查必然放行),未改动时那份拷贝纯属浪费。 +// // keepToolCallNamespaces 保留工具调用项(function_call / custom_tool_call 等)上的 // namespace,让 Codex 调用能按上游要求原样回传;判定见 // shouldKeepOpenAIResponsesToolCallNamespaces。 func stripOpenAIResponsesInputNamespaces(body []byte, keepToolCallNamespaces bool) ([]byte, error) { - if !bytes.Contains(body, []byte(`"namespace"`)) { + if !bytes.Contains(body, openAIResponsesNamespaceFieldBytes) { return body, nil } - // Zero-copy view: input.Raw aliases body and is only read below; the - // rebuilt array is written into a fresh buffer. input := parseRawJSONView(body).Get("input") if !input.IsArray() { return body, nil } + // inputStart/inputEnd 是 input 数组在 body 里的字节区间。 + inputStart := input.Index + inputEnd := inputStart + len(input.Raw) - var rebuilt bytes.Buffer - changed := false + // 输出缓冲只在首次真正改写时分配,容量按整个 body 预留,prefix + 改写后的数组 + + // suffix 一次写完,不再额外走一遍 sjson.SetRawBytes(那会再拷一份完整 body)。 + var out []byte // Offsets below are relative to input.Raw, not the full request body. copyFrom := 0 var stripErr error @@ -214,35 +226,30 @@ func stripOpenAIResponsesInputNamespaces(body []byte, keepToolCallNamespaces boo (keepToolCallNamespaces && isOpenAIResponsesToolCallItemType(item.Get("type").String())) { return true } - itemBody, err := sjson.DeleteBytes([]byte(item.Raw), "namespace") + itemBody, err := sjson.Delete(item.Raw, "namespace") if err != nil { stripErr = err return false } - if !changed { - // Allocate only on the first change; copy unchanged spans without - // traversing their items again or converting them to byte slices. - rebuilt.Grow(len(input.Raw)) - changed = true + if out == nil { + out = make([]byte, 0, len(body)) + out = append(out, body[:inputStart]...) } itemStart := item.Index - input.Index - _, _ = rebuilt.WriteString(input.Raw[copyFrom:itemStart]) - _, _ = rebuilt.Write(itemBody) + out = append(out, input.Raw[copyFrom:itemStart]...) + out = append(out, itemBody...) copyFrom = itemStart + len(item.Raw) return true }) if stripErr != nil { return body, fmt.Errorf("delete OpenAI input namespace: %w", stripErr) } - if !changed { + if out == nil { return body, nil } - _, _ = rebuilt.WriteString(input.Raw[copyFrom:]) - stripped, err := sjson.SetRawBytes(body, "input", rebuilt.Bytes()) - if err != nil { - return body, fmt.Errorf("replace OpenAI input after namespace deletion: %w", err) - } - return stripped, nil + out = append(out, input.Raw[copyFrom:]...) + out = append(out, body[inputEnd:]...) + return out, nil } func setOpenAIResponsesNamespaceNames(c *gin.Context, names map[string]apicompat.ResponsesNamespaceName) { diff --git a/backend/internal/service/openai_responses_namespace_benchmark_test.go b/backend/internal/service/openai_responses_namespace_benchmark_test.go index 9297354b02..7cd84ff966 100644 --- a/backend/internal/service/openai_responses_namespace_benchmark_test.go +++ b/backend/internal/service/openai_responses_namespace_benchmark_test.go @@ -10,7 +10,9 @@ import ( "github.com/tidwall/gjson" ) -func BenchmarkStripOpenAIResponsesInputNamespaces(b *testing.B) { +type stripFunc func(body []byte, keep bool) ([]byte, error) + +func benchmarkStripOpenAIResponsesInputNamespaces(b *testing.B, variant string, fn stripFunc) { for _, size := range []int{1 << 20, 8 << 20} { message := `{"type":"message","content":"` + strings.Repeat("x", size) + `"}` call := `{"type":"function_call","namespace":"files","name":"search"}` @@ -20,15 +22,16 @@ func BenchmarkStripOpenAIResponsesInputNamespaces(b *testing.B) { keep bool stripIndex int }{ + // tools 里带 namespace 声明、input 里没有:Codex 常态,入口预检查必然放行。 {"tools_only", message, false, -1}, {"nested_only", `{"content":{"namespace":"nested"}},` + message, false, -1}, {"keep_calls", call + "," + message, true, -1}, {"strip_first", call + "," + message, false, 0}, {"strip_last", message + "," + call, false, 1}, } { - b.Run(fmt.Sprintf("%s/%dMiB", tc.name, size>>20), func(b *testing.B) { + b.Run(fmt.Sprintf("%s/%s/%dMiB", variant, tc.name, size>>20), func(b *testing.B) { body := []byte(`{"tools":[{"type":"namespace","name":"files","tools":[]}],"input":[` + tc.input + `]}`) - out, err := stripOpenAIResponsesInputNamespaces(body, tc.keep) + out, err := fn(body, tc.keep) if err != nil { b.Fatal(err) } @@ -43,7 +46,7 @@ func BenchmarkStripOpenAIResponsesInputNamespaces(b *testing.B) { b.SetBytes(int64(len(body))) b.ResetTimer() for i := 0; i < b.N; i++ { - out, err = stripOpenAIResponsesInputNamespaces(body, tc.keep) + out, err = fn(body, tc.keep) if err != nil { b.Fatal(err) } @@ -53,3 +56,11 @@ func BenchmarkStripOpenAIResponsesInputNamespaces(b *testing.B) { } } } + +func BenchmarkStripOpenAIResponsesInputNamespaces(b *testing.B) { + benchmarkStripOpenAIResponsesInputNamespaces(b, "current", stripOpenAIResponsesInputNamespaces) +} + +func BenchmarkStripOpenAIResponsesInputNamespacesLegacy(b *testing.B) { + benchmarkStripOpenAIResponsesInputNamespaces(b, "legacy", legacyStripOpenAIResponsesInputNamespaces) +} diff --git a/backend/internal/service/openai_responses_namespace_equivalence_test.go b/backend/internal/service/openai_responses_namespace_equivalence_test.go new file mode 100644 index 0000000000..3e8f0600fe --- /dev/null +++ b/backend/internal/service/openai_responses_namespace_equivalence_test.go @@ -0,0 +1,241 @@ +package service + +import ( + "bytes" + "fmt" + "strings" + "testing" + + "github.com/stretchr/testify/require" + "github.com/tidwall/gjson" + "github.com/tidwall/sjson" +) + +// legacyStripOpenAIResponsesInputNamespaces 是改动前的逐字副本,作为差分基准。 +func legacyStripOpenAIResponsesInputNamespaces(body []byte, keepToolCallNamespaces bool) ([]byte, error) { + if !bytes.Contains(body, []byte(`"namespace"`)) { + return body, nil + } + input := gjson.GetBytes(body, "input") + if !input.IsArray() { + return body, nil + } + + var rebuilt bytes.Buffer + changed := false + copyFrom := 0 + var stripErr error + input.ForEach(func(_, item gjson.Result) bool { + if !item.IsObject() || !item.Get("namespace").Exists() || + (keepToolCallNamespaces && isOpenAIResponsesToolCallItemType(item.Get("type").String())) { + return true + } + itemBody, err := sjson.DeleteBytes([]byte(item.Raw), "namespace") + if err != nil { + stripErr = err + return false + } + if !changed { + rebuilt.Grow(len(input.Raw)) + changed = true + } + itemStart := item.Index - input.Index + _, _ = rebuilt.WriteString(input.Raw[copyFrom:itemStart]) + _, _ = rebuilt.Write(itemBody) + copyFrom = itemStart + len(item.Raw) + return true + }) + if stripErr != nil { + return body, fmt.Errorf("delete OpenAI input namespace: %w", stripErr) + } + if !changed { + return body, nil + } + _, _ = rebuilt.WriteString(input.Raw[copyFrom:]) + stripped, err := sjson.SetRawBytes(body, "input", rebuilt.Bytes()) + if err != nil { + return body, fmt.Errorf("replace OpenAI input after namespace deletion: %w", err) + } + return stripped, nil +} + +type stripSnapshot struct { + err string + output string + unchanged bool // 是否原样返回了传入的 slice(两个实现都应如此) +} + +func stripSnapshotOf(out []byte, err error, body []byte) stripSnapshot { + snap := stripSnapshot{} + if err != nil { + snap.err = err.Error() + } + snap.output = string(out) + if len(out) == len(body) && len(body) > 0 && &out[0] == &body[0] { + snap.unchanged = true + } + if len(out) == 0 && len(body) == 0 { + snap.unchanged = true + } + return snap +} + +func stripBoth(t *testing.T, input string, keep bool) (stripSnapshot, stripSnapshot) { + t.Helper() + legacyBody := []byte(input) + legacyOut, legacyErr := legacyStripOpenAIResponsesInputNamespaces(legacyBody, keep) + + newBody := []byte(input) + newOut, newErr := stripOpenAIResponsesInputNamespaces(newBody, keep) + + return stripSnapshotOf(legacyOut, legacyErr, legacyBody), stripSnapshotOf(newOut, newErr, newBody) +} + +func TestStripOpenAIResponsesInputNamespacesMatchesLegacy(t *testing.T) { + escape := string(rune(92)) + cases := []string{ + ``, + `{}`, + `{"model":"gpt-5.5"}`, + // 无 namespace:入口预检查直接返回 + `{"input":[{"type":"message","content":"hi"}]}`, + // namespace 只在 tools 里(Codex 常态) + `{"tools":[{"type":"namespace","name":"image_gen"}],"input":[{"type":"message","content":"hi"}]}`, + // namespace 嵌套在 item 内容里,不是数组项的直接字段 + `{"input":[{"content":{"namespace":"nested"}}]}`, + `{"tools":[{"type":"namespace"}],"input":[{"content":{"namespace":"nested"}}]}`, + // 真正要改写 + `{"input":[{"type":"function_call","namespace":"files","name":"search"}]}`, + `{"input":[{"namespace":"files"},{"type":"message","content":"hi"}]}`, + `{"input":[{"type":"message","content":"hi"},{"namespace":"files"}]}`, + `{"input":[{"namespace":"a"},{"namespace":"b"},{"namespace":"c"}]}`, + `{"input":[{"namespace":null}]}`, + `{"input":[{"namespace":["x"]}]}`, + `{"input":[{"namespace":"files","namespace":"dup"}]}`, + // 工具调用项在 keep 模式下的区分 + `{"input":[{"type":"function_call","namespace":"files"}]}`, + `{"input":[{"type":"custom_tool_call","namespace":"files"}]}`, + `{"input":[{"type":"mcp_tool_call","namespace":"files"}]}`, + `{"input":[{"type":"tool_call","namespace":"files"}]}`, + `{"input":[{"type":"message","namespace":"files"}]}`, + `{"input":[{"type":"FUNCTION_CALL","namespace":"files"}]}`, + // 非对象 item + `{"input":["x",null,{"namespace":"files"},42]}`, + // input 不是数组 / 缺失 + `{"input":{"namespace":"x"}}`, + `{"input":"namespace"}`, + `{"input":null}`, + `{"namespace":"top"}`, + // 重复 input 键:两边都取第一个 + `{"input":[{"namespace":"first"}],"input":[{"namespace":"second"}]}`, + `{"input":[],"input":[{"namespace":"second"}]}`, + // 转义的键与值 + `{"` + escape + `u0069nput":[{"namespace":"files"}]}`, + `{"input":[{"namespace":"fi` + escape + `u006ces"}]}`, + // 大内容与 unicode + `{"input":[{"namespace":"files","content":"` + strings.Repeat("x", 4096) + `"},{"type":"message","content":"中文 😀"}]}`, + // item 内部同时有直接 namespace 与嵌套 namespace + `{"input":[{"namespace":"files","content":{"namespace":"nested"}}]}`, + // 非法 JSON + `{"input":[{"namespace":"files"}]`, + `{"input":[{"namespace":"files"},`, + // 根不是对象 + `[{"namespace":"files"}]`, + `"namespace"`, + } + + for _, tc := range cases { + for _, keep := range []bool{false, true} { + t.Run(fmt.Sprintf("%s/keep=%v", truncateForName(tc), keep), func(t *testing.T) { + want, got := stripBoth(t, tc, keep) + if !gjson.ValidBytes([]byte(tc)) { + // 畸形输入上 gjson.GetBytes 与 gjson.Parse 返回的区间不同: + // 前者会一路扫到结尾,后者遇到非法结构就停。本实现走后者,因此在 + // 无法解析的片段上不改写(更保守),只比较错误。 + require.Equal(t, want.err, got.err, "input=%q keep=%v", tc, keep) + return + } + require.Equal(t, want, got, "input=%q keep=%v", tc, keep) + }) + } + } +} + +func truncateForName(s string) string { + if len(s) > 40 { + return s[:40] + "..." + } + if s == "" { + return "empty" + } + return s +} + +// 组合随机:多个 item、namespace 位置随机、keep 随机。 +func TestStripOpenAIResponsesInputNamespacesMatchesLegacyRandomized(t *testing.T) { + items := []string{ + `{"type":"message","content":"hi"}`, + `{"namespace":"files"}`, + `{"type":"function_call","namespace":"files","name":"search"}`, + `{"type":"custom_tool_call","namespace":"files"}`, + `{"content":{"namespace":"nested"}}`, + `{"namespace":"files","content":"` + strings.Repeat("y", 200) + `"}`, + `{"namespace":null}`, + `"literal"`, + `42`, + `null`, + } + prefixes := []string{ + `{"input":[`, + `{"tools":[{"type":"namespace"}],"input":[`, + `{"metadata":{"user_id":"u"},"input":[`, + } + + seed := uint64(0x243f6a8885a308d3) + next := func() uint64 { + seed ^= seed << 13 + seed ^= seed >> 7 + seed ^= seed << 17 + return seed + } + + for i := 0; i < 3000; i++ { + n := int(next()%5) + 1 + parts := make([]string, 0, n) + for j := 0; j < n; j++ { + parts = append(parts, items[int(next()%uint64(len(items)))]) + } + body := prefixes[int(next()%uint64(len(prefixes)))] + strings.Join(parts, ",") + `]}` + keep := next()%2 == 0 + + want, got := stripBoth(t, body, keep) + require.Equal(t, want, got, "iteration=%d keep=%v body=%s", i, keep, body) + } +} + +// 畸形输入的行为差异有明确用例固定,避免后续误改: +func TestStripOpenAIResponsesInputNamespacesMalformedRootIsConservative(t *testing.T) { + const malformed = `0{"input"[{ "namespace"00` + out, err := stripOpenAIResponsesInputNamespaces([]byte(malformed), true) + require.NoError(t, err) + require.Equal(t, malformed, string(out), "改写在无法解析的片段上必须放弃") +} + +func FuzzStripOpenAIResponsesInputNamespaces(f *testing.F) { + f.Add([]byte(`{"input":[{"namespace":"files"}]}`), false) + f.Add([]byte(`{"tools":[{"type":"namespace"}],"input":[{"type":"message"}]}`), true) + f.Add([]byte(`{"input":[{"type":"function_call","namespace":"files"}]}`), true) + f.Add([]byte(`{"input":"namespace"}`), false) + f.Fuzz(func(t *testing.T, body []byte, keep bool) { + legacyBody := append([]byte(nil), body...) + newBody := append([]byte(nil), body...) + legacyOut, legacyErr := legacyStripOpenAIResponsesInputNamespaces(legacyBody, keep) + newOut, newErr := stripOpenAIResponsesInputNamespaces(newBody, keep) + require.Equal(t, fmt.Sprint(legacyErr), fmt.Sprint(newErr), "body=%q", body) + if legacyErr != nil || !gjson.ValidBytes(body) { + // 畸形输入两个 gjson API 的取值区间不同,见表驱动测试里的说明。 + return + } + require.Equal(t, string(legacyOut), string(newOut), "body=%q keep=%v", body, keep) + }) +} From 09840b8027a308b46ed62268151d6de71877e09f Mon Sep 17 00:00:00 2001 From: lishuangqiang <142634204+lishuangqiang@users.noreply.github.com> Date: Tue, 17 Nov 2026 00:14:52 +0800 Subject: [PATCH 36/85] test(gateway): stop ignoring strings.Builder errors in the scan benchmark The benchmark body builder discarded the results of strings.Builder.WriteString, which errcheck rejects (the repo enables errcheck with check-blank off, so a plain call is flagged even though Builder never returns an error). Route the writes through one helper that assigns the result. --- .../gateway_request_scan_benchmark_test.go | 34 ++++++++++--------- 1 file changed, 18 insertions(+), 16 deletions(-) diff --git a/backend/internal/service/gateway_request_scan_benchmark_test.go b/backend/internal/service/gateway_request_scan_benchmark_test.go index 82e5634ccc..f74bf09937 100644 --- a/backend/internal/service/gateway_request_scan_benchmark_test.go +++ b/backend/internal/service/gateway_request_scan_benchmark_test.go @@ -11,35 +11,37 @@ import ( func buildGatewayRequestBenchmarkBody(targetBytes int, anthropic bool) []byte { var sb strings.Builder sb.Grow(targetBytes + 1024) + // strings.Builder.WriteString 的 error 恒为 nil,errcheck 不接受裸忽略,收口在这里。 + write := func(s string) { _, _ = sb.WriteString(s) } item := `{"type":"message","role":"user","content":[{"type":"input_text","text":"` + strings.Repeat("x", 4000) + `"}]}` if anthropic { - sb.WriteString(`{"model":"claude-sonnet-5-5","stream":true,"system":[{"type":"text","text":"`) - sb.WriteString(strings.Repeat("z", targetBytes/8)) - sb.WriteString(`"}],"tools":[{"name":"shell","description":"`) - sb.WriteString(strings.Repeat("y", targetBytes/16)) - sb.WriteString(`"}],"messages":[`) + write(`{"model":"claude-sonnet-5-5","stream":true,"system":[{"type":"text","text":"`) + write(strings.Repeat("z", targetBytes/8)) + write(`"}],"tools":[{"name":"shell","description":"`) + write(strings.Repeat("y", targetBytes/16)) + write(`"}],"messages":[`) msg := `{"role":"user","content":[{"type":"text","text":"` + strings.Repeat("x", 4000) + `"}]}` for i := 0; sb.Len() < targetBytes; i++ { if i > 0 { - sb.WriteString(`,`) + write(`,`) } - sb.WriteString(msg) + write(msg) } - sb.WriteString(`]}`) + write(`]}`) return []byte(sb.String()) } - sb.WriteString(`{"model":"gpt-5.5","stream":true,"instructions":"`) - sb.WriteString(strings.Repeat("z", targetBytes/8)) - sb.WriteString(`","tools":[{"type":"function","name":"shell","description":"`) - sb.WriteString(strings.Repeat("y", targetBytes/16)) - sb.WriteString(`"}],"input":[`) + write(`{"model":"gpt-5.5","stream":true,"instructions":"`) + write(strings.Repeat("z", targetBytes/8)) + write(`","tools":[{"type":"function","name":"shell","description":"`) + write(strings.Repeat("y", targetBytes/16)) + write(`"}],"input":[`) for i := 0; sb.Len() < targetBytes; i++ { if i > 0 { - sb.WriteString(`,`) + write(`,`) } - sb.WriteString(item) + write(item) } - sb.WriteString(`]}`) + write(`]}`) return []byte(sb.String()) } From 596696356e2fb4a62d3e4797dc5cdcf71553cfdb Mon Sep 17 00:00:00 2001 From: lishuangqiang <142634204+lishuangqiang@users.noreply.github.com> Date: Tue, 17 Nov 2026 00:29:48 +0800 Subject: [PATCH 37/85] style(openai): gofmt the namespace strip equivalence test --- .../service/openai_responses_namespace_equivalence_test.go | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/backend/internal/service/openai_responses_namespace_equivalence_test.go b/backend/internal/service/openai_responses_namespace_equivalence_test.go index 3e8f0600fe..52f766d7da 100644 --- a/backend/internal/service/openai_responses_namespace_equivalence_test.go +++ b/backend/internal/service/openai_responses_namespace_equivalence_test.go @@ -60,8 +60,8 @@ func legacyStripOpenAIResponsesInputNamespaces(body []byte, keepToolCallNamespac } type stripSnapshot struct { - err string - output string + err string + output string unchanged bool // 是否原样返回了传入的 slice(两个实现都应如此) } From e7c587e14de55c286edc816fda2f18e550d58492 Mon Sep 17 00:00:00 2001 From: lishuangqiang <142634204+lishuangqiang@users.noreply.github.com> Date: Tue, 17 Nov 2026 01:39:42 +0800 Subject: [PATCH 38/85] perf(openai): stop walking every request body in the tool-schema sanitizer sanitizeOpenAIResponsesToolSchemasForPlatform runs on every OpenAI Responses forward attempt, on WS normalization and on /v1/messages conversion, and its two passes both ran far more often than they need to: * the regex-pattern pass was gated on "the body contains '('", and tool descriptions, code samples and user messages contain parentheses constantly, so the gate let essentially everything through; * the parameter-type pass had no gate at all and ran for OpenAI, Anthropic, Grok and every CN platform. A 1MiB Codex request therefore walked its body twice with the hand-written parser before reaching the upstream. Profiling put 92% of that in parseString, which scanned strings byte by byte while long content strings are most of a request body. Changes: 1. parseString skips the plain run of a string eight bytes at a time (SWAR), stopping only on '"', '\\' or a control byte - exactly the three bytes it has to stop at. 2.2 GB/s -> 10.5 GB/s. 2. An input item is no longer walked twice. The type probe walked the whole item and then the item was walked again just to skip it; the probe's end position is now reused. Messages dominate input history. 3. json.Valid(body) only runs when the walk actually produced an edit. With no edits the body is returned untouched, so that second full-body validation proved nothing; patches are still validated after they are applied. 4. Both gates are now necessary conditions that can be proven complete. hasUnsupportedOpenAIRegexPattern only fires on an unsupported backslash escape, a trailing backslash, or group syntax "(?"; the first two need a decoded backslash, which JSON can only spell "\\\\" or \\u005c, and the third can have either character escaped. The parameter pass only edits a literal null value or a oneOf/anyOf union, and the union repair accepts any parameters object containing a backslash, so an escaped keyword such as "one\\u004ff" counts too - hence the \\u00XX needle. 5. Patterns are checked in place when the JSON span carries no escape, instead of strconv.Unquote per pattern, and object member names are parsed once into openAIResponsesJSONKey rather than rescanning the span for every candidate name. Benchmark (Apple M5 Pro, 1MiB Codex-shaped body: 30 tools + 1MiB input): platform entry, OpenAI 7.48ms / 512 allocs -> 96us / 0 allocs platform entry, Anthropic 3.75ms / 256 allocs -> 66us / 0 allocs patterns pass 3.71ms / 256 allocs -> 30us / 0 allocs parameter-types pass 3.69ms / 256 allocs -> 66us / 0 allocs Existing benchmarks: ..._Patterns_ByteSpanPatch 1586609ns / 2017 allocs -> 915199ns / 17 ..._ParameterTypes_ByteSpanPatch 1011697ns / 17 allocs -> 647160ns / 17 Correctness: parseString keeps the previous byte-at-a-time scanner as legacy* and compares return values and error positions across a corpus plus fuzzing; the probe reuse asserts that the probe and the skip walk stop at the same byte; the gates are pinned by the invariant "if the sanitizer changed the body, the gate must have let it through", over a corpus that spells out every unsupported pattern shape and fuzzing; dropping the pre-edit json.Valid relies on "the parser accepts implies encoding/json accepts", which is fuzzed too. Fuzzing found two bugs in this change, both fixed and kept as regression seeds under testdata/fuzz: an out-of-range read when a body ended in "\\\\", and a gate that was narrower than the necessary condition for a pattern whose value is a lone backslash. The second means such patterns are now cleaned up where the old gate only caught them by accident, when the body happened to contain a parenthesis elsewhere. --- .../service/openai_responses_tool_schema.go | 267 ++++++++++---- ...ai_responses_tool_schema_benchmark_test.go | 129 +++++++ .../openai_responses_tool_schema_scan_test.go | 334 ++++++++++++++++++ .../19981bffc2abbaf1 | 2 + .../430233b3de39cf96 | 2 + .../6c31f0fa5746a2cd | 2 + .../e90985907f88433e | 2 + 7 files changed, 664 insertions(+), 74 deletions(-) create mode 100644 backend/internal/service/openai_responses_tool_schema_benchmark_test.go create mode 100644 backend/internal/service/openai_responses_tool_schema_scan_test.go create mode 100644 backend/internal/service/testdata/fuzz/FuzzOpenAIResponsesToolSchemaGatesAreNecessary/19981bffc2abbaf1 create mode 100644 backend/internal/service/testdata/fuzz/FuzzOpenAIResponsesToolSchemaGatesAreNecessary/430233b3de39cf96 create mode 100644 backend/internal/service/testdata/fuzz/FuzzOpenAIResponsesToolSchemaGatesAreNecessary/6c31f0fa5746a2cd create mode 100644 backend/internal/service/testdata/fuzz/FuzzOpenAIResponsesToolSchemaGatesAreNecessary/e90985907f88433e diff --git a/backend/internal/service/openai_responses_tool_schema.go b/backend/internal/service/openai_responses_tool_schema.go index 4880efbf7a..440a1b0a9d 100644 --- a/backend/internal/service/openai_responses_tool_schema.go +++ b/backend/internal/service/openai_responses_tool_schema.go @@ -2,6 +2,7 @@ package service import ( "bytes" + "encoding/binary" "encoding/json" "errors" "fmt" @@ -86,7 +87,7 @@ func sanitizeOpenAIResponsesToolSchemaPatterns(body []byte) ([]byte, bool, error // oneOf/anyOf. Other missing types and nested property schemas are left // unchanged. func sanitizeOpenAIResponsesToolParameterTypes(body []byte) ([]byte, bool, error) { - if len(body) == 0 { + if len(body) == 0 || !openAIResponsesBodyMayNeedToolParameterRepair(body) { return body, false, nil } return sanitizeOpenAIResponsesToolSchemas(body, openAIResponsesToolSchemaOptions{ @@ -96,31 +97,85 @@ func sanitizeOpenAIResponsesToolParameterTypes(body []byte) ([]byte, bool, error }) } +var ( + openAIResponsesNullLiteral = []byte("null") + // Short needles on purpose: bytes.Contains switches to a much slower + // algorithm for longer needles (a quoted 7-byte key costs ~12x a 5-byte one) + // and these run on every request. + openAIResponsesOneOfHint = []byte("oneOf") + openAIResponsesAnyOfHint = []byte("anyOf") + openAIResponsesRegexGroupBytes = []byte("(?") + openAIResponsesJSONUnicodeEscape = []byte(`\u`) + // Any escaped spelling of an ASCII letter is \u00XX, so this also stands in + // for a union keyword written that way. + openAIResponsesUnicodeLetterEscape = []byte(`\u00`) + openAIResponsesJSONBackslashPair = []byte(`\\`) +) + +// openAIResponsesBodyMayNeedToolParameterRepair is a necessary condition for +// sanitizeOpenAIResponsesToolParameterTypes to change anything. +// +// Every repair reads either a literal null value (type / required), which the +// JSON grammar cannot spell with escapes, or a oneOf/anyOf union. The union +// repair first accepts a parameters object that contains "oneOf", "anyOf" or +// any backslash at all, then decides on the decoded keys - so a union keyword +// written as "one\u004ff" also qualifies. Any escaped spelling of an ASCII +// letter is a \u00XX escape, which is what the last needle covers. +func openAIResponsesBodyMayNeedToolParameterRepair(body []byte) bool { + return bytes.Contains(body, openAIResponsesNullLiteral) || + bytes.Contains(body, openAIResponsesOneOfHint) || + bytes.Contains(body, openAIResponsesAnyOfHint) || + bytes.Contains(body, openAIResponsesUnicodeLetterEscape) +} + +// openAIResponsesBodyMayContainUnsupportedRegex is a necessary condition for +// sanitizeOpenAIResponsesToolSchemaPatterns to change anything. It is +// deliberately much narrower than "the body contains a parenthesis": prose, +// descriptions and code samples contain those constantly, so that test passed +// on nearly every request and made this pass walk every request body. func openAIResponsesBodyMayContainUnsupportedRegex(body []byte) bool { - // An opening parenthesis may be literal or encoded as JSON's canonical - // Unicode escape. A backslash inside a JSON string is escaped as \\, so the - // sequence \\ exposes the decoded regex escape without parsing. - if bytes.Contains(body, []byte("(")) || bytes.Contains(body, []byte(`\u0028`)) || - bytes.Contains(body, []byte(`\u005c`)) || bytes.Contains(body, []byte(`\u005C`)) { + // hasUnsupportedOpenAIRegexPattern 只有三种触发方式,这里逐一给出必要字节条件: + // + // 1. 一个反斜杠后跟了非白名单的字母; + // 2. 字符串以反斜杠结尾; + // 3. 分组语法 "(?"。 + // + // 前两种都需要解码后的反斜杠,而 JSON 里它只能写成 "\\" 或 \u005c。 + // 第三种里 "(" 和 "?" 各自都可能是转义写法。 + if bytes.Contains(body, openAIResponsesJSONBackslashPair) { return true } - for i := 0; i+2 < len(body); i++ { - if body[i] != '\\' || body[i+1] != '\\' { - continue - } - escaped := body[i+2] - if isASCIILetter(escaped) && !pythonRegexEscapeAllowed(escaped) { - return true - } + if bytes.Contains(body, openAIResponsesRegexGroupBytes) { + return true } - return false + if !bytes.Contains(body, openAIResponsesJSONUnicodeEscape) { + return false + } + // 任何 \u00XX 转义都可能写成上述三种形态里的括号、问号或反斜杠。 + return bytes.Contains(body, openAIResponsesUnicodeLetterEscape) +} + +// openAIResponsesJSONPatternIsUnsupported reports whether a JSON string span +// (quotes included) decodes to a pattern Python re rejects. Spans without an +// escape - the overwhelming majority - are checked in place, so the common +// "many tools, no bad patterns" body neither decodes nor allocates per pattern. +func openAIResponsesJSONPatternIsUnsupported(raw []byte) bool { + if len(raw) < 2 || raw[0] != '"' || raw[len(raw)-1] != '"' { + return false + } + inner := raw[1 : len(raw)-1] + if bytes.IndexByte(inner, '\\') < 0 { + return hasUnsupportedOpenAIRegexPattern(inner) + } + decoded, err := decodeOpenAIResponsesJSONString(raw) + return err == nil && hasUnsupportedOpenAIRegexPattern([]byte(decoded)) } // hasUnsupportedOpenAIRegexPattern reports whether Python re rejects pattern. // OpenAI validates tool-schema patterns with Python re, which supports neither // lookaround nor the .NET/Java (?...) and (?'name'...) group forms, and // reserves unknown ASCII-letter escapes such as \p and \R. -func hasUnsupportedOpenAIRegexPattern(pattern string) bool { +func hasUnsupportedOpenAIRegexPattern(pattern []byte) bool { inCharacterClass := false for i := 0; i < len(pattern); i++ { switch pattern[i] { @@ -231,10 +286,10 @@ func sanitizeOpenAIResponsesToolSchemas( if p.pos != len(body) { return nil, false, fmt.Errorf("sanitize OpenAI Responses tool schemas: trailing data at byte %d", p.pos) } - if !json.Valid(body) { - return nil, false, fmt.Errorf("sanitize OpenAI Responses tool schemas: invalid JSON") - } if len(p.edits) == 0 { + // The walk above already rejected everything encoding/json rejects, so a + // clean parse needs no second full-body validation. When there are edits + // the result is validated after patching. return body, false, nil } return applyOpenAIResponsesToolSchemaEdits(body, p.edits) @@ -269,7 +324,11 @@ func (p *openAIResponsesToolSchemaParser) parseValue( case "additional_tools": context = openAIResponsesToolSchemaToolCarrier default: - context = openAIResponsesToolSchemaSkip + // Nothing inside this item can be edited, so the probe walk is the + // whole job: reuse where it stopped instead of walking the item a + // second time just to skip it. Messages dominate input history. + p.pos = probe.pos + return nil } } switch p.body[p.pos] { @@ -319,7 +378,7 @@ func (p *openAIResponsesToolSchemaParser) parseObject( if err != nil { return err } - key := p.body[keyStart:keyEnd] + key := newOpenAIResponsesJSONKey(p.body[keyStart:keyEnd]) p.skipWhitespace() if !p.consume(':') { return p.syntaxError("expected colon") @@ -335,26 +394,26 @@ func (p *openAIResponsesToolSchemaParser) parseObject( p.skipWhitespace() deleteMember := false - if context == openAIResponsesToolSchemaTypeProbe && openAIResponsesJSONStringEquals(key, "type") { + if context == openAIResponsesToolSchemaTypeProbe && key.is("type") { if value, ok := decodeOpenAIResponsesJSONStringValue(p.body[valueStart:valueEnd]); ok { p.probeType = strings.TrimSpace(value) } } if (context == openAIResponsesToolSchemaTool || context == openAIResponsesToolSchemaFunction) && - openAIResponsesJSONStringEquals(key, "parameters") { + key.is("parameters") { parameterCount++ parameterValueStart = valueStart parameterValueEnd = valueEnd } if p.options.removeUnsupportedRegexPatterns { - if context == openAIResponsesToolSchema && openAIResponsesJSONStringEquals(key, "patternProperties") { + if context == openAIResponsesToolSchema && key.is("patternProperties") { // The child parser records how many keys it had to remove. A // closed sibling object must be reopened in that case. if p.patternPropertiesDrops[valueStart] > 0 { lostPatternProperty = true } } - if context == openAIResponsesToolSchema && openAIResponsesJSONStringEquals(key, "additionalProperties") && + if context == openAIResponsesToolSchema && key.is("additionalProperties") && !bytes.Equal(p.body[valueStart:valueEnd], []byte("true")) { // Defer the edit: patternProperties may appear after this // member, and only actual key removal requires reopening. @@ -364,15 +423,14 @@ func (p *openAIResponsesToolSchemaParser) parseObject( replacement: "true", }) } - if context == openAIResponsesToolSchema && openAIResponsesJSONStringEquals(key, "pattern") { - if pattern, ok := decodeOpenAIResponsesJSONStringValue(p.body[valueStart:valueEnd]); ok && hasUnsupportedOpenAIRegexPattern(pattern) { + if context == openAIResponsesToolSchema && key.is("pattern") { + if openAIResponsesJSONPatternIsUnsupported(p.body[valueStart:valueEnd]) { deleteMember = true } } - if context == openAIResponsesToolSchemaPatternPropertiesMap { - if pattern, ok := decodeOpenAIResponsesJSONStringValue(key); ok && hasUnsupportedOpenAIRegexPattern(pattern) { - deleteMember = true - } + if context == openAIResponsesToolSchemaPatternPropertiesMap && + openAIResponsesJSONPatternIsUnsupported(key.raw) { + deleteMember = true } } // JSON Schema requires "required" to be an array. Clients occasionally emit @@ -380,11 +438,11 @@ func (p *openAIResponsesToolSchemaParser) parseObject( // "required" is the semantic equivalent of an empty one, so dropping the // member preserves the client's intent while satisfying strict validators. if context == openAIResponsesToolSchema && p.options.dropNullRequired && - openAIResponsesJSONStringEquals(key, "required") && + key.is("required") && bytes.Equal(p.body[valueStart:valueEnd], []byte("null")) { deleteMember = true } - if context == openAIResponsesToolSchema && schemaRoot && openAIResponsesJSONStringEquals(key, "type") { + if context == openAIResponsesToolSchema && schemaRoot && key.is("type") { // Duplicate JSON keys have parser-dependent effective values. Repair a // root type only when it is unique rather than choosing a winner and // potentially changing the client's effective schema. @@ -570,52 +628,95 @@ func (p *openAIResponsesToolSchemaParser) parseArray( } } +// openAIResponsesJSONKey is one object member name, prepared for repeated +// comparison. parseObject tests the same key against a dozen candidate names, +// so the escape question is answered once here instead of rescanning the span +// on every comparison. +type openAIResponsesJSONKey struct { + raw []byte + inner []byte + plain bool +} + +func newOpenAIResponsesJSONKey(raw []byte) openAIResponsesJSONKey { + key := openAIResponsesJSONKey{raw: raw} + if len(raw) < 2 || raw[0] != '"' || raw[len(raw)-1] != '"' { + return key + } + key.inner = raw[1 : len(raw)-1] + key.plain = bytes.IndexByte(key.inner, '\\') < 0 + return key +} + +// is reports whether the member name equals want. A key carrying an escape +// decodes to fewer bytes than it occupies, so an escape-free span can be +// compared in place; only escaped spellings need to be decoded. +func (k openAIResponsesJSONKey) is(want string) bool { + if k.inner == nil { + return false + } + if k.plain { + return len(k.inner) == len(want) && string(k.inner) == want + } + decoded, err := decodeOpenAIResponsesJSONString(k.raw) + return err == nil && decoded == want +} + +func (k openAIResponsesJSONKey) isAny(candidates ...string) bool { + for _, candidate := range candidates { + if k.is(candidate) { + return true + } + } + return false +} + func openAIResponsesToolSchemaChildContext( - context openAIResponsesToolSchemaContext, key []byte, + context openAIResponsesToolSchemaContext, key openAIResponsesJSONKey, ) (openAIResponsesToolSchemaContext, bool) { switch context { case openAIResponsesToolSchemaDocument: switch { - case openAIResponsesJSONStringEquals(key, "tools"): + case key.is("tools"): return openAIResponsesToolSchemaTools, false - case openAIResponsesJSONStringEquals(key, "input"): + case key.is("input"): return openAIResponsesToolSchemaInput, false } case openAIResponsesToolSchemaTool: switch { // Anthropic Messages carries the same JSON Schema under input_schema, so // /v1/messages tools must reach the sanitizer too. - case openAIResponsesJSONStringMatchesAny(key, "parameters", "input_schema"): + case key.isAny("parameters", "input_schema"): return openAIResponsesToolSchema, true - case openAIResponsesJSONStringEquals(key, "function"): + case key.is("function"): return openAIResponsesToolSchemaFunction, false - case openAIResponsesJSONStringEquals(key, "tools"): + case key.is("tools"): return openAIResponsesToolSchemaTools, false } case openAIResponsesToolSchemaToolCarrier: - if openAIResponsesJSONStringEquals(key, "tools") { + if key.is("tools") { return openAIResponsesToolSchemaTools, false } case openAIResponsesToolSchemaFunction: switch { - case openAIResponsesJSONStringEquals(key, "parameters"): + case key.is("parameters"): return openAIResponsesToolSchema, true - case openAIResponsesJSONStringEquals(key, "tools"): + case key.is("tools"): return openAIResponsesToolSchemaTools, false } case openAIResponsesToolSchema: switch { - case openAIResponsesJSONStringMatchesAny(key, + case key.isAny( "additionalProperties", "additionalItems", "contains", "not", "if", "then", "else", "propertyNames", "unevaluatedProperties", "unevaluatedItems", "contentSchema"): return openAIResponsesToolSchema, false - case openAIResponsesJSONStringEquals(key, "items"): + case key.is("items"): return openAIResponsesToolSchemaOrArray, false - case openAIResponsesJSONStringMatchesAny(key, "anyOf", "oneOf", "allOf", "prefixItems"): + case key.isAny("anyOf", "oneOf", "allOf", "prefixItems"): return openAIResponsesToolSchemaArray, false - case openAIResponsesJSONStringEquals(key, "patternProperties"): + case key.is("patternProperties"): return openAIResponsesToolSchemaPatternPropertiesMap, false - case openAIResponsesJSONStringMatchesAny(key, + case key.isAny( "properties", "$defs", "definitions", "dependentSchemas", "dependencies"): return openAIResponsesToolSchemaMap, false } @@ -631,7 +732,14 @@ func (p *openAIResponsesToolSchemaParser) parseString() (int, int, error) { } start := p.pos p.pos++ - for p.pos < len(p.body) { + for { + // Skip the plain run in word-sized steps: string payloads dominate large + // request bodies, and a byte-at-a-time walk here was the bulk of the + // cost of the whole sanitizer. + p.pos += openAIResponsesJSONPlainStringRun(p.body[p.pos:]) + if p.pos >= len(p.body) { + return 0, 0, p.syntaxError("unterminated string") + } switch p.body[p.pos] { case '"': p.pos++ @@ -652,20 +760,51 @@ func (p *openAIResponsesToolSchemaParser) parseString() (int, int, error) { } } p.pos += 5 - continue case '"', '\\', '/', 'b', 'f', 'n', 'r', 't': p.pos++ default: return 0, 0, p.syntaxError("invalid string escape") } default: - if p.body[p.pos] < 0x20 { - return 0, 0, p.syntaxError("control character in string") - } - p.pos++ + // Everything else that ends the plain run is a control byte. + return 0, 0, p.syntaxError("control character in string") } } - return 0, 0, p.syntaxError("unterminated string") +} + +const ( + openAIResponsesSWARByteOnes = 0x0101010101010101 + openAIResponsesSWARHighBits = 0x8080808080808080 +) + +// openAIResponsesJSONWordHasZeroByte reports whether any byte of word is 0x00. +func openAIResponsesJSONWordHasZeroByte(word uint64) bool { + return (word-openAIResponsesSWARByteOnes)&^word&openAIResponsesSWARHighBits != 0 +} + +// openAIResponsesJSONPlainStringRun returns the length of the leading run of +// bytes in bulk that can be copied through a JSON string verbatim: no closing +// quote, no escape backslash and no control byte. Those three are exactly the +// bytes parseString has to stop at. +func openAIResponsesJSONPlainStringRun(bulk []byte) int { + offset := 0 + for ; offset+8 <= len(bulk); offset += 8 { + word := binary.LittleEndian.Uint64(bulk[offset:]) + // '"' and '\\' are found by zero-byte detection on the XOR, which flags + // a whole word at once; (value & 0xE0) == 0 means value < 0x20. + if openAIResponsesJSONWordHasZeroByte(word^0x2222222222222222) || + openAIResponsesJSONWordHasZeroByte(word^0x5c5c5c5c5c5c5c5c) || + openAIResponsesJSONWordHasZeroByte(word&0xe0e0e0e0e0e0e0e0) { + break + } + } + for ; offset < len(bulk); offset++ { + value := bulk[offset] + if value == '"' || value == '\\' || value < 0x20 { + break + } + } + return offset } func isOpenAIResponsesJSONHexDigit(value byte) bool { @@ -767,26 +906,6 @@ func decodeOpenAIResponsesJSONString(raw []byte) (string, error) { return decoded, nil } -func openAIResponsesJSONStringEquals(raw []byte, want string) bool { - if len(raw) < 2 || raw[0] != '"' || raw[len(raw)-1] != '"' { - return false - } - if !bytes.Contains(raw, []byte{'\\'}) { - return bytes.Equal(raw[1:len(raw)-1], []byte(want)) - } - decoded, err := decodeOpenAIResponsesJSONString(raw) - return err == nil && decoded == want -} - -func openAIResponsesJSONStringMatchesAny(raw []byte, candidates ...string) bool { - for _, candidate := range candidates { - if openAIResponsesJSONStringEquals(raw, candidate) { - return true - } - } - return false -} - func decodeOpenAIResponsesJSONStringValue(raw []byte) (string, bool) { if len(raw) < 2 || raw[0] != '"' || raw[len(raw)-1] != '"' { return "", false diff --git a/backend/internal/service/openai_responses_tool_schema_benchmark_test.go b/backend/internal/service/openai_responses_tool_schema_benchmark_test.go new file mode 100644 index 0000000000..9d775d22c2 --- /dev/null +++ b/backend/internal/service/openai_responses_tool_schema_benchmark_test.go @@ -0,0 +1,129 @@ +package service + +import ( + "fmt" + "strings" + "testing" +) + +// buildToolSchemaBenchmarkBody 造一份贴近真实 Codex 请求的 body:小 tools 数组 + +// 大 input 历史。description 里带括号,因为真实工具的说明几乎都有。 +func buildToolSchemaBenchmarkBody(targetBytes, tools int, withLookaround bool) []byte { + var sb strings.Builder + sb.Grow(targetBytes + 4096) + write := func(s string) { _, _ = sb.WriteString(s) } + write(`{"model":"gpt-5.6","stream":true,"instructions":"You are Codex, a coding agent.","tools":[`) + for i := 0; i < tools; i++ { + if i > 0 { + write(",") + } + pattern := "" + if withLookaround && i == 0 { + pattern = `,"pattern":"(?=x).*"` + } + write(fmt.Sprintf( + `{"type":"function","name":"tool_%d","description":"Runs a shell command (supports pipes).","parameters":{"type":"object","properties":{"query":{"type":"string"%s},"limit":{"type":"integer","minimum":1}},"required":["query"]}}`, + i, pattern)) + } + write(`],"input":[`) + item := `{"type":"message","role":"user","content":[{"type":"input_text","text":"` + strings.Repeat("x", 4000) + `"}]}` + for i := 0; sb.Len() < targetBytes; i++ { + if i > 0 { + write(",") + } + write(item) + } + write(`]}`) + return []byte(sb.String()) +} + +// ungated 是改动前入口在这类 body 上的实际走向:旧的预检查是「body 里有 (」, +// 而工具说明几乎都带括号,所以请求无一例外走整趟解析。 +func benchmarkToolSchemaEntry( + b *testing.B, body []byte, + ungated func([]byte) ([]byte, bool, error), + gated func([]byte) ([]byte, bool, error), +) { + b.Helper() + b.Run("ungated", func(b *testing.B) { + b.SetBytes(int64(len(body))) + b.ReportAllocs() + for range b.N { + _, _, _ = ungated(body) + } + }) + b.Run("gated", func(b *testing.B) { + b.SetBytes(int64(len(body))) + b.ReportAllocs() + for range b.N { + _, _, _ = gated(body) + } + }) +} + +func BenchmarkSanitizeOpenAIResponsesToolSchemaPatternsClean1MiB(b *testing.B) { + body := buildToolSchemaBenchmarkBody(1<<20, 30, false) + benchmarkToolSchemaEntry(b, body, + func(in []byte) ([]byte, bool, error) { + return sanitizeOpenAIResponsesToolSchemas(in, openAIResponsesToolSchemaOptions{removeUnsupportedRegexPatterns: true}) + }, + sanitizeOpenAIResponsesToolSchemaPatterns, + ) +} + +func BenchmarkSanitizeOpenAIResponsesToolParameterTypesClean1MiB(b *testing.B) { + body := buildToolSchemaBenchmarkBody(1<<20, 30, false) + benchmarkToolSchemaEntry(b, body, + func(in []byte) ([]byte, bool, error) { + return sanitizeOpenAIResponsesToolSchemas(in, openAIResponsesToolSchemaOptions{ + replaceNullParameterTypes: true, + injectObjectUnionRootObjectType: true, + dropNullRequired: true, + }) + }, + sanitizeOpenAIResponsesToolParameterTypes, + ) +} + +func BenchmarkOpenAIResponsesToolSchemaGates(b *testing.B) { + body := buildToolSchemaBenchmarkBody(1<<20, 30, false) + b.Run("unsupported_regex", func(b *testing.B) { + b.SetBytes(int64(len(body))) + for range b.N { + _ = openAIResponsesBodyMayContainUnsupportedRegex(body) + } + }) + b.Run("parameter_repair", func(b *testing.B) { + b.SetBytes(int64(len(body))) + for range b.N { + _ = openAIResponsesBodyMayNeedToolParameterRepair(body) + } + }) +} + +// 字符串扫描是解析里最重的一段:请求体的大头是长内容字符串。 +func BenchmarkOpenAIResponsesJSONStringScan(b *testing.B) { + body := []byte(`"` + strings.Repeat("abcdefgh", 1<<14) + `"`) + b.Run("legacy", func(b *testing.B) { + b.SetBytes(int64(len(body))) + for range b.N { + _, _, _, _ = legacyParseOpenAIResponsesJSONString(body, 0) + } + }) + b.Run("current", func(b *testing.B) { + b.SetBytes(int64(len(body))) + for range b.N { + _ = currentParseOpenAIResponsesJSONString(body, 0) + } + }) +} + +// 平台入口就是三个调用点(HTTP 转发、WS 归一化、/v1/messages 转换)实际走的路径。 +func BenchmarkSanitizeOpenAIResponsesToolSchemasForPlatformClean1MiB(b *testing.B) { + body := buildToolSchemaBenchmarkBody(1<<20, 30, false) + b.SetBytes(int64(len(body))) + b.ReportAllocs() + for range b.N { + _, _, _ = sanitizeOpenAIResponsesToolSchemasForPlatform(body, PlatformOpenAI) + } +} diff --git a/backend/internal/service/openai_responses_tool_schema_scan_test.go b/backend/internal/service/openai_responses_tool_schema_scan_test.go new file mode 100644 index 0000000000..f98a80b4d7 --- /dev/null +++ b/backend/internal/service/openai_responses_tool_schema_scan_test.go @@ -0,0 +1,334 @@ +package service + +import ( + "encoding/json" + "fmt" + "strings" + "testing" + "unicode/utf8" + + "github.com/stretchr/testify/require" +) + +// legacyParseOpenAIResponsesJSONString is the byte-at-a-time scanner this file +// replaced. It stays here as the differential baseline for parseString. +func legacyParseOpenAIResponsesJSONString(body []byte, pos int) (int, int, string, int) { + if pos >= len(body) || body[pos] != '"' { + return 0, 0, "expected string", pos + } + start := pos + pos++ + for pos < len(body) { + switch body[pos] { + case '"': + pos++ + return start, pos, "", 0 + case '\\': + pos++ + if pos >= len(body) { + return 0, 0, "unterminated string escape", pos + } + switch body[pos] { + case 'u': + if pos+4 >= len(body) { + return 0, 0, "short unicode escape", pos + } + for _, digit := range body[pos+1 : pos+5] { + if !isOpenAIResponsesJSONHexDigit(digit) { + return 0, 0, "invalid unicode escape", pos + } + } + pos += 5 + continue + case '"', '\\', '/', 'b', 'f', 'n', 'r', 't': + pos++ + default: + return 0, 0, "invalid string escape", pos + } + default: + if body[pos] < 0x20 { + return 0, 0, "control character in string", pos + } + pos++ + } + } + return 0, 0, "unterminated string", pos +} + +type stringScanResult struct { + start, end int + err string + errPos int +} + +func currentParseOpenAIResponsesJSONString(body []byte, pos int) stringScanResult { + p := openAIResponsesToolSchemaParser{body: body, pos: pos} + start, end, err := p.parseString() + if err != nil { + message, errPos := splitOpenAIResponsesToolSchemaError(err) + return stringScanResult{err: message, errPos: errPos} + } + return stringScanResult{start: start, end: end} +} + +func splitOpenAIResponsesToolSchemaError(err error) (string, int) { + text := err.Error() + const prefix = "sanitize OpenAI Responses tool schemas: " + text = strings.TrimPrefix(text, prefix) + at := strings.LastIndex(text, " at byte ") + if at < 0 { + return text, -1 + } + var pos int + if _, scanErr := fmt.Sscanf(text[at+len(" at byte "):], "%d", &pos); scanErr != nil { + return text, -1 + } + return text[:at], pos +} + +func TestOpenAIResponsesToolSchemaParseStringMatchesLegacy(t *testing.T) { + escape := string(rune(92)) + cases := []string{ + `""`, + `"abc"`, + `"a b c"`, + `"` + strings.Repeat("x", 64) + `"`, + `"` + strings.Repeat("x", 63) + `"`, // exercises the 8-byte tail + `"` + strings.Repeat("x", 65) + `"`, + `"a\"b"`, + `"a\\b"`, + `"a\/b"`, + `"` + escape + `u00e9"`, + `"` + escape + `uD83D` + escape + `uDE00"`, + `"` + escape + `u00E9"`, + // 控制字符 + "\"a\nb\"", + "\"a\tb\"", + "\"a\x00b\"", + "\"a\x1fb\"", + "\"a\x7fb\"", // DEL 是合法 JSON + // 非法转义 / 截断 + `"a\qb"`, + `"a\u12"`, + `"a\u12zz"`, + `"a\u`, + `"a\`, + `"unterminated`, + `"`, + ``, + `abc`, + // 多字节 UTF-8 + `"中文 😀"`, + `"` + strings.Repeat("中", 40) + `"`, + } + + for _, tc := range cases { + for _, pos := range []int{0, 1} { + body := []byte(tc) + if pos == 1 { + body = append([]byte("x"), body...) + } + wantStart, wantEnd, wantErr, wantErrPos := legacyParseOpenAIResponsesJSONString(body, pos) + got := currentParseOpenAIResponsesJSONString(body, pos) + require.Equal(t, stringScanResult{start: wantStart, end: wantEnd, err: wantErr, errPos: wantErrPos}, got, + "input=%q pos=%d", tc, pos) + } + } +} + +func FuzzOpenAIResponsesToolSchemaParseString(f *testing.F) { + f.Add([]byte(`"abc"`), 0) + f.Add([]byte(`"a\"b"`), 0) + f.Add([]byte{'"', 'a', '\n', '"'}, 0) + f.Add([]byte(`"`), 0) + f.Add([]byte(`x"aé"`), 1) + f.Fuzz(func(t *testing.T, body []byte, pos int) { + if pos < 0 || pos > len(body) { + return + } + wantStart, wantEnd, wantErr, wantErrPos := legacyParseOpenAIResponsesJSONString(body, pos) + got := currentParseOpenAIResponsesJSONString(body, pos) + require.Equal(t, stringScanResult{start: wantStart, end: wantEnd, err: wantErr, errPos: wantErrPos}, got, + "body=%q pos=%d", body, pos) + }) +} + +// 探测走完的终点必须与「跳过」走完的终点一致,探针结果才能被当作跳过复用。 +func TestOpenAIResponsesToolSchemaInputItemSkipMatchesProbe(t *testing.T) { + values := []string{ + `{"type":"message","role":"user","content":[{"type":"input_text","text":"hi"}]}`, + `{"type":"function","name":"x","parameters":{"type":"object"}}`, + `{"type":"function_call","arguments":"{}"}`, + `{"type":"custom","name":"x"}`, + `{"type":"tool_search"}`, + `{"type":"namespace","tools":[]}`, + `{"type":"additional_tools","tools":[{"type":"namespace"}]}`, + `{"type":"\\u0066unction","parameters":{"type":"null"}}`, + `{"type": "message" , "content" : [ 1 , 2 , {"a":null} ] }`, + `{}`, + `{"a":[{"b":[{"c":"d"}]}]}`, + `{"type":"message","content":"\\u0000\\u001f"}`, + } + for _, value := range values { + body := []byte(value) + probe := openAIResponsesToolSchemaParser{body: body, pos: 0} + require.NoError(t, probe.parseValue(openAIResponsesToolSchemaTypeProbe, false, 0), "value=%s", value) + + skip := openAIResponsesToolSchemaParser{body: body, pos: 0} + require.NoError(t, skip.parseValue(openAIResponsesToolSchemaSkip, false, 0), "value=%s", value) + + require.Equal(t, skip.pos, probe.pos, "value=%s", value) + require.Equal(t, len(body), probe.pos, "value=%s", value) + } +} + +// 解析器接受的 body 必须也是 encoding/json 认可的有效 JSON——否则去掉改写前的 +// json.Valid 预检查就会放过畸形请求。 +func TestOpenAIResponsesToolSchemaParserAcceptsOnlyValidJSON(t *testing.T) { + corpus := append(openAIResponsesToolSchemaGateCorpus(), []string{ + `{}`, `[]`, `null`, `0`, `""`, `{"a":1}`, `[1,2,3]`, + }...) + for _, body := range corpus { + p := openAIResponsesToolSchemaParser{body: []byte(body)} + err := p.parseValue(openAIResponsesToolSchemaDocument, false, 0) + if err != nil { + continue + } + p.skipWhitespace() + if p.pos != len(body) { + continue + } + require.True(t, json.Valid([]byte(body)), "解析器接受了 encoding/json 拒绝的输入: %q", body) + } +} + +func FuzzOpenAIResponsesToolSchemaParserAcceptsOnlyValidJSON(f *testing.F) { + for _, seed := range []string{ + `{"tools":[{"type":"function","parameters":{"type":"null"}}]}`, + `{"a":1,"b":[true,null,"x"]}`, + `0{"input"[{ "namespace"00`, + `{"a":01}`, + `{"a":"\u12zz"}`, + `{"a":1} trailing`, + } { + f.Add([]byte(seed)) + } + f.Fuzz(func(t *testing.T, body []byte) { + if !utf8.Valid(body) { + return // 入口先做 utf8 校验,这里只看解析器本身 + } + p := openAIResponsesToolSchemaParser{body: body} + if err := p.parseValue(openAIResponsesToolSchemaDocument, false, 0); err != nil { + return + } + p.skipWhitespace() + if p.pos != len(body) { + return + } + require.True(t, json.Valid(body), "解析器接受了 encoding/json 拒绝的输入: %q", body) + }) +} + +// openAIResponsesToolSchemaGateCorpus 覆盖两个门控必须放行的每一种写法。 +func openAIResponsesToolSchemaGateCorpus() []string { + escape := string(rune(92)) + pattern := func(p string) string { + return `{"tools":[{"type":"function","name":"f","parameters":{"type":"object","properties":{"q":{"type":"string","pattern":"` + p + `"}}}}]}` + } + return []string{ + // —— 非法正则 —— + pattern(`(?=x)`), + pattern(`(?!x)`), + pattern(`(?<=x)`), + pattern(`(?x)`), + pattern(`(?'name'x)`), + pattern(`a` + escape + escape + `p{L}`), + pattern(`a` + escape + escape + `R`), + pattern(`a` + escape + `u005cp`), + pattern(`a` + escape + `u0028` + escape + `u003f=x)`), + pattern(`a` + escape + `u0028?=x)`), + pattern(`a(` + escape + `u003f=x)`), + pattern(`a` + escape + escape + escape + escape + `d`), + // patternProperties 的键 + `{"tools":[{"type":"function","parameters":{"type":"object","patternProperties":{"(?=x)":{"type":"string"}}}}]}`, + `{"tools":[{"type":"function","parameters":{"type":"object","patternProperties":{"` + escape + `u0028` + escape + `u003f=x)":{"type":"string"}}}}]}`, + // —— 参数类型修复 —— + `{"tools":[{"type":"function","parameters":{"type":null}}]}`, + `{"tools":[{"type":"function","parameters":{"required":null}}]}`, + `{"tools":[{"type":"function","parameters":{"oneOf":[{"type":"object"},{"type":"object"}]}}]}`, + `{"tools":[{"type":"function","parameters":{"anyOf":[{"properties":{}}]}}]}`, + // union 关键字用 \u004f / \u0066 转义写出:字面 needle 不命中,但 + // openAIMissingRootObjectUnionTypeEdit 会因为 raw 里有反斜杠而继续解析。 + `{"tools":[{"type":"function","name":"other","parameters":{"one` + escape + `u004ff":[{"type":"object"}]}}]}`, + `{"tools":[{"type":"function","name":"other","parameters":{"anyO` + escape + `u0066":[{"type":"object"}]}}]}`, + `{"messages":[{"role":"user","content":"x","input_schema":{"type":null}}]}`, + // —— 合法正则不应触发修复,但门控允许放行 —— + pattern(`^a+$`), + pattern(`a` + escape + escape + `d{3}`), + `{"input":[{"type":"message","content":"a null mention (and parens)"}]}`, + } +} + +// 门控必须是「会改写」的必要条件:只要消毒真的改了 body,门控就必须放行。 +// 反向不成立——门控故意留了余量(例如 body 里出现任何 \\ 就放行),因为算出 +// 精确条件比放行一两次解析更贵也更易错。 +func requireOpenAIResponsesToolSchemaPatternGateCovers(t *testing.T, body []byte) { + t.Helper() + _, changed, err := sanitizeOpenAIResponsesToolSchemas(body, + openAIResponsesToolSchemaOptions{removeUnsupportedRegexPatterns: true}) + if err != nil { + return // 解析失败的 body 不会被改写,错误本身交给既有用例覆盖 + } + if changed { + require.True(t, openAIResponsesBodyMayContainUnsupportedRegex(body), + "改写已发生但正则门控放过了: %q", body) + } +} + +// 类型修复原本没有门控,同样用绝对不变量:只要真的改了 body,门控就必须放行。 +func requireOpenAIResponsesToolParameterGateCovers(t *testing.T, body []byte) { + t.Helper() + _, changed, err := sanitizeOpenAIResponsesToolSchemas(body, openAIResponsesToolSchemaOptions{ + replaceNullParameterTypes: true, + injectObjectUnionRootObjectType: true, + dropNullRequired: true, + }) + if err != nil { + return + } + if changed { + require.True(t, openAIResponsesBodyMayNeedToolParameterRepair(body), + "改写已发生但类型门控放过了: %q", body) + } +} + +// 门控必须真的能挡住普通请求,否则上面那条不变量会被「永远返回 true」蒙混过关。 +func TestOpenAIResponsesToolSchemaGatesSkipOrdinaryTraffic(t *testing.T) { + clean := buildToolSchemaBenchmarkBody(1<<20, 30, false) + require.False(t, openAIResponsesBodyMayContainUnsupportedRegex(clean), + "普通的 1 MiB 请求不该进入正则 pattern 消毒") + require.False(t, openAIResponsesBodyMayNeedToolParameterRepair(clean), + "普通的 1 MiB 请求不该进入参数类型修复") +} + +func TestOpenAIResponsesToolSchemaGatesAreNecessary(t *testing.T) { + for _, body := range openAIResponsesToolSchemaGateCorpus() { + raw := []byte(body) + requireOpenAIResponsesToolSchemaPatternGateCovers(t, raw) + requireOpenAIResponsesToolParameterGateCovers(t, raw) + } +} + +func FuzzOpenAIResponsesToolSchemaGatesAreNecessary(f *testing.F) { + for _, seed := range openAIResponsesToolSchemaGateCorpus() { + f.Add([]byte(seed)) + } + f.Fuzz(func(t *testing.T, body []byte) { + if len(body) == 0 { + return + } + requireOpenAIResponsesToolSchemaPatternGateCovers(t, body) + requireOpenAIResponsesToolParameterGateCovers(t, body) + }) +} diff --git a/backend/internal/service/testdata/fuzz/FuzzOpenAIResponsesToolSchemaGatesAreNecessary/19981bffc2abbaf1 b/backend/internal/service/testdata/fuzz/FuzzOpenAIResponsesToolSchemaGatesAreNecessary/19981bffc2abbaf1 new file mode 100644 index 0000000000..ecbe8afb9b --- /dev/null +++ b/backend/internal/service/testdata/fuzz/FuzzOpenAIResponsesToolSchemaGatesAreNecessary/19981bffc2abbaf1 @@ -0,0 +1,2 @@ +go test fuzz v1 +[]byte("A") diff --git a/backend/internal/service/testdata/fuzz/FuzzOpenAIResponsesToolSchemaGatesAreNecessary/430233b3de39cf96 b/backend/internal/service/testdata/fuzz/FuzzOpenAIResponsesToolSchemaGatesAreNecessary/430233b3de39cf96 new file mode 100644 index 0000000000..41376806e2 --- /dev/null +++ b/backend/internal/service/testdata/fuzz/FuzzOpenAIResponsesToolSchemaGatesAreNecessary/430233b3de39cf96 @@ -0,0 +1,2 @@ +go test fuzz v1 +[]byte("{\"tools\":[{\"parameters\":{\"properties\":{\"\":{\"\":\"(\",\"pattern\":\"\\\\\"}}}}]}") diff --git a/backend/internal/service/testdata/fuzz/FuzzOpenAIResponsesToolSchemaGatesAreNecessary/6c31f0fa5746a2cd b/backend/internal/service/testdata/fuzz/FuzzOpenAIResponsesToolSchemaGatesAreNecessary/6c31f0fa5746a2cd new file mode 100644 index 0000000000..f9d7f69b33 --- /dev/null +++ b/backend/internal/service/testdata/fuzz/FuzzOpenAIResponsesToolSchemaGatesAreNecessary/6c31f0fa5746a2cd @@ -0,0 +1,2 @@ +go test fuzz v1 +[]byte("0\\\\") diff --git a/backend/internal/service/testdata/fuzz/FuzzOpenAIResponsesToolSchemaGatesAreNecessary/e90985907f88433e b/backend/internal/service/testdata/fuzz/FuzzOpenAIResponsesToolSchemaGatesAreNecessary/e90985907f88433e new file mode 100644 index 0000000000..3a4d1d4e1f --- /dev/null +++ b/backend/internal/service/testdata/fuzz/FuzzOpenAIResponsesToolSchemaGatesAreNecessary/e90985907f88433e @@ -0,0 +1,2 @@ +go test fuzz v1 +[]byte("{\"tools\":[{\"parameters\":{\"properties\":{\"\":{\"pattern\":\"\\\\\"}}}}]}") From d0c232401fb1ad977682602ab2d8af4c1b8ace26 Mon Sep 17 00:00:00 2001 From: wucm667 Date: Tue, 17 Nov 2026 11:22:55 +0800 Subject: [PATCH 39/85] ci: rerun checks after allocation guard failure From bcb22d4de855635ffb2827a610ecde0c846461f0 Mon Sep 17 00:00:00 2001 From: zhanghuaxiang <870255124@qq.com> Date: Mon, 16 Nov 2026 13:22:54 +0800 Subject: [PATCH 40/85] fix(openai): stop pinning large request bodies after the handler Clone the few request-view strings that outlive the handler instead of aliasing the request body, drop the converted Responses input once it is marshaled, and avoid pointing usage logs at the forward input. Async prompt audit checks its scope before copying the body and no longer clones twice, splits and trims prompts without full []rune copies, and skips redaction rewrites that cannot match. Co-authored-by: Cursor --- backend/internal/securityaudit/coordinator.go | 4 +- .../prompt_memory_optimization_test.go | 225 ++++++++++++++++++ .../internal/securityaudit/prompt_scanner.go | 23 +- .../internal/securityaudit/prompt_service.go | 15 ++ .../internal/securityaudit/prompt_snapshot.go | 51 ++-- .../openai_gateway_chat_completions.go | 3 + .../service/openai_gateway_messages.go | 3 + .../service/openai_gateway_request_body.go | 17 +- .../openai_gateway_service_hotpath_test.go | 15 ++ .../internal/service/openai_gateway_usage.go | 13 +- 10 files changed, 335 insertions(+), 34 deletions(-) create mode 100644 backend/internal/securityaudit/prompt_memory_optimization_test.go diff --git a/backend/internal/securityaudit/coordinator.go b/backend/internal/securityaudit/coordinator.go index e6d9c0d929..023616f8ca 100644 --- a/backend/internal/securityaudit/coordinator.go +++ b/backend/internal/securityaudit/coordinator.go @@ -13,6 +13,8 @@ type LegacyEngine interface { type PromptEngine interface { EffectiveMode() Mode + // Enqueue borrows req read-only for this call; implementations must copy + // any request memory retained after returning. Enqueue(ctx context.Context, req Request) error Evaluate(ctx context.Context, req Request) (*PromptDecision, error) } @@ -38,7 +40,7 @@ func (c *Coordinator) Check(ctx context.Context, req Request) Decision { case ModeAsync: // Enqueue is deliberately best-effort. The implementation owns a bounded // context and copies request memory before it can outlive the Handler. - _ = c.prompt.Enqueue(ctx, req.Clone()) + _ = c.prompt.Enqueue(ctx, req) legacy, _ := c.checkLegacy(ctx, req) return prioritize(legacy, nil) case ModeBlocking: diff --git a/backend/internal/securityaudit/prompt_memory_optimization_test.go b/backend/internal/securityaudit/prompt_memory_optimization_test.go new file mode 100644 index 0000000000..5ed1178958 --- /dev/null +++ b/backend/internal/securityaudit/prompt_memory_optimization_test.go @@ -0,0 +1,225 @@ +package securityaudit + +import ( + "context" + "math/rand" + "runtime" + "strings" + "sync" + "sync/atomic" + "testing" + + "github.com/stretchr/testify/require" +) + +func memoryTestPromptService(cfg ActiveConfig, repo JobRepository) *PromptService { + store := &fakeConfigStore{cfg: cfg, active: true} + metrics := NewAtomicMetrics() + return &PromptService{config: store, metrics: metrics, background: context.Background(), enqueueSlots: make(chan struct{}, 128), + enqueuer: NewEnqueuer(store, repo, &fakePayloadStore{}, metrics)} +} + +func TestAsyncAuditOutOfScopeSkipsLargeBodyCopy(t *testing.T) { + cfg := asyncConfig() + cfg.AllGroups = false + cfg.GroupIDs = []int64{1} + groupID := int64(2) + svc := memoryTestPromptService(cfg, &fakeJobRepository{}) + req := Request{GroupID: &groupID, Protocol: "openai_responses", Body: []byte(`{"input":"` + strings.Repeat("x", 1<<20) + `"}`)} + runtime.GC() + var before, after runtime.MemStats + runtime.ReadMemStats(&before) + decision := NewCoordinator(nil, svc).Check(context.Background(), req) + svc.enqueueWG.Wait() + runtime.ReadMemStats(&after) + require.True(t, decision.AllowNextStage) + require.Less(t, after.TotalAlloc-before.TotalAlloc, uint64(len(req.Body)/2), "out-of-scope audit must not copy the body") + runtime.KeepAlive(req) +} + +func TestTrimRunesMatchesOriginalWithoutAllocatingTheWholePrompt(t *testing.T) { + for _, value := range []string{"", "abc", "中文😀suffix", "a\xff\xfebc", strings.Repeat("x", 1<<20)} { + for _, limit := range []int{0, 1, 3, 96} { + want := "" + if limit > 0 { + runes := []rune(value) + want = value + if len(runes) > limit { + want = string(runes[:limit]) + "…" + } + } + require.Equal(t, want, TrimRunes(value, limit)) + } + } + value := strings.Repeat("x", 1<<20) + var before, after runtime.MemStats + runtime.ReadMemStats(&before) + out := TrimRunes(value, 96) + runtime.ReadMemStats(&after) + require.Less(t, after.TotalAlloc-before.TotalAlloc, uint64(64<<10)) + runtime.KeepAlive(out) +} + +func TestSplitRunesPreservesChunksWithoutWholeTranscriptCopies(t *testing.T) { + for _, value := range []string{"", "abcdef", "中文😀suffix", "a\xff\xfebc", "abc" + promptAuditPrioritySeparator + "中文😀"} { + for _, limit := range []int{1, 3, 4000} { + want := []string{} + for _, segment := range strings.Split(value, promptAuditPrioritySeparator) { + runes := []rune(segment) + for start := 0; start < len(runes); start += limit { + want = append(want, string(runes[start:min(start+limit, len(runes))])) + } + } + require.Equal(t, want, SplitRunes(value, limit)) + } + } + value := strings.Repeat("x", 1<<20) + var before, after runtime.MemStats + runtime.ReadMemStats(&before) + chunks := SplitRunes(value, 4000) + runtime.ReadMemStats(&after) + require.Equal(t, value, strings.Join(chunks, "")) + require.Less(t, after.TotalAlloc-before.TotalAlloc, uint64(64<<10)) + runtime.KeepAlive(chunks) +} + +func TestRedactPreviewPreservesCompleteInputReplacementOrder(t *testing.T) { + for _, value := range []string{ + "Bearer abcdefghijklmnop token=abcdefghijkl USER_CANARY_example user@example.org +86 138 1234 5678", + strings.Repeat("x", 1<<20), + strings.Repeat("前缀😀", 40) + " Bearer abcdefghijklmnop", + "short password:abcdefghijkl suffix", + } { + want := bearerPattern.ReplaceAllString(value, "Bearer ***") + want = apiKeyPattern.ReplaceAllStringFunc(want, func(match string) string { + if index := strings.IndexAny(match, ":= \t"); index >= 0 { + return match[:index+1] + "***" + } + return "***" + }) + want = canaryPattern.ReplaceAllString(want, "${1}***") + want = emailPattern.ReplaceAllString(want, "***@***") + want = phonePattern.ReplaceAllString(want, "***PHONE***") + require.Equal(t, TrimRunes(want, 96), RedactPreview(value, 96)) + } + value := strings.Repeat("x", 1<<20) + var before, after runtime.MemStats + runtime.ReadMemStats(&before) + out := RedactPreview(value, 96) + runtime.ReadMemStats(&after) + require.Less(t, after.TotalAlloc-before.TotalAlloc, uint64(64<<10)) + runtime.KeepAlive(out) +} + +type memoryTestGatedConfig struct { + *fakeConfigStore + reads atomic.Int32 + resume <-chan struct{} +} + +func (c *memoryTestGatedConfig) Active() (ActiveConfig, bool) { + if c.reads.Add(1) >= 2 { + <-c.resume + } + return c.fakeConfigStore.Active() +} + +type memoryTestLegacyMutation struct{ mutate func(Request) } + +func (l memoryTestLegacyMutation) Check(_ context.Context, req Request) (*LegacyDecision, error) { + l.mutate(req) + return &LegacyDecision{Allowed: true}, nil +} + +func TestAsyncAuditOwnsCopyBeforeLegacyOrHandlerCanMutateInput(t *testing.T) { + cfg := asyncConfig() + cfg.AllGroups = false + cfg.GroupIDs = []int64{1} + resume := make(chan struct{}) + store := &memoryTestGatedConfig{fakeConfigStore: &fakeConfigStore{cfg: cfg, active: true}, resume: resume} + repo := &fakeJobRepository{} + svc := memoryTestPromptService(cfg, repo) + svc.config, svc.enqueuer.config = store, store + groupID := int64(1) + req := asyncRequest() + req.GroupID = &groupID + want, err := ExtractPromptSnapshot(req) + require.NoError(t, err) + legacy := memoryTestLegacyMutation{mutate: func(borrowed Request) { + borrowed.Body[0] = '!' + *borrowed.GroupID = 2 + close(resume) + }} + decision := NewCoordinator(legacy, svc).Check(context.Background(), req) + svc.enqueueWG.Wait() + require.True(t, decision.AllowNextStage) + require.Equal(t, AuditMetricsSnapshot{Enqueued: 1}, svc.metrics.AuditSnapshot()) + require.Equal(t, want.PromptHash, repo.createdSnapshot.PromptHash) + require.Equal(t, int64(1), *repo.createdSnapshot.GroupID) +} + +func TestAsyncAuditConcurrentRequestsStillEnqueueWithoutNewDrops(t *testing.T) { + svc := memoryTestPromptService(asyncConfig(), &fakeJobRepository{}) + coordinator := NewCoordinator(nil, svc) + req := asyncRequest() + var callers sync.WaitGroup + for i := 0; i < 8; i++ { + callers.Add(1) + go func() { defer callers.Done(); coordinator.Check(context.Background(), req) }() + } + callers.Wait() + svc.enqueueWG.Wait() + require.Equal(t, AuditMetricsSnapshot{Enqueued: 8}, svc.metrics.AuditSnapshot()) +} + +func originalTrimRunesForMemoryTest(value string, limit int) string { + if limit <= 0 { + return "" + } + runes := []rune(value) + if len(runes) <= limit { + return value + } + return string(runes[:limit]) + "…" +} + +func originalRedactForMemoryTest(value string, limit int) string { + value = bearerPattern.ReplaceAllString(value, "Bearer ***") + value = apiKeyPattern.ReplaceAllStringFunc(value, func(match string) string { + if index := strings.IndexAny(match, ":= \t"); index >= 0 { + return match[:index+1] + "***" + } + return "***" + }) + value = canaryPattern.ReplaceAllString(value, "${1}***") + value = emailPattern.ReplaceAllString(value, "***@***") + value = phonePattern.ReplaceAllString(value, "***PHONE***") + return originalTrimRunesForMemoryTest(value, limit) +} + +func TestAuditTextOptimizationsMatchOriginalOnDeterministicCorpus(t *testing.T) { + rng := rand.New(rand.NewSource(20261111)) + atoms := []string{"x", "中文", "😀", " ", "\xff\xfe", "\x00", "Bearer abcdefghijklmnop", " secret:abcdefghijkl ", " user@example.org ", " +86 138 1234 5678 ", promptAuditPrioritySeparator} + for sample := 0; sample < 100; sample++ { + var builder strings.Builder + for n := rng.Intn(128); n > 0; n-- { + _, _ = builder.WriteString(atoms[rng.Intn(len(atoms))]) + } + value := builder.String() + for _, limit := range []int{0, 1, 24, 96, 4000} { + require.Equal(t, originalTrimRunesForMemoryTest(value, limit), TrimRunes(value, limit)) + require.Equal(t, originalRedactForMemoryTest(value, limit), RedactPreview(value, limit)) + var want []string + if limit > 0 { + want = []string{} + for _, segment := range strings.Split(value, promptAuditPrioritySeparator) { + runes := []rune(segment) + for start := 0; start < len(runes); start += limit { + want = append(want, string(runes[start:min(start+limit, len(runes))])) + } + } + } + require.Equal(t, want, SplitRunes(value, limit)) + } + } +} diff --git a/backend/internal/securityaudit/prompt_scanner.go b/backend/internal/securityaudit/prompt_scanner.go index 103d100454..232fcf422c 100644 --- a/backend/internal/securityaudit/prompt_scanner.go +++ b/backend/internal/securityaudit/prompt_scanner.go @@ -5,6 +5,7 @@ import ( "sort" "strings" "time" + "unicode/utf8" ) func SplitRunes(value string, limit int) []string { @@ -14,18 +15,28 @@ func SplitRunes(value string, limit int) []string { segments := strings.Split(value, promptAuditPrioritySeparator) chunks := make([]string, 0, len(segments)) for _, segment := range segments { - runes := []rune(segment) - for start := 0; start < len(runes); start += limit { - end := start + limit - if end > len(runes) { - end = len(runes) + start, count := 0, 0 + for end := range segment { + if count == limit { + chunks = append(chunks, promptScanChunk(segment[start:end])) + start, count = end, 0 } - chunks = append(chunks, string(runes[start:end])) + count++ + } + if start < len(segment) { + chunks = append(chunks, promptScanChunk(segment[start:])) } } return chunks } +func promptScanChunk(value string) string { + if utf8.ValidString(value) { + return value // immutable substring; no full-transcript rune buffer/copy + } + return string([]rune(value)) // preserve the previous invalid-UTF-8 behavior +} + func AggregateResults(results []*NormalizedResult, latency time.Duration) (*NormalizedResult, error) { if len(results) == 0 { return nil, errors.New("prompt guard produced no complete result") diff --git a/backend/internal/securityaudit/prompt_service.go b/backend/internal/securityaudit/prompt_service.go index 322d3c75e3..5f04322b1d 100644 --- a/backend/internal/securityaudit/prompt_service.go +++ b/backend/internal/securityaudit/prompt_service.go @@ -112,6 +112,21 @@ func (s *PromptService) Enqueue(_ context.Context, req Request) error { if s == nil || s.enqueuer == nil || s.EffectiveMode() != ModeAsync { return nil } + // Enqueuer rechecks configuration before persistence. Check it here too so + // requests outside the audit scope never copy their potentially large body. + cfg, ok := s.config.Active() + if !ok || cfg.EffectiveMode() != ModeAsync { + return nil + } + if !cfg.IncludesGroup(req.GroupID) { + LogInfo(EventEnqueueSkipped, mergeLogFields(requestLogFields(req), map[string]any{"config_version": cfg.ConfigVersion, "status": "skipped", "error_code": "group_out_of_scope"})) + return nil + } + if len(cfg.EnabledEndpoints()) == 0 { + s.enqueuer.recordDropped() + LogWarn(EventEnqueueDropped, mergeLogFields(requestLogFields(req), map[string]any{"config_version": cfg.ConfigVersion, "status": "dropped", "error_code": "no_enabled_endpoint"})) + return nil + } select { case s.enqueueSlots <- struct{}{}: default: diff --git a/backend/internal/securityaudit/prompt_snapshot.go b/backend/internal/securityaudit/prompt_snapshot.go index 74a0d25974..407f323722 100644 --- a/backend/internal/securityaudit/prompt_snapshot.go +++ b/backend/internal/securityaudit/prompt_snapshot.go @@ -636,16 +636,29 @@ func systemPromptSegments(texts []string) []promptSegment { } func RedactPreview(value string, maxRunes int) string { - value = bearerPattern.ReplaceAllString(value, "Bearer ***") - value = apiKeyPattern.ReplaceAllStringFunc(value, func(match string) string { - if index := strings.IndexAny(match, ":= \t"); index >= 0 { - return match[:index+1] + "***" - } - return "***" - }) - value = canaryPattern.ReplaceAllString(value, "${1}***") - value = emailPattern.ReplaceAllString(value, "***@***") - value = phonePattern.ReplaceAllString(value, "***PHONE***") + // ReplaceAllString copies even an unchanged input. Most prompts do not + // match these patterns, so avoid ten full-text allocations just to build a + // short preview. Preserve the replacement order and complete-input matching. + if bearerPattern.MatchString(value) { + value = bearerPattern.ReplaceAllString(value, "Bearer ***") + } + if apiKeyPattern.MatchString(value) { + value = apiKeyPattern.ReplaceAllStringFunc(value, func(match string) string { + if index := strings.IndexAny(match, ":= \t"); index >= 0 { + return match[:index+1] + "***" + } + return "***" + }) + } + if canaryPattern.MatchString(value) { + value = canaryPattern.ReplaceAllString(value, "${1}***") + } + if emailPattern.MatchString(value) { + value = emailPattern.ReplaceAllString(value, "***@***") + } + if phonePattern.MatchString(value) { + value = phonePattern.ReplaceAllString(value, "***PHONE***") + } return TrimRunes(value, maxRunes) } @@ -713,11 +726,21 @@ func TrimRunes(value string, limit int) string { if limit <= 0 { return "" } - runes := []rune(value) - if len(runes) <= limit { - return value + count := 0 + for index := range value { + if count == limit { + // Decode only the retained prefix. Converting the entire prompt to + // []rune just to keep 96/65536 runes allocates four bytes per rune. + // Keep the old replacement behavior for invalid UTF-8 prefixes. + prefix := value[:index] + if utf8.ValidString(prefix) { + return prefix + "…" + } + return string([]rune(prefix)) + "…" + } + count++ } - return string(runes[:limit]) + "…" + return value } func stringValue(value any) string { diff --git a/backend/internal/service/openai_gateway_chat_completions.go b/backend/internal/service/openai_gateway_chat_completions.go index 482060ec8e..4ae13faa19 100644 --- a/backend/internal/service/openai_gateway_chat_completions.go +++ b/backend/internal/service/openai_gateway_chat_completions.go @@ -241,6 +241,9 @@ func (s *OpenAIGatewayService) forwardAsChatCompletions( if err != nil { return nil, fmt.Errorf("marshal responses request: %w", err) } + // responsesReq lives until billing after the stream; only its scalar + // fields are read from here on, so drop the body-sized input. + responsesReq.Input = nil } logFields := []zap.Field{ diff --git a/backend/internal/service/openai_gateway_messages.go b/backend/internal/service/openai_gateway_messages.go index 14aaee67a2..48c03e4a79 100644 --- a/backend/internal/service/openai_gateway_messages.go +++ b/backend/internal/service/openai_gateway_messages.go @@ -220,6 +220,9 @@ func (s *OpenAIGatewayService) ForwardAsAnthropic( if err != nil { return nil, fmt.Errorf("marshal responses request: %w", err) } + // responsesReq lives until billing after the stream; only its scalar + // fields are read from here on, so drop the body-sized input. + responsesReq.Input = nil if account.UsesOpenAICodexProtocol() && account.Platform != PlatformGrok { var reqBody map[string]any diff --git a/backend/internal/service/openai_gateway_request_body.go b/backend/internal/service/openai_gateway_request_body.go index ca990500c0..3fc1282958 100644 --- a/backend/internal/service/openai_gateway_request_body.go +++ b/backend/internal/service/openai_gateway_request_body.go @@ -1108,12 +1108,17 @@ func newOpenAIRequestView(body []byte) openAIRequestView { view := openAIRequestView{body: body} var seen uint8 - // parseRawJSONView reads body without copying; view keeps body alive for extracted strings. + // parseRawJSONView reads body without copying, so extracted strings alias the + // body. They flow into usage logs and async tasks that outlive the request, so + // clone them; otherwise a multi-MB body stays alive after its budget is freed. + field := func(value gjson.Result) string { + return strings.Clone(strings.TrimSpace(value.String())) + } parseRawJSONView(body).ForEach(func(key, value gjson.Result) bool { switch key.Str { case "model": if seen&modelField == 0 { - view.Model = strings.TrimSpace(value.String()) + view.Model = field(value) seen |= modelField } case "stream": @@ -1123,22 +1128,22 @@ func newOpenAIRequestView(body []byte) openAIRequestView { } case "prompt_cache_key": if seen&promptCacheKeyField == 0 { - view.PromptCacheKey = strings.TrimSpace(value.String()) + view.PromptCacheKey = field(value) seen |= promptCacheKeyField } case "previous_response_id": if seen&previousResponseIDField == 0 { - view.PreviousResponseID = strings.TrimSpace(value.String()) + view.PreviousResponseID = field(value) seen |= previousResponseIDField } case "service_tier": if seen&serviceTierField == 0 { - view.ServiceTier = strings.TrimSpace(value.String()) + view.ServiceTier = field(value) seen |= serviceTierField } case "reasoning": if seen&reasoningField == 0 { - view.ReasoningEffort = strings.TrimSpace(value.Get("effort").String()) + view.ReasoningEffort = field(value.Get("effort")) seen |= reasoningField } } diff --git a/backend/internal/service/openai_gateway_service_hotpath_test.go b/backend/internal/service/openai_gateway_service_hotpath_test.go index a703b46a86..916a59f236 100644 --- a/backend/internal/service/openai_gateway_service_hotpath_test.go +++ b/backend/internal/service/openai_gateway_service_hotpath_test.go @@ -39,6 +39,21 @@ func TestOpenAIRequestView_ExtractsFieldsAfterLargeInput(t *testing.T) { require.Equal(t, "high", view.ReasoningEffort) } +func TestOpenAIRequestView_FieldsDoNotAliasBody(t *testing.T) { + body := []byte(`{"model":"gpt-5","prompt_cache_key":"session-1","previous_response_id":"resp-1","service_tier":"flex","reasoning":{"effort":"high"}}`) + + view := newOpenAIRequestView(body) + for i := range body { + body[i] = 'x' + } + + require.Equal(t, "gpt-5", view.Model) + require.Equal(t, "session-1", view.PromptCacheKey) + require.Equal(t, "resp-1", view.PreviousResponseID) + require.Equal(t, "flex", view.ServiceTier) + require.Equal(t, "high", view.ReasoningEffort) +} + func TestOpenAIRequestView_KeepsFirstDuplicateField(t *testing.T) { view := newOpenAIRequestView([]byte(`{"model":"gpt-5","model":"gpt-5.1","reasoning":{"effort":"low"},"reasoning":{"effort":"high"}}`)) diff --git a/backend/internal/service/openai_gateway_usage.go b/backend/internal/service/openai_gateway_usage.go index e77efee7e7..aaf19f3039 100644 --- a/backend/internal/service/openai_gateway_usage.go +++ b/backend/internal/service/openai_gateway_usage.go @@ -467,14 +467,13 @@ func (s *OpenAIGatewayService) RecordUsage(ctx context.Context, input *OpenAIRec billingMode := string(BillingModeToken) usageLog.BillingMode = &billingMode } - // 添加 UserAgent - if input.UserAgent != "" { - usageLog.UserAgent = &input.UserAgent + // 添加 UserAgent / IPAddress。取副本地址:指向 input 字段会让整个 input(含 Result + // 及其引用的请求体)随异步写入的 usageLog 一直存活。 + if userAgent := input.UserAgent; userAgent != "" { + usageLog.UserAgent = &userAgent } - - // 添加 IPAddress - if input.IPAddress != "" { - usageLog.IPAddress = &input.IPAddress + if ipAddress := input.IPAddress; ipAddress != "" { + usageLog.IPAddress = &ipAddress } // 添加 SessionID(客户端显式会话标识;缺失/无效时保持 nil) From 570d59e9ac0f32bf5caa51f0a1a72c60f40fbc01 Mon Sep 17 00:00:00 2001 From: wucm667 Date: Tue, 17 Nov 2026 15:13:03 +0800 Subject: [PATCH 41/85] fix(anthropic): expose metadata-backed long-context models --- backend/internal/handler/gateway_handler.go | 16 ++++ .../internal/handler/gateway_models_test.go | 76 +++++++++++++++++++ .../internal/service/anthropic_models_list.go | 47 ++++++++++++ backend/internal/service/upstream_models.go | 7 +- .../internal/service/upstream_models_test.go | 46 +++++++++++ 5 files changed, 191 insertions(+), 1 deletion(-) create mode 100644 backend/internal/service/anthropic_models_list.go diff --git a/backend/internal/handler/gateway_handler.go b/backend/internal/handler/gateway_handler.go index d3921ef932..300db262d5 100644 --- a/backend/internal/handler/gateway_handler.go +++ b/backend/internal/handler/gateway_handler.go @@ -1195,6 +1195,22 @@ func (h *GatewayHandler) Models(c *gin.Context) { // Get available models from account configurations for the selected group platform. availableModels := h.gatewayService.GetAvailableModels(c.Request.Context(), groupID, platform) + if platform == service.PlatformAnthropic { + var group *service.Group + if apiKey != nil { + group = apiKey.Group + } + source := availableModels + if group != nil && group.ModelAllowlistEnabled() { + source = modelListingSource(platform, availableModels, defaultModelIDsForPlatform(platform)) + } else if len(source) == 0 { + source = defaultModelIDsForPlatform(platform) + } + expanded := h.gatewayService.ExpandAnthropicLongContextModels(c.Request.Context(), group, source) + if len(availableModels) > 0 || len(expanded) > len(source) || (group != nil && group.ModelAllowlistEnabled()) { + availableModels = expanded + } + } if apiKey != nil && apiKey.Group != nil && apiKey.Group.ModelAllowlistEnabled() { source := modelListingSource(platform, availableModels, defaultModelIDsForPlatform(platform)) writeAllowlistedModelsList(c, platform, apiKey.Group.ModelAllowlist.FilterForListing(source)) diff --git a/backend/internal/handler/gateway_models_test.go b/backend/internal/handler/gateway_models_test.go index 27daa74f8c..0d5b9b2fc7 100644 --- a/backend/internal/handler/gateway_models_test.go +++ b/backend/internal/handler/gateway_models_test.go @@ -23,6 +23,82 @@ type gatewayModelsAccountRepoStub struct { byGroup map[int64][]service.Account } +func TestGatewayModelsAnthropicLongContextVariants(t *testing.T) { + gin.SetMode(gin.TestMode) + const groupID int64 = 8880 + for _, test := range []struct { + name string + platform string + mapping map[string]any + metadata map[string]service.UpstreamModelMetadata + allowlist []string + routing map[string][]int64 + otherAccounts []service.Account + wantVariants []string + absent []string + }{ + {name: "mapped target and threshold", mapping: map[string]any{"public": "upstream", "short": "short", "max-only": "max-only"}, + metadata: map[string]service.UpstreamModelMetadata{"upstream": {ContextWindow: 900_000}, "short": {ContextWindow: 899_999}, "max-only": {MaxContextWindow: 1_000_000}, "hidden": {ContextWindow: 1_000_000}}, + wantVariants: []string{"public[1m]"}, absent: []string{"upstream", "upstream[1m]", "hidden", "hidden[1m]", "short[1m]", "max-only[1m]", claude.DefaultModels[0].ID}}, + {name: "wildcard mappings are not concrete variants", mapping: map[string]any{"public*": "upstream"}, + metadata: map[string]service.UpstreamModelMetadata{"upstream": {ContextWindow: 1_000_000}}, absent: []string{"public*[1m]"}}, + {name: "source metadata cannot override mapped target", mapping: map[string]any{"public": "short"}, + metadata: map[string]service.UpstreamModelMetadata{"public": {ContextWindow: 1_000_000}, "short": {ContextWindow: 200_000}}, absent: []string{"public[1m]"}}, + {name: "no duplicate suffix", mapping: map[string]any{"public": "upstream", "public[1m]": "upstream", "other[1M]": "upstream"}, + metadata: map[string]service.UpstreamModelMetadata{"upstream": {ContextWindow: 1_000_000}}, wantVariants: []string{"public[1m]", "other[1M]"}, absent: []string{"public[1m][1m]", "other[1M][1m]"}}, + {name: "allowlist filters variants", mapping: map[string]any{"public": "upstream", "private": "upstream"}, + metadata: map[string]service.UpstreamModelMetadata{"upstream": {ContextWindow: 1_000_000}}, allowlist: []string{"public"}, absent: []string{"public[1m]", "private", "private[1m]"}}, + {name: "allowlist can select variant", mapping: map[string]any{"public": "upstream"}, + metadata: map[string]service.UpstreamModelMetadata{"upstream": {ContextWindow: 1_000_000}}, allowlist: []string{"public[1m]"}, wantVariants: []string{"public[1m]"}, absent: []string{"public"}}, + {name: "routing excludes metadata account", mapping: map[string]any{"public": "upstream"}, + metadata: map[string]service.UpstreamModelMetadata{"upstream": {ContextWindow: 1_000_000}}, routing: map[string][]int64{"public": {2}}, absent: []string{"public[1m]"}}, + {name: "routing includes metadata account", mapping: map[string]any{"public": "upstream"}, + metadata: map[string]service.UpstreamModelMetadata{"upstream": {ContextWindow: 1_000_000}}, routing: map[string][]int64{"pub*": {1}}, wantVariants: []string{"public[1m]"}}, + {name: "non-Anthropic listing", platform: service.PlatformOpenAI, mapping: map[string]any{"public": "upstream"}, + metadata: map[string]service.UpstreamModelMetadata{"upstream": {ContextWindow: 1_000_000}}, absent: []string{"public[1m]"}}, + {name: "unmapped defaults", metadata: map[string]service.UpstreamModelMetadata{claude.DefaultModels[0].ID: {ContextWindow: 1_000_000}, "hidden": {ContextWindow: 1_000_000}}, + wantVariants: []string{claude.DefaultModels[0].ID + "[1m]"}, absent: []string{"hidden", "hidden[1m]"}}, + {name: "other platform account metadata", mapping: map[string]any{"public": "upstream"}, + otherAccounts: []service.Account{{ID: 2, Platform: service.PlatformOpenAI, Extra: map[string]any{service.UpstreamModelMetadataExtraKey: service.UpstreamModelMetadataSnapshot{Models: map[string]service.UpstreamModelMetadata{"upstream": {ContextWindow: 1_000_000}}}}}}, absent: []string{"public[1m]"}}, + {name: "unsupported model metadata", mapping: map[string]any{"public": "upstream"}, + otherAccounts: []service.Account{{ID: 2, Platform: service.PlatformAnthropic, Credentials: map[string]any{"model_mapping": map[string]any{"private": "private"}}, Extra: map[string]any{service.UpstreamModelMetadataExtraKey: service.UpstreamModelMetadataSnapshot{Models: map[string]service.UpstreamModelMetadata{"public": {ContextWindow: 1_000_000}}}}}}, absent: []string{"public[1m]"}}, + } { + t.Run(test.name, func(t *testing.T) { + platform := test.platform + if platform == "" { + platform = service.PlatformAnthropic + } + account := service.Account{ID: 1, Platform: platform, Type: service.AccountTypeOAuth, Credentials: map[string]any{"model_mapping": test.mapping}} + account.SetUpstreamModelMetadataSnapshot(service.UpstreamModelMetadataSnapshot{Models: test.metadata}) + outsideAccount := service.Account{ID: 3, Platform: service.PlatformAnthropic} + outsideAccount.SetUpstreamModelMetadataSnapshot(service.UpstreamModelMetadataSnapshot{Models: map[string]service.UpstreamModelMetadata{"upstream": {ContextWindow: 1_000_000}}}) + h := newGatewayModelsHandlerForTest(&gatewayModelsAccountRepoStub{byGroup: map[int64][]service.Account{ + groupID: append([]service.Account{account}, test.otherAccounts...), groupID + 1: {outsideAccount}, + }}) + rec := httptest.NewRecorder() + ctx, _ := gin.CreateTestContext(rec) + ctx.Request = httptest.NewRequest(http.MethodGet, "/v1/models", nil) + ctx.Set(string(middleware2.ContextKeyAPIKey), &service.APIKey{Group: &service.Group{ + ID: groupID, Platform: platform, + ModelAllowlist: service.GroupModelAllowlist{Enabled: test.allowlist != nil, Models: test.allowlist}, + ModelRoutingEnabled: test.routing != nil, ModelRouting: test.routing, + }}) + h.Models(ctx) + require.Equal(t, http.StatusOK, rec.Code) + var response gatewayModelsResponseForTest + require.NoError(t, json.Unmarshal(rec.Body.Bytes(), &response)) + ids := modelIDsForTest(response.Data) + for _, variant := range test.wantVariants { + require.Contains(t, ids, variant) + } + for _, absent := range test.absent { + require.NotContains(t, ids, absent) + } + require.Len(t, mergeModelIDs(ids, nil), len(ids)) + }) + } +} + type gatewayModelsRouteRepoStub struct { service.CompositeModelRouteRepository routes []service.CompositeModelRoute diff --git a/backend/internal/service/anthropic_models_list.go b/backend/internal/service/anthropic_models_list.go new file mode 100644 index 0000000000..e337693594 --- /dev/null +++ b/backend/internal/service/anthropic_models_list.go @@ -0,0 +1,47 @@ +package service + +import ( + "context" + "slices" + "strings" +) + +func (s *GatewayService) ExpandAnthropicLongContextModels(ctx context.Context, group *Group, models []string) []string { + var accounts []Account + var err error + if group != nil { + accounts, err = s.accountRepo.ListSchedulableByGroupID(ctx, group.ID) + } else { + accounts, err = s.accountRepo.ListSchedulable(ctx) + } + if err != nil { + return models + } + result := cloneStringSlice(models) + seen := make(map[string]bool, len(models)) + for _, model := range models { + seen[strings.ToLower(model)] = true + } + for _, model := range models { + if strings.HasSuffix(strings.ToLower(model), claudeCodeLongContextModelSuffix) || strings.Contains(model, "*") { + continue + } + var routedAccountIDs []int64 + if group != nil { + routedAccountIDs = group.GetRoutingAccountIDs(model) + } + for _, account := range accounts { + if !account.IsAnthropic() || !account.IsModelSupported(model) || + (len(routedAccountIDs) > 0 && !slices.Contains(routedAccountIDs, account.ID)) { + continue + } + metadata, ok := account.GetUpstreamModelMetadata(account.GetMappedModel(model)) + variant := model + claudeCodeLongContextModelSuffix + if ok && metadata.ContextWindow >= 900_000 && !seen[strings.ToLower(variant)] { + result = append(result, variant) + seen[strings.ToLower(variant)] = true + } + } + } + return result +} diff --git a/backend/internal/service/upstream_models.go b/backend/internal/service/upstream_models.go index c6587cee50..82fd9a5876 100644 --- a/backend/internal/service/upstream_models.go +++ b/backend/internal/service/upstream_models.go @@ -683,7 +683,10 @@ func upstreamModelRegistryBaseURL(account *Account) string { case account.IsGemini(): return account.GetGeminiBaseURL(geminicli.AIStudioBaseURL) case account.IsAnthropic(): - return account.GetBaseURL() + if baseURL := strings.TrimSpace(account.GetCredential("base_url")); baseURL != "" { + return baseURL + } + return "https://api.anthropic.com" case account.Platform == PlatformAntigravity: return account.GetGeminiBaseURL(geminicli.AIStudioBaseURL) default: @@ -734,6 +737,8 @@ func matchModelsDevProviderByKnownHost(registry map[string]modelsDevProvider, ac } providerID := "" switch host { + case "api.anthropic.com": + providerID = "anthropic" case "api.openai.com", "chatgpt.com": providerID = "openai" case "opencode.ai": diff --git a/backend/internal/service/upstream_models_test.go b/backend/internal/service/upstream_models_test.go index 8d023f0383..be5aeb0276 100644 --- a/backend/internal/service/upstream_models_test.go +++ b/backend/internal/service/upstream_models_test.go @@ -15,6 +15,52 @@ import ( "github.com/stretchr/testify/require" ) +func TestAnthropicModelRegistryBaseURLAndProvider(t *testing.T) { + registry := map[string]modelsDevProvider{ + "anthropic": {Models: map[string]modelsDevModel{"claude-test": {}}}, + "gateway": {ID: "gateway", API: "https://gateway.example/v1", Models: map[string]modelsDevModel{"custom": {}}}, + } + for _, accountType := range []string{AccountTypeOAuth, AccountTypeSetupToken, AccountTypeAPIKey} { + for _, test := range []struct { + name, credential, wantURL, wantProvider string + }{ + {"default", "", "https://api.anthropic.com", "anthropic"}, + {"blank", " \t ", "https://api.anthropic.com", "anthropic"}, + {"official", " https://api.anthropic.com/v1/ ", "https://api.anthropic.com/v1/", "anthropic"}, + {"custom", " https://gateway.example/v1 ", "https://gateway.example/v1", "gateway"}, + {"unknown", "https://unknown.example/v1", "https://unknown.example/v1", ""}, + } { + t.Run(accountType+"/"+test.name, func(t *testing.T) { + account := &Account{Platform: PlatformAnthropic, Type: accountType, + Credentials: map[string]any{"base_url": test.credential}} + baseURL := upstreamModelRegistryBaseURL(account) + require.Equal(t, test.wantURL, baseURL) + provider, ok := matchModelsDevProvider(registry, baseURL) + require.Equal(t, test.wantProvider != "", ok) + require.Equal(t, test.wantProvider, provider.ID) + }) + } + } +} + +func TestFetchModelsDevMetadataAnthropicOAuthAndSetupToken(t *testing.T) { + for _, accountType := range []string{AccountTypeOAuth, AccountTypeSetupToken} { + t.Run(accountType, func(t *testing.T) { + upstream := &httpUpstreamRecorder{responses: []*http.Response{{ + StatusCode: http.StatusOK, + Header: http.Header{"Content-Type": []string{"application/json"}}, + Body: io.NopCloser(strings.NewReader(`{"anthropic":{"models":{"claude-test":{"id":"claude-test","limit":{"context":1000000}}}}}`)), + }}} + svc := &AccountTestService{httpUpstream: upstream, cfg: upstreamModelSyncTestConfig()} + metadata, err := svc.fetchModelsDevMetadata(context.Background(), &Account{ + Platform: PlatformAnthropic, Type: accountType, + }, []string{"claude-test"}) + require.NoError(t, err) + require.Equal(t, int64(1_000_000), metadata["claude-test"].ContextWindow) + }) + } +} + type upstreamModelMetadataRepoStub struct { AccountRepository accountID int64 From f66984fc5df773522559396c4a7cda0a7a843f0e Mon Sep 17 00:00:00 2001 From: SipengXie2024 <184713193+SipengXie2024@users.noreply.github.com> Date: Tue, 17 Nov 2026 08:28:24 +0000 Subject: [PATCH 42/85] fix(openai): keep relayed image usage on a single SSE data line The Codex direct Images endpoints pretty-print their JSON. When a streaming request gets a plain JSON answer, the usage object is copied verbatim into the completed event, so its newlines split the SSE data payload. Strict SSE clients then read a truncated JSON line and report no image even though the event carries b64_json. Compact usage before embedding it. --- .../service/openai_images_direct_test.go | 26 +++++++++++++++++++ .../service/openai_images_responses.go | 6 +++++ 2 files changed, 32 insertions(+) diff --git a/backend/internal/service/openai_images_direct_test.go b/backend/internal/service/openai_images_direct_test.go index aa5e410d00..4172f696a2 100644 --- a/backend/internal/service/openai_images_direct_test.go +++ b/backend/internal/service/openai_images_direct_test.go @@ -126,6 +126,32 @@ func TestCodexDirectImagesStreamDeliversPlainJSON(t *testing.T) { require.Contains(t, rec.Body.String(), `"b64_json":"aGVsbG8="`) } +// The live endpoint pretty-prints its JSON; the usage copied into the +// completed event must not split the SSE data line. +func TestCodexDirectImagesStreamKeepsPrettyPrintedUsageOnOneLine(t *testing.T) { + body := []byte(`{"model":"gpt-image-2","prompt":"draw","stream":true}`) + c, rec := newOpenAIImagesTestContext(t, body) + resp := openAIImagesJSONResponse() + resp.Body = io.NopCloser(strings.NewReader("{\n \"created\": 1710000000,\n \"data\": [\n {\n \"b64_json\": \"aGVsbG8=\"\n }\n ],\n \"usage\": {\n \"input_tokens\": 10,\n \"output_tokens\": 20\n }\n}\n")) + svc := newOpenAIImagesTestService(&httpUpstreamRecorder{resp: resp}) + parsed, err := svc.ParseOpenAIImagesRequest(c, body) + require.NoError(t, err) + _, err = svc.ForwardImages(context.Background(), c, directImagesTestAccount(), body, parsed, "") + require.NoError(t, err) + + out := strings.TrimRight(rec.Body.String(), "\n") + var data string + for _, line := range strings.Split(out, "\n") { + require.True(t, line == "" || strings.HasPrefix(line, "event: ") || strings.HasPrefix(line, "data: "), "SSE line split mid-payload: %q", line) + if strings.HasPrefix(line, "data: ") { + data = strings.TrimPrefix(line, "data: ") + } + } + require.True(t, gjson.Valid(data), "data line is not complete JSON: %q", data) + require.Equal(t, "aGVsbG8=", gjson.Get(data, "b64_json").String()) + require.Equal(t, int64(20), gjson.Get(data, "usage.output_tokens").Int()) +} + func TestCodexDirectImagesMultipleOutputs(t *testing.T) { for _, stream := range []bool{false, true} { t.Run(fmt.Sprint(stream), func(t *testing.T) { diff --git a/backend/internal/service/openai_images_responses.go b/backend/internal/service/openai_images_responses.go index 5effc98bc0..54541b2981 100644 --- a/backend/internal/service/openai_images_responses.go +++ b/backend/internal/service/openai_images_responses.go @@ -4,6 +4,7 @@ import ( "bytes" "context" "encoding/base64" + "encoding/json" "errors" "fmt" "io" @@ -300,6 +301,11 @@ func buildOpenAIImagesStreamCompletedPayload( payload, _ = sjson.SetBytes(payload, "model", img.Model) } if len(usageRaw) > 0 && gjson.ValidBytes(usageRaw) { + // Upstream JSON may be pretty-printed; a newline would split the SSE data line. + var compact bytes.Buffer + if json.Compact(&compact, usageRaw) == nil { + usageRaw = compact.Bytes() + } payload, _ = sjson.SetRawBytes(payload, "usage", usageRaw) } return payload From 18c42a29d2edb2e314eef5115021fe33b7fa5af6 Mon Sep 17 00:00:00 2001 From: r266-tech Date: Mon, 16 Nov 2026 15:00:05 +0800 Subject: [PATCH 43/85] perf(scheduler): omit expanded groups from account cache --- .../internal/repository/scheduler_cache.go | 4 + .../scheduler_cache_integration_test.go | 9 +- .../scheduler_cache_payload_unit_test.go | 116 ++++++++++++++++++ .../repository/scheduler_cache_unit_test.go | 1 - 4 files changed, 128 insertions(+), 2 deletions(-) create mode 100644 backend/internal/repository/scheduler_cache_payload_unit_test.go diff --git a/backend/internal/repository/scheduler_cache.go b/backend/internal/repository/scheduler_cache.go index b003ae10cc..05a322396e 100644 --- a/backend/internal/repository/scheduler_cache.go +++ b/backend/internal/repository/scheduler_cache.go @@ -1345,6 +1345,10 @@ func newSchedulerAccountMetaRevision() string { } func marshalSchedulerCacheAccount(account service.Account) ([]byte, []byte, error) { + // Hydration needs account configuration and group membership, not expanded + // group objects (also repeated in AccountGroups). Keep the caller's graph intact. + account.Groups = nil + account.AccountGroups = filterSchedulerAccountGroups(account.AccountGroups) fullPayload, err := json.Marshal(account) if err != nil { return nil, nil, fmt.Errorf("marshal account: %w", err) diff --git a/backend/internal/repository/scheduler_cache_integration_test.go b/backend/internal/repository/scheduler_cache_integration_test.go index 52673315c8..063521397b 100644 --- a/backend/internal/repository/scheduler_cache_integration_test.go +++ b/backend/internal/repository/scheduler_cache_integration_test.go @@ -57,6 +57,7 @@ func TestSchedulerCacheSnapshotUsesSlimMetadataButKeepsFullAccount(t *testing.T) SessionWindowEnd: &windowEnd, SessionWindowStatus: "active", GroupIDs: []int64{bucket.GroupID}, + Groups: []*service.Group{{ID: bucket.GroupID, Description: strings.Repeat("unused group configuration", 1024)}}, AccountGroups: []service.AccountGroup{ { AccountID: 101, @@ -101,8 +102,14 @@ func TestSchedulerCacheSnapshotUsesSlimMetadataButKeepsFullAccount(t *testing.T) require.NotNil(t, full) require.Equal(t, "secret-access-token", full.GetCredential("access_token")) require.Equal(t, strings.Repeat("x", 4096), full.GetCredential("huge_blob")) + require.Equal(t, account.GroupIDs, full.GroupIDs) + require.Empty(t, full.Groups) require.Len(t, full.AccountGroups, 1) - require.NotNil(t, full.AccountGroups[0].Group) + require.Equal(t, account.ID, full.AccountGroups[0].AccountID) + require.Equal(t, bucket.GroupID, full.AccountGroups[0].GroupID) + require.Equal(t, 5, full.AccountGroups[0].Priority) + require.Nil(t, full.AccountGroups[0].Group) + require.Nil(t, full.AccountGroups[0].Account) } func TestSchedulerCacheRetireAndReopenFencesOldEpochIntegration(t *testing.T) { diff --git a/backend/internal/repository/scheduler_cache_payload_unit_test.go b/backend/internal/repository/scheduler_cache_payload_unit_test.go new file mode 100644 index 0000000000..8802bccbaf --- /dev/null +++ b/backend/internal/repository/scheduler_cache_payload_unit_test.go @@ -0,0 +1,116 @@ +//go:build unit + +package repository + +import ( + "context" + "encoding/json" + "fmt" + "strconv" + "strings" + "testing" + "time" + + "github.com/Wei-Shaw/sub2api/internal/service" + "github.com/stretchr/testify/require" +) + +func TestSchedulerCacheAccountOmitsExpandedGroups(t *testing.T) { + for _, groupCount := range []int{1, 10, 100, 241} { + t.Run(strconv.Itoa(groupCount), func(t *testing.T) { + ctx := context.Background() + cache := newSchedulerCacheUnit(t) + now := time.Date(2026, time.November, 16, 12, 0, 0, 0, time.UTC) + resetAt := now.Add(time.Hour) + rate := 0.0 + proxyID := int64(5) + expected := service.Account{ + ID: 8842, Name: "multi-group", Platform: service.PlatformOpenAI, + Type: service.AccountTypeOAuth, Status: service.StatusActive, Schedulable: true, + Credentials: map[string]any{ + "access_token": "fixture-access", "refresh_token": "fixture-refresh", + "openai_capabilities": []any{"responses"}, + "model_mapping": map[string]any{"public-model": "upstream-model"}, + }, + Extra: map[string]any{"custom_account_setting": "keep", "openai_oauth_passthrough": true}, + ProxyID: &proxyID, Proxy: &service.Proxy{ID: proxyID, Protocol: "http", Host: "proxy.example", Port: 8080}, + Concurrency: 3, Priority: 7, RateMultiplier: &rate, + RateLimitResetAt: &resetAt, LastUsedAt: &now, + CreatedAt: now, UpdatedAt: now, + } + for i := 1; i <= groupCount; i++ { + expected.GroupIDs = append(expected.GroupIDs, int64(i)) + expected.AccountGroups = append(expected.AccountGroups, service.AccountGroup{ + AccountID: expected.ID, GroupID: int64(i), Priority: i, CreatedAt: now, + }) + } + account := expected + account.AccountGroups = append([]service.AccountGroup(nil), expected.AccountGroups...) + for i := range account.AccountGroups { + group := &service.Group{ + ID: int64(i + 1), Name: fmt.Sprintf("group-%d", i+1), + Description: strings.Repeat("unused group configuration ", 128), + } + account.Groups = append(account.Groups, group) + account.AccountGroups[i].Group = group + account.AccountGroups[i].Account = &service.Account{ID: account.ID, Name: "unused account edge"} + } + original, err := json.Marshal(account) + require.NoError(t, err) + + // Both account updates and bucket rebuilds write the same global record. + for _, write := range []string{"account", "snapshot"} { + t.Run(write, func(t *testing.T) { + if write == "account" { + require.NoError(t, cache.SetAccount(ctx, &account)) + } else { + bucket := service.SchedulerBucket{GroupID: 1, Platform: account.Platform, Mode: service.SchedulerModeSingle} + token, err := cache.CaptureBucketWriteToken(ctx, bucket) + require.NoError(t, err) + require.NoError(t, cache.SetSnapshot(ctx, bucket, token, []service.Account{account})) + snapshot, hit, err := cache.GetSnapshot(ctx, bucket) + require.NoError(t, err) + require.True(t, hit) + require.Len(t, snapshot, 1) + require.Equal(t, expected.GroupIDs, snapshot[0].GroupIDs) + require.Equal(t, expected.AccountGroups, snapshot[0].AccountGroups) + } + full, err := cache.GetAccount(ctx, account.ID) + require.NoError(t, err) + require.NotNil(t, full) + require.Zero(t, len(full.Groups), "full cache must omit expanded groups") + for _, membership := range full.AccountGroups { + require.True(t, membership.Group == nil && membership.Account == nil, "full cache must omit relationship objects") + } + require.Equal(t, &expected, full, "hydration must retain account configuration and membership") + payload, err := cache.rdb.Get(ctx, schedulerAccountKey(strconv.FormatInt(account.ID, 10))).Bytes() + require.NoError(t, err) + require.NotContains(t, string(payload), "unused group configuration") + require.NotContains(t, string(payload), "unused account edge") + require.Less(t, len(payload)*4, len(original)) + t.Logf("groups=%d expanded_bytes=%d cached_bytes=%d", groupCount, len(original), len(payload)) + }) + } + + // Serialization must not detach relationships from the repository's object. + after, err := json.Marshal(account) + require.NoError(t, err) + require.Equal(t, original, after) + }) + } +} + +func TestSchedulerCacheReadsLegacyExpandedGroups(t *testing.T) { + ctx := context.Background() + cache := newSchedulerCacheUnit(t) + account := service.Account{ + ID: 8843, GroupIDs: []int64{2}, Groups: []*service.Group{{ID: 2, Name: "legacy"}}, + AccountGroups: []service.AccountGroup{{AccountID: 8843, GroupID: 2, Priority: 4, Group: &service.Group{ID: 2}}}, + } + payload, err := json.Marshal(account) + require.NoError(t, err) + require.NoError(t, cache.rdb.Set(ctx, schedulerAccountKey("8843"), payload, 0).Err()) + full, err := cache.GetAccount(ctx, account.ID) + require.NoError(t, err) + require.Equal(t, &account, full, "rolling upgrades can still read records written by old instances") +} diff --git a/backend/internal/repository/scheduler_cache_unit_test.go b/backend/internal/repository/scheduler_cache_unit_test.go index fde314835f..2e3e9c14ad 100644 --- a/backend/internal/repository/scheduler_cache_unit_test.go +++ b/backend/internal/repository/scheduler_cache_unit_test.go @@ -276,7 +276,6 @@ func TestMarshalSchedulerCacheAccountKeepsEncodingJSONWireFormat(t *testing.T) { Credentials: map[string]any{}, Extra: map[string]any{}, GroupIDs: []int64{}, - Groups: []*service.Group{}, }}, {name: "nested maps and escaping", account: service.Account{ ID: 803, From 77ba3346d1ae9aa3930dc1b347d05582e1bae93d Mon Sep 17 00:00:00 2001 From: SipengXie2024 <184713193+SipengXie2024@users.noreply.github.com> Date: Tue, 17 Nov 2026 09:50:16 +0000 Subject: [PATCH 44/85] fix(openai): skip foreign-vendor models on ChatGPT OAuth accounts, passthrough included Empty-mapping OpenAI OAuth accounts accepted claude-* models, and OAuth or setup-token accounts with openai_passthrough accepted every model. Both send requests to chatgpt.com/backend-api/codex, which answers foreign models with a non-retryable 400 ("not supported when using Codex with a ChatGPT account"), so mixed groups handed claude-* requests from Codex clients to the OAuth account instead of the API-key account that serves them. - Add "claude-" to openAIOAuthForeignModelPrefixes. - Apply the foreign-prefix check to OAuth and setup-token passthrough too; API-key passthrough keeps allowing every model. - Schedule /v1/messages by the channel-mapped model, as Responses, Chat Completions and the Responses WebSocket already do, so a channel mapping a claude-* alias to a GPT model still lands on OAuth accounts. --- .../handler/openai_gateway_handler.go | 5 ++- backend/internal/service/account.go | 12 +++-- .../internal/service/openai_model_mapping.go | 7 +-- .../openai_oauth_model_support_test.go | 44 ++++++++++++++++--- 4 files changed, 54 insertions(+), 14 deletions(-) diff --git a/backend/internal/handler/openai_gateway_handler.go b/backend/internal/handler/openai_gateway_handler.go index d2d5448bdf..a0cd8ddd66 100644 --- a/backend/internal/handler/openai_gateway_handler.go +++ b/backend/internal/handler/openai_gateway_handler.go @@ -1250,7 +1250,6 @@ func (h *OpenAIGatewayHandler) Messages(c *gin.Context) { return } bindOpenAIReasoningEffortPolicyForMessagesRequest(c, apiKey, body) - routingModel := service.NormalizeOpenAICompatRequestedModel(reqModel) preferredMappedModel := resolveOpenAIMessagesDispatchMappedModel(c, apiKey, reqModel) reqStream := gjson.GetBytes(body, "stream").Bool() @@ -1267,6 +1266,10 @@ func (h *OpenAIGatewayHandler) Messages(c *gin.Context) { // 解析渠道级模型映射 channelMappingMsg, _ := h.gatewayService.ResolveChannelMappingAndRestrict(c.Request.Context(), apiKey.GroupID, reqModel) mappedBodyForMessages := newOpenAIModelMappedBodyCache(body, h.gatewayService.ReplaceModelInBody) + // Schedule by the channel-mapped model, as the Responses and Chat Completions + // paths do: the forwarded body carries that model, so account model filters + // must judge it rather than the client's alias. + routingModel := service.NormalizeOpenAICompatRequestedModel(openAIChannelForwardModel(channelMappingMsg, reqModel)) // 绑定错误透传服务,允许 service 层在非 failover 错误场景复用规则。 if h.errorPassthroughService != nil { diff --git a/backend/internal/service/account.go b/backend/internal/service/account.go index 51b253bcab..a59813ce5c 100644 --- a/backend/internal/service/account.go +++ b/backend/internal/service/account.go @@ -957,8 +957,8 @@ func resolveRequestedModelInMapping(mapping map[string]string, requestedModel st // IsModelSupported 检查模型是否在 model_mapping 中(支持通配符) // 如果未配置 mapping,返回 true(允许所有模型)。 // -// 例外:OpenAI OAuth 账号(Codex 上游)的空映射会排除明确属于其他厂商 -// 家族的模型(deepseek-*/glm-* 等)——转发阶段 normalizeOpenAIModelForUpstream +// 例外:OpenAI OAuth 账号(Codex 上游)的空映射与透传模式都会排除明确属于 +// 其他厂商家族的模型(claude-*/deepseek-*/glm-* 等)——转发阶段 normalizeOpenAIModelForUpstream // 会把未知模型原样透传,Codex 上游对这类模型必然返回不可重试的 400,导致 // 请求卡死在该账号上、无法 failover 到真正支持该模型的 API Key 账号(#3662)。 // 未知/自定义别名仍保持允许(兼容渠道级映射),见 isOpenAIOAuthServableModel。 @@ -971,11 +971,17 @@ func (a *Account) IsModelSupported(requestedModel string) bool { } func (a *Account) isModelMappingSupported(requestedModel string) bool { - // 透传模式仅替换认证、模型语义完全交由上游决定,因此放行所有模型。 + // 透传模式仅替换认证、模型语义交由上游决定,因此除下面 OAuth 的异族厂商模型外放行所有模型。 // 该短路必须在 model_mapping 判定之前:账号从"白名单模式"切换到透传后, // credentials 里常残留旧的非空 model_mapping,若不在此放行,透传账号会被 // model_mapping 白名单错误排除出候选集,导致 no available accounts / 404(issue #4936)。 if a.IsOpenAIPassthroughEnabled() { + // OAuth 与 Setup Token 透传的出口恒为 chatgpt.com/backend-api/codex(见 + // buildUpstreamRequestOpenAIPassthrough),异族厂商模型在那里必然是不可重试的 400, + // 因此透传也要在调度阶段跳过它们;API Key 透传的上游由 base_url 决定,不受此限。 + if a.IsOpenAIOAuthLike() && !isOpenAIOAuthServableModel(requestedModel) { + return false + } if !a.IsOpenAIPassthroughModelFilterEnabled() { return true } diff --git a/backend/internal/service/openai_model_mapping.go b/backend/internal/service/openai_model_mapping.go index 7fd67468b1..a590c76a84 100644 --- a/backend/internal/service/openai_model_mapping.go +++ b/backend/internal/service/openai_model_mapping.go @@ -25,11 +25,12 @@ func resolveOpenAIForwardModel(account *Account, requestedModel, messagesDispatc // Codex 上游不可能服务这些模型:转发阶段 normalizeOpenAIModelForUpstream // 对未知模型原样透传,上游必然返回不可重试的 400。 // -// 采用保守黑名单而非 Codex 模型白名单:未知/自定义别名保持「允许」, -// 以兼容渠道级模型映射等「账号选定之后才改写模型名」的部署方式 -// (调度过滤看到的是改写前的原始模型名)。前缀分类的先例见 +// 采用保守黑名单而非 Codex 模型白名单:未知/自定义别名保持「允许」。 +// 渠道级模型映射不受影响:各 OpenAI 入口都按渠道映射后的模型名调度, +// 把 claude-* 等别名映射到 gpt-5.x 的渠道照常落到 OAuth 账号。前缀分类的先例见 // ResolveThinkingProtocol(thinking_protocol.go)。 var openAIOAuthForeignModelPrefixes = []string{ + "claude-", "deepseek-", "glm-", "kimi-", diff --git a/backend/internal/service/openai_oauth_model_support_test.go b/backend/internal/service/openai_oauth_model_support_test.go index 8ea10d1371..cce75a4eb0 100644 --- a/backend/internal/service/openai_oauth_model_support_test.go +++ b/backend/internal/service/openai_oauth_model_support_test.go @@ -28,9 +28,7 @@ func TestIsModelSupported_OpenAIOAuthEmptyMapping_ServableModels(t *testing.T) { "gpt-5", "codex-mini-latest", "gpt5.3codexspark", // 别名拼写 - "gpt-image-1", // 图像生成模型 - "claude-sonnet-4-6", // /v1/messages 调度默认映射兜底 - "claude-3-opus-20240229", + "gpt-image-1", // 图像生成模型 "gpt-4o", // 保守 fail-open:非黑名单模型保持允许 "my-custom-alias", // 自定义别名可能由渠道级映射在转发前改写,保持允许 } @@ -45,6 +43,9 @@ func TestIsModelSupported_OpenAIOAuthEmptyMapping_RejectsForeignModels(t *testin // Codex 上游必然以不可重试的 400 拒绝这些厂商家族;调度阶段就应跳过 // 该账号,让显式声明支持的 API Key 账号接手(#3662)。 foreign := []string{ + "claude-sonnet-4-6", // /v1/messages 的 opus/sonnet/haiku 在调度前已映射到 gpt-5.x + "claude-3-opus-20240229", + "claude-fable-5-1", "deepseek-v4", "deepseek-chat", "glm-4.7", @@ -80,11 +81,39 @@ func TestIsModelSupported_OpenAIOAuthExplicitMappingUnchanged(t *testing.T) { require.False(t, account.IsModelSupported("glm-4.7")) } -func TestIsModelSupported_OpenAIOAuthPassthroughAllowsAll(t *testing.T) { +func TestIsModelSupported_OpenAIOAuthPassthroughRejectsForeignModels(t *testing.T) { account := newOpenAIOAuthAccountForModelTest() account.Extra = map[string]any{"openai_passthrough": true} - // 透传模式仅替换认证,模型语义由上游决定,保持"允许所有"。 + // 透传仍放行 Codex 上游可能认识的任意名字,但 OAuth 透传的出口恒为 + // chatgpt.com/backend-api/codex,异族厂商模型在那里必然 400,调度阶段就应跳过。 + require.True(t, account.IsModelSupported("gpt-5.6-sol")) + require.True(t, account.IsModelSupported("my-custom-alias")) + require.False(t, account.IsModelSupported("claude-fable-5-1")) + require.False(t, account.IsModelSupported("claude-opus-5-5")) + require.False(t, account.IsModelSupported("deepseek-v4")) + + setupToken := &Account{ + ID: 5, + Platform: PlatformOpenAI, + Type: AccountTypeSetupToken, + Extra: map[string]any{"openai_passthrough": true}, + } + // Setup Token 与 OAuth 共用 Codex 出口。 + require.True(t, setupToken.IsModelSupported("gpt-5.6-sol")) + require.False(t, setupToken.IsModelSupported("claude-fable-5-1")) +} + +func TestIsModelSupported_OpenAIAPIKeyPassthroughAllowsForeignModels(t *testing.T) { + account := &Account{ + ID: 4, + Platform: PlatformOpenAI, + Type: AccountTypeAPIKey, + Extra: map[string]any{"openai_passthrough": true}, + } + + // API Key 透传的上游由 base_url 决定,可能正是服务 claude-*/deepseek-* 的中转站。 + require.True(t, account.IsModelSupported("claude-fable-5-1")) require.True(t, account.IsModelSupported("deepseek-v4")) } @@ -99,7 +128,7 @@ func TestIsModelSupported_OpenAIOAuthPassthroughIgnoresLeftoverMapping(t *testin } require.True(t, account.IsModelSupported("gpt-5.6-sol"), "透传应放行不在残留白名单中的新模型") - require.True(t, account.IsModelSupported("deepseek-v4"), "透传应放行任意模型") + require.True(t, account.IsModelSupported("my-custom-alias"), "透传应放行不在残留白名单中的自定义别名") } func TestIsModelSupported_OpenAIAPIKeyEmptyMappingAllowsAll(t *testing.T) { @@ -123,7 +152,8 @@ func TestIsModelSupported_NonOpenAIPlatformsUnchanged(t *testing.T) { func TestIsOpenAIOAuthServableModel(t *testing.T) { require.True(t, isOpenAIOAuthServableModel("gpt-5.4-high")) require.True(t, isOpenAIOAuthServableModel(" gpt-5.3-codex ")) - require.True(t, isOpenAIOAuthServableModel("claude-3-5-haiku-20241022")) + require.False(t, isOpenAIOAuthServableModel("claude-3-5-haiku-20241022")) + require.False(t, isOpenAIOAuthServableModel("provider/claude-fable-5-1")) require.True(t, isOpenAIOAuthServableModel("DeepThink-x")) // 非黑名单前缀,保持允许 require.False(t, isOpenAIOAuthServableModel("DeepSeek-V4")) // 大小写不敏感 require.False(t, isOpenAIOAuthServableModel("qwen3-235b-thinking")) From 3b95559788e2538450c6c06765ae508b9f146a7e Mon Sep 17 00:00:00 2001 From: r266-tech Date: Tue, 17 Nov 2026 21:46:58 +0800 Subject: [PATCH 45/85] fix(accounts): opt in to bulk passthrough model filter changes --- .../account/BulkEditAccountModal.vue | 58 ++++++-- .../__tests__/BulkEditAccountModal.spec.ts | 133 ++++++++++++++++-- 2 files changed, 173 insertions(+), 18 deletions(-) diff --git a/frontend/src/components/account/BulkEditAccountModal.vue b/frontend/src/components/account/BulkEditAccountModal.vue index d04af5f3f7..48235d55eb 100644 --- a/frontend/src/components/account/BulkEditAccountModal.vue +++ b/frontend/src/components/account/BulkEditAccountModal.vue @@ -79,20 +79,50 @@ ]" /> -