From f8b5f2ce8e77c508ab746784ac2da5be0ecf148b Mon Sep 17 00:00:00 2001 From: tejas ghatte Date: Mon, 20 Jul 2026 17:28:27 +0530 Subject: [PATCH] fix: bill for serving fallback model in anthropic --- core/providers/anthropic/anthropic.go | 31 +- core/providers/anthropic/chat.go | 4 + core/providers/anthropic/responses.go | 4 + .../anthropic/serversidefallback_test.go | 334 ++++++++++++++++++ core/providers/anthropic/types.go | 42 ++- core/providers/anthropic/utils.go | 12 + core/schemas/bifrost.go | 19 + core/schemas/chatcompletions.go | 5 + framework/modelcatalog/datasheet/cost.go | 35 +- framework/modelcatalog/datasheet/cost_test.go | 155 ++++++++ .../e2e/api/collections/provider-harness.json | 167 +++++++++ 11 files changed, 795 insertions(+), 13 deletions(-) diff --git a/core/providers/anthropic/anthropic.go b/core/providers/anthropic/anthropic.go index 7104e84c7c2..134bf63ec42 100644 --- a/core/providers/anthropic/anthropic.go +++ b/core/providers/anthropic/anthropic.go @@ -887,6 +887,11 @@ func HandleAnthropicChatCompletionStreaming( // across events and set on the final chunk: fast mode and data residency. var servedSpeed *string var servedInferenceGeo *string + // Model that actually served the turn after a server-side fallback handoff. + // Latched like the two above because it appears only on the usage event's + // iterations, and the neutral chat usage drops iterations before pricing — + // so the final chunk's RoutingInfo is the only place it can survive. + var servedFallbackModel *string // Register the accumulating usage handle so a mid-stream cancel/timeout // can bill for tokens already processed Mutated in place below; // the deferred HandleStreamCancellation/Timeout reads it from context. @@ -982,6 +987,10 @@ func HandleAnthropicChatCompletionStreaming( servedInferenceGeo = usageToProcess.InferenceGeo usage.InferenceGeo = usageToProcess.InferenceGeo } + if served := usageToProcess.ServerSideFallbackModel(); served != nil { + servedFallbackModel = served + usage.ServerSideFallbackModel = served + } // Collect usage information and send at the end of the stream // Here in some cases usage comes before final message // So we need to check if the response.Usage is nil and then if usage != nil @@ -1150,6 +1159,9 @@ func HandleAnthropicChatCompletionStreaming( if servedInferenceGeo != nil { response.InferenceGeo = servedInferenceGeo } + if servedFallbackModel != nil { + response.ExtraFields.RoutingInfo.ServerSideFallbackModel = servedFallbackModel + } // Set raw request if enabled if sendBackRawRequest { providerUtils.ParseAndSetRawRequest(&response.ExtraFields, jsonBody) @@ -1508,6 +1520,10 @@ func HandleAnthropicResponsesStream( var modelName string var servedSpeed *string var servedInferenceGeo *string + // Model that served the turn after a server-side fallback handoff. Latched + // here rather than stamped in the converter: the per-chunk loop below replaces + // ExtraFields wholesale, so anything the converter puts there is discarded. + var servedFallbackModel *string for { // If context was cancelled/timed out, let defer handle it @@ -1570,6 +1586,12 @@ func HandleAnthropicResponsesStream( billedUsage.InferenceGeo = usageToProcess.InferenceGeo } } + if served := usageToProcess.ServerSideFallbackModel(); served != nil { + servedFallbackModel = served + if billedUsage != nil { + billedUsage.ServerSideFallbackModel = served + } + } } responses, bifrostErr, isLastChunk := event.ToBifrostResponsesStream(ctx, chunkIndex, streamState) @@ -1634,6 +1656,11 @@ func HandleAnthropicResponsesStream( if servedInferenceGeo != nil { response.Response.InferenceGeo = servedInferenceGeo } + // Applied after the per-chunk ExtraFields reset above, which is + // what makes this survive to the cost calculation. + if servedFallbackModel != nil { + response.ExtraFields.RoutingInfo.ServerSideFallbackModel = servedFallbackModel + } // Set raw request if enabled if sendBackRawRequest { providerUtils.ParseAndSetRawRequest(&response.ExtraFields, jsonBody) @@ -2738,6 +2765,8 @@ func (provider *AnthropicProvider) CountTokens(ctx *schemas.BifrostContext, key request, AnthropicRequestBuildConfig{ Provider: schemas.Anthropic, + Model: request.Model, + IsCountTokens: true, IsStreaming: false, BetaHeaderOverrides: provider.networkConfig.BetaHeaderOverrides, ShouldSendBackRawRequest: provider.sendBackRawRequest, @@ -3058,4 +3087,4 @@ func (provider *AnthropicProvider) PassthroughStream( }, }, ), nil -} \ No newline at end of file +} diff --git a/core/providers/anthropic/chat.go b/core/providers/anthropic/chat.go index 38c9f5bc3a7..c201d6fda8f 100644 --- a/core/providers/anthropic/chat.go +++ b/core/providers/anthropic/chat.go @@ -899,6 +899,10 @@ func (response *AnthropicMessageResponse) ToBifrostChatResponse(ctx *schemas.Bif Created: int(time.Now().Unix()), } + // Record the server-side fallback serving model before usage is flattened — + // the neutral chat usage has no iterations to recover it from later. + bifrostResponse.ExtraFields.RoutingInfo.ServerSideFallbackModel = response.Usage.ServerSideFallbackModel() + // Check if we have a structured output tool var structuredOutputToolName string if ctx != nil { diff --git a/core/providers/anthropic/responses.go b/core/providers/anthropic/responses.go index 763a709477a..d6d7b690d0d 100644 --- a/core/providers/anthropic/responses.go +++ b/core/providers/anthropic/responses.go @@ -4065,6 +4065,10 @@ func (response *AnthropicMessageResponse) ToBifrostResponsesResponse(ctx *schema // Convert usage information using common converter (handles iterations recursively) bifrostResp.Usage = ConvertAnthropicUsageToBifrostUsage(response.Usage) + // Record the model that actually served the turn when server-side fallback + // handed off mid-request. Routing cannot see this, so pricing reads it here. + bifrostResp.ExtraFields.RoutingInfo.ServerSideFallbackModel = response.Usage.ServerSideFallbackModel() + // Convert content to Responses output messages using the new conversion method if len(response.Content) > 0 { // Create a temporary message to use the conversion method diff --git a/core/providers/anthropic/serversidefallback_test.go b/core/providers/anthropic/serversidefallback_test.go index 913f9081e70..dcd19e28511 100644 --- a/core/providers/anthropic/serversidefallback_test.go +++ b/core/providers/anthropic/serversidefallback_test.go @@ -3,9 +3,11 @@ package anthropic import ( "context" "slices" + "strings" "testing" "time" + "github.com/bytedance/sonic" "github.com/maximhq/bifrost/core/schemas" "github.com/tidwall/gjson" ) @@ -1083,3 +1085,335 @@ func TestFallbackBlockTrigger_OmittedWhenAbsent(t *testing.T) { t.Errorf("expected no trigger emitted, got %+v", block.Trigger) } } + +// --- RoutingInfo.ServerSideFallbackModel population (drives cost) --- + +func TestServerSideFallbackModel_FromIterations(t *testing.T) { + t.Parallel() + + usage := &AnthropicUsage{ + InputTokens: 31, OutputTokens: 257, + Iterations: []AnthropicUsage{ + {Type: schemas.Ptr("message"), Model: schemas.Ptr("claude-fable-5"), InputTokens: 31, OutputTokens: 1}, + {Type: schemas.Ptr(AnthropicUsageIterationTypeFallbackMessage), Model: schemas.Ptr("claude-opus-4-8"), InputTokens: 31, OutputTokens: 257}, + }, + } + got := usage.ServerSideFallbackModel() + if got == nil || *got != "claude-opus-4-8" { + t.Errorf("ServerSideFallbackModel() = %v, want claude-opus-4-8", got) + } + + // Sticky routing: the requested model is never tried, so there is only the + // serving entry and no declining one. + sticky := &AnthropicUsage{Iterations: []AnthropicUsage{ + {Type: schemas.Ptr(AnthropicUsageIterationTypeFallbackMessage), Model: schemas.Ptr("claude-opus-4-8")}, + }} + if got := sticky.ServerSideFallbackModel(); got == nil || *got != "claude-opus-4-8" { + t.Errorf("sticky ServerSideFallbackModel() = %v, want claude-opus-4-8", got) + } + + // Ordinary responses carry no iterations and must stay nil so pricing is + // unchanged for the overwhelming majority of traffic. + if got := (&AnthropicUsage{InputTokens: 31, OutputTokens: 257}).ServerSideFallbackModel(); got != nil { + t.Errorf("expected nil on a response with no iterations, got %v", got) + } + // Compaction also uses iterations, but has no fallback_message entry. + compaction := &AnthropicUsage{Iterations: []AnthropicUsage{ + {Type: schemas.Ptr("compaction"), InputTokens: 1000}, + {Type: schemas.Ptr("message"), Model: schemas.Ptr("claude-opus-4-8")}, + }} + if got := compaction.ServerSideFallbackModel(); got != nil { + t.Errorf("expected nil for compaction iterations, got %v", got) + } + if got := (*AnthropicUsage)(nil).ServerSideFallbackModel(); got != nil { + t.Errorf("expected nil for nil usage, got %v", got) + } +} + +func TestServerSideFallbackModel_OnResponsesAndChatResponses(t *testing.T) { + t.Parallel() + + ctx, cancel := schemas.NewBifrostContextWithCancel(context.Background()) + defer cancel() + + usage := &AnthropicUsage{ + InputTokens: 31, OutputTokens: 257, + Iterations: []AnthropicUsage{ + {Type: schemas.Ptr("message"), Model: schemas.Ptr("claude-fable-5"), InputTokens: 31, OutputTokens: 1}, + {Type: schemas.Ptr(AnthropicUsageIterationTypeFallbackMessage), Model: schemas.Ptr("claude-opus-4-8"), InputTokens: 31, OutputTokens: 257}, + }, + } + resp := &AnthropicMessageResponse{ + ID: "msg_fb", Type: "message", Role: "assistant", Model: "claude-opus-4-8", + Content: []AnthropicContentBlock{{Type: AnthropicContentBlockTypeText, Text: schemas.Ptr("hi")}}, + StopReason: AnthropicStopReasonEndTurn, + Usage: usage, + } + + got := resp.ToBifrostResponsesResponse(ctx).ExtraFields.RoutingInfo.ServerSideFallbackModel + if got == nil || *got != "claude-opus-4-8" { + t.Errorf("responses path: ServerSideFallbackModel = %v, want claude-opus-4-8", got) + } + + // The chat path drops iterations from the neutral usage, so this must be + // captured from the wire response before that happens. + got = resp.ToBifrostChatResponse(ctx).ExtraFields.RoutingInfo.ServerSideFallbackModel + if got == nil || *got != "claude-opus-4-8" { + t.Errorf("chat path: ServerSideFallbackModel = %v, want claude-opus-4-8", got) + } +} + +// PopulateRoutingInfo overwrites RoutingInfo wholesale; the provider-owned +// serving model must survive that, or streaming loses it entirely. +func TestServerSideFallbackModel_SurvivesPopulateRoutingInfo(t *testing.T) { + t.Parallel() + + resp := &schemas.BifrostResponse{ + ResponsesResponse: &schemas.BifrostResponsesResponse{ + ExtraFields: schemas.BifrostResponseExtraFields{ + RoutingInfo: schemas.RoutingInfo{ServerSideFallbackModel: schemas.Ptr("claude-opus-4-8")}, + }, + }, + } + + // Core's snapshot predates the handoff and carries no serving model. + resp.PopulateRoutingInfo(schemas.RoutingInfo{Provider: schemas.Anthropic, Model: "claude-fable-5"}) + + got := resp.ResponsesResponse.ExtraFields.RoutingInfo.ServerSideFallbackModel + if got == nil || *got != "claude-opus-4-8" { + t.Fatalf("serving model was clobbered by PopulateRoutingInfo: %v", got) + } + if resp.ResponsesResponse.ExtraFields.RoutingInfo.Model != "claude-fable-5" { + t.Error("expected the rest of RoutingInfo to come from core's snapshot") + } +} + +// Chat streaming has no chunk to stamp at the converter (its message_delta case +// returns nil), so HandleAnthropicChatCompletionStreaming latches the serving +// model off the usage event and applies it to the final chunk. This pins the +// contract that latch depends on: the exact stream events Anthropic sends. +func TestServerSideFallbackModel_FromStreamUsageEvents(t *testing.T) { + t.Parallel() + + // message_start carries usage but never iterations — must not latch anything. + start := &AnthropicStreamEvent{ + Type: AnthropicStreamEventTypeMessageStart, + Message: &AnthropicMessageResponse{ + Model: "claude-opus-4-8", + Usage: &AnthropicUsage{InputTokens: 29, OutputTokens: 1}, + }, + } + if got := start.Message.Usage.ServerSideFallbackModel(); got != nil { + t.Errorf("message_start must not yield a serving model, got %v", got) + } + + // The final message_delta is the only event carrying iterations. + delta := &AnthropicStreamEvent{ + Type: AnthropicStreamEventTypeMessageDelta, + Usage: &AnthropicUsage{ + InputTokens: 29, OutputTokens: 354, + Iterations: []AnthropicUsage{ + {Type: schemas.Ptr("message"), Model: schemas.Ptr("claude-fable-5"), InputTokens: 29, OutputTokens: 7}, + {Type: schemas.Ptr(AnthropicUsageIterationTypeFallbackMessage), Model: schemas.Ptr("claude-opus-4-8"), InputTokens: 29, OutputTokens: 354}, + }, + }, + } + got := delta.Usage.ServerSideFallbackModel() + if got == nil || *got != "claude-opus-4-8" { + t.Fatalf("message_delta ServerSideFallbackModel = %v, want claude-opus-4-8", got) + } +} + +// Every BetaFallbackParam field must survive the union type's custom +// UnmarshalJSON — anything unmodelled is silently dropped on the typed path, +// so the fallback attempt would run without the override the caller asked for. +func TestNativeFallbackEntry_AllFieldsRoundTrip(t *testing.T) { + t.Parallel() + + raw := []byte(`{ + "model": "claude-fable-5", + "max_tokens": 1024, + "fallbacks": [{ + "model": "claude-opus-4-8", + "max_tokens": 2048, + "speed": "fast", + "thinking": {"type": "enabled", "budget_tokens": 512}, + "output_config": {"effort": "high"} + }], + "messages": [{"role": "user", "content": "hi"}] + }`) + + var req AnthropicMessageRequest + if err := sonic.Unmarshal(raw, &req); err != nil { + t.Fatalf("unmarshal failed: %v", err) + } + native := req.nativeFallbacks() + if len(native) != 1 { + t.Fatalf("expected 1 native fallback, got %d", len(native)) + } + fb := native[0] + if fb.Model != "claude-opus-4-8" { + t.Errorf("Model = %q, want claude-opus-4-8", fb.Model) + } + if fb.MaxTokens == nil || *fb.MaxTokens != 2048 { + t.Errorf("MaxTokens = %v, want 2048", fb.MaxTokens) + } + if fb.Speed == nil || *fb.Speed != "fast" { + t.Errorf("Speed = %v, want fast", fb.Speed) + } + if fb.Thinking == nil || fb.Thinking.Type != "enabled" || + fb.Thinking.BudgetTokens == nil || *fb.Thinking.BudgetTokens != 512 { + t.Errorf("Thinking = %+v, want enabled/512", fb.Thinking) + } + if fb.OutputConfig == nil || fb.OutputConfig.Effort == nil || *fb.OutputConfig.Effort != "high" { + t.Errorf("OutputConfig = %+v, want effort=high", fb.OutputConfig) + } + + // ...and back onto the wire with every field intact. + out, err := sonic.Marshal(req.Fallbacks) + if err != nil { + t.Fatalf("marshal failed: %v", err) + } + for _, want := range []string{`"model":"claude-opus-4-8"`, `"max_tokens":2048`, `"speed":"fast"`, `"budget_tokens":512`, `"effort":"high"`} { + if !strings.Contains(string(out), want) { + t.Errorf("re-marshalled entry missing %s: %s", want, out) + } + } +} + +// Regression: AnthropicProvider.CountTokens omitted IsCountTokens, so the +// count-tokens strip never ran and the endpoint answered +// "fallback_credit_token: Extra inputs are not permitted". +func TestBuildAnthropicResponsesRequestBody_CountTokensStripsRejectedFields(t *testing.T) { + t.Parallel() + + rawBody := []byte(`{"model":"claude-opus-4-8","max_tokens":1024,"temperature":0.5,` + + `"messages":[{"role":"user","content":"hi"}],"fallback_credit_token":"tok"}`) + ctx := schemas.NewBifrostContext(context.Background(), time.Time{}) + ctx.SetValue(schemas.BifrostContextKeyUseRawRequestBody, true) + + result, bifrostErr := BuildAnthropicResponsesRequestBody(ctx, + &schemas.BifrostResponsesRequest{ + Provider: schemas.Anthropic, + Model: "claude-opus-4-8", + RawRequestBody: rawBody, + }, + AnthropicRequestBuildConfig{ + Provider: schemas.Anthropic, + Model: "claude-opus-4-8", + IsCountTokens: true, + }) + if bifrostErr != nil { + t.Fatalf("unexpected error: %v", bifrostErr) + } + for _, field := range []string{"fallback_credit_token", "max_tokens", "temperature"} { + if gjson.GetBytes(result, field).Exists() { + t.Errorf("count_tokens rejects %q; expected it stripped, got: %s", field, result) + } + } + // The model must survive — the count-tokens branch rewrites it from cfg.Model, + // so an empty cfg.Model here would blank it out. + if got := gjson.GetBytes(result, "model").String(); got != "claude-opus-4-8" { + t.Errorf("model = %q, want claude-opus-4-8: %s", got, result) + } + if !gjson.GetBytes(result, "messages").Exists() { + t.Errorf("strip damaged the body: %s", result) + } +} + +// A fallback entry's speed override needs the fast-mode beta just as a top-level +// speed does; without it the parameter is rejected as unrecognised. +func TestFallbackEntrySpeed_InjectsFastModeBetaHeader(t *testing.T) { + t.Parallel() + + newReq := func(entry AnthropicNativeFallback) *AnthropicMessageRequest { + return &AnthropicMessageRequest{ + Model: "claude-fable-5", + MaxTokens: 64, + Messages: []AnthropicMessage{{Role: "user", Content: AnthropicContent{ContentStr: schemas.Ptr("hi")}}}, + Fallbacks: []AnthropicFallbackEntry{{Native: &entry}}, + } + } + hasFastMode := func(t *testing.T, req *AnthropicMessageRequest, provider schemas.ModelProvider) bool { + t.Helper() + ctx, cancel := schemas.NewBifrostContextWithCancel(context.Background()) + defer cancel() + if err := AddMissingBetaHeadersToContext(ctx, req, provider); err != nil { + t.Fatalf("unexpected error: %v", err) + } + hdrs, _ := ctx.Value(schemas.BifrostContextKeyExtraHeaders).(map[string][]string) + return slices.Contains(hdrs[AnthropicBetaHeader], AnthropicFastModeBetaHeader) + } + + // Speed lives only on the fallback entry — no top-level speed to trigger it. + if !hasFastMode(t, newReq(AnthropicNativeFallback{Model: "claude-opus-4-8", Speed: schemas.Ptr("fast")}), schemas.Anthropic) { + t.Error("expected fast-mode beta header for a fallback entry requesting speed") + } + // No speed anywhere — the header must not appear. + if hasFastMode(t, newReq(AnthropicNativeFallback{Model: "claude-opus-4-8"}), schemas.Anthropic) { + t.Error("did not expect fast-mode beta header when no entry requests speed") + } + // Gated on the entry's own model: sending the header for a model that cannot + // serve fast mode guarantees a 400. + if hasFastMode(t, newReq(AnthropicNativeFallback{Model: "claude-haiku-4-5", Speed: schemas.Ptr("fast")}), schemas.Anthropic) { + t.Error("did not expect fast-mode beta header for a model without fast mode") + } +} + +// Documents the contract for the overloaded "fallbacks" key: entries are routed by +// shape, so the two features coexist in one array and neither consumes the other's. +func TestFallbacksArray_RoutedByEntryShape(t *testing.T) { + t.Parallel() + + for _, tc := range []struct { + name string + fallbacks string + wantGateway []schemas.Fallback // Bifrost cross-provider failover + wantNative []string // forwarded to Anthropic + }{ + { + name: "strings only -> gateway failover, nothing forwarded", + fallbacks: `["openai/gpt-4o-mini","vertex/claude-opus-4-7"]`, + wantGateway: []schemas.Fallback{{Provider: "openai", Model: "gpt-4o-mini"}, {Provider: "vertex", Model: "claude-opus-4-7"}}, + }, + { + name: "objects only -> forwarded to the provider, no gateway failover", + fallbacks: `[{"model":"claude-opus-4-8"}]`, + wantNative: []string{"claude-opus-4-8"}, + }, + { + name: "mixed -> each half goes to its own owner", + fallbacks: `["openai/gpt-4o-mini",{"model":"claude-opus-4-8"}]`, + wantGateway: []schemas.Fallback{{Provider: "openai", Model: "gpt-4o-mini"}}, + wantNative: []string{"claude-opus-4-8"}, + }, + } { + t.Run(tc.name, func(t *testing.T) { + t.Parallel() + ctx, cancel := schemas.NewBifrostContextWithCancel(context.Background()) + defer cancel() + + var req AnthropicMessageRequest + body := `{"model":"claude-fable-5","max_tokens":64,` + + `"messages":[{"role":"user","content":"hi"}],"fallbacks":` + tc.fallbacks + `}` + if err := sonic.Unmarshal([]byte(body), &req); err != nil { + t.Fatalf("unmarshal failed: %v", err) + } + + bifrostReq := req.ToBifrostResponsesRequest(ctx) + if !slices.Equal(bifrostReq.Fallbacks, tc.wantGateway) { + t.Errorf("gateway fallbacks = %+v, want %+v", bifrostReq.Fallbacks, tc.wantGateway) + } + + var gotNative []string + if v, ok := bifrostReq.Params.ExtraParams["fallbacks"].([]AnthropicNativeFallback); ok { + for _, n := range v { + gotNative = append(gotNative, n.Model) + } + } + if !slices.Equal(gotNative, tc.wantNative) { + t.Errorf("native fallbacks forwarded = %v, want %v", gotNative, tc.wantNative) + } + }) + } +} diff --git a/core/providers/anthropic/types.go b/core/providers/anthropic/types.go index 4f91452ad03..d36adb72ebb 100644 --- a/core/providers/anthropic/types.go +++ b/core/providers/anthropic/types.go @@ -459,10 +459,16 @@ type AnthropicMessageRequest struct { // AnthropicNativeFallback is one entry of Anthropic's native server-side fallback // list (beta server-side-fallback-2026-06-01): a model to retry the request on when // the primary model refuses, with optional per-attempt max_tokens/thinking overrides. +// Every field except Model overrides the corresponding request-level value for +// that attempt only. Carried verbatim: the per-attempt gates (e.g. whether the +// fallback model supports fast mode or the effort parameter) belong to Anthropic, +// which validates the request against every named model up front. type AnthropicNativeFallback struct { - Model string `json:"model"` - MaxTokens *int `json:"max_tokens,omitempty"` - Thinking *AnthropicThinking `json:"thinking,omitempty"` + Model string `json:"model"` + MaxTokens *int `json:"max_tokens,omitempty"` + Thinking *AnthropicThinking `json:"thinking,omitempty"` + OutputConfig *AnthropicOutputConfig `json:"output_config,omitempty"` + Speed *string `json:"speed,omitempty"` // "standard" | "fast" } // AnthropicFallbackEntry is one entry of the overloaded request-level "fallbacks" @@ -1786,6 +1792,36 @@ type AnthropicUsage struct { Iterations []AnthropicUsage `json:"iterations,omitempty"` // Iterations statistics } +// AnthropicUsageIterationTypeFallbackMessage marks the usage.iterations entry for +// the attempt that actually served the response after a server-side fallback +// handoff. Declining attempts appear as ordinary "message" entries. +const AnthropicUsageIterationTypeFallbackMessage = "fallback_message" + +// ServerSideFallbackModel returns the model named by the fallback_message entry in +// usage.iterations — the attempt whose token counts the top-level usage mirrors, +// and therefore the model those tokens must be priced against. Returns nil on +// every ordinary response, which carries no iterations at all. +// +// Matched on entry type rather than position: the docs put the serving attempt +// last, but keying on the type says what we mean and survives a shape change. +func (u *AnthropicUsage) ServerSideFallbackModel() *string { + if u == nil { + return nil + } + var served *string + for i := range u.Iterations { + it := u.Iterations[i] + if it.Type == nil || *it.Type != AnthropicUsageIterationTypeFallbackMessage { + continue + } + if it.Model != nil && *it.Model != "" { + m := *it.Model + served = &m + } + } + return served +} + // AnthropicServerToolUseUsage represents server tool use statistics in usage type AnthropicServerToolUseUsage struct { WebSearchRequests int `json:"web_search_requests"` // Number of web search requests made diff --git a/core/providers/anthropic/utils.go b/core/providers/anthropic/utils.go index 2e209e41a0c..645ba411eae 100644 --- a/core/providers/anthropic/utils.go +++ b/core/providers/anthropic/utils.go @@ -1224,6 +1224,18 @@ func AddMissingBetaHeadersToContext(ctx *schemas.BifrostContext, req *AnthropicM headers = appendUniqueHeader(headers, AnthropicFastModeBetaHeader) } } + // A fallback entry can override speed for its own attempt, so a fast-mode request + // can carry no top-level speed at all. Gate on the entry's own model — that is the + // one that would run fast — and take it verbatim rather than alias-resolving it, + // since it names an Anthropic model directly, not a Bifrost alias. + if !hasProvider || features.FastMode { + for _, fb := range req.nativeFallbacks() { + if fb.Speed != nil && SupportsFastMode(fb.Model) { + headers = appendUniqueHeader(headers, AnthropicFastModeBetaHeader) + break + } + } + } // Check for task budget if req.OutputConfig != nil && req.OutputConfig.TaskBudget != nil { if !hasProvider || features.TaskBudgets { diff --git a/core/schemas/bifrost.go b/core/schemas/bifrost.go index 0a7c6bed8df..813a065b329 100644 --- a/core/schemas/bifrost.go +++ b/core/schemas/bifrost.go @@ -1232,6 +1232,14 @@ func (r *BifrostResponse) PopulateRoutingInfo(info RoutingInfo) { return } if ef := r.GetExtraFields(); ef != nil { + // ServerSideFallbackModel is the one provider-owned field on RoutingInfo: + // the orchestrator cannot see a model swap that happened inside a single + // upstream call, so carry the provider's value across this overwrite. + // Streaming relies on this too — the closure's snapshot predates the final + // usage chunk that reveals the handoff. + if info.ServerSideFallbackModel == nil { + info.ServerSideFallbackModel = ef.RoutingInfo.ServerSideFallbackModel + } ef.RoutingInfo = info syncDeprecatedFromRoutingInfo(info, &ef.Provider, &ef.OriginalModelRequested, &ef.ResolvedModelUsed) } @@ -1695,6 +1703,17 @@ type RoutingInfo struct { // What the caller asked for, before any fallback resolution (populated only when fallback resolution occurred) PrimaryProvider *ModelProvider `json:"primary_provider,omitempty"` PrimaryModel *string `json:"primary_model,omitempty"` + + // ServerSideFallbackModel names the model that actually produced the response + // when the provider swapped models *inside* a single upstream call — today only + // Anthropic's server-side fallback (server-side-fallback-2026-06-01). Model + // still names what the caller asked for, since routing never saw the swap. + // + // Unlike every other field here this one is provider-owned, not written by the + // orchestrator: only the provider can see a handoff that happened within its own + // response. PopulateRoutingInfo preserves it across core's overwrite. Nil on + // every ordinary response, so pricing behaviour is unchanged when it is absent. + ServerSideFallbackModel *string `json:"server_side_fallback_model,omitempty"` } type ResolvedKeyAlias struct { diff --git a/core/schemas/chatcompletions.go b/core/schemas/chatcompletions.go index d3873326815..c8b0cbaf633 100644 --- a/core/schemas/chatcompletions.go +++ b/core/schemas/chatcompletions.go @@ -1647,6 +1647,11 @@ type BifrostLLMUsage struct { // the tier multiplier. json:"-" keeps them out of every serialized usage payload. Speed *string `json:"-"` InferenceGeo *string `json:"-"` + // Model that actually served the turn after a server-side fallback handoff. + // Carried here for the same reason as the two above: the bare-usage billing path + // (CalculateCostForUsage) never sees RoutingInfo, so without it a fallback-served + // turn is priced at the requested model's rates. + ServerSideFallbackModel *string `json:"-"` } type ChatPromptTokensDetails struct { diff --git a/framework/modelcatalog/datasheet/cost.go b/framework/modelcatalog/datasheet/cost.go index e92fea73fbf..ecd51583df5 100644 --- a/framework/modelcatalog/datasheet/cost.go +++ b/framework/modelcatalog/datasheet/cost.go @@ -62,7 +62,11 @@ func (s *Store) CalculateCostForUsage(usage *schemas.BifrostLLMUsage, provider s return s.computeCostFromInput( input, - schemas.RoutingInfo{Provider: provider, Model: model}, + schemas.RoutingInfo{ + Provider: provider, + Model: model, + ServerSideFallbackModel: usage.ServerSideFallbackModel, + }, normalizeStreamRequestType(requestType), lookupScopes, ) @@ -1132,10 +1136,13 @@ func populateOutputImageCount(imageUsage *schemas.ImageUsage, dataLen int) { // resolvePricing resolves the pricing entry for a request directly from the // RoutingInfo populated on the response/error by core.bifrost at request time. // -// Lookup precedence — AliasModelName → AliasModelID → ModelName. Each -// non-empty candidate is tried against the base catalog in order; the first -// hit wins. +// Lookup precedence — ServerSideFallbackModel → AliasModelName → AliasModelID → +// ModelName. Each non-empty candidate is tried against the base catalog in +// order; the first hit wins. // +// - ServerSideFallbackModel is the model that produced the response when the +// provider swapped models inside one call (Anthropic server-side fallback). +// Ranked first: the tokens being priced are its own. Nil on ordinary responses. // - AliasModelName (RoutingInfo.ResolvedKeyAlias.ModelName) is the canonical // model name the admin tagged on the matched alias. Catches the // opaque-deployment-ID case where the wire model wouldn't hit the catalog @@ -1145,9 +1152,12 @@ func populateOutputImageCount(imageUsage *schemas.ImageUsage, dataLen int) { // - ModelName (RoutingInfo.Model) is the model string the caller sent — the // alias key when an alias matched, or the raw user input when none did. // -// Overrides are applied keyed by the wire model (AliasModelID when an alias -// matched, otherwise ModelName) so per-deployment override pricing stays -// addressable in either flow. +// Overrides are applied keyed by the wire model (ServerSideFallbackModel when the +// provider handed off mid-call, else AliasModelID when an alias matched, otherwise +// ModelName) so per-deployment override pricing stays addressable in either flow. +// A fallback-served turn keys on the serving model so base rates and overrides +// agree: an override negotiated for the model that actually ran is the one that +// applies. func (s *Store) resolvePricing(routingInfo schemas.RoutingInfo, requestType schemas.RequestType, scopes LookupScopes) *configstoreTables.TableModelPricing { provider := string(routingInfo.Provider) var aliasModelID, aliasModelName string @@ -1157,7 +1167,14 @@ func (s *Store) resolvePricing(routingInfo schemas.RoutingInfo, requestType sche aliasModelName = *rka.ModelName } } - overrideKey := aliasModelID + var serverSideFallbackModel string + if routingInfo.ServerSideFallbackModel != nil { + serverSideFallbackModel = *routingInfo.ServerSideFallbackModel + } + overrideKey := serverSideFallbackModel + if overrideKey == "" { + overrideKey = aliasModelID + } if overrideKey == "" { overrideKey = routingInfo.Model } @@ -1167,7 +1184,7 @@ func (s *Store) resolvePricing(routingInfo schemas.RoutingInfo, requestType sche scopes.Provider = provider } - for _, candidate := range []string{aliasModelName, aliasModelID, routingInfo.Model} { + for _, candidate := range []string{serverSideFallbackModel, aliasModelName, aliasModelID, routingInfo.Model} { if candidate == "" { continue } diff --git a/framework/modelcatalog/datasheet/cost_test.go b/framework/modelcatalog/datasheet/cost_test.go index 126f447e05d..a4cc984ebde 100644 --- a/framework/modelcatalog/datasheet/cost_test.go +++ b/framework/modelcatalog/datasheet/cost_test.go @@ -3669,3 +3669,158 @@ func TestTieredCacheCreationRate_PriorityWinsOver200kBand(t *testing.T) { // Non-priority at the same size still uses the standard >200k rate. assert.Equal(t, 0.000002, tieredCacheCreationInputTokenRate(&p, 250000, serviceTier{})) } + +// --------------------------------------------------------------------------- +// Anthropic server-side fallback: price the model that actually served +// --------------------------------------------------------------------------- + +// seedFallbackPricing loads the real published Fable 5 / Opus 4.8 rates. Fable 5 +// is exactly 2x Opus 4.8 on both input and output, which is what makes pricing a +// fallback-served turn against the requested model a clean doubling. +func seedFallbackPricing(s *Store) { + s.pricingData[makeKey("claude-fable-5", "anthropic", "responses")] = configstoreTables.TableModelPricing{ + Model: "claude-fable-5", Provider: "anthropic", Mode: "responses", + InputCostPerToken: bifrost.Ptr(10.0 / 1_000_000), + OutputCostPerToken: bifrost.Ptr(50.0 / 1_000_000), + } + s.pricingData[makeKey("claude-opus-4-8", "anthropic", "responses")] = configstoreTables.TableModelPricing{ + Model: "claude-opus-4-8", Provider: "anthropic", Mode: "responses", + InputCostPerToken: bifrost.Ptr(5.0 / 1_000_000), + OutputCostPerToken: bifrost.Ptr(25.0 / 1_000_000), + } +} + +// fallbackResponse mirrors a real server-side-fallback payload: the caller asked +// for claude-fable-5, claude-opus-4-8 served, and the top-level usage mirrors the +// serving attempt. +func fallbackResponse(servingModel *string, in, out int) *schemas.BifrostResponse { + return &schemas.BifrostResponse{ + ResponsesResponse: &schemas.BifrostResponsesResponse{ + Model: "claude-opus-4-8", + Usage: &schemas.ResponsesResponseUsage{InputTokens: in, OutputTokens: out}, + ExtraFields: schemas.BifrostResponseExtraFields{ + RequestType: schemas.ResponsesRequest, + RoutingInfo: schemas.RoutingInfo{ + Provider: schemas.Anthropic, + Model: "claude-fable-5", + ServerSideFallbackModel: servingModel, + }, + }, + }, + } +} + +func TestCalculateCost_ServerSideFallback_PricesServingModel(t *testing.T) { + s := newTestStore() + seedFallbackPricing(s) + + // Real payload: 31 in / 257 out, served by Opus after Fable declined. + // Before the fix this returned the Fable figure, which is exactly double. + resp := fallbackResponse(bifrost.Ptr("claude-opus-4-8"), 31, 257) + assert.InDelta(t, 31*(5.0/1_000_000)+257*(25.0/1_000_000), s.CalculateCost(resp, nil), 1e-12, + "expected Opus 4.8 rates (the serving model), not Fable 5") +} + +// No handoff — the overwhelming majority of responses — must be untouched, even +// though the response's own model field names a different model. +func TestCalculateCost_NoServerSideFallback_UsesRoutingModel(t *testing.T) { + s := newTestStore() + seedFallbackPricing(s) + + resp := fallbackResponse(nil, 31, 257) + assert.InDelta(t, 31*(10.0/1_000_000)+257*(50.0/1_000_000), s.CalculateCost(resp, nil), 1e-12, + "without a recorded handoff, pricing must stay on the requested model") +} + +// An unpriceable serving model falls through the candidate chain to the +// requested model rather than collapsing the cost to zero. +func TestCalculateCost_ServerSideFallback_UnknownServingModelFallsThrough(t *testing.T) { + s := newTestStore() + seedFallbackPricing(s) + + resp := fallbackResponse(bifrost.Ptr("claude-not-in-catalog"), 31, 257) + cost := s.CalculateCost(resp, nil) + assert.InDelta(t, 31*(10.0/1_000_000)+257*(50.0/1_000_000), cost, 1e-12) + assert.NotZero(t, cost, "an unknown serving model must not zero the cost") +} + +// A key alias would otherwise win the lookup; the serving model outranks it. +func TestCalculateCost_ServerSideFallback_OutranksKeyAlias(t *testing.T) { + s := newTestStore() + seedFallbackPricing(s) + + resp := fallbackResponse(bifrost.Ptr("claude-opus-4-8"), 31, 257) + resp.ResponsesResponse.ExtraFields.RoutingInfo.Model = "my-fast-alias" + resp.ResponsesResponse.ExtraFields.RoutingInfo.ResolvedKeyAlias = &schemas.ResolvedKeyAlias{ + ModelID: "claude-fable-5", + ModelName: bifrost.Ptr("claude-fable-5"), + } + + assert.InDelta(t, 31*(5.0/1_000_000)+257*(25.0/1_000_000), s.CalculateCost(resp, nil), 1e-12, + "the alias must not outrank the model that actually served") +} + +// Overrides follow the serving model, so a negotiated rate for the model that +// actually ran is the one that applies. +func TestCalculateCost_ServerSideFallback_OverridesKeyOnServingModel(t *testing.T) { + s := newTestStore() + seedFallbackPricing(s) + providerID := "anthropic" + require.NoError(t, s.SetOverrides([]configstoreTables.TablePricingOverride{{ + ID: "opus-negotiated-rate", + ScopeKind: string(ScopeKindProvider), + ProviderID: &providerID, + MatchType: string(MatchTypeExact), + Pattern: "claude-opus-4-8", + RequestTypes: []schemas.RequestType{schemas.ResponsesRequest}, + PricingPatchJSON: `{"input_cost_per_token":0.000001,"output_cost_per_token":0.000002}`, + }})) + + resp := fallbackResponse(bifrost.Ptr("claude-opus-4-8"), 31, 257) + assert.InDelta(t, 31*0.000001+257*0.000002, s.CalculateCost(resp, nil), 1e-12, + "an override for the serving model must apply to a fallback-served turn") +} + +// Streaming is billed through CalculateCostForUsage, which receives only +// (usage, provider, requestedModel) and never sees RoutingInfo. A live +// fallback-served stream (38 in / 345 out, served by Opus after Fable declined) +// was reported at $0.01763 — exactly the Fable figure, i.e. double. +func TestCalculateCostForUsage_ServerSideFallback_PricesServingModel(t *testing.T) { + s := newTestStore() + seedFallbackPricing(s) + + usage := &schemas.BifrostLLMUsage{ + PromptTokens: 38, + CompletionTokens: 345, + TotalTokens: 383, + ServerSideFallbackModel: bifrost.Ptr("claude-opus-4-8"), + } + got := s.CalculateCostForUsage(usage, schemas.Anthropic, "claude-fable-5", schemas.ResponsesRequest, nil) + assert.InDelta(t, 38*(5.0/1_000_000)+345*(25.0/1_000_000), got, 1e-12, + "expected Opus 4.8 rates for a fallback-served stream") + assert.InDelta(t, 0.008815, got, 1e-6, "expected the Opus figure, not the $0.01763 Fable one") +} + +// Sticky-routed stream: a single fallback_message iteration, 38 in / 320 out, +// reported live at $0.01638 (Fable). Should be $0.00819. +func TestCalculateCostForUsage_ServerSideFallback_StickyStream(t *testing.T) { + s := newTestStore() + seedFallbackPricing(s) + + usage := &schemas.BifrostLLMUsage{ + PromptTokens: 38, CompletionTokens: 320, TotalTokens: 358, + ServerSideFallbackModel: bifrost.Ptr("claude-opus-4-8"), + } + assert.InDelta(t, 0.00819, + s.CalculateCostForUsage(usage, schemas.Anthropic, "claude-fable-5", schemas.ResponsesRequest, nil), 1e-6) +} + +// No handoff: the bare-usage path must keep pricing the requested model. +func TestCalculateCostForUsage_NoServerSideFallback_Unchanged(t *testing.T) { + s := newTestStore() + seedFallbackPricing(s) + + usage := &schemas.BifrostLLMUsage{PromptTokens: 38, CompletionTokens: 345, TotalTokens: 383} + assert.InDelta(t, 38*(10.0/1_000_000)+345*(50.0/1_000_000), + s.CalculateCostForUsage(usage, schemas.Anthropic, "claude-fable-5", schemas.ResponsesRequest, nil), 1e-12) +} diff --git a/tests/e2e/api/collections/provider-harness.json b/tests/e2e/api/collections/provider-harness.json index 0e481957f83..2adf3223378 100644 --- a/tests/e2e/api/collections/provider-harness.json +++ b/tests/e2e/api/collections/provider-harness.json @@ -41080,6 +41080,173 @@ ] } ] + }, + { + "name": "27. Anthropic Fallback Credit Strip + Fallback Entry Fields", + "description": "Fallback credit (fallback-credit-2026-06-01; -2026-06-09 on the AWS surfaces) is a different feature from server-side fallback and has the INVERSE support matrix: the fallbacks parameter is Claude-API-only, while fallback_credit_token is supported nearly everywhere. A fallback entry also accepts output_config and speed, which were unmodelled and therefore dropped on the typed path.\n\nSCOPE NOTE: this folder covers only what a 2xx-asserting suite can observe. Proving that fallback_credit_token is FORWARDED needs a token the platform will evaluate, and an invalid one is rejected with a 400 by design - which the collection-level \"Status code is 2xx\" test treats as a failure. Forwarding, the per-provider beta gating and the AWS beta-date rewrite are therefore covered by unit tests in core/providers/anthropic instead. Response-side shapes (the fallback content block and its trigger, stop_details.fallback_credit_token / fallback_has_prefill_claim) are also unit-tested: reproducing them here would require provoking a safety classifier, which is non-deterministic and inappropriate for a shared suite.", + "item": [ + { + "name": "anthropic/claude-opus-4-8 · count_tokens strips fallback_credit_token", + "request": { + "method": "POST", + "header": [ + { + "key": "Content-Type", + "value": "application/json" + } + ], + "body": { + "mode": "raw", + "raw": "{\n \"model\": \"anthropic/claude-opus-4-8\",\n \"messages\": [\n {\n \"role\": \"user\",\n \"content\": \"Hello\"\n }\n ],\n \"fallback_credit_token\": \"bifrost-harness-probe-token\"\n}" + }, + "url": { + "raw": "{{baseUrl}}/anthropic/v1/messages/count_tokens", + "host": [ + "{{baseUrl}}" + ], + "path": [ + "anthropic", + "v1", + "messages", + "count_tokens" + ] + } + }, + "event": [ + { + "listen": "test", + "script": { + "type": "text/javascript", + "exec": [ + "// Infra noise (auth / rate limit / upstream 5xx) skips so it does not false-fail.", + "// 400 is deliberately NOT guarded - a 400 IS the regression signature for this folder.", + "if ([401, 403, 429, 500, 502, 503, 504].indexOf(pm.response.code) !== -1) { return; }", + "var raw = pm.response.text() || '';", + "var lower = raw.toLowerCase();", + "pm.test('anthropic/claude-opus-4-8: count_tokens succeeds with the credit token stripped', function () {", + " // The token is rejected outright on this endpoint, so the gateway must remove it.", + " // The token here is intentionally not a real one: if the strip regresses, the", + " // request fails on the unexpected field before its value is ever evaluated.", + " pm.expect(raw.indexOf('Extra inputs are not permitted'), 'fallback_credit_token survived into count_tokens: ' + raw).to.equal(-1);", + " pm.expect(lower.indexOf('fallback_credit_token'), 'fallback_credit_token survived into count_tokens: ' + raw).to.equal(-1);", + " pm.expect(pm.response.code, 'count_tokens failed: ' + raw).to.be.below(400);", + " pm.expect(pm.response.json()).to.have.property('input_tokens');", + "});" + ] + } + } + ] + }, + { + "name": "anthropic/claude-fable-5 · fallback entry carries speed + output_config", + "request": { + "method": "POST", + "header": [ + { + "key": "Content-Type", + "value": "application/json" + } + ], + "body": { + "mode": "raw", + "raw": "{\n \"model\": \"anthropic/claude-fable-5\",\n \"max_tokens\": 64,\n \"messages\": [\n {\n \"role\": \"user\",\n \"content\": \"Hello\"\n }\n ],\n \"fallbacks\": [\n {\n \"model\": \"claude-opus-4-8\",\n \"max_tokens\": 64,\n \"speed\": \"standard\",\n \"output_config\": {\n \"effort\": \"low\"\n }\n }\n ]\n}" + }, + "url": { + "raw": "{{baseUrl}}/anthropic/v1/messages", + "host": [ + "{{baseUrl}}" + ], + "path": [ + "anthropic", + "v1", + "messages" + ] + } + }, + "event": [ + { + "listen": "test", + "script": { + "type": "text/javascript", + "exec": [ + "// Infra noise (auth / rate limit / upstream 5xx) skips so it does not false-fail.", + "// 400 is deliberately NOT guarded - a 400 IS the regression signature for this folder.", + "if ([401, 403, 429, 500, 502, 503, 504].indexOf(pm.response.code) !== -1) { return; }", + "var raw = pm.response.text() || '';", + "var lower = raw.toLowerCase();", + "pm.test('anthropic/claude-fable-5: fallback entry keeps every documented key', function () {", + " // A fallback entry accepts model, max_tokens, thinking, output_config and speed.", + " // output_config and speed were unmodelled, so the typed path silently discarded them", + " // and the retry ran without the overrides the caller asked for. A serialization", + " // mistake on either new key surfaces here as a rejected request.", + " pm.expect(lower.indexOf('invalid json'), 'gateway failed to parse the fallback entry: ' + raw).to.equal(-1);", + " pm.expect(raw.indexOf('Extra inputs are not permitted'), 'a fallback entry key was rejected: ' + raw).to.equal(-1);", + " pm.expect(pm.response.code, 'request failed: ' + raw).to.be.below(400);", + "});" + ] + } + } + ] + }, + { + "name": "anthropic/claude-fable-5 · fallback entry keys preserved on Claude Code passthrough (claude-cli UA)", + "request": { + "method": "POST", + "header": [ + { + "key": "Content-Type", + "value": "application/json" + }, + { + "key": "User-Agent", + "value": "claude-cli/1.0" + } + ], + "body": { + "mode": "raw", + "raw": "{\n \"model\": \"anthropic/claude-fable-5\",\n \"max_tokens\": 64,\n \"messages\": [\n {\n \"role\": \"user\",\n \"content\": \"Hello\"\n }\n ],\n \"fallbacks\": [\n {\n \"model\": \"claude-opus-4-8\",\n \"max_tokens\": 64,\n \"speed\": \"standard\",\n \"output_config\": {\n \"effort\": \"low\"\n }\n }\n ]\n}" + }, + "url": { + "raw": "{{baseUrl}}/anthropic/v1/messages", + "host": [ + "{{baseUrl}}" + ], + "path": [ + "anthropic", + "v1", + "messages" + ] + } + }, + "event": [ + { + "listen": "test", + "script": { + "type": "text/javascript", + "exec": [ + "// Infra noise (auth / rate limit / upstream 5xx) skips so it does not false-fail.", + "// 400 is deliberately NOT guarded - a 400 IS the regression signature for this folder.", + "if ([401, 403, 429, 500, 502, 503, 504].indexOf(pm.response.code) !== -1) { return; }", + "var raw = pm.response.text() || '';", + "var lower = raw.toLowerCase();", + "pm.test('anthropic/claude-fable-5: fallback entry survives the raw-body passthrough path', function () {", + " // A fallback entry accepts model, max_tokens, thinking, output_config and speed.", + " // output_config and speed were unmodelled, so the typed path silently discarded them", + " // and the retry ran without the overrides the caller asked for. A serialization", + " // mistake on either new key surfaces here as a rejected request.", + " pm.expect(lower.indexOf('invalid json'), 'gateway failed to parse the fallback entry: ' + raw).to.equal(-1);", + " pm.expect(raw.indexOf('Extra inputs are not permitted'), 'a fallback entry key was rejected: ' + raw).to.equal(-1);", + " pm.expect(pm.response.code, 'request failed: ' + raw).to.be.below(400);", + "});", + "// The CLI user-agent routes this through the raw-body path, where the entry is", + "// rewritten by the gjson/sjson strip rather than the typed marshaller - a separate", + "// code path with its own way to corrupt the array." + ] + } + } + ] + } + ] } ] } \ No newline at end of file