diff --git a/internal/gateway/claude_subscription.go b/internal/gateway/claude_subscription.go index f7481c3f4..3e9f56d15 100644 --- a/internal/gateway/claude_subscription.go +++ b/internal/gateway/claude_subscription.go @@ -3859,7 +3859,7 @@ func relay(w http.ResponseWriter, r *http.Request, from provider.Protocol, name // the status Claude Code got, else a guess from the words if head[n-1].Status >= 400 { code = head[n-1].Status - } else if quotaWords.MatchString(msg) { + } else if quotaSaid(msg) { code = 429 } } @@ -3920,7 +3920,7 @@ func relay(w http.ResponseWriter, r *http.Request, from provider.Protocol, name usage.add(Usage{ErrType: col.errCode}) if col.errStatus >= 400 { code = col.errStatus - } else if quotaWords.MatchString(col.err) { + } else if quotaSaid(col.err) { code = 429 } return writeError(w, from, code, name+": "+col.err), col.err diff --git a/internal/gateway/fallback.go b/internal/gateway/fallback.go index d1b9c50f9..1c7f36200 100644 --- a/internal/gateway/fallback.go +++ b/internal/gateway/fallback.go @@ -931,6 +931,14 @@ func restOf(id string) (Rest, bool) { // status code doesn't: some answer 400 or 403 with it. var quotaWords = regexp.MustCompile(`(?i)quota|insufficient|balance|credit|billing|out of budget|budget (exceeded|exhausted)|exceeded|rate.?limit|usage.?limit|limit.?reached|hit your .*limit|limit.{0,24}resets|too many requests|overloaded|余额|额度|欠费|限流|频率|套餐|用量|上限`) +// quotaSaid is whether an error's words, with no status to go by, say +// out of quota or slow down: quotaWords, unless they say the conversation +// is too long for the model, whose "context_length_exceeded" or "exceeds +// the maximum" holds quotaWords' "exceeded" (#1944). +func quotaSaid(msg string) bool { + return quotaWords.MatchString(msg) && !tooLong(http.StatusBadRequest, msg) +} + // unservedWords are how a vendor says the model isn't one it serves this // key, or this way — words another provider, or key, may not answer with. var unservedWords = regexp.MustCompile(`(?i)model.{0,80}(not (supported|accessible|available|found|enabled|allowed)|unsupported|does ?n[o']t exist|unknown|invalid)|(no such|unknown|invalid|unsupported) model|model_not_found|模型.{0,12}(不存在|不支持|无权|未开通)`) @@ -2742,11 +2750,17 @@ func refusedReply(b []byte) (string, bool) { func streamStatus(msg string) int { l := strings.ToLower(msg) switch { + case tooLong(http.StatusBadRequest, msg): + // before the quota words: the ChatGPT backend's response.failed + // for a Codex conversation past the model's window says + // "context_length_exceeded", whose "exceeded" read as a rate + // limit, and the same request was sent again and again (#1944) + return 400 case strings.Contains(l, "overloaded"): return 529 case creditWords.MatchString(msg) && !strings.Contains(l, "rate"): return 402 - case strings.Contains(l, "rate_limit"), strings.Contains(l, "rate limit"), strings.Contains(l, "too many"), quotaWords.MatchString(msg): + case strings.Contains(l, "rate_limit"), strings.Contains(l, "rate limit"), strings.Contains(l, "too many"), quotaSaid(msg): return 429 case unservedWords.MatchString(msg): return 400 diff --git a/internal/gateway/overflow_stream_test.go b/internal/gateway/overflow_stream_test.go new file mode 100644 index 000000000..a492dfa85 --- /dev/null +++ b/internal/gateway/overflow_stream_test.go @@ -0,0 +1,83 @@ +package gateway + +import ( + "strings" + "testing" + + "github.com/yetone/magpie/internal/provider" +) + +// The error object ASD-max's Codex got (#1944), as the ChatGPT backend +// puts it in a response.failed: a conversation past the model's window. +const overflowError = `{"message":"Your input exceeds the context window of this model. Please adjust your input and try again.","type":"invalid_request_error","param":"input","code":"context_length_exceeded"}` + +const overflowFailed = `event: response.failed` + "\n" + `data: {"type":"response.failed","response":{"id":"r0","status":"failed","error":` + overflowError + `}}` + +// overflowStream is what the ChatGPT backend answered gpt-5.5 asked with +// about 2 MB of input on 2026-10-13, as it came (its safety_identifier +// left out): a 200, its frames, an error event and response.failed, each +// saying context_length_exceeded. +var overflowStream = []string{ + `event: response.created` + "\n" + `data: {"type":"response.created","response":{"id":"resp_0aef60959b6fc063016acdd9f0ac6c87d09ebb9c76c496f0c9","object":"response","created_at":1791875568,"status":"in_progress","access_programs":null,"background":false,"completed_at":null,"error":null,"frequency_penalty":0.0,"incomplete_details":null,"instructions":"You are a helpful assistant.","max_output_tokens":null,"max_tool_calls":null,"model":"gpt-5.5","moderation":null,"output":[],"parallel_tool_calls":true,"presence_penalty":0.0,"previous_response_id":null,"prompt_cache_key":"ffbebcaa-3636-42d4-a4ae-ca41c6dcec8e","prompt_cache_retention":"24h","reasoning":{"context":"current_turn","effort":"medium","mode":"standard","summary":null},"safety_identifier":"user-redacted","service_tier":"auto","store":false,"temperature":1.0,"text":{"format":{"type":"text"},"verbosity":"medium"},"tool_choice":"auto","tool_usage":{"image_gen":{"input_tokens":0,"input_tokens_details":{"image_tokens":0,"text_tokens":0},"output_tokens":0,"output_tokens_details":{"image_tokens":0,"text_tokens":0},"total_tokens":0},"web_search":{"num_requests":0}},"tools":[],"top_logprobs":0,"top_p":0.98,"truncation":"disabled","usage":null,"user":null,"metadata":{}},"sequence_number":0}`, + `event: response.in_progress` + "\n" + `data: {"type":"response.in_progress","response":{"id":"resp_0aef60959b6fc063016acdd9f0ac6c87d09ebb9c76c496f0c9","object":"response","created_at":1791875568,"status":"in_progress","access_programs":null,"background":false,"completed_at":null,"error":null,"frequency_penalty":0.0,"incomplete_details":null,"instructions":"You are a helpful assistant.","max_output_tokens":null,"max_tool_calls":null,"model":"gpt-5.5","moderation":null,"output":[],"parallel_tool_calls":true,"presence_penalty":0.0,"previous_response_id":null,"prompt_cache_key":"ffbebcaa-3636-42d4-a4ae-ca41c6dcec8e","prompt_cache_retention":"24h","reasoning":{"context":"current_turn","effort":"medium","mode":"standard","summary":null},"safety_identifier":"user-redacted","service_tier":"auto","store":false,"temperature":1.0,"text":{"format":{"type":"text"},"verbosity":"medium"},"tool_choice":"auto","tool_usage":{"image_gen":{"input_tokens":0,"input_tokens_details":{"image_tokens":0,"text_tokens":0},"output_tokens":0,"output_tokens_details":{"image_tokens":0,"text_tokens":0},"total_tokens":0},"web_search":{"num_requests":0}},"tools":[],"top_logprobs":0,"top_p":0.98,"truncation":"disabled","usage":null,"user":null,"metadata":{}},"sequence_number":1}`, + `event: error` + "\n" + `data: {"type":"error","error":{"type":"invalid_request_error","code":"context_length_exceeded","message":"Your input exceeds the context window of this model. Please adjust your input and try again.","param":"input"},"sequence_number":2}`, + `event: response.failed` + "\n" + `data: {"type":"response.failed","response":{"id":"resp_0aef60959b6fc063016acdd9f0ac6c87d09ebb9c76c496f0c9","object":"response","created_at":1791875568,"status":"failed","access_programs":null,"background":false,"completed_at":null,"error":{"code":"context_length_exceeded","message":"Your input exceeds the context window of this model. Please adjust your input and try again."},"frequency_penalty":0.0,"incomplete_details":null,"instructions":"You are a helpful assistant.","max_output_tokens":null,"max_tool_calls":null,"model":"gpt-5.5","moderation":null,"output":[],"parallel_tool_calls":true,"presence_penalty":0.0,"previous_response_id":null,"prompt_cache_key":"ffbebcaa-3636-42d4-a4ae-ca41c6dcec8e","prompt_cache_retention":"24h","reasoning":{"context":"current_turn","effort":"medium","mode":"standard","summary":null},"safety_identifier":"user-redacted","service_tier":"auto","store":false,"temperature":1.0,"text":{"format":{"type":"text"},"verbosity":"medium"},"tool_choice":"auto","tool_usage":{"image_gen":{"input_tokens":0,"input_tokens_details":{"image_tokens":0,"text_tokens":0},"output_tokens":0,"output_tokens_details":{"image_tokens":0,"text_tokens":0},"total_tokens":0},"web_search":{"num_requests":0}},"tools":[],"top_logprobs":0,"top_p":0.98,"truncation":"disabled","usage":null,"user":null,"metadata":{}},"sequence_number":3}`, +} + +// An error in a stream that says the conversation is too long for the +// model stands for a 400, not a rate limit: its "context_length_exceeded" +// held quotaWords' "exceeded", and the same request was asked again 7 or 8 +// times (#1944). A real rate limit, an overload and a spent quota read as +// before. +func TestStreamOverflowNotRateLimit(t *testing.T) { + for _, c := range []struct { + ev string + want int + }{ + {overflowFailed, 400}, + {`event: error` + "\n" + `data: {"type":"error","error":` + overflowError + `}`, 400}, + {`event: response.failed` + "\n" + `data: {"type":"response.failed","response":{"status":"failed","error":{"message":"Rate limit reached for gpt-5.5 in organization org-x on tokens per min (TPM): Limit 30000, Used 25000, Requested 9000. Please try again in 8s.","type":"tokens","param":null,"code":"rate_limit_exceeded"}}}`, 429}, + {overloadedFailed, 529}, + {overflowStream[2], 400}, + {overflowStream[3], 400}, + {`event: error` + "\n" + `data: {"type":"error","error":{"message":"The usage limit has been reached","type":"usage_limit_reached"}}`, 429}, + } { + kind, status, msg := streamEvent([]byte(c.ev + "\n\n")) + if kind != eventError || status != c.want { + t.Errorf("%s: kind %d status %d (want %d) %q", c.ev, kind, status, c.want, msg) + } + } + if quotaSaid(overflowError) || !quotaSaid("You exceeded your current quota, please check your plan and billing details.") { + t.Error("quotaSaid") + } +} + +// What #1944 saw, end to end: Codex through a group of one member whose +// stream, the backend's own, fails as too long. The agent is told +// context_length_exceeded at once, to compact, and the member isn't asked +// again; before, the failure was a rate limit, the group's patience asked +// the same member again, and the second reply here, not the agent's +// error, was what it got. +func TestCodexOverflowInGroupNotAskedAgain(t *testing.T) { + fresh(t) + failed := reply{200, "text/event-stream", sse(overflowStream...)} + done := reply{200, "text/event-stream", sse( + `event: response.output_text.delta`+"\n"+`data: {"type":"response.output_text.delta","delta":"hello"}`, + `event: response.completed`+"\n"+`data: {"type":"response.completed","response":{"id":"r1","status":"completed","output":[]}}`)} + a := &scripted{replies: []reply{failed, done}} + responsesOn(t, "a", a) + if err := provider.SaveGroup(provider.Group{Name: "G", Members: []string{"a/m"}, Routing: provider.Ordered}); err != nil { + t.Fatal(err) + } + s := New() + code, body := sendTo(s, "/v1/responses", `{"model":"group/g","stream":true,"input":"hi"}`) + if !strings.Contains(body, "context_length_exceeded") || strings.Contains(body, "hello") || a.n != 1 { + t.Fatalf("%d %q (asked %d times)", code, body, a.n) + } + r := s.trace.routes[len(s.trace.routes)-1] + for _, try := range r.Tries { + if try.Fail == failRate || try.Rest != nil { + t.Errorf("an overflow read as a rate limit: %+v", try) + } + } +}