gateway: a probe's reply that thinks its 16 tokens and ends unsaid is answered (plugins#827)
Through a Remote magpie, the plain model test of Open Design's
glm-5.3-flash was red. The model always thinks. It spent the test's 16
tokens on that and ended after content_block_stop, with no message_delta
or message_stop. So:
- translate made it a 502 "ended before it was complete";
- the 502 is busy, so the remote retried it and waited out its 60s
patience;
- the asking magpie had given the remote only 20s (testWait), and said
no answer came.
Each step is now fixed for the class, not for this model:
- A reply whose request was capped at a short probe's worth
(cutVoidTokens, 1024) and that spent some of it, then ended cleanly
with nothing saying it ended, ended at its length (endsAtProbeCap).
- This holds in translate, in streamTranslated and in gathered (a
Responses plugin's stream asked whole becomes response.incomplete at
max_output_tokens).
- It covers Anthropic and Responses upstreams only. Gemini always
ends with a finishReason, so a Gemini stream without one stays a cut
(TestGeminiUpstreamEndedShort, asked for 256, caught a wider first
draft).
- A reply asked for more than 1024, or one that spent nothing, is
still the 502.
- A client may say how long it waits (provider.WaitHeader,
X-Magpie-Wait, in seconds). The gateway then takes no same-one retry
pause and no patience round that would end within clientRoom (10s) of
that wait (keptAlive.outlives), so the client gets the error while it
still waits. Like every X-Magpie- header, it is not sent upstream.
- A model test through a remote magpie waits pluginTestWait (60s), as a
plugin's test does here, and sends that wait as X-Magpie-Wait.
Not changed: a stream relayed as it came (passthrough to an agent of the
same protocol) still gets no end added. That is filed as #5736 and named
in gateway-routing.md.
Run, through mote-run:
- At the pushed tree, rebased on origin/main b68218f43 (802f03e68 after
it changes only site/): go vet, GOOS=windows go vet and GOOS=linux go
vet -tags nogui of internal/gateway and internal/provider are ok. go
test of both packages with -run
"ProbeCap|Gathered|ClientWait|RemoteMagpie|EndedShort|Gemini|SingleProvider|Responses|Enum|Group|Spent|Capped|Patience"
is ok. That covers the base's new Responses-enum and group commits.
At 8a7f77cb7 the same kind of run, with Compact|Signin|Carry for that
base's commits, was ok.
- Full run at 9c34dc7cb (the same change, rebased on origin/main
e2afbfc15): go vet
./internal/..., GOOS=linux go vet -tags nogui ./internal/..., and
GOOS=windows go vet ./internal/... are ok; go test ./internal/gateway
./internal/provider -timeout 45m: provider is ok; gateway is ok
except TestCodexGeneratedImagesPastOldLimit (#5281: held 31s
without routing in a full run; at this head it passes alone, 3 of
3, with -count=3)
- At 32a31963b, the first draft: go vet ./..., GOOS=linux go vet -tags
nogui ./... and GOOS=windows go vet ./... were ok; gofmt -l was empty.
The suite there:
- TestGeminiUpstreamEndedShort was red. The rule was too wide, and it
is scoped above.
- TestCodexGeneratedImagesPastOldLimit was red: #5281, the
images-body hold, not on these paths.
- TestCodexListTagNotKeptOverAFreshFile was red: #4216, under load.
Broken by hand, then put back:
- endsAtProbeCap returning false:
- TestProbeCapEndsAtLength goes red, both whole (502 ended before it
was complete) and stream (no finish_reason length).
- TestGatheredProbeCapIncomplete goes red (capped 16: 502).
- outlives returning false: TestClientWaitBoundsPatience/short_wait goes
red (upstream asked 6 times).
- probeOnce's remote-magpie wait and header taken out:
TestRemoteMagpieProbeWait goes red ("no answer in 1s", X-Magpie-Wait
said "").
Not tried: a real Open Design account, and a real two-magpie Remote
setup. The fixture is the reporter's described ending (thinking block,
content_block_stop, close), not their captured bytes.
Reported-by: Gitleonan
This commit is contained in:
File diff suppressed because one or more lines are too long
@@ -78,6 +78,35 @@ var errStreamCut = errors.New("stream cut mid-reply")
|
||||
// and be whole, so Chat is not one.
|
||||
var errEndedShort = errors.New("the reply ended before it was complete")
|
||||
|
||||
// endsAtProbeCap says whether a reply that stopped short of its end, its
|
||||
// connection closed cleanly, is taken as one that ended at its length:
|
||||
// the request capped it at a short probe's worth (cutVoidTokens) and the
|
||||
// reply spent some of it, thinking or saying something. A vendor that
|
||||
// ends a reply at max_tokens with no closing event looks the same as one
|
||||
// that cut it, and a reply asked for 16 tokens that thought them all is
|
||||
// what such an ending most likely is: Open Design's glm-5.3-flash always
|
||||
// thinks, spent a model test's 16 tokens on it and ended after
|
||||
// content_block_stop, with no message_delta or message_stop, so every
|
||||
// plain test of it through a remote magpie was a 502 waited out through
|
||||
// the patience (plugins#827). A larger reply that ends so is still a cut,
|
||||
// and so is a Gemini or Code Assist one of any size: Gemini ends every
|
||||
// reply with its finishReason, MAX_TOKENS included, so one without it was
|
||||
// cut (vertexCut, asked for 256, TestGeminiUpstreamEndedShort).
|
||||
func endsAtProbeCap(proto provider.Protocol, capped int, spent bool) bool {
|
||||
return (proto == provider.Anthropic || proto == provider.Responses) &&
|
||||
spent && capped > 0 && capped <= cutVoidTokens
|
||||
}
|
||||
|
||||
// spends says whether an event spent some of a reply's tokens: text,
|
||||
// a call, reasoning, a search or an image.
|
||||
func spends(ev Event) bool {
|
||||
switch ev.Kind {
|
||||
case KThink, KSealed:
|
||||
return true
|
||||
}
|
||||
return saysSomething(ev)
|
||||
}
|
||||
|
||||
// geminiEnds says whether a Gemini chunk ends the reply, as replyEnds
|
||||
// does for events that name their type. Gemini's and Code Assist's chunks
|
||||
// name none and there is no [DONE]: the last one is the one whose
|
||||
@@ -439,6 +468,8 @@ func (s *Server) streamTranslated(w http.ResponseWriter, r *http.Request, p prov
|
||||
// try's reasoning was found stuck in a loop before it had, and it is
|
||||
// let go to ask again (loopReasks)
|
||||
var spoke, relooped bool
|
||||
// spent: this try spent some of the reply's tokens (endsAtProbeCap)
|
||||
var spent bool
|
||||
var summaryUpstream bool
|
||||
reasks := 0
|
||||
if h, ok := w.(*holdWriter); ok {
|
||||
@@ -460,6 +491,7 @@ func (s *Server) streamTranslated(w http.ResponseWriter, r *http.Request, p prov
|
||||
return // the rest of a try let go for its loop
|
||||
}
|
||||
spoke = spoke || saysSomething(ev)
|
||||
spent = spent || spends(ev)
|
||||
switch ev.Kind {
|
||||
case KThink, KSealed:
|
||||
if ev.Kind == KThink && !summaryUpstream {
|
||||
@@ -526,7 +558,7 @@ func (s *Server) streamTranslated(w http.ResponseWriter, r *http.Request, p prov
|
||||
// continuation's prefill away
|
||||
cutBy, cutCode, cutErr := failed, failedCode, serr
|
||||
failed, failedCode, failedStatus, cut, serr = "", "", 0, false, nil
|
||||
errNamed = 0
|
||||
errNamed, spent = 0, false
|
||||
var held func() // what a textCallSee of this try holds back
|
||||
req := request
|
||||
if cont.resume {
|
||||
@@ -657,6 +689,14 @@ func (s *Server) streamTranslated(w http.ResponseWriter, r *http.Request, p prov
|
||||
// finish_reason after its generation was done
|
||||
u.add(Usage{Stop: fin})
|
||||
serr = dec(string(finishChunk(fin)), attemptSee)
|
||||
} else if endsAtProbeCap(actual, req.MaxTokens, spent) {
|
||||
// a short probe's reply that stopped at its own
|
||||
// small limit with no end said (plugins#827):
|
||||
// ended at its length, as the vendor should have
|
||||
// said
|
||||
u.add(Usage{Stop: "length"})
|
||||
serr = nil
|
||||
attemptSee(Event{Kind: KStop, Stop: "length"})
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -3089,6 +3089,9 @@ type keptAlive struct {
|
||||
// 40 MB upload asked four times) failed 502 instead of being made
|
||||
// without a model (#4862)
|
||||
whole bool
|
||||
// clientEnd is when the client said it stops waiting (clientEnd),
|
||||
// zero when it said nothing
|
||||
clientEnd time.Time
|
||||
// Only opted-in Claude cache reporting can defer initial keepalives.
|
||||
// Selection releases it before process startup; expiry keeps the stream alive.
|
||||
cacheReportUntil time.Time
|
||||
@@ -3125,6 +3128,32 @@ func (a *keptAlive) tooQuiet(d time.Duration) bool {
|
||||
return a != nil && a.streams && a.proto == provider.Responses && !a.told.IsZero() && time.Since(a.told)+d >= agentQuietMost
|
||||
}
|
||||
|
||||
// clientRoom is how long a client that said how long it waits is left,
|
||||
// after a pause, for the try the pause is for to answer and the reply or
|
||||
// its error to reach it.
|
||||
const clientRoom = 10 * time.Second
|
||||
|
||||
// clientEnd is when a request's client stops waiting, from the seconds
|
||||
// it named in provider.WaitHeader (a model test asking a remote magpie),
|
||||
// counted from start; zero when it named none, or nothing readable.
|
||||
func clientEnd(h http.Header, start time.Time) time.Time {
|
||||
n, err := strconv.Atoi(strings.TrimSpace(h.Get(provider.WaitHeader)))
|
||||
if err != nil || n <= 0 {
|
||||
return time.Time{}
|
||||
}
|
||||
return start.Add(time.Duration(min(n, 3600)) * time.Second)
|
||||
}
|
||||
|
||||
// outlives says whether a pause of d, with clientRoom after it, would end
|
||||
// past the time the client said it waits: its pause isn't taken, and the
|
||||
// client has the error while it still waits for one (plugins#827: a
|
||||
// remote magpie's model test waited 20s while the server kept its 502
|
||||
// through the provider's patience, 45s and more, and the test said only
|
||||
// that no answer came).
|
||||
func (a *keptAlive) outlives(d time.Duration) bool {
|
||||
return a != nil && !a.clientEnd.IsZero() && time.Now().Add(d+clientRoom).After(a.clientEnd)
|
||||
}
|
||||
|
||||
// keepAlive tells the agent of a stream held past keepHeldAfter for its
|
||||
// reasoning that it goes on, every keepHeldEvery: held for up to
|
||||
// holdThinking (4 minutes), the agent heard nothing at all, and Alma's
|
||||
|
||||
@@ -3210,7 +3210,7 @@ func (s *Server) serve(w http.ResponseWriter, r *http.Request, from provider.Pro
|
||||
unlisted, unlistedW = nil, nil
|
||||
}
|
||||
// what the tries' held streams sent the agent ahead of a reply (#751)
|
||||
kept := &keptAlive{proto: from, model: askedFor, told: start, whole: wantsWhole(r.Context())}
|
||||
kept := &keptAlive{proto: from, model: askedFor, told: start, whole: wantsWhole(r.Context()), clientEnd: clientEnd(r.Header, start)}
|
||||
if k := handedOnOf(r); k != nil && !kept.whole {
|
||||
// Codex's own sign-in waited for first, with Codex kept alive
|
||||
kept = k
|
||||
@@ -4868,7 +4868,7 @@ func (s *Server) serve(w http.ResponseWriter, r *http.Request, from provider.Pro
|
||||
if memberWait == 0 {
|
||||
memberWait = patience
|
||||
}
|
||||
if next, wait, ok := replan(busyNow, rounds, waitFrom, patienceFallback); ok && !kept.tooQuiet(wait) {
|
||||
if next, wait, ok := replan(busyNow, rounds, waitFrom, patienceFallback); ok && !kept.tooQuiet(wait) && !kept.outlives(wait) {
|
||||
try.Fail, try.Again = failureOf(c, hw.code(), hw.errBody()), wait.Milliseconds()
|
||||
if lastSpent {
|
||||
rest := s.restAfterMarked(c, hw.code(), hw.header, hw.errBody(), hw.sharedPool)
|
||||
@@ -4892,7 +4892,7 @@ func (s *Server) serve(w http.ResponseWriter, r *http.Request, from provider.Pro
|
||||
break
|
||||
}
|
||||
}
|
||||
if wait, ok := passing(hw.code(), hw.header, hw.errBody(), again); ok && !protected && !sameRefusal && !hw.turnedAway && hw.failed() && waitFrom.IsZero() && !kept.tooQuiet(wait) {
|
||||
if wait, ok := passing(hw.code(), hw.header, hw.errBody(), again); ok && !protected && !sameRefusal && !hw.turnedAway && hw.failed() && waitFrom.IsZero() && !kept.tooQuiet(wait) && !kept.outlives(wait) {
|
||||
// nobody else is left: the same one again, after a moment (not
|
||||
// what Antigravity turned away: it turns it away again; nor
|
||||
// once the group's patience is spent)
|
||||
@@ -6143,7 +6143,7 @@ func (s *Server) passthrough(w http.ResponseWriter, r *http.Request, p provider.
|
||||
// asked streamed, the stream read here (gathered)
|
||||
var gather *gathered
|
||||
if gathers(p, proto, body) {
|
||||
gather = &gathered{h: http.Header{}, status: http.StatusOK}
|
||||
gather = &gathered{h: http.Header{}, status: http.StatusOK, capped: int(gjson.GetBytes(body, "max_output_tokens").Int())}
|
||||
body = withFields(body, map[string]any{"stream": true})
|
||||
}
|
||||
searchFn := false // Codex's tool search sent as a function
|
||||
@@ -8702,9 +8702,13 @@ func (s *Server) translate(w http.ResponseWriter, r *http.Request, p provider.Pr
|
||||
}
|
||||
var col collector
|
||||
ended := false // the upstream said its reply ended
|
||||
spent := false // the reply spent some of its tokens (endsAtProbeCap)
|
||||
var tail chatTail
|
||||
var found searchTally // the searches it ran by itself
|
||||
see, held := written(zenSee(zen, col.add))
|
||||
see, held := written(zenSee(zen, func(ev Event) {
|
||||
spent = spent || spends(ev)
|
||||
col.add(ev)
|
||||
}))
|
||||
err = readSSE(rd, func(_, data string) error {
|
||||
tail.see([]byte(data))
|
||||
found.see(actual, []byte(data))
|
||||
@@ -8757,6 +8761,13 @@ func (s *Server) translate(w http.ResponseWriter, r *http.Request, p provider.Pr
|
||||
// with: a minute limit in a 200 stream is a 429, not a 502
|
||||
return writeVendorError(w, from, cmp.Or(col.errStatus, streamStatus(said)), p.Name+": "+said, col.errSaid), said
|
||||
}
|
||||
if col.err == "" && !ended && saysItsEnd(p, actual, model) && r.Context().Err() == nil && endsAtProbeCap(actual, request.MaxTokens, spent) {
|
||||
// a short probe's reply that stopped at its own small limit with
|
||||
// no end said (endsAtProbeCap, plugins#827): ended at its length,
|
||||
// as the vendor should have said
|
||||
col.add(Event{Kind: KStop, Stop: "length"})
|
||||
ended = true
|
||||
}
|
||||
if col.err == "" && !ended && saysItsEnd(p, actual, model) && r.Context().Err() == nil {
|
||||
// an Anthropic stream that just stopped — no stop_reason, no
|
||||
// message_stop — or a Responses one with no response.completed is
|
||||
|
||||
@@ -29,6 +29,9 @@ type gathered struct {
|
||||
h http.Header
|
||||
status int
|
||||
buf bytes.Buffer
|
||||
// capped: the max_output_tokens the client asked, for a reply that
|
||||
// stopped at it with no end said (endsAtProbeCap)
|
||||
capped int
|
||||
}
|
||||
|
||||
func (g *gathered) Header() http.Header { return g.h }
|
||||
@@ -40,7 +43,9 @@ func (g *gathered) Write(b []byte) (int, error) { return g.buf.Write(b) }
|
||||
// stream's items, or else its text, when the event left it empty.
|
||||
// A reply that came whole goes as it came. A stream that failed, or ended
|
||||
// before saying its reply had, is a 502, as a translated one is
|
||||
// (TestNonStreamEndedShort), never an empty 200.
|
||||
// (TestNonStreamEndedShort), never an empty 200 — unless a short probe's
|
||||
// reply stopped at its own small limit (endsAtProbeCap): its response as
|
||||
// the stream began it, incomplete at max_output_tokens.
|
||||
func (g *gathered) finish(w http.ResponseWriter, p provider.Provider, sse bool, cut string, failed string) (int, string) {
|
||||
if !sse {
|
||||
for k, vs := range g.h {
|
||||
@@ -50,7 +55,8 @@ func (g *gathered) finish(w http.ResponseWriter, p provider.Provider, sse bool,
|
||||
w.Write(g.buf.Bytes())
|
||||
return g.status, failed
|
||||
}
|
||||
var resp json.RawMessage
|
||||
var resp, begun json.RawMessage // begun: the response as the stream began it
|
||||
spent := false // a delta of the reply's came (endsAtProbeCap)
|
||||
items := map[int]json.RawMessage{}
|
||||
var text strings.Builder // the reply's text, for a stream with no items
|
||||
streamErr := ""
|
||||
@@ -68,7 +74,12 @@ func (g *gathered) finish(w http.ResponseWriter, p provider.Provider, sse bool,
|
||||
if e.Type == "" {
|
||||
e.Type = event
|
||||
}
|
||||
if strings.HasSuffix(e.Type, ".delta") {
|
||||
spent = true
|
||||
}
|
||||
switch e.Type {
|
||||
case "response.created", "response.in_progress":
|
||||
begun = e.Response
|
||||
case "response.output_text.delta":
|
||||
text.WriteString(e.Delta)
|
||||
case "response.output_item.done":
|
||||
@@ -82,6 +93,10 @@ func (g *gathered) finish(w http.ResponseWriter, p provider.Provider, sse bool,
|
||||
}
|
||||
return nil
|
||||
})
|
||||
if (len(resp) == 0 || resp[0] != '{') && streamErr == "" && cut == "" && failed == "" &&
|
||||
len(begun) > 0 && begun[0] == '{' && endsAtProbeCap(provider.Responses, g.capped, spent) {
|
||||
resp = incompleteAtLength(begun)
|
||||
}
|
||||
if len(resp) == 0 || resp[0] != '{' {
|
||||
msg := failed
|
||||
switch {
|
||||
@@ -111,6 +126,22 @@ func (g *gathered) finish(w http.ResponseWriter, p provider.Provider, sse bool,
|
||||
return http.StatusOK, ""
|
||||
}
|
||||
|
||||
// incompleteAtLength is a response as its stream began it, made the
|
||||
// response.incomplete a reply stopped at its max_output_tokens ends with.
|
||||
func incompleteAtLength(begun json.RawMessage) json.RawMessage {
|
||||
var m map[string]json.RawMessage
|
||||
if json.Unmarshal(begun, &m) != nil {
|
||||
return nil
|
||||
}
|
||||
m["status"] = json.RawMessage(`"incomplete"`)
|
||||
m["incomplete_details"] = json.RawMessage(`{"reason":"max_output_tokens"}`)
|
||||
b, err := json.Marshal(m)
|
||||
if err != nil {
|
||||
return nil
|
||||
}
|
||||
return b
|
||||
}
|
||||
|
||||
// withStreamedOutput is resp with the stream's items as its output when
|
||||
// its own output is missing or empty.
|
||||
func withStreamedOutput(resp json.RawMessage, items map[int]json.RawMessage) json.RawMessage {
|
||||
|
||||
@@ -0,0 +1,148 @@
|
||||
package gateway
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/yetone/magpie/internal/provider"
|
||||
)
|
||||
|
||||
// Open Design's glm-5.3-flash, as plugins#827's log has it: a reply that
|
||||
// thinks, closes its block and ends, with no message_delta or
|
||||
// message_stop, when the model test's 16 tokens are spent.
|
||||
func probeCapStream(model string) []string {
|
||||
return []string{
|
||||
anthStart(model, 5),
|
||||
`{"type":"content_block_start","index":0,"content_block":{"type":"thinking","thinking":""}}`,
|
||||
anthThink("The user says hi. I should"),
|
||||
`{"type":"content_block_stop","index":0}`,
|
||||
}
|
||||
}
|
||||
|
||||
func probeCapAsk(maxTokens string, stream bool) string {
|
||||
s := "false"
|
||||
if stream {
|
||||
s = "true"
|
||||
}
|
||||
return `{"model":"up/glm-5.3-flash","max_tokens":` + maxTokens + `,"stream":` + s + `,"messages":[{"role":"user","content":"hi"}]}`
|
||||
}
|
||||
|
||||
// A short probe's reply that thought its whole small budget and ended
|
||||
// with no end said ended at its length, whole or streamed (plugins#827:
|
||||
// every plain test of such a model was a 502 "ended before it was
|
||||
// complete", waited out through the patience). A reply asked for more
|
||||
// that ends so is still a cut, and so is one that spent nothing.
|
||||
func TestProbeCapEndsAtLength(t *testing.T) {
|
||||
for _, stream := range []bool{false, true} {
|
||||
name := map[bool]string{false: "whole", true: "stream"}[stream]
|
||||
t.Run(name, func(t *testing.T) {
|
||||
up := func(events ...string) {
|
||||
fresh(t)
|
||||
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
w.Header().Set("Content-Type", "text/event-stream")
|
||||
for _, ev := range events {
|
||||
w.Write([]byte("data: " + ev + "\n\n"))
|
||||
}
|
||||
}))
|
||||
t.Cleanup(srv.Close)
|
||||
if err := provider.Save(provider.Provider{ID: "up", Name: "UP", Key: "k", Models: []string{"glm-5.3-flash"}, Anthropic: srv.URL}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
up(probeCapStream("glm-5.3-flash")...)
|
||||
code, body := post(t, "/v1/chat/completions", probeCapAsk("16", stream))
|
||||
if code != 200 || strings.Contains(body, "ended before") || !strings.Contains(body, `"finish_reason":"length"`) {
|
||||
t.Errorf("probe's reply at its cap: status %d: %s", code, body)
|
||||
}
|
||||
// asked for more than a probe's worth: a cut
|
||||
code, body = post(t, "/v1/chat/completions", probeCapAsk("4096", stream))
|
||||
if !strings.Contains(body, "ended before it was complete") || (!stream && code != 502) {
|
||||
t.Errorf("a long reply cut short served as ended (status %d): %s", code, body)
|
||||
}
|
||||
// nothing spent: a cut, whatever its cap
|
||||
up(anthStart("glm-5.3-flash", 5))
|
||||
code, body = post(t, "/v1/chat/completions", probeCapAsk("16", stream))
|
||||
if !strings.Contains(body, "ended before it was complete") || (!stream && code != 502) {
|
||||
t.Errorf("a reply that spent nothing served as ended (status %d): %s", code, body)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// A Responses plugin's stream asked whole, capped at a probe's worth and
|
||||
// ended with no response.completed after spending some of it, is the
|
||||
// response incomplete at max_output_tokens, not a 502; one capped past a
|
||||
// probe's worth is still the 502.
|
||||
func TestGatheredProbeCapIncomplete(t *testing.T) {
|
||||
stream := sse(
|
||||
`data: {"type":"response.created","response":{"id":"r1","object":"response","model":"m","status":"in_progress"}}`,
|
||||
`data: {"type":"response.reasoning_summary_text.delta","delta":"The user"}`)
|
||||
for _, c := range []struct {
|
||||
capped int
|
||||
code int
|
||||
}{{16, 200}, {4096, 502}, {0, 502}} {
|
||||
g := &gathered{h: http.Header{}, status: 200, capped: c.capped}
|
||||
g.h.Set("Content-Type", "text/event-stream")
|
||||
g.Write([]byte(stream))
|
||||
rec := httptest.NewRecorder()
|
||||
code, _ := g.finish(rec, provider.Provider{Name: "p"}, true, "", "")
|
||||
if code != c.code {
|
||||
t.Errorf("capped %d: status %d, want %d: %s", c.capped, code, c.code, rec.Body)
|
||||
continue
|
||||
}
|
||||
if code == 200 && (!strings.Contains(rec.Body.String(), `"status":"incomplete"`) || !strings.Contains(rec.Body.String(), `"reason":"max_output_tokens"`)) {
|
||||
t.Errorf("capped %d: %s", c.capped, rec.Body)
|
||||
}
|
||||
}
|
||||
// a stream that spent nothing is still the 502
|
||||
g := &gathered{h: http.Header{}, status: 200, capped: 16}
|
||||
g.h.Set("Content-Type", "text/event-stream")
|
||||
g.Write([]byte(sse(`data: {"type":"response.created","response":{"id":"r1","object":"response","status":"in_progress"}}`)))
|
||||
rec := httptest.NewRecorder()
|
||||
if code, _ := g.finish(rec, provider.Provider{Name: "p"}, true, "", ""); code != 502 {
|
||||
t.Errorf("nothing spent: status %d: %s", code, rec.Body)
|
||||
}
|
||||
}
|
||||
|
||||
// A client that says how long it waits (provider.WaitHeader: a model test
|
||||
// asking a remote magpie) is told a busy failure while it still waits:
|
||||
// no retry pause or patience round is taken that would end past it
|
||||
// (plugins#827: the test waited 20s, the server held its 502 through the
|
||||
// provider's patience, and the test said only that nothing answered).
|
||||
// A client that said nothing, or a wait long enough, is retried as
|
||||
// before.
|
||||
func TestClientWaitBoundsPatience(t *testing.T) {
|
||||
const busy = `{"type":"error","error":{"type":"api_error","message":"upstream went away"}}`
|
||||
for _, c := range []struct {
|
||||
name string
|
||||
wait string
|
||||
retry bool
|
||||
}{{"short wait", "1", false}, {"no wait said", "", true}, {"unreadable", "soon", true}, {"long wait", "3600", true}} {
|
||||
t.Run(c.name, func(t *testing.T) {
|
||||
u := &busyUpstream{replies: []busyReply{{code: 502, body: busy}}}
|
||||
s := busyProvider(t, u)
|
||||
scaled(t, 300*time.Millisecond)
|
||||
gw := httptest.NewServer(s.Handler())
|
||||
t.Cleanup(gw.Close)
|
||||
req, _ := http.NewRequest("POST", gw.URL+"/v1/messages", strings.NewReader(singleAsk(false)))
|
||||
req.Header.Set("Content-Type", "application/json")
|
||||
if c.wait != "" {
|
||||
req.Header.Set(provider.WaitHeader, c.wait)
|
||||
}
|
||||
res, err := http.DefaultClient.Do(req)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
res.Body.Close()
|
||||
if res.StatusCode != 502 {
|
||||
t.Errorf("status %d, want the 502", res.StatusCode)
|
||||
}
|
||||
if n := u.asked(); (n > 1) != c.retry {
|
||||
t.Errorf("upstream asked %d times, retried want %v", n, c.retry)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -55,6 +55,13 @@ const (
|
||||
// (host.js), as it does the two above.
|
||||
const FallbackHeader = "X-Magpie-Fallback"
|
||||
|
||||
// WaitHeader tells a magpie's gateway how many seconds its client waits
|
||||
// for the answer: a model test asking a remote magpie sends its own wait,
|
||||
// and the gateway takes no retry pause or patience round that would end
|
||||
// past it, so the test is told the error rather than running out of time
|
||||
// (plugins#827). Like every X-Magpie- header it goes no further.
|
||||
const WaitHeader = "X-Magpie-Wait"
|
||||
|
||||
// SessionToPluginHeader and SubagentToPluginHeader tell a plugin's fetch
|
||||
// the session the agent named (sessionOf: Claude Code's
|
||||
// x-claude-code-session-id and the rest) and the Claude Code subagent the
|
||||
|
||||
@@ -0,0 +1,51 @@
|
||||
package provider
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"sync"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
// A model test through a remote magpie waits as long as a plugin's test
|
||||
// does here (pluginTestWait), since the remote serves plugins' models and
|
||||
// retries for them, and tells the remote how long it waits (WaitHeader)
|
||||
// so the remote answers with its error inside it (plugins#827: the test
|
||||
// gave the remote 20s, the remote held its 502 for 45s and more).
|
||||
func TestRemoteMagpieProbeWait(t *testing.T) {
|
||||
defer func(w, pw time.Duration) { testWait, pluginTestWait = w, pw }(testWait, pluginTestWait)
|
||||
testWait, pluginTestWait = 1*time.Second, 4*time.Second
|
||||
var mu sync.Mutex
|
||||
var said []string
|
||||
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
mu.Lock()
|
||||
said = append(said, r.Header.Get(WaitHeader))
|
||||
mu.Unlock()
|
||||
time.Sleep(1500 * time.Millisecond) // past testWait, within pluginTestWait
|
||||
w.Header().Set("Content-Type", "text/event-stream")
|
||||
fmt.Fprint(w, "data: {\"choices\":[{\"index\":0,\"delta\":{\"content\":\"hi\"}}]}\n\ndata: [DONE]\n\n")
|
||||
}))
|
||||
defer srv.Close()
|
||||
p := Provider{ID: "office", Preset: RemoteMagpiePreset, Key: "sk-magpie-k", Chat: srv.URL + "/v1"}
|
||||
r := probe(context.Background(), p, Chat, srv.URL+"/v1/chat/completions", []byte(`{"model":"m","stream":true}`), "m", testWait)
|
||||
if !r.OK {
|
||||
t.Errorf("remote magpie's test given testWait only: %+v", r)
|
||||
}
|
||||
mu.Lock()
|
||||
defer mu.Unlock()
|
||||
if len(said) == 0 || said[0] != "4" {
|
||||
t.Errorf("%s said %q, want the probe's own wait, 4", WaitHeader, said)
|
||||
}
|
||||
// a provider that isn't a remote magpie is told nothing
|
||||
said = nil
|
||||
mu.Unlock()
|
||||
q := Provider{ID: "relay", Key: "k", Chat: srv.URL + "/v1"}
|
||||
probe(context.Background(), q, Chat, srv.URL+"/v1/chat/completions", []byte(`{"model":"m","stream":true}`), "m", 3*time.Second)
|
||||
mu.Lock()
|
||||
if len(said) != 1 || said[0] != "" {
|
||||
t.Errorf("a relay was told %s %q", WaitHeader, said)
|
||||
}
|
||||
}
|
||||
@@ -17,6 +17,7 @@ import (
|
||||
"net/url"
|
||||
"regexp"
|
||||
"slices"
|
||||
"strconv"
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
@@ -265,7 +266,9 @@ func tinyBody(q Provider, proto Protocol, model string) (url, body string) {
|
||||
// sign-in or ask its vendor more than once before it answers, as it does
|
||||
// for the gateway, which gives it no such bound (mingxia_16024 on
|
||||
// Discord: every Qoder and WorkBuddy model's test ended at 20s while
|
||||
// agents were answered).
|
||||
// agents were answered), and for a remote magpie, whose gateway serves
|
||||
// such plugins' models in turn and asks again where its own retries do
|
||||
// (plugins#827: a plugin model tested in 60s here had 20s through it).
|
||||
// connectWait is how long a probe waits for its connection (a TLS
|
||||
// handshake done, through any proxy) before it gives up on the host: an
|
||||
// address nothing answers at is said in that time, not the whole wait's
|
||||
@@ -806,6 +809,11 @@ func probeOnce(ctx context.Context, p Provider, proto Protocol, url string, body
|
||||
p.warmPlugin(ctx)
|
||||
wait = max(wait, pluginTestWait)
|
||||
}
|
||||
if p.IsRemoteMagpie() {
|
||||
// it serves plugins' models too, and retries for them
|
||||
// (pluginTestWait)
|
||||
wait = max(wait, pluginTestWait)
|
||||
}
|
||||
ctx, cancel := context.WithTimeout(probelog.WithModel(ctx, model), wait)
|
||||
defer cancel()
|
||||
rctx := ctx
|
||||
@@ -854,6 +862,11 @@ func probeOnce(ctx context.Context, p Provider, proto Protocol, url string, body
|
||||
// out for minutes as an agent's turn is (Qoder's free models)
|
||||
req.Header.Set(FallbackHeader, "1")
|
||||
}
|
||||
if p.IsRemoteMagpie() {
|
||||
// its gateway takes no pause that ends past the test's wait, and
|
||||
// the test is told the error (WaitHeader, plugins#827)
|
||||
req.Header.Set(WaitHeader, strconv.Itoa(int(wait/time.Second)))
|
||||
}
|
||||
if err := p.Sign(ctx, req, proto, body); err != nil {
|
||||
r.Error = err.Error()
|
||||
return r
|
||||
|
||||
Reference in New Issue
Block a user