gateway: a stalled upload's retry waits for its connection to close (#7017)
stallGuard dropped the connection of an upload that stalled past bodyStall and retried through GetBody at once, so the retry could start while the stalled connection was still closing. The retry now waits for that close (dropped, closed once inside onStall, the only place errUploadStalled is set). From recih's branch (fix/web-restart-session-persistence, 04bac6196), ported as its own commit. Run: TestStalledBodyRetryWaitsForConnectionClose red on origin/main48fffb60c("retry began before the stalled connection finished closing"), green here. The full stack's run, on mote at e4506887c (this stack on origin/main7300be4d0): go test -timeout 45m ./...: 101 packages ok, 2 FAIL, both open issues that fail the same at7300be4d0on mote, where an ssh session forwards 127.0.0.1:3425 to a real magpie: internal/cli's TestHealthcheckFindsTheRunningGatewayWithoutMagpieAddr, TestUpdateRestartsTheGatewayItFindsWithoutMagpieAddr and TestUpdateFindsAMagpieThatWroteNoRecord (#6223), internal/gui's TestLaneLimitRoutes (#5150). On mica: gofmt -l clean; go vet ./..., GOOS=linux go vet -tags nogui ./..., GOOS=windows go vet ./..., go build, GOOS=linux go build -tags nogui, GOOS=windows go build all ok. go test -race -count=2 of the new and touched tests in internal/gateway, gui, plugin, tui ok on mote. Rebased since. Atdc507aefdon mote: go vet (darwin, GOOS=linux -tags nogui, windows) ok; go test of internal/cli, tui, plugin, gateway, gui, claudebridge ok but for the same #6223 and #5150 reds. At 939fe31b6 (on origin/main78b6d47cc) on mote: gofmt -l clean, the three vets ok, the stack's tests with TestClaude* and TestCoreScriptBudget ok in all six packages. Pushed onb400566f9after a clean rebase; the commits between touch no Go file this stack does. Co-authored-by: recih <240406+recih@users.noreply.github.com>
This commit is contained in:
@@ -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`): `<base>/publishers/anthropic/models/<model>: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 `<base>/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 `<base>/publishers/google/models/<model>: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
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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")
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user