gateway: a stream that has said nothing but its frames stays held while the agent is kept alive, so a server_is_overloaded after 15s goes to the group's next member (#1418, Aliceonly)
Aliceonly's trace: plus-B answered 200 with response.created, in_progress and codex.rate_limits, nothing else, and 36s on failed the response with server_is_overloaded. The holdWriter let any stream through on the first write after holdLongest (15s), so the failure came after passing was set: it reached Codex as the turn's end, and sub2api, next in the group, was never asked. A stream with nothing but its lead frames is now held as long as one that is thinking (holdLead = holdThinking) when its agent is being kept alive with SSE comments (keptQuiet: a streaming agent that isn't Gemini). The comments keep the agent from timing out, so holding costs nothing; a stream with content is let through as before, and a Gemini stream, whose agent takes no comment, is let through at 15s as before. Run: - TestLeadOnlyStreamHeldWhileKeptAlive (new): fails on the old code with "let through after 15s with nothing said" (checked by putting the old hold back), passes now. - go test -tags nogui ./internal/gateway under a temp HOME: ok. - gofmt -l internal/gateway: clean.
This commit is contained in:
@@ -47,7 +47,7 @@ served by a plugin are in [Provider and plugin ownership](provider-plugins.md).
|
||||
- A fallback happens only while none of the reply has been sent. An agent never gets half a reply from one upstream and the rest from another.
|
||||
- A request whose key is a Claude sign-in (`claudeSignIn`: `Authorization: Bearer sk-ant-oat…`, Claude Code signed in to claude.ai with magpie as its base URL) is never told a 401, nor a 403 saying "OAuth token has been revoked". magpie never passes that sign-in on, so such an answer is a provider refusing magpie's credential, or one of magpie's own Claude accounts lapsing; told it, Claude Code renews its own sign-in before each of its retries (ten for one request) and then asks to `/login`. Any error whose message mentions x-api-key, whatever its status, Claude Code tells as "Not logged in · Please run /login" too. It is told as a 502 in magpie's words, an `api_error` saying "<provider> refused magpie's credential (HTTP 401): …" with x-api-key said as "API key", and any other error such a request is told keeps its status with x-api-key said as "API key", as does a stream's error after its 200 (`keepsSignIn`, `claude_signin.go`). Recent calls and the usage log keep the provider's status and message. Any other 403, and a request with magpie's key or an API key, is answered as before. The sign-in's beta (`oauth-…` in `anthropic-beta`) isn't passed on either (`askedBetas`), so a provider gets the request as Claude Code with magpie's key sends it; a provider's own `header.anthropic-beta` still goes.
|
||||
- A 2xx that can't be an API's answer is the 502 it stands for (`notAnAPIReply`, #1012): a web page (`text/html`, or a body that begins as one: a sign-in page, Cloudflare's challenge), a body with nothing in it, or one sent as JSON that doesn't begin as JSON. Every upstream request goes through it (`forwardOnce`, and the built-in clients' own: the ChatGPT backend's `/responses`, Kiro, Zed, Qoder, Devin, Cursor, Command Code), so it fails over, rests and is logged as a 502 does, its reason naming the page's title. Only the first bytes are peeked, which a stream waits for anyway, and a compressed body is left as it came.
|
||||
- A streamed request is never left silent while its vendor says nothing. `holdWriter.watch` runs beside each try: past `keepHeldAfter` (15s) it sends a held try's agent the stream's 200 and SSE comments (`keepAlive`), none of the try, so another candidate may still answer in the same stream; once the reply passes, it puts a comment between two of its lines after `keepaliveEvery` of quiet. It stops after `keepaliveLongest` (5 minutes) with nothing from the vendor. A try waiting for its key's or account's slot or for room in its minute (`lanes.take`, `rpms.wait`) is kept alive the same way (`keepQueued`), for as long as it waits; once the 200 is out, the try is held, and its failure or its queue turning it away reaches the agent as the stream's error (`failTo`), not a status (coeo91 on Discord). A wait shorter than `keepHeldAfter` sends nothing, so its 429 keeps its `Retry-After`. A proxy in front such as Cloudflare (125s) otherwise ends the request (#947). Gemini streams get no comments (#934). A vendor that then ignores `stream:true` and answers 200 with its reply whole has it sent as the agent's stream (`wholeAsStream`: Chat, Responses, Anthropic), not as the stream's error, while a stream under a type that says neither JSON nor a stream goes through as it comes (`sseStart` reads its first bytes); a 200 that is no reply of the protocol's fails as a translated reply that didn't stream does (502, "… did not stream"), for the next candidate to answer, and the last one's reaches the agent as the stream's error.
|
||||
- A streamed request is never left silent while its vendor says nothing. `holdWriter.watch` runs beside each try: past `keepHeldAfter` (15s) it sends a held try's agent the stream's 200 and SSE comments (`keepAlive`), none of the try, so another candidate may still answer in the same stream; once the reply passes, it puts a comment between two of its lines after `keepaliveEvery` of quiet. It stops after `keepaliveLongest` (5 minutes) with nothing from the vendor. A try waiting for its key's or account's slot or for room in its minute (`lanes.take`, `rpms.wait`) is kept alive the same way (`keepQueued`), for as long as it waits; once the 200 is out, the try is held, and its failure or its queue turning it away reaches the agent as the stream's error (`failTo`), not a status (coeo91 on Discord). A wait shorter than `keepHeldAfter` sends nothing, so its 429 keeps its `Retry-After`. A proxy in front such as Cloudflare (125s) otherwise ends the request (#947). Gemini streams get no comments (#934). A vendor that then ignores `stream:true` and answers 200 with its reply whole has it sent as the agent's stream (`wholeAsStream`: Chat, Responses, Anthropic), not as the stream's error, while a stream under a type that says neither JSON nor a stream goes through as it comes (`sseStart` reads its first bytes); a 200 that is no reply of the protocol's fails as a translated reply that didn't stream does (502, "… did not stream"), for the next candidate to answer, and the last one's reaches the agent as the stream's error. A held stream that has sent nothing but the frames before a reply (`response.created`, `response.in_progress`, `codex.rate_limits`, pings, an empty part begun: `eventLead`) stays held as long as its agent is kept alive, up to `holdLead` (4 minutes, under the 300s Codex waits for an event; `keptQuiet`), so a `server_is_overloaded` that comes after it is a failure the next candidate answers (#1418: let through at 15s, the ChatGPT backend's failure 36s in ended Codex's turn with sub2api, next in the group, never asked). A stream whose agent can't be kept alive (Gemini's) is let through after `holdLongest` (15s), as before.
|
||||
- Claude's, GPT's and Gemini's reasoning is held (`refusesAfterThinking`, up to `holdThinking`, 4 minutes) so that a refusal after it goes to the next candidate unseen (#248). It is held only while one could: on the last candidate a refusal isn't asked again, so Claude's and GPT's reasoning streams as it comes there, and a refusal after it reaches the agent as the vendor's own. Held there, a lone relay's Claude or GPT showed Claude Code its thinking all at once with the text, and Codex none until then (iTianbao on X). Gemini's stays held on the last candidate too, for a reply that only reasoned to be asked again (#667). Any other model's reasoning is never held.
|
||||
- A streamed reply stuck in a loop is ended, not let run to its output limit (#1359, Moody-Sin: WorkBuddy's DeepSeek v4.1 flash reasoned round "Now." "Writing." "Go." "Let me write." "OK." until max tokens while dsh and Pi waited). `holdWriter.Write` feeds every streamed try, passed through or translated, a key's, a built-in subscription's or a plugin's (a moved WorkBuddy's fetch in the plugin host, `TestLoopEndsWorkBuddysReply`), in each of the agent's protocols, to a `loopGuard` ([`loop_guard.go`](../../internal/gateway/loop_guard.go)). It cuts the reasoning and the text, each apart, into units, its lines and sentences (a list's `1.` or a decimal is no sentence's end), compared without case or a closing stop. A unit with no word in it (a letter run with no digit: not a brace, a rule, `0x00`, a hash or a row of numbers) isn't counted. When the last `loopWindow` (256) counted units of either are among no more than `loopDistinct` (24) different ones, the try is cut (`cutLoop`): what came with that write goes out, then the protocol's stream error (`streamError`, 502) naming the loop and quoting its units, and the vendor's request is cancelled. It falls back to nobody and rests nobody (`failLoop`); its usage record's error type is `reply_loop`. A reply magpie translates into the agent's protocol (`streamTranslated`) whose *reasoning* loops before it has said a text or a call, and isn't a continuation, is asked again once in place instead (`loopReasks`, through `holdWriter.onLoop`; cdredfox on X, WorkBuddy AI's DeepSeek v4 flash): the agent keeps the reasoning it has, the next try's follows it in the same stream, as an empty reply's re-ask does (#667), and only a loop on that try ends the reply with the error (`TestReasoningLoopIsAskedAgain`). A loop in the text, or after a text or call, is ended at once (`TestLoopAfterTextIsNotAskedAgain`), and so is a Chat stream passed through as it comes, whose bytes aren't magpie's to splice. A cycle need not be exact. Code, tables, lists, logs, CSV and base64 differ line to line or have no words, and don't trip it (`TestLoopGuardLeavesOrdinaryRepliesAlone` feeds magpie's own sources and docs through it). A reply sent whole (no stream, or Gemini without `alt=sse`) isn't read. Settings › Models › Replies › *Stop looping replies* (`noLoopGuard`) turns it off.
|
||||
- The order of the steps a request's accounts go through, how much the accounts' own order (*Make first*) counts under each routing, and how often an allowance is read are described for users in [How magpie picks an account](../reference.md#how-magpie-picks-an-account). Smart compares renewals window by window, biggest first, each truncated to the hour (`weighRouted`), so the order decides only when every window falls in the same hour. Affinity keeps a conversation on an account at 90–97%: only `SpentShareOf` (98%, 100% In order) stops it (`affine`), while the 90% tier (`lowShare`) orders only conversations nobody has answered.
|
||||
|
||||
@@ -1340,6 +1340,20 @@ const holdBuffered = 4 * time.Minute
|
||||
// reasoning with it, as soon as it does.
|
||||
const holdThinking = 4 * time.Minute
|
||||
|
||||
// holdLead is how long a stream with nothing but the frames that come
|
||||
// before a reply is held, when its agent is kept alive meanwhile
|
||||
// (keptQuiet): as long as one that only reasons, under the 300s Codex
|
||||
// waits for its next event. With nothing to keep the agent alive (a
|
||||
// Gemini stream), it is let through at holdLongest as before.
|
||||
const holdLead = holdThinking
|
||||
|
||||
// keptQuiet says whether the agent of a held stream is kept alive with
|
||||
// SSE comments while it is held (keepQuiet, keepAlive): it asked for a
|
||||
// stream, in a protocol that takes a comment.
|
||||
func (h *holdWriter) keptQuiet() bool {
|
||||
return h.streams && h.alive != nil && h.alive.proto != provider.Gemini
|
||||
}
|
||||
|
||||
// refusesAfterThinking tells whether a model's vendor may end a reply that
|
||||
// has only reasoned with its safety filter's refusal: Claude's stop_reason
|
||||
// refusal, OpenAI's content_filter or bio_policy, Gemini's SAFETY (#248).
|
||||
@@ -1400,6 +1414,14 @@ func (h *holdWriter) scan() {
|
||||
if h.thinking {
|
||||
longest = max(longest, holdThinking)
|
||||
}
|
||||
if h.keptQuiet() {
|
||||
// a stream of nothing but its frames — response.created, pings,
|
||||
// an empty message begun — while its agent is kept alive with
|
||||
// comments: let through at 15s, the 200 the agent then had made
|
||||
// the vendor's server_is_overloaded 21s later the agent's error,
|
||||
// with the group's next member never asked (#1418)
|
||||
longest = max(longest, holdLead)
|
||||
}
|
||||
// a group that asks the next member when one is slow to start holds
|
||||
// the stream until then, for nothing of it to have reached the agent
|
||||
waiting := h.firstWait > 0 && h.first.first == 0
|
||||
@@ -1410,14 +1432,15 @@ func (h *holdWriter) scan() {
|
||||
h.flow()
|
||||
return
|
||||
}
|
||||
if (h.thinking || h.buffered || waiting) && time.Since(h.since) >= keepHeldAfter {
|
||||
if (h.thinking || h.buffered || waiting || h.keptQuiet()) && time.Since(h.since) >= keepHeldAfter {
|
||||
h.keepAlive()
|
||||
}
|
||||
}
|
||||
|
||||
// keepHeldAfter is how long a stream held for its reasoning waits before
|
||||
// its agent is first kept alive, as long as a stream with nothing in it
|
||||
// is held (holdLongest); a refusal after it still goes to another account,
|
||||
// is held where its agent can't be (holdLongest); a refusal after it still
|
||||
// goes to another account,
|
||||
// whose stream follows the comments in the same response.
|
||||
var keepHeldAfter = holdLongest
|
||||
|
||||
|
||||
@@ -0,0 +1,65 @@
|
||||
package gateway
|
||||
|
||||
import (
|
||||
"io"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/yetone/magpie/internal/provider"
|
||||
)
|
||||
|
||||
// What the ChatGPT backend sent Aliceonly's Codex on plus-B (#1418): a 200
|
||||
// and the frames before a reply, nothing said, and 36s on the response
|
||||
// failed with server_is_overloaded.
|
||||
var overloadedLead = []string{
|
||||
`event: response.created` + "\n" + `data: {"type":"response.created","response":{"id":"r0","status":"in_progress"}}`,
|
||||
`event: response.in_progress` + "\n" + `data: {"type":"response.in_progress","response":{"id":"r0","status":"in_progress"}}`,
|
||||
`event: codex.rate_limits` + "\n" + `data: {"type":"codex.rate_limits","plan_type":"plus","rate_limits":{"allowed":true}}`,
|
||||
}
|
||||
|
||||
const overloadedFailed = `event: response.failed` + "\n" + `data: {"type":"response.failed","response":{"id":"r0","status":"failed","error":{"code":"server_is_overloaded","message":"Our servers are currently overloaded. Please try again later."}}}`
|
||||
|
||||
// A stream with nothing but its frames, held past 15s while its agent is
|
||||
// kept alive with comments, stays held: its server_is_overloaded after
|
||||
// that is a failure the group's next member answers, not the agent's
|
||||
// error (#1418). Before, the frame that came after 15s let the stream
|
||||
// through, and the failure 21s later reached Codex as the turn's end with
|
||||
// sub2api, next in the group, never asked. A Gemini stream, whose agent
|
||||
// takes no comment, is let through at 15s as before.
|
||||
func TestLeadOnlyStreamHeldWhileKeptAlive(t *testing.T) {
|
||||
held := func(proto provider.Protocol) (*holdWriter, *httptest.ResponseRecorder) {
|
||||
rec := httptest.NewRecorder()
|
||||
h := newHoldWriter(rec, true)
|
||||
h.alive, h.streams = &keptAlive{proto: proto}, true
|
||||
h.Header().Set("Content-Type", "text/event-stream")
|
||||
h.WriteHeader(200)
|
||||
io.WriteString(h, sse(overloadedLead[:2]...))
|
||||
h.since = time.Now().Add(-(holdLongest + 5*time.Second))
|
||||
io.WriteString(h, sse(overloadedLead[2]))
|
||||
io.WriteString(h, ": ping\n\n")
|
||||
return h, rec
|
||||
}
|
||||
h, rec := held(provider.Responses)
|
||||
if h.passing || strings.Contains(rec.Body.String(), "response.created") {
|
||||
t.Fatalf("let through after %s with nothing said: %q", holdLongest, rec.Body.String())
|
||||
}
|
||||
io.WriteString(h, sse(overloadedFailed))
|
||||
if !h.failed() || h.code() != 529 || !strings.Contains(h.failMsg, "server_is_overloaded") || strings.Contains(rec.Body.String(), "server_is_overloaded") {
|
||||
t.Fatalf("failed %v (%d %q); sent %q", h.failed(), h.code(), h.failMsg, rec.Body.String())
|
||||
}
|
||||
|
||||
// held so long, it is let through as before
|
||||
h, rec = held(provider.Responses)
|
||||
h.since = time.Now().Add(-(holdLead + time.Second))
|
||||
io.WriteString(h, ": ping\n\n")
|
||||
if !h.passing || !strings.Contains(rec.Body.String(), "response.created") {
|
||||
t.Fatalf("held past %s: %q", holdLead, rec.Body.String())
|
||||
}
|
||||
|
||||
h, rec = held(provider.Gemini)
|
||||
if !h.passing || !strings.Contains(rec.Body.String(), "response.created") {
|
||||
t.Fatalf("a stream whose agent takes no comment held past %s", holdLongest)
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user