diff --git a/docs/de/features/users.mdx b/docs/de/features/users.mdx index 0c4b18e99..aa2a60624 100644 --- a/docs/de/features/users.mdx +++ b/docs/de/features/users.mdx @@ -261,12 +261,15 @@ Obergrenzen greifen nach den [Overrides virtueller Modelle](/de/features/virtual bei jedem Versuch, auch bei Failover-Versuchen, und begrenzen daher auch einen Effort oder ein `max_tokens`, das ein virtuelles Modell erzwingt oder als Standard setzt. Sie gelten für Chat Completions, die Responses API und die -Anthropic Messages API; ein Messages-Request innerhalb der Obergrenzen wird -weiterhin nativ an Anthropic weitergeleitet, einer darüber nimmt den -übersetzten Pfad, damit er gesenkt werden kann. Ein Request, den nur Anthropic -lesen kann (etwa mit Server-Tool-Verlauf), hat keinen übersetzten Pfad; bei ihm -werden `max_tokens`, das Thinking-Budget und `output_config.effort` stattdessen -im weitergeleiteten Body gesenkt. Unter einer Obergrenze `none` wird sein +Anthropic Messages API. Obergrenzen nehmen einen Messages-Request nicht von +der nativen Weiterleitung an Anthropic: Würde er ohne sie nativ weitergeleitet +und liegt er über den Obergrenzen, werden `max_tokens`, das Thinking-Budget +und `output_config.effort` im weitergeleiteten Body gesenkt; seine übrigen +Felder und seine `anthropic-beta`-Header bleiben erhalten. Ein Request, der +den Response-Cache, Failover, einen erzwungenen Reasoning-Effort oder +Request-Parameter oder eine Guardrail oder ein Plugin nutzt, das ihn +umschreibt, nimmt wie bisher den übersetzten Pfad und wird dort gesenkt. Unter +einer Obergrenze `none` wird bei einem nativ weitergeleiteten Request das Thinking mit `thinking: {"type": "disabled"}` ausgeschaltet; ein Modell, das immer denkt (Fable 5.x, Mythos 5.x, Opus 5.5), erhält stattdessen `low`, wie auf dem übersetzten Pfad. Bekannte Einschränkung: Sonnet 5.5 lehnt `disabled` ab, diff --git a/docs/features/users.mdx b/docs/features/users.mdx index f6701fbc4..374cd4138 100644 --- a/docs/features/users.mdx +++ b/docs/features/users.mdx @@ -246,12 +246,15 @@ and the capped `max_tokens` bounds what it spends. Claude Opus 4.6 and Sonnet Ceilings apply after [virtual model overrides](/features/virtual-models#force-a-reasoning-effort), on every attempt, including failover legs, so they also bound an effort or a `max_tokens` that a virtual model forces or defaults. They apply to Chat -Completions, the Responses API, and the Anthropic Messages API; a Messages -request within the ceilings is still forwarded natively to Anthropic, and one -above them takes the translated path so it can be lowered. A request only -Anthropic can read (server-tool history, for example) has no translated path, -so its `max_tokens`, thinking budget, and `output_config.effort` are lowered in -the forwarded body instead. Under a `none` ceiling its thinking is turned off +Completions, the Responses API, and the Anthropic Messages API. Ceilings do +not take a Messages request off native forwarding to Anthropic: where it +would be forwarded natively without them, one above the ceilings has its +`max_tokens`, thinking budget, and `output_config.effort` lowered in the +forwarded body, and keeps its other members and its `anthropic-beta` headers. +A request that uses the response cache, failover, a forced reasoning effort or +request parameters, or a guardrail or plugin that rewrites it takes the +translated path as before, and is lowered there. Under a `none` ceiling a +natively forwarded request's thinking is turned off with `thinking: {"type": "disabled"}`; a model that always thinks (Fable 5.x, Mythos 5.x, Opus 5.5) gets `low` instead, as on the translated path. Known limit: Sonnet 5.5 rejects `disabled`, so such a request to it fails with diff --git a/docs/pl/features/users.mdx b/docs/pl/features/users.mdx index f7f24ddce..084367f9b 100644 --- a/docs/pl/features/users.mdx +++ b/docs/pl/features/users.mdx @@ -246,13 +246,15 @@ Claude Opus 4.6 i Sonnet 4.6 przyjmują `max`, ale nie `xhigh`, więc przy limic Limity działają po [nadpisaniach modeli wirtualnych](/pl/features/virtual-models#wymuszanie-reasoning-effort), przy każdej próbie, także przy próbach failover, więc ograniczają też effort lub `max_tokens`, które model wirtualny wymusza albo ustawia domyślnie. Dotyczą -Chat Completions, Responses API i Anthropic Messages API; request Messages -mieszczący się w limitach jest nadal przekazywany natywnie do Anthropic, a -przekraczający je idzie ścieżką tłumaczoną, żeby można go było obniżyć. -Request, który potrafi odczytać tylko Anthropic (np. z historią narzędzi -serwerowych), nie ma ścieżki tłumaczonej, więc jego `max_tokens`, budżet -thinking i `output_config.effort` są obniżane w przekazywanym body. Przy -limicie `none` jego thinking jest wyłączany przez +Chat Completions, Responses API i Anthropic Messages API. Limity nie +wyłączają natywnego przekazywania requestu Messages do Anthropic: jeśli bez +nich byłby przekazany natywnie, a przekracza limity, jego `max_tokens`, budżet +thinking i `output_config.effort` są obniżane w przekazywanym body, a pozostałe +pola i nagłówki `anthropic-beta` zostają zachowane. Request, który korzysta z +cache odpowiedzi, failover, wymuszonego reasoning effort lub parametrów +requestu albo z guardraila lub pluginu, który go przepisuje, idzie jak dotąd +ścieżką tłumaczoną i tam jest obniżany. Przy limicie `none` thinking requestu +przekazywanego natywnie jest wyłączany przez `thinking: {"type": "disabled"}`; model, który zawsze myśli (Fable 5.x, Mythos 5.x, Opus 5.5), dostaje zamiast tego `low`, tak jak na ścieżce tłumaczonej. Znane ograniczenie: Sonnet 5.5 odrzuca `disabled`, więc taki diff --git a/docs/zh/features/users.mdx b/docs/zh/features/users.mdx index a838c7492..2596c1667 100644 --- a/docs/zh/features/users.mdx +++ b/docs/zh/features/users.mdx @@ -156,7 +156,7 @@ users: 关闭推理的控制项(`false`、零预算、`{"type": "disabled"}`)以及不超过上限的级别会保留。刻度无法定位的值(例如 token 预算或 `true`)视为超过上限:网关会移除客户端的所有推理控制项,改为发送上限作为推理强度。同时关闭推理的请求(例如 `enable_thinking: false` 与 `thinking_budget` 并存)不会因此被开启推理,重复 `type` 且只有最后一次为 `disabled` 的控制对象也是如此:这些控制项同样会被移除,取而代之的是请求在别处指定且不超过上限的最高推理强度,若没有其他推理强度则为 `none`。Messages 的 `budget_tokens` 若高于网关自身为上限级别发送的预算(`low` 为 5000,`medium` 为 10000,`high` 及以上为 20000),会被降到该预算。“从不添加推理强度”只有一个例外:未指定 `output_config.effort` 的 Messages 自适应 thinking(`thinking: {"type": "adaptive"}`)。此时 thinking 已经开启,Anthropic 按 `high` 运行它,因此在更低的上限下会把该上限作为它的推理强度发送。适配器自行填入的值(Anthropic 的默认 `max_tokens` 及其在 thinking 预算之上预留的空间、OpenCode Zen 的默认推理强度)同样保持在上限之内:thinking 预算会缩小到能放进受限的 `max_tokens`,连最小预算都放不下时则关闭 thinking。自适应 thinking(Claude Opus 4.6、Sonnet 4.6 及更新的模型)没有预算:它保持开启,其消耗由受限的 `max_tokens` 约束。Claude Opus 4.6 和 Sonnet 4.6 接受 `max` 但不接受 `xhigh`,因此在 `xhigh` 上限下会向它们发送 `high`。 -上限在[虚拟模型覆盖](/zh/features/virtual-models#强制推理强度)之后生效,作用于每一次尝试,包括故障转移尝试,因此也会约束虚拟模型强制或默认设置的推理强度或 `max_tokens`。它们适用于 Chat Completions、Responses API 和 Anthropic Messages API;在上限之内的 Messages 请求仍会原生转发给 Anthropic,超过上限的请求会改走转换路径以便降低。只有 Anthropic 能读取的请求(例如带有服务器工具历史)没有转换路径,因此会直接在转发的请求体中降低其 `max_tokens`、thinking 预算和 `output_config.effort`。在 `none` 上限下,它的 thinking 会通过 `thinking: {"type": "disabled"}` 关闭;始终思考的模型(Fable 5.x、Mythos 5.x、Opus 5.5)则改为收到 `low`,与转换路径一致。已知限制:Sonnet 5.5 会拒绝 `disabled`,因此发往该模型的这类请求会以 Anthropic 的 `400` 失败。原生转发的请求体若重复其中某个成员或以不同大小写书写,到达 Anthropic 时只保留一个:最低的 `max_tokens`,以及最后一个 `thinking` 和 `output_config`。网关无法降到上限之内的请求体会以 `400` 拒绝,绝不会超过上限转发。嵌入和媒体端点不会被改写。[响应缓存](/zh/features/cache)的条目与生效的上限绑定,因此在设置或修改上限之前缓存的回答不会在新上限下返回。 +上限在[虚拟模型覆盖](/zh/features/virtual-models#强制推理强度)之后生效,作用于每一次尝试,包括故障转移尝试,因此也会约束虚拟模型强制或默认设置的推理强度或 `max_tokens`。它们适用于 Chat Completions、Responses API 和 Anthropic Messages API。上限不会让 Messages 请求离开对 Anthropic 的原生转发:原本会被原生转发的请求若超过上限,会直接在转发的请求体中降低其 `max_tokens`、thinking 预算和 `output_config.effort`,其余字段和 `anthropic-beta` 请求头会被保留。使用响应缓存、故障转移、强制推理强度或请求参数,或者会被护栏或插件改写的请求,仍像以前一样走转换路径,并在那里被降低。在 `none` 上限下,原生转发的请求的 thinking 会通过 `thinking: {"type": "disabled"}` 关闭;始终思考的模型(Fable 5.x、Mythos 5.x、Opus 5.5)则改为收到 `low`,与转换路径一致。已知限制:Sonnet 5.5 会拒绝 `disabled`,因此发往该模型的这类请求会以 Anthropic 的 `400` 失败。原生转发的请求体若重复其中某个成员或以不同大小写书写,到达 Anthropic 时只保留一个:最低的 `max_tokens`,以及最后一个 `thinking` 和 `output_config`。网关无法降到上限之内的请求体会以 `400` 拒绝,绝不会超过上限转发。嵌入和媒体端点不会被改写。[响应缓存](/zh/features/cache)的条目与生效的上限绑定,因此在设置或修改上限之前缓存的回答不会在新上限下返回。 批处理、Realtime 会话(`/v1/realtime`)和 `/p/` 下的提供商直通**不受**上限约束:它们的请求体会原样发往上游。受限的密钥如果还能使用它们,就可以绕过该策略,因此请为受限的密钥禁止这些端点。[ChatGPT](/zh/providers/chatgpt) 提供商不接受输出 token 上限,因此 `max_output_tokens` 不会在其模型上强制执行。token 上限约束的是每一个回答:要求多个候选回答(`n`)的 Chat Completions 请求,得到的输出可以达到上限的相应倍数。如有需要,请用模型的 [`params`](/zh/features/virtual-models#设置请求参数) 强制设置 `n`。 diff --git a/internal/gateway/request_ceilings.go b/internal/gateway/request_ceilings.go index f4b377178..e392342b2 100644 --- a/internal/gateway/request_ceilings.go +++ b/internal/gateway/request_ceilings.go @@ -31,12 +31,6 @@ func ResponsesRequestWithCeilings(req *core.ResponsesRequest, ceilings requestpa return requestparams.CapResponsesTokens(req, ceilings) } -// ChatRequestExceedsCeilings reports whether the ceilings would change req. -func ChatRequestExceedsCeilings(req *core.ChatRequest, ceilings requestparams.Ceilings) bool { - capped, err := ChatRequestWithCeilings(req, ceilings) - return err != nil || capped != req -} - // effortWithinCeiling reports whether the efforts a request carries, in any // spelling, have to be replaced, and the effort that replaces them all. One // above ceiling is replaced by the ceiling, and so is one the common scale diff --git a/internal/gateway/request_ceilings_test.go b/internal/gateway/request_ceilings_test.go index d56d9931f..7ac1d8b41 100644 --- a/internal/gateway/request_ceilings_test.go +++ b/internal/gateway/request_ceilings_test.go @@ -118,7 +118,6 @@ func TestChatRequestWithCeilingsReasoningEffort(t *testing.T) { capped, err := ChatRequestWithCeilings(req, requestparams.Ceilings{ReasoningEffort: tt.ceiling}) require.NoError(t, err) - assert.Equal(t, !tt.unchanged, ChatRequestExceedsCeilings(req, requestparams.Ceilings{ReasoningEffort: tt.ceiling})) if tt.unchanged { assert.Same(t, req, capped) return diff --git a/internal/server/messages_handler.go b/internal/server/messages_handler.go index fbf820862..2f613988c 100644 --- a/internal/server/messages_handler.go +++ b/internal/server/messages_handler.go @@ -198,7 +198,7 @@ func (s *translatedInferenceService) Messages(c *echo.Context) error { // the translated pipeline can actually carry the request: content it cannot // represent (server-tool history, …) still belongs upstream verbatim. unsignedThinking := translateErr == nil && anthropicapi.HasUnsignedThinking(decoded) - if s.canForwardMessagesNatively(ctx, workflow, req, decoded, unsignedThinking, translateErr != nil) { + if s.canForwardMessagesNatively(ctx, workflow, unsignedThinking) { return s.dispatchMessagesNative(c, prepared, decoded, workflow) } if translateErr != nil { diff --git a/internal/server/messages_native.go b/internal/server/messages_native.go index ea470b0c5..a659078b9 100644 --- a/internal/server/messages_native.go +++ b/internal/server/messages_native.go @@ -19,7 +19,6 @@ import ( "github.com/enterpilot/gomodel/ext" "github.com/enterpilot/gomodel/internal/anthropicapi" "github.com/enterpilot/gomodel/internal/core" - "github.com/enterpilot/gomodel/internal/gateway" "github.com/enterpilot/gomodel/internal/requestlog" "github.com/enterpilot/gomodel/internal/streaming" ) @@ -35,10 +34,7 @@ const anthropicProviderType = "anthropic" // requests using guardrails patching, response caching, failover, or a forced // reasoning effort stay on the translated pipeline. So does a request replaying an unsigned thinking // block, which Anthropic rejects and only the translated pipeline can drop. -// req is the client's request as translated, before any override, and -// decoded the request as sent. nativeOnly marks a request the translated -// pipeline cannot carry. -func (s *translatedInferenceService) canForwardMessagesNatively(ctx context.Context, workflow *core.Workflow, req *core.ChatRequest, decoded *anthropicapi.MessagesRequest, unsignedThinking, nativeOnly bool) bool { +func (s *translatedInferenceService) canForwardMessagesNatively(ctx context.Context, workflow *core.Workflow, unsignedThinking bool) bool { if workflow == nil || strings.TrimSpace(workflow.ProviderType) != anthropicProviderType { return false } @@ -58,19 +54,12 @@ func (s *translatedInferenceService) canForwardMessagesNatively(ctx context.Cont return false } // A forced reasoning effort or request parameters rewrite the request, - // which the verbatim body cannot carry. Ceilings rewrite only a request - // that exceeds them: one already within them is forwarded as it is. The - // translation keeps only a coarse level of the thinking config (a budget's - // band, "medium" for adaptive thinking that Anthropic runs at "high"), so - // the config itself is checked too, as the forwarded body would carry it; - // the translated pipeline then sends the ceiling level. A request only - // the native path can carry stays on it above the ceilings too: - // dispatchMessagesNative lowers its body to them. - overrides := s.inference().RequestOverrides(ctx, workflow) - if overrides.Forces() { - return false - } - if !nativeOnly && (gateway.ChatRequestExceedsCeilings(req, overrides.Ceilings) || messagesExceedCeilings(decoded, nativeMessagesCeilings(workflow, overrides.Ceilings), modelAlwaysThinks(workflow))) { + // which the verbatim body cannot carry. Ceilings do not take a request off + // the native path: dispatchMessagesNative lowers max_tokens, the thinking + // config and output_config.effort where they stand in the body, so one + // above them keeps its anthropic-beta headers and every member the + // translation does not model (metadata, context_management). + if s.inference().RequestOverrides(ctx, workflow).Forces() { return false } _, ok := s.provider.(core.RoutablePassthrough) diff --git a/internal/server/plugin_phases_test.go b/internal/server/plugin_phases_test.go index 9c7976b03..23cea86fb 100644 --- a/internal/server/plugin_phases_test.go +++ b/internal/server/plugin_phases_test.go @@ -290,7 +290,7 @@ func TestCanForwardMessagesNatively_DisabledByPostResponsePlugins(t *testing.T) chains := phaseChains(t, map[string]string{"response": "warn"}, guardrails.StepReference{Ref: "phase", Phase: pluginapi.KindResponse, Step: 1}) svc := &translatedInferenceService{provider: &capturingProvider{}, pluginChains: staticChainsResolver{chains: chains}} workflow := &core.Workflow{ProviderType: anthropicProviderType} - require.False(t, svc.canForwardMessagesNatively(context.Background(), workflow, &core.ChatRequest{}, nil, false, false)) + require.False(t, svc.canForwardMessagesNatively(context.Background(), workflow, false)) svc.pluginChains = staticChainsResolver{chains: &plugins.Chains{}} require.False(t, svc.hasPostResponsePlugins(context.Background())) diff --git a/internal/server/user_path_ceilings_upstream_test.go b/internal/server/user_path_ceilings_upstream_test.go index 3d7bc06ab..f3450a690 100644 --- a/internal/server/user_path_ceilings_upstream_test.go +++ b/internal/server/user_path_ceilings_upstream_test.go @@ -106,9 +106,8 @@ func TestCeilingHoldsThroughAnthropicThinkingRoom(t *testing.T) { } } -// Native Messages forwarding sends the client's body verbatim, so an explicit -// thinking budget above the ceiling level's own budget must send the request -// through the translated pipeline, which sends that level's budget. +// An explicit thinking budget above the ceiling level's own budget is lowered +// to that level's budget in the body native Messages forwarding sends. func TestCeilingBoundsNativeMessagesThinkingBudget(t *testing.T) { tests := []struct { name string diff --git a/internal/server/user_path_native_ceilings_upstream_test.go b/internal/server/user_path_native_ceilings_upstream_test.go index af1d918ef..511cb9b5f 100644 --- a/internal/server/user_path_native_ceilings_upstream_test.go +++ b/internal/server/user_path_native_ceilings_upstream_test.go @@ -2,7 +2,6 @@ package server import ( "net/http" - "strings" "testing" "github.com/stretchr/testify/assert" @@ -145,14 +144,12 @@ func TestCeilingLowersAPerMessageEffortOfANativeMessagesBody(t *testing.T) { assert.Equal(t, `{"model":"claude-opus-5",`+body("low"), string(f.upstreams["anthropic"].Last(t).Body)) }) - t.Run("a request the translated pipeline lowers carries no per-message effort", func(t *testing.T) { + t.Run("with a top-level effort above the ceiling in a body the pipeline could carry", func(t *testing.T) { f := newUpstreamFixture(t, cappedRows, nil) rec := f.post(t, "/low", "/v1/messages", `{"model":"anthropic/claude-opus-5","max_tokens":512,"output_config":{"effort":"max"},`+effortTurns("max")+`}`) require.Equal(t, http.StatusOK, rec.Code, rec.Body.String()) - sent := string(f.upstreams["anthropic"].Last(t).Body) - assert.Equal(t, 1, strings.Count(sent, `"effort"`), sent) - assert.Equal(t, "low", object(t, f.sent(t, "anthropic"), "output_config")["effort"]) + assert.Equal(t, `{"model":"claude-opus-5","max_tokens":512,"output_config":{"effort":"low"},`+effortTurns("low")+`}`, string(f.upstreams["anthropic"].Last(t).Body)) }) } @@ -167,11 +164,11 @@ func TestXHighCeilingSendsHighToAModelWithoutThatLevel(t *testing.T) { want string }{ {name: "chat completions", path: "/v1/chat/completions", body: `{"model":"anthropic/claude-opus-4-6","reasoning_effort":"max",` + hiMessages + `}`, want: "high"}, - {name: "messages, lowered by the translated pipeline", path: "/v1/messages", body: `{"model":"anthropic/claude-opus-4-6","max_tokens":512,"output_config":{"effort":"max"},` + hiMessages + `}`, want: "high"}, + {name: "messages, lowered in the forwarded body", path: "/v1/messages", body: `{"model":"anthropic/claude-opus-4-6","max_tokens":512,"output_config":{"effort":"max"},` + hiMessages + `}`, want: "high"}, {name: "messages, lowered in a native-only body", path: "/v1/messages", body: `{"model":"anthropic/claude-opus-4-6","max_tokens":512,"output_config":{"effort":"max"},` + serverToolHistory + `}`, want: "high"}, {name: "messages within the ceiling", path: "/v1/messages", body: `{"model":"anthropic/claude-opus-4-6","max_tokens":512,"output_config":{"effort":"high"},` + hiMessages + `}`, want: "high"}, {name: "sonnet 4.6, chat completions", path: "/v1/chat/completions", body: `{"model":"anthropic/claude-sonnet-4-6","reasoning_effort":"max",` + hiMessages + `}`, want: "high"}, - {name: "sonnet 4.6, messages lowered by the translated pipeline", path: "/v1/messages", body: `{"model":"anthropic/claude-sonnet-4-6","max_tokens":512,"output_config":{"effort":"max"},` + hiMessages + `}`, want: "high"}, + {name: "sonnet 4.6, messages lowered in the forwarded body", path: "/v1/messages", body: `{"model":"anthropic/claude-sonnet-4-6","max_tokens":512,"output_config":{"effort":"max"},` + hiMessages + `}`, want: "high"}, {name: "sonnet 4.6, messages lowered in a native-only body", path: "/v1/messages", body: `{"model":"anthropic/claude-sonnet-4-6","max_tokens":512,"output_config":{"effort":"max"},` + serverToolHistory + `}`, want: "high"}, {name: "a model with the level gets it", path: "/v1/chat/completions", body: `{"model":"anthropic/claude-opus-5","reasoning_effort":"max",` + hiMessages + `}`, want: "xhigh"}, {name: "a model with the level gets it in a native-only body", path: "/v1/messages", body: `{"model":"anthropic/claude-opus-5","max_tokens":512,"output_config":{"effort":"max"},` + serverToolHistory + `}`, want: "xhigh"}, diff --git a/internal/server/user_path_native_duplicates_upstream_test.go b/internal/server/user_path_native_duplicates_upstream_test.go index 45aca6c78..7808bbd50 100644 --- a/internal/server/user_path_native_duplicates_upstream_test.go +++ b/internal/server/user_path_native_duplicates_upstream_test.go @@ -53,26 +53,23 @@ func single(t *testing.T, object, key string) string { // A decoder may keep the first occurrence of a repeated member, or read only // the exact name, where the gateway's reads the last in any letter case. A // body that names its limit more than once therefore reaches Anthropic with -// one max_tokens, within the cap: the lowest the client named when the body -// is forwarded natively, and the one the gateway read, capped, when it takes -// the translated pipeline because that one is above the cap. +// one max_tokens, within the cap: the lowest the client named, whichever +// order they stand in. func TestNativeMessagesForwardOneLimitWithinTheCap(t *testing.T) { tests := []struct { name string limit string - // wantNative is the max_tokens a native-only request is forwarded - // with, wantTranslatable that of a request the pipeline can carry. - wantNative, wantTranslatable int + want int }{ - {"review request: a re-cased duplicate after", `"max_tokens":100000,"MAX_TOKENS":5`, 5, 5}, - {"a re-cased duplicate before", `"MAX_TOKENS":5,"max_tokens":100000`, 5, 1000}, - {"review request: an exact duplicate", `"max_tokens":64000,"max_tokens":500`, 500, 500}, - {"an exact duplicate in the other order", `"max_tokens":500,"max_tokens":64000`, 500, 1000}, - {"duplicates that are all above the cap", `"max_tokens":64000,"Max_Tokens":32000,"max_tokens":16000`, 1000, 1000}, - {"only a re-cased member", `"Max_Tokens":64000`, 1000, 1000}, - {"a re-cased member within the cap on its own", `"MAX_TOKENS":500`, 500, 500}, - {"a null after the limit", `"max_tokens":64000,"max_tokens":null`, 1000, 1000}, - {"a null before the limit", `"MAX_TOKENS":null,"max_tokens":64000`, 1000, 1000}, + {"review request: a re-cased duplicate after", `"max_tokens":100000,"MAX_TOKENS":5`, 5}, + {"a re-cased duplicate before", `"MAX_TOKENS":5,"max_tokens":100000`, 5}, + {"review request: an exact duplicate", `"max_tokens":64000,"max_tokens":500`, 500}, + {"an exact duplicate in the other order", `"max_tokens":500,"max_tokens":64000`, 500}, + {"duplicates that are all above the cap", `"max_tokens":64000,"Max_Tokens":32000,"max_tokens":16000`, 1000}, + {"only a re-cased member", `"Max_Tokens":64000`, 1000}, + {"a re-cased member within the cap on its own", `"MAX_TOKENS":500`, 500}, + {"a null after the limit", `"max_tokens":64000,"max_tokens":null`, 1000}, + {"a null before the limit", `"MAX_TOKENS":null,"max_tokens":64000`, 1000}, } for history, messages := range messagesHistories { for _, tt := range tests { @@ -81,11 +78,7 @@ func TestNativeMessagesForwardOneLimitWithinTheCap(t *testing.T) { rec := f.post(t, "/tokens", "/v1/messages", `{"model":"anthropic/claude-sonnet-4-5",`+tt.limit+`,`+messages+`}`) require.Equal(t, http.StatusOK, rec.Code, rec.Body.String()) - want := tt.wantTranslatable - if messages == serverToolHistory { - want = tt.wantNative - } - assert.Equal(t, strconv.Itoa(want), single(t, string(f.upstreams["anthropic"].Last(t).Body), "max_tokens")) + assert.Equal(t, strconv.Itoa(tt.want), single(t, string(f.upstreams["anthropic"].Last(t).Body), "max_tokens")) }) } } diff --git a/internal/server/user_path_request_policy_test.go b/internal/server/user_path_request_policy_test.go index 939c14dc6..0ffe2bb3b 100644 --- a/internal/server/user_path_request_policy_test.go +++ b/internal/server/user_path_request_policy_test.go @@ -347,8 +347,8 @@ func TestUserPathCeilingsOnADirectModelRequest(t *testing.T) { } // An Anthropic Messages request is forwarded verbatim while it stays within -// the caller's ceilings and takes the translated pipeline, which can lower -// it, once it exceeds them or names no model. +// the caller's ceilings. One above them is forwarded too, with only its +// limits lowered, so it keeps the members the translation does not model. func TestUserPathPolicyAndNativeMessagesForwarding(t *testing.T) { newFixture := func(t *testing.T) (*capturingProvider, func(userPath, body string) *httptest.ResponseRecorder) { t.Helper() @@ -395,21 +395,23 @@ func TestUserPathPolicyAndNativeMessagesForwarding(t *testing.T) { require.NotNil(t, provider.lastPassthroughReq, "the request should have been forwarded natively") assert.Nil(t, provider.capturedChatReq) }) - t.Run("above the token ceiling is translated and capped", func(t *testing.T) { + t.Run("above the token ceiling is forwarded with the limit lowered in place", func(t *testing.T) { provider, post := newFixture(t) - post("/eng/alice", `{"model":"anthropic/claude-test","max_tokens":32000,"messages":[{"role":"user","content":"hi"}]}`) - assert.Nil(t, provider.lastPassthroughReq) - require.NotNil(t, provider.capturedChatReq) - require.NotNil(t, provider.capturedChatReq.MaxTokens) - assert.Equal(t, 4096, *provider.capturedChatReq.MaxTokens) + post("/eng/alice", `{"model":"anthropic/claude-test","max_tokens":32000,"metadata":{"user_id":"u1"},"context_management":{"edits":[{"type":"clear_tool_uses_20250919"}]},"messages":[{"role":"user","content":"hi"}]}`) + require.NotNil(t, provider.lastPassthroughReq, "the request should have been forwarded natively") + assert.Nil(t, provider.capturedChatReq) + forwarded, err := io.ReadAll(provider.lastPassthroughReq.Body) + require.NoError(t, err) + assert.Equal(t, `{"model":"claude-test","max_tokens":4096,"metadata":{"user_id":"u1"},"context_management":{"edits":[{"type":"clear_tool_uses_20250919"}]},"messages":[{"role":"user","content":"hi"}]}`, string(forwarded)) }) - t.Run("above the effort ceiling is translated and lowered", func(t *testing.T) { + t.Run("above the effort ceiling is forwarded with the effort lowered in place", func(t *testing.T) { provider, post := newFixture(t) post("/eng/alice", `{"model":"anthropic/claude-test","max_tokens":1024,"output_config":{"effort":"max"},"messages":[{"role":"user","content":"hi"}]}`) - assert.Nil(t, provider.lastPassthroughReq) - require.NotNil(t, provider.capturedChatReq) - require.NotNil(t, provider.capturedChatReq.Reasoning) - assert.Equal(t, "medium", provider.capturedChatReq.Reasoning.Effort) + require.NotNil(t, provider.lastPassthroughReq, "the request should have been forwarded natively") + assert.Nil(t, provider.capturedChatReq) + forwarded, err := io.ReadAll(provider.lastPassthroughReq.Body) + require.NoError(t, err) + assert.Equal(t, `{"model":"claude-test","max_tokens":1024,"output_config":{"effort":"medium"},"messages":[{"role":"user","content":"hi"}]}`, string(forwarded)) }) t.Run("a request served by the default model is forwarded with the model added", func(t *testing.T) { provider, post := newFixture(t) diff --git a/internal/storage/sqlx/conformance_test.go b/internal/storage/sqlx/conformance_test.go index b8591e7f0..f9bd840ce 100644 --- a/internal/storage/sqlx/conformance_test.go +++ b/internal/storage/sqlx/conformance_test.go @@ -504,3 +504,22 @@ func TestSchemaToleratesConcurrentApplication(t *testing.T) { } }) } + +func TestIsUniqueViolationRecognizesARepeatedKey(t *testing.T) { + sqlxtest.Run(t, func(t *testing.T, db sqlx.DB) { + ctx := context.Background() + db = newConformanceDB(t, db) + insert := `INSERT INTO conformance (id, flag, updated_at) VALUES (?, FALSE, 1)` + _, err := db.Exec(ctx, insert, "a") + require.NoError(t, err) + + _, err = db.Exec(ctx, insert, "a") + require.Error(t, err) + assert.True(t, sqlx.IsUniqueViolation(err), err.Error()) + + _, err = db.Exec(ctx, `INSERT INTO conformance (id, flag, updated_at) VALUES (?, FALSE, NULL)`, "b") + require.Error(t, err) + assert.False(t, sqlx.IsUniqueViolation(err), err.Error()) + assert.False(t, sqlx.IsUniqueViolation(nil)) + }) +} diff --git a/internal/storage/sqlx/errors.go b/internal/storage/sqlx/errors.go new file mode 100644 index 000000000..93a794834 --- /dev/null +++ b/internal/storage/sqlx/errors.go @@ -0,0 +1,24 @@ +package sqlx + +import ( + "errors" + "strings" + + "github.com/jackc/pgx/v5/pgconn" +) + +// uniqueViolation is the SQLSTATE of a row that repeats a unique key. +const uniqueViolation = "23505" + +// IsUniqueViolation reports whether err is an engine's refusal of a row that +// repeats a unique key: PostgreSQL's SQLSTATE 23505, and SQLite's "UNIQUE +// constraint failed". +func IsUniqueViolation(err error) bool { + if err == nil { + return false + } + if pgErr, ok := errors.AsType[*pgconn.PgError](err); ok { + return pgErr.Code == uniqueViolation + } + return strings.Contains(err.Error(), "UNIQUE constraint failed") +} diff --git a/internal/workflows/store_sql.go b/internal/workflows/store_sql.go index 23a6aaa29..c35f0d1bd 100644 --- a/internal/workflows/store_sql.go +++ b/internal/workflows/store_sql.go @@ -164,7 +164,26 @@ func (s *SQLStore) Create(ctx context.Context, input CreateInput) (*Version, err // EnsureManagedDefaultGlobal publishes the managed default workflow unless the // active global version is already it, or was authored by an operator. +// +// Gateways that start together race to publish it: the unique indexes let one +// insert through and refuse the others. A refused caller reads again and +// finds the version the winner published, as the MongoDB store does. func (s *SQLStore) EnsureManagedDefaultGlobal(ctx context.Context, input CreateInput, workflowHash string) (*Version, error) { + var lastErr error + for range 5 { + version, err := s.ensureManagedDefaultGlobal(ctx, input, workflowHash) + if err == nil { + return version, nil + } + if !sqlx.IsUniqueViolation(err) { + return nil, err + } + lastErr = err + } + return nil, fmt.Errorf("ensure managed default workflow after concurrent retries: %w", lastErr) +} + +func (s *SQLStore) ensureManagedDefaultGlobal(ctx context.Context, input CreateInput, workflowHash string) (*Version, error) { var created *Version err := s.db.InTx(ctx, func(q sqlx.Querier) error { active, hasActive, err := activeGlobalVersion(ctx, q) diff --git a/internal/workflows/store_suite_test.go b/internal/workflows/store_suite_test.go index d0e7ce5e2..e3eaf4881 100644 --- a/internal/workflows/store_suite_test.go +++ b/internal/workflows/store_suite_test.go @@ -2,7 +2,9 @@ package workflows import ( "context" + "fmt" "sort" + "sync" "testing" "time" @@ -234,3 +236,43 @@ func TestStoreEnsureManagedDefaultGlobalLeavesOperatorVersionAlone(t *testing.T) assert.Equal(t, operator.ID, active[0].ID) }) } + +// Gateways that start together all publish the managed default at once, on +// an empty database or after its definition changed. Every one of them must +// come up, and each definition is published once. +func TestStoreEnsureManagedDefaultGlobalSurvivesConcurrentStarts(t *testing.T) { + runStoreSuite(t, func(t *testing.T, store Store) { + ctx := context.Background() + input := CreateInput{ + Name: ManagedDefaultGlobalName, + Description: ManagedDefaultGlobalDescription, + Payload: testWorkflowPayload(), + Managed: true, + Activate: true, + } + + // The first round also opens the pool's connections, so the later + // ones start their transactions together. + const rounds = 5 + for round := 1; round <= rounds; round++ { + hash := fmt.Sprintf("hash-%d", round) + start := make(chan struct{}) + var wg sync.WaitGroup + for range 8 { + wg.Go(func() { + <-start + _, err := store.EnsureManagedDefaultGlobal(ctx, input, hash) + assert.NoError(t, err) + }) + } + close(start) + wg.Wait() + + active, err := store.ListActive(ctx) + require.NoError(t, err) + require.Len(t, active, 1) + assert.Equal(t, hash, active[0].WorkflowHash) + assert.Equal(t, round, active[0].Version) + } + }) +}