diff --git a/docs/subsystems/gateway-routing.md b/docs/subsystems/gateway-routing.md index af65db1e5..a93c8e5b0 100644 --- a/docs/subsystems/gateway-routing.md +++ b/docs/subsystems/gateway-routing.md @@ -69,6 +69,15 @@ another for the conversation instead of listing every id | Vertex AI | A [Google Vertex AI provider](providers-accounts.md#responsibilities-and-sources-of-truth) speaks Gemini for its Gemini models, chat completions for its partner models, and Anthropic's Messages API for Claude. Claude (`provider.VertexClaude`: `claude-opus-5-5`, `claude-sonnet-4-5@20250929`) is relayed or translated as at any Anthropic vendor, and `forwardOnce`, after every other change to the body, moves the request to where Anthropic's Vertex SDK sends it (`provider.VertexClaudeRequest`): `/publishers/anthropic/models/:streamRawPredict` when the body streams, `:rawPredict` when it doesn't, the model out of the body; count_tokens to `count-tokens:rawPredict` with the model kept (`countTokens` counts at a provider whose `Base(Anthropic)` is set); `anthropic_version` `vertex-2023-10-16` added unless the body has one; Claude Code's `?beta=true` never sent. `thinkingOffAsTaken` and `samplingAsTaken` run before, so they read the model from the body. Tool search's beta goes as `tool-search-tool-2025-10-19`, the name Claude Code gives it for Vertex as for Bedrock (`bedrockBetas`); Bedrock's left-out betas aren't left out for it. Gemini's effort rules (`vertexEffort`) don't touch it (`TestVertexClaudeModel`). A partner model (`provider.VertexPartner`: a `publisher/model` id such as `deepseek-ai/deepseek-v4.1-flash-maas`) goes to Google's OpenAI-compatible `/endpoints/openapi/chat/completions` (`Base(Chat)`, `ListedAPIs`), signed with the same token, its full id in the body. It is relayed or translated there as any chat completions vendor is, and none of the Gemini rules below (`vertexEffort`, `vertexThinking`, signatures) touch it (`TestVertexPartnerModel`). A Gemini model's request goes to `/publishers/google/models/:streamGenerateContent?alt=sse` (`provider.VertexPath`, `upstreamPath`), the model named as the user's upstream name for it says (`UpstreamNameIn`, which the usage log's endpoint names too), with no `model` or `stream` field in its body (`passthrough`, `forwardOnce`, `geminiRequest`). A Gemini client's request is relayed as it came, its own `thinkingConfig`, `safetySettings` and the rest kept: streamed there, asked whole to `:generateContent` (`provider.VertexWholePath`), which answers one JSON body (Factory's rule of translating a whole request, as its route only streams, isn't Vertex AI's). Every other API's is translated (`buildFor`, `buildVertex`) and its stream read by `codeAssistDecoder`, which gives thought parts as reasoning, never as the answer's text. Effort: `vertexEffort` fits it to the model's levels, reasoning turned off going as `minimal` fitted the same way, and holds a model whose levels aren't known to `low`…`high`. `vertexThinking` sends Gemini 3 a `thinkingLevel` (`includeThoughts` false with reasoning off) and 2.5 a `thinkingBudget` in the model's range (`vertexBudgets`): turned off, the budget that stops its thinking, or Pro's least, as Pro can't stop. Thought signatures are every Gemini path's (#1445): a call's signature reaches the client in its id (`signedID`) and goes back on the call it came on, while a call with none in a step Vertex AI signed goes without; a step with nothing to give back has every call sent `skip_thought_signature_validator`. A 400 `Invalid thought signature.` (or AI Studio's `Corrupted thought signature.`, `signatureRefused`) is asked again with every call sent so (`withoutSignatures`), for that request only, at any upstream Gemini's signatures reach (`signaturesReach`), relayed too; it rests no account and lets a group go on (`restAfterMarked`, `shapeRefused`). A 400 refusing `minimal` (`geminiRefusedLevel`) is asked again at the model's lowest other level (`onEffort`), and `markUnfit(offRefused)` keeps that level until magpie restarts; that retry is the translated path's. Vertex AI's own Google Search grounding isn't used: `searchHosts` names only `generativelanguage.googleapis.com` for Gemini, so magpie searches for it (`search.go`). | [`vertex.go`](../../internal/gateway/vertex.go), [`gateway.go`](../../internal/gateway/gateway.go), [`codeassist.go`](../../internal/gateway/codeassist.go), [`gemini.go`](../../internal/gateway/gemini.go), [`gemini_signature.go`](../../internal/gateway/gemini_signature.go), [`search.go`](../../internal/gateway/search.go) | | Bedrock Mantle | A request on chat completions or Responses to an [Amazon Bedrock Mantle provider](providers-accounts.md#responsibilities-and-sources-of-truth) goes to the prefix that serves its model (`mantleRoutes`, `provider.MantleBase` in `forwardOnce`): `/openai/v1` for OpenAI's closed GPTs and xAI's Grok, `/v1` for the rest. A model Mantle refuses there with "model `x` isn't supported on this route" (a maker the rule doesn't know yet) is asked once more at the other prefix, and when it is taken there that prefix is remembered for the model in `unfit` (`mantleRouteKey`) until the gateway restarts. A model refused at both gets the first refusal and nothing is remembered (`mantleReroute`). Messages go to `/anthropic` alone. | [`mantle.go`](../../internal/gateway/mantle.go), [`gateway.go`](../../internal/gateway/gateway.go) | +A request body that stops moving while the transport holds a chunk is +bounded by `bodyStall` (`upstream_stall.go`). `stallGuard` cancels that try, +closes its connection, and waits for the close to finish before retrying +once with a fresh body. Cancellation alone wakes `RoundTrip` before the +close is complete: retrying then can send headers on the old connection +and count an extra attempt at the vendor. `TestStalledBodyRetryWaitsForConnectionClose` +holds the close to check this ordering; `TestBodyStalledByFlowControlIsGivenUp` +checks the two attempts against an HTTP/2 server that never reads the body. + ## Routing recipes A routing group's templates (`provider.Templates` in diff --git a/internal/gateway/upstream_stall.go b/internal/gateway/upstream_stall.go index 2d552486e..d1b558cf5 100644 --- a/internal/gateway/upstream_stall.go +++ b/internal/gateway/upstream_stall.go @@ -86,9 +86,14 @@ func (g stallGuard) try(r *http.Request) (*http.Response, error) { // one found closed) with a body from GetBody, which must be watched as // this one is, or a retried send is not bounded st := &stallTry{} + dropped := make(chan struct{}) + var dropOnce sync.Once st.onStall = func() { - cancel(errUploadStalled{after: bodyStall}) - st.dropConn() + dropOnce.Do(func() { + cancel(errUploadStalled{after: bodyStall}) + st.dropConn() + close(dropped) + }) } sb := st.watch(r.Body) trace := &httptrace.ClientTrace{GotConn: func(i httptrace.GotConnInfo) { st.setConn(i.Conn) }} @@ -109,6 +114,9 @@ func (g stallGuard) try(r *http.Request) (*http.Response, error) { cause := context.Cause(ctx) cancel(nil) if s, ok := cause.(errUploadStalled); ok { + // Cancellation wakes RoundTrip before the timer has finished + // closing the connection. Do not retry through that live socket. + <-dropped return nil, s } return nil, err diff --git a/internal/gateway/upstream_stall_close_test.go b/internal/gateway/upstream_stall_close_test.go new file mode 100644 index 000000000..a69d6593e --- /dev/null +++ b/internal/gateway/upstream_stall_close_test.go @@ -0,0 +1,90 @@ +package gateway + +import ( + "context" + "errors" + "net" + "net/http" + "net/http/httptrace" + "strings" + "sync" + "sync/atomic" + "testing" + "time" +) + +type stallClosingConn struct { + net.Conn + closing chan struct{} + release chan struct{} +} + +func (c *stallClosingConn) Close() error { + close(c.closing) + <-c.release + return c.Conn.Close() +} + +type stallCloseTransport func(*http.Request) (*http.Response, error) + +func (f stallCloseTransport) RoundTrip(r *http.Request) (*http.Response, error) { return f(r) } + +// Cancellation wakes RoundTrip before the timer finishes closing the old +// connection. A retry must not reach the pool until that close has finished. +func TestStalledBodyRetryWaitsForConnectionClose(t *testing.T) { + a, b := net.Pipe() + defer a.Close() + defer b.Close() + c := &stallClosingConn{Conn: a, closing: make(chan struct{}), release: make(chan struct{})} + var once sync.Once + release := func() { once.Do(func() { close(c.release) }) } + var calls atomic.Int32 + retried := make(chan struct{}) + retryErr := errors.New("retry reached a new connection") + g := stallGuard{next: stallCloseTransport(func(r *http.Request) (*http.Response, error) { + defer r.Body.Close() + if calls.Add(1) > 1 { + close(retried) + return nil, retryErr + } + httptrace.ContextClientTrace(r.Context()).GotConn(httptrace.GotConnInfo{Conn: c}) + go r.Body.(*stallBody).fire() + <-r.Context().Done() + return nil, r.Context().Err() + })} + ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) + defer cancel() + req, err := http.NewRequestWithContext(ctx, http.MethodPost, "http://vendor/", strings.NewReader("body")) + if err != nil { + t.Fatal(err) + } + done := make(chan error, 1) + go func() { _, err := g.RoundTrip(req); done <- err }() + defer func() { + release() + select { + case err := <-done: + if !errors.Is(err, retryErr) { + t.Errorf("retry result: %v", err) + } + case <-time.After(5 * time.Second): + t.Error("request did not finish") + } + }() + select { + case <-c.closing: + case <-ctx.Done(): + t.Fatal("stalled connection was not closed") + } + select { + case <-retried: + t.Fatal("retry began before the stalled connection finished closing") + case <-time.After(50 * time.Millisecond): + } + release() + select { + case <-retried: + case <-ctx.Done(): + t.Fatal("retry did not begin after close") + } +}