diff --git a/internal/gateway/fallback.go b/internal/gateway/fallback.go index 60ad65556..12ed3a51c 100644 --- a/internal/gateway/fallback.go +++ b/internal/gateway/fallback.go @@ -1957,25 +1957,49 @@ func saysLength(status int, body []byte) bool { // trouble, a model it doesn't serve, a region it doesn't serve, or one // already saying it overflowed. A request error that speaks of length // (saysLength) needs only lengthMargin of the window. -func tooLongUnsaid(p provider.Provider, model string, tokens, status int, body []byte) (string, bool) { +// +// A 5xx is a vendor's busy or broken moment, which a client asks again, +// and is read so only for a vendor seen to answer an overflow with one +// (busyOverflows): a custom Responses relay's plain 502 "Upstream service +// temporarily unavailable", at 385K tokens of a conversation it had just +// answered at 454K, was told as more than gpt-6-astra's 272K, and Codex +// ended the turn instead of asking again (ne9ko9 on Discord). Nor is a +// failure that is no answer at all (transportFailed): a dial or read +// that timed out, a connection reset, a stream cut short, each in +// magpie's own words. held is the most the model was seen to answer for +// this provider (Server.heldOf), and the window is never less than it, +// nor than the most the provider's list says the model may be asked for +// (windowMost). +func tooLongUnsaid(p provider.Provider, model string, tokens, held, status int, body []byte) (string, bool) { switch status { - case 400, 413, 422, 500, 502, 503, 504: + case 400, 413, 422: + case 500, 502, 503, 504: + if !busyOverflows(p) { + return "", false + } default: return "", false } raw := body // the words are matched decoded, too (#1669) body = wordsOf(body) + if transportFailed(raw) || transportFailed(body) { + return "", false + } if overflowed(status, body) || failure(status, body) != failOther || quotaWords.Match(body) || unservedWords.Match(body) || refusedWords.Match(body) || provider.EdgeBlocked(body) || regionRefused(status, body) || zdrRefused(status, body) { return "", false } window := windowOf(p, model) + if window <= 0 { + return "", false + } + window = max(window, windowMost(p, model), held) margin := unsaidMargin if saysLength(status, raw) { margin = lengthMargin } - if window <= 0 || float64(tokens) < float64(window)*margin { + if float64(tokens) < float64(window)*margin { return "", false } msg := fmt.Sprintf("prompt is too long: about %d tokens, more than %s's context window of %d", tokens, model, window) @@ -1993,6 +2017,75 @@ func tooLongUnsaid(p provider.Provider, model string, tokens, status int, body [ return fmt.Sprintf("%s (%s answered %d)", msg, p.Name, status), true } +// busyOverflows says p's vendor answers a request past its model's window +// with a 5xx that says nothing of length: Devin's 502 "We are currently +// experiencing capacity issues" for a conversation of about 300K tokens +// on swe-1.7-lightning (202,752), answered at a size it holds (b3ab3e42e). +// Devin is served by its plugin now, under its own id or another. +func busyOverflows(p provider.Provider) bool { + return p.ID == "devin" || buildHost(p) == "devin" +} + +// transportWords are a failure that never reached a vendor's answer, as Go, +// Bun or Windows say it, or magpie's own words for a reply that broke off: +// a request that met one may well fit, and is asked again. +var transportWords = regexp.MustCompile(`(?i)dial (tcp|udp)|connectex|wsarecv|wsasend|i/o timeout|TLS handshake timeout|context deadline exceeded|Client\.Timeout|timeout awaiting response headers|connection (was )?(reset|refused|aborted|closed)|forcibly closed|broken pipe|unexpected EOF|no such host|network is unreachable|no route to host|server closed idle connection|Unable to connect|ConnectionRefused|ConnectionClosed|FailedToOpenSocket|ETIMEDOUT|ECONNRESET|ECONNREFUSED|ECONNABORTED|ENOTFOUND|EAI_AGAIN|ENETUNREACH|EHOSTUNREACH|EPIPE`) + +// transportFailed says an error body is a transport failure rather than a +// vendor's answer (transportWords), or one magpie made of a reply that +// broke off or said nothing. +func transportFailed(body []byte) bool { + return transportWords.Match(body) || bytes.Contains(body, []byte(errEndedShort.Error())) || + bytes.Contains(body, []byte(didNotStream)) || magpieSaid(string(body)) +} + +// noteHeld keeps n as the most prompt tokens the provider's model has +// answered, when it is more than the most kept: a model that answered a +// prompt of n holds one of n, whatever its window is said to be (ne9ko9 +// on Discord: gpt-6-astra, said at 272K, answered 454K and 474K). +func (s *Server) noteHeld(id, model string, n int) { + if n <= 0 { + return + } + key := id + "\x00" + model + for { + cur, ok := s.held.Load(key) + if !ok { + if _, loaded := s.held.LoadOrStore(key, n); !loaded { + return + } + continue + } + if cur.(int) >= n || s.held.CompareAndSwap(key, cur, n) { + return + } + } +} + +// heldOf is the most prompt tokens the provider's model has answered since +// magpie started (noteHeld), 0 when none. +func (s *Server) heldOf(id, model string) int { + if v, ok := s.held.Load(id + "\x00" + model); ok { + return v.(int) + } + return 0 +} + +// windowMost is the most the provider's list says its model may be asked +// for (Entry.MaxContext), 0 when it says none: a Codex entry's +// max_context_window of 872K above a 272K context_window, which Codex is +// handed and may work a conversation up to. +func windowMost(p provider.Provider, model string) int { + cat := provider.Served() + for i := range cat { + e := &cat[i] + if e.Group == "" && e.Provider.ID == p.ID && (e.Model == model || e.ID == model) { + return e.MaxContext + } + } + return 0 +} + // windowOf is the tokens a provider's model takes, where known: the // user's for the model, else its catalog entry's (Provider.WindowOf, where // the one set for all the provider's models is no larger than the model's diff --git a/internal/gateway/fallback_test.go b/internal/gateway/fallback_test.go index 1555c1418..d1851303c 100644 --- a/internal/gateway/fallback_test.go +++ b/internal/gateway/fallback_test.go @@ -296,7 +296,7 @@ func TestEscapedWordsReadByEveryDecider(t *testing.T) { t.Errorf("escaped %v: a shape refusal that says the quota is spent rests nobody", esc) } p := provider.Provider{ID: "fake", Name: "Fake", Contexts: map[string]int{"m": 100}} - if said, ok := tooLongUnsaid(p, "m", 1000, 400, say("该模型不支持当前令牌计划")); ok { + if said, ok := tooLongUnsaid(p, "m", 1000, 0, 400, say("该模型不支持当前令牌计划")); ok { t.Errorf("escaped %v: a model the plan doesn't serve told as too long: %s", esc, said) } } diff --git a/internal/gateway/gateway.go b/internal/gateway/gateway.go index 61cada718..bf8ac782e 100644 --- a/internal/gateway/gateway.go +++ b/internal/gateway/gateway.go @@ -505,6 +505,9 @@ type Server struct { // codexTurns is the model each Codex last had a turn of its own // answered on, by caller (codexMemoryStandIn) codexTurns sync.Map + // held is the most prompt tokens each provider's model answered + // (heldOf), by provider id and model + held sync.Map // codexLeads is the model each Codex conversation's own turns last // went on, for its side calls to follow (codexFollowTo) codexLeads codexLeads @@ -3838,6 +3841,11 @@ func (s *Server) serve(w http.ResponseWriter, r *http.Request, from provider.Pro w = spliceAfter(w, hw.over) } reasked += hw.reasked + if hw.code() > 0 && hw.code() < 400 && !hw.refused { + // an answer, passing or held whole: the model holds a prompt + // this size (tooLongUnsaid) + s.noteHeld(c.p.ID, c.model, call.Usage.prompt()) + } if hw.passing { clientResponseID = call.Usage.ResponseID } @@ -3850,7 +3858,7 @@ func (s *Server) serve(w http.ResponseWriter, r *http.Request, from provider.Pro outgrew := false // a failure that didn't say so was the request's length if !hw.passing && !hw.refused && hw.code() >= 400 { if req, err := parse(from, attemptBody); err == nil { - if msg, ok := tooLongUnsaid(c.p, c.model, estimate(req), hw.code(), hw.errBody()); ok { + if msg, ok := tooLongUnsaid(c.p, c.model, estimate(req), s.heldOf(c.p.ID, c.model), hw.code(), hw.errBody()); ok { // told as an overflow: not asked again, of this one or // another, and nobody rests hw.failure, hw.failMsg, outgrew = http.StatusBadRequest, msg, true diff --git a/internal/gateway/payload_too_large_test.go b/internal/gateway/payload_too_large_test.go index 41a28963a..f169988b9 100644 --- a/internal/gateway/payload_too_large_test.go +++ b/internal/gateway/payload_too_large_test.go @@ -30,10 +30,10 @@ func TestPayloadTooLargeIsNotContextOverflow(t *testing.T) { {Kind: Text, Text: strings.Repeat("word", 100)}, {Kind: Image, Data: strings.Repeat(pngA, 4096)}, }}}}) - if inferred, ok := tooLongUnsaid(p, "m", tokens, 413, []byte(msg)); ok { + if inferred, ok := tooLongUnsaid(p, "m", tokens, 0, 413, []byte(msg)); ok { t.Errorf("byte limit inferred as token limit: %s", inferred) } - if inferred, ok := tooLongUnsaid(p, "m", 1000, 413, []byte(msg)); !ok || !strings.Contains(inferred, "prompt is too long") { + if inferred, ok := tooLongUnsaid(p, "m", 1000, 0, 413, []byte(msg)); !ok || !strings.Contains(inferred, "prompt is too long") { t.Errorf("text estimate past the window lost compaction: %s", inferred) } if retryable(413, []byte(msg)) { diff --git a/internal/gateway/region_fallback_test.go b/internal/gateway/region_fallback_test.go index a59f905d1..018085595 100644 --- a/internal/gateway/region_fallback_test.go +++ b/internal/gateway/region_fallback_test.go @@ -44,12 +44,12 @@ func TestRegionRefusalIsRetryable(t *testing.T) { func TestRegionRefusalIsNotTooLong(t *testing.T) { p := provider.Provider{ID: "fake", Name: "Fake", Contexts: map[string]int{"m": 100}} for _, body := range []string{antigravityRegion400, googleRegion400} { - if said, ok := tooLongUnsaid(p, "m", 1000, 400, []byte(body)); ok { + if said, ok := tooLongUnsaid(p, "m", 1000, 0, 400, []byte(body)); ok { t.Errorf("region refusal read as too long: %s", said) } } // the same size, refused without saying why, still is - if _, ok := tooLongUnsaid(p, "m", 1000, 400, []byte(`{"error":{"message":"Invalid request parameters"}}`)); !ok { + if _, ok := tooLongUnsaid(p, "m", 1000, 0, 400, []byte(`{"error":{"message":"Invalid request parameters"}}`)); !ok { t.Error("an unsaid overflow is no longer inferred") } } diff --git a/internal/gateway/toolong_transport_test.go b/internal/gateway/toolong_transport_test.go new file mode 100644 index 000000000..1c5f7113a --- /dev/null +++ b/internal/gateway/toolong_transport_test.go @@ -0,0 +1,188 @@ +package gateway + +import ( + "net" + "net/http/httptest" + "strings" + "testing" + + "github.com/yetone/magpie/internal/catalog" + "github.com/yetone/magpie/internal/provider" +) + +// overflowTold says an agent's reply tells it the prompt is too long. +func overflowTold(body string) bool { + return strings.Contains(body, "prompt is too long") || strings.Contains(body, "context_length_exceeded") +} + +// magpieError is the body magpie writes for a try that got no answer, as +// the gateway hands it to tooLongUnsaid. +func magpieError(msg string) []byte { + rec := httptest.NewRecorder() + writeError(rec, provider.Responses, 502, msg) + return rec.Body.Bytes() +} + +// A try that got no vendor's answer at all — the connection never made, +// a read that timed out, a reply cut off — says nothing of the request's +// length, however long it is: ne9ko9 on Discord had a TCP connect +// timeout and a read timeout on a custom Responses relay each told to +// Codex as "prompt is too long … more than gpt-6-astra's context window +// of 272000", and Codex ended the turn instead of asking again. Not for +// Devin either, whose own 5xx is read as an overflow. +func TestTransportFailureIsNotTooLong(t *testing.T) { + devin := provider.PluginForTest("devin", "devin") + devin.Name, devin.Contexts = "Devin", map[string]int{"m": 2000} + plain := provider.Provider{ID: "relay", Name: "Codex relay", Contexts: map[string]int{"m": 2000}} + for _, msg := range []string{ + // the reporter's connect timeout, as Go on Windows says it + `Codex relay: Post "https://relay.example/v1/responses": dial tcp 203.0.113.7:443: connectex: A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond.`, + // a read timeout + `Codex relay: Post "https://relay.example/v1/responses": read tcp 192.168.1.5:53012->203.0.113.7:443: i/o timeout`, + `Codex relay: read tcp 192.168.1.5:53012->203.0.113.7:443: wsarecv: An existing connection was forcibly closed by the remote host.`, + `Codex relay: Post "https://relay.example/v1/responses": net/http: timeout awaiting response headers`, + `Codex relay: Post "https://relay.example/v1/responses": context deadline exceeded (Client.Timeout exceeded while awaiting headers)`, + `Codex relay: read: connection reset by peer`, + `Codex relay: unexpected EOF`, + // a plugin's fetch, as Bun says it + `Devin: Unable to connect. Is the computer able to access the url? (ConnectionRefused)`, + // a stream that broke off before any of it was sent + "Codex relay: " + errEndedShort.Error(), + } { + for _, p := range []provider.Provider{plain, devin} { + if said, ok := tooLongUnsaid(p, "m", 3000, 0, 502, magpieError(msg)); ok { + t.Errorf("%s, %s: told as too long: %s", p.ID, msg, said) + } + } + } +} + +// Devin answered a conversation well past its model's window with a 502 +// "capacity issues" (b3ab3e42e), which is still told as too long, at +// once, its plugin served under its own id or another; one it holds is +// a busy moment. +func TestDevinBusyOverflowStillTooLong(t *testing.T) { + body := []byte(`{"error":{"message":"We are currently experiencing capacity issues. Please try again later."}}`) + for _, id := range []string{"devin", "devin-plugin"} { + p := provider.PluginForTest(id, "devin") + p.Name, p.Contexts = "Devin", map[string]int{"m": 2000} + if said, ok := tooLongUnsaid(p, "m", 3000, 0, 502, body); !ok || !strings.Contains(said, "prompt is too long") { + t.Errorf("%s: past the window: %q %v", id, said, ok) + } + if said, ok := tooLongUnsaid(p, "m", 1000, 0, 502, body); ok { + t.Errorf("%s: within the window: %s", id, said) + } + } +} + +// A plain 502 from a vendor not seen to say an overflow so is the +// vendor's busy moment, asked again, however long the request: the +// reporter's relay answered "Upstream service temporarily unavailable" +// at 385K, between replies at 454K and 474K (ne9ko9 on Discord). +func TestPlain502IsNotTooLong(t *testing.T) { + reply := `{"code":"upstream_error","message":"Upstream service temporarily unavailable"}` + f := &fake{code: 502, ctype: "application/json", reply: reply} + up := setup(t, provider.Responses, f) + p := provider.Provider{ID: "fake", Name: "Codex relay", Key: "k", Models: []string{"m1"}, Responses: up.URL + "/v1", Contexts: map[string]int{"m1": 2000}} + if err := provider.Save(p); err != nil { + t.Fatal(err) + } + big := strings.Repeat("word ", 2400) // about 3000 tokens as estimated + code, body := post(t, "/v1/responses", `{"model":"fake/m1","input":"`+big+`"}`) + if code != 502 || overflowTold(body) || f.calls != 1+lastRetries+replanRounds { + t.Fatalf("status %d after %d calls (want 502 after %d): %s", code, f.calls, 1+lastRetries+replanRounds, body) + } + // a 400 that says it overflowed still says so + f.code, f.reply, f.calls = 400, `{"error":`+overflowError+`}`, 0 + code, body = post(t, "/v1/responses", `{"model":"fake/m1","input":"`+big+`"}`) + if code != 400 || !strings.Contains(body, "context_length_exceeded") || f.calls != 1 { + t.Fatalf("an overflow the vendor said: %d after %d calls: %s", code, f.calls, body) + } +} + +// A provider that can't be reached at all hands the agent the failure to +// connect, not an overflow, whatever the request's size. +func TestUnreachableIsNotTooLong(t *testing.T) { + setup(t, provider.Responses, &fake{}) + ln, err := net.Listen("tcp", "127.0.0.1:0") + if err != nil { + t.Fatal(err) + } + addr := ln.Addr().String() + ln.Close() // nothing listens there now + p := provider.Provider{ID: "fake", Name: "Codex relay", Key: "k", Models: []string{"m1"}, Responses: "http://" + addr + "/v1", Contexts: map[string]int{"m1": 2000}} + if err := provider.Save(p); err != nil { + t.Fatal(err) + } + big := strings.Repeat("word ", 2400) + code, body := post(t, "/v1/responses", `{"model":"fake/m1","input":"`+big+`"}`) + if code < 500 || overflowTold(body) { + t.Fatalf("unreachable: %d %s", code, body) + } +} + +// A model that has answered a prompt holds one of that size, whatever its +// window is said to be: gpt-6-astra, said at 272K, answered 454K and 474K +// in the reporter's session. A failure that doesn't say why, of a request +// no larger, is the vendor's error, not an overflow; one well past what +// was answered still is. +func TestWindowNotBelowWhatWasAnswered(t *testing.T) { + fresh(t) + invalid := `{"error":{"message":"Invalid request parameters"}}` + answered := `{"id":"ok","choices":[{"index":0,"message":{"role":"assistant","content":"hello"},"finish_reason":"stop"}],"usage":{"prompt_tokens":5000,"completion_tokens":1,"total_tokens":5001}}` + s := &scripted{replies: []reply{{400, "", invalid}, {200, "", answered}, {400, "", invalid}, {400, "", invalid}}} + roomyMember(t, "relay", 2000, s) + srv := New() + ask := func(words int) (int, string) { + return postAs(t, srv, "", `{"model":"relay/m","messages":[{"role":"user","content":"`+strings.Repeat("word ", words)+`"}]}`) + } + // nothing answered yet: past the window, it overflowed + if code, body := ask(2400); code != 400 || !overflowTold(body) { + t.Fatalf("before an answer: %d %s", code, body) + } + if code, body := ask(10); code != 200 { + t.Fatalf("the answer of 5000: %d %s", code, body) + } + if code, body := ask(2400); code != 400 || overflowTold(body) || !strings.Contains(body, "Invalid request parameters") { + t.Fatalf("after an answer of 5000, at about 3000: %d %s", code, body) + } + // about 7500, past 5000 by more than the margin + if code, body := ask(6000); code != 400 || !overflowTold(body) { + t.Fatalf("well past what was answered: %d %s", code, body) + } +} + +// The window an overflow is inferred against is no less than the most the +// provider's list says the model may be asked for: a Codex entry's +// max_context_window of 872K above its 272K context_window, which Codex +// is handed and works to (ne9ko9 on Discord: Codex's window 828,400). +func TestWindowNotBelowListedMax(t *testing.T) { + invalid := `{"error":{"message":"Invalid request parameters"}}` + f := &fake{code: 400, ctype: "application/json", reply: invalid} + up := setup(t, provider.Chat, f) + if err := catalog.SaveLive("fake", up.URL+"/v1", []catalog.Model{{ID: "m1", Context: 2000, MaxContext: 8000}}); err != nil { + t.Fatal(err) + } + p, err := provider.Find("fake") + if err != nil { + t.Fatal(err) + } + // its working window, as the reporter's 272K + p.Contexts = map[string]int{"m1": 2000} + if err := provider.Save(*p); err != nil { + t.Fatal(err) + } + if w := windowOf(*p, "m1"); w != 2000 { + t.Fatalf("the window is %d, want 2000", w) + } + ask := func(words int) (int, string) { + return post(t, "/v1/chat/completions", `{"model":"fake/m1","messages":[{"role":"user","content":"`+strings.Repeat("word ", words)+`"}]}`) + } + if code, body := ask(2400); code != 400 || overflowTold(body) { + t.Fatalf("about 3000, within the max: %d %s", code, body) + } + // about 10000, past the max by more than the margin + if code, body := ask(8000); code != 400 || !overflowTold(body) || !strings.Contains(body, "8000") { + t.Fatalf("past the max: %d %s", code, body) + } +} diff --git a/internal/gateway/toolong_unsaid_test.go b/internal/gateway/toolong_unsaid_test.go index c23286250..19cd0bd3b 100644 --- a/internal/gateway/toolong_unsaid_test.go +++ b/internal/gateway/toolong_unsaid_test.go @@ -26,7 +26,10 @@ func TestOverflowTheVendorDidntSay(t *testing.T) { wantCode, calls int want string }{ - {"502 anthropic", "/v1/messages", big, 502, `{"error":{"message":"We are experiencing capacity issues"}}`, 400, 1, "prompt is too long"}, + // a 5xx only from Devin, which answers an overflow so + // (TestDevinBusyOverflowStillTooLong): a plain provider's is its + // busy moment, asked again (ne9ko9 on Discord) + {"502 plain", "/v1/messages", big, 502, `{"error":{"message":"We are experiencing capacity issues"}}`, 502, 1 + lastRetries + replanRounds, "capacity issues"}, {"400 chat", "/v1/chat/completions", big, 400, `{"error":{"message":"Invalid request parameters"}}`, 400, 1, "context_length_exceeded"}, // Text alone well past the window is enough to ask for compaction. {"413 bytes", "/v1/messages", big, 413, `{"error":{"message":"Request Entity Too Large"}}`, 400, 1, "prompt is too long"}, diff --git a/internal/provider/models.go b/internal/provider/models.go index 8d583f339..ac4e0ea43 100644 --- a/internal/provider/models.go +++ b/internal/provider/models.go @@ -2982,6 +2982,10 @@ type Entry struct { // told it whole rather than magpie's default working window // (CompactFor, #1809). WindowSet bool `json:"-"` + // MaxContext is the most a prompt may hold when asked for, above + // Context, as the provider's list says it (catalog.Model's: a Codex + // entry's max_context_window, which Codex is handed and may work to) + MaxContext int `json:"-"` // Output is the most tokens a reply may hold, when known (a group's: // the least of its members') Output int `json:"output,omitempty"` @@ -3274,7 +3278,7 @@ func entryFor(p Provider, m catalog.Model, s settings.Settings) Entry { // an agent's list showed the whole magpie// (#955) name := cmp.Or(m.Name, m.ID) e := Entry{ID: p.ID + "/" + m.ID, Model: m.ID, Family: p.Family, Name: name, Efforts: effortsOf(m), Provider: p, - Images: images, ImageInput: imageInput, Context: ctx, WindowSet: p.ContextOf(m.ID) > 0, Output: output, OutputSet: outputOf(s, p.ID, m.ID) > 0, Free: m.Free, Rate: m.Rate, RateWas: m.RateWas, Tiers: m.Tiers, Released: m.Released, + Images: images, ImageInput: imageInput, Context: ctx, WindowSet: p.ContextOf(m.ID) > 0, MaxContext: m.MaxContext, Output: output, OutputSet: outputOf(s, p.ID, m.ID) > 0, Free: m.Free, Rate: m.Rate, RateWas: m.RateWas, Tiers: m.Tiers, Released: m.Released, Inputs: m.InputModalities, Outputs: m.OutputModalities, Codex: m.Codex, AlwaysThinks: m.AlwaysThinks, DynamicTools: m.DynamicTools, DefaultEffort: m.DefaultEffort} if lv, ok := catalog.CodexLevels(m.Codex); ok {