gateway: a translated Responses reply the upstream cut short ends in an error, not as if whole (#1562, ggbdpq)
What changed: streamTranslated ended a translated reply in "the reply ended before it was complete" when an Anthropic upstream's stream stopped with no stop_reason and no message_stop; a Responses upstream's stream that stopped with no terminal event (no response.completed, response.incomplete, response.failed) was still finished as if whole, and the agent's turn ended a few words in with nothing to say why — the same reply the passthrough already tells apart (sniff.whole, #370). It now ends in the same error, asked again in place where the upstream goes on from a prefill, as an Anthropic cut is. The event that ends a stream is read by its type as the passthrough reads it (upstreamEnds, was anthropicEnds, already lastEvent), so a response.completed carrying no status field still counts as the reply's last. Chat (may end without [DONE] and be whole) and Gemini stay as the passthrough treats them. Run (review, yetone's session): TestResponsesUpstreamEndedShort passes; with the Responses half of the end check taken out by hand it fails ("a cut reply finished as whole", finish_reason "stop", no error). TestRelayStream*, TestRelayStop* ok. The full suite, gofmt and the cross-OS vets are in the series' last commit. Author's run: the red/green above, -race -count=20 on the relay-stop tests, gofmt, go vet and go build on darwin, linux, windows, go test ./... (TestOffline red on the clean baseline too, offline machine). Co-authored-by: factory-droid[bot] <138933559+factory-droid[bot]@users.noreply.github.com>
This commit is contained in:
committed by
yetone
co-authored by
factory-droid[bot]
parent
cf8a16cf56
commit
e435fe00f1
@@ -51,7 +51,7 @@ served by a plugin are in [Provider and plugin ownership](provider-plugins.md).
|
||||
- A request is one usage record, counted once by how it ended (小一 on Discord: Codex on credits showed "5,482 · 1,094 failed" while rows said "2 tries/3 tries" and had been answered). The final record carries `tries` when the route took more than one (`rec.Tries`, from the trace's `Tries`). A try a vendor refused or turned away (`hw.refused`, `hw.turnedAway`) still writes its own record, for what it billed and why it failed, marked `handed_on`; `usage.Totals.count` skips such a record for calls and failures. A request failed only when the agent got an error (`LostRequest`); one answered after a failed try is counted beside it as answered on a retry (`Totals.Retried`, `RetriedRequest`, the `retried` filter). Logs written before `handed_on` are read the same way: the log index marks a failed, non-rejected record followed by another of the same route id as handed on (`routeRows` in [`log_index.go`](../../internal/usage/log_index.go)). Counts by account or route (`vias`, window holds) still count every try.
|
||||
- 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 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. Codex counts only events toward that 300s, not comments, so the bound is the request's, not each try's: once Codex on Responses has heard no event for `agentQuietMost` (4 minutes) since the request began or its last event (`keptAlive.tooQuiet`), the try in hand is let through (`scan`, `keepQuiet`), and no group replan or same-one retry is taken whose pause would end past it (fadenoob on Discord: held tries and replan pauses added up past 300s and Codex reconnected on "idle timeout waiting for SSE").
|
||||
- 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. Codex counts only events toward that 300s, not comments, so the bound is the request's, not each try's: once Codex on Responses has heard no event for `agentQuietMost` (4 minutes) since the request began or its last event (`keptAlive.tooQuiet`), the try in hand is let through (`scan`, `keepQuiet`), and no group replan or same-one retry is taken whose pause would end past it (fadenoob on Discord: held tries and replan pauses added up past 300s and Codex reconnected on "idle timeout waiting for SSE"). A translated reply whose upstream stream stops before it said its reply had — an Anthropic one with no stop_reason and no message_stop, a Responses one with no `response.completed`, the same two a relayed one is told by (`sniff.whole`; a Chat stream may end without `[DONE]` and be whole) — ends the turn with "the reply ended before it was complete" (`errEndedShort`, `TestResponsesUpstreamEndedShort`), asked again in place where the upstream goes on from a prefill (`continuation.go`).
|
||||
- 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.
|
||||
|
||||
@@ -56,13 +56,20 @@ const loopReasks = 1
|
||||
// without waiting on a vendor that keeps the connection open after it.
|
||||
var errStreamCut = errors.New("stream cut mid-reply")
|
||||
|
||||
// errEndedShort is an Anthropic stream that ended, its connection closed
|
||||
// cleanly, before it said its reply had: the passthrough's word for it.
|
||||
// errEndedShort is a stream that ended, its connection closed cleanly,
|
||||
// before it said its reply had — an Anthropic one with no stop_reason and
|
||||
// no message_stop, a Responses one with no response.completed: the same
|
||||
// two the passthrough tells apart. A Chat stream may end without [DONE]
|
||||
// and be whole, so Chat is not one.
|
||||
var errEndedShort = errors.New("the reply ended before it was complete")
|
||||
|
||||
// anthropicEnds says whether an Anthropic stream's event ends the reply:
|
||||
// its message_stop (a stop_reason is upstreamStop's), or an error.
|
||||
func anthropicEnds(data string) bool {
|
||||
// upstreamEnds says whether a stream's event ends the reply, by its type
|
||||
// as the passthrough's sniffer counts it (sniff.whole): an Anthropic
|
||||
// message_stop or error, a Responses response.completed,
|
||||
// response.incomplete or response.failed — a response.completed carrying
|
||||
// no status field among them, as relays send it. upstreamStop reads the
|
||||
// stop a stop_reason or a response status carries; this reads the type.
|
||||
func upstreamEnds(data string) bool {
|
||||
var v struct {
|
||||
Type string `json:"type"`
|
||||
}
|
||||
@@ -409,7 +416,8 @@ func (s *Server) streamTranslated(w http.ResponseWriter, r *http.Request, p prov
|
||||
serr = readSSEAlive(rd, func(_, data string) error {
|
||||
st := upstreamStop([]byte(data))
|
||||
u.add(Usage{Upstream: upstreamOf([]byte(data)), Stop: st})
|
||||
ended = ended || st != "" || actual == provider.Anthropic && anthropicEnds(data)
|
||||
ended = ended || st != "" ||
|
||||
(actual == provider.Anthropic || actual == provider.Responses) && upstreamEnds(data)
|
||||
if err := dec(data, attemptSee); err != nil {
|
||||
return err
|
||||
}
|
||||
@@ -422,12 +430,15 @@ func (s *Server) streamTranslated(w http.ResponseWriter, r *http.Request, p prov
|
||||
if errors.Is(serr, errStreamCut) {
|
||||
serr = nil
|
||||
}
|
||||
if serr == nil && failed == "" && !ended && !relooped && actual == provider.Anthropic && r.Context().Err() == nil {
|
||||
if serr == nil && failed == "" && !ended && !relooped &&
|
||||
(actual == provider.Anthropic || actual == provider.Responses) && r.Context().Err() == nil {
|
||||
// an Anthropic stream that just stopped — no
|
||||
// stop_reason, no message_stop — is a reply cut
|
||||
// short, not a finished one: a relay's (蓝猫 on
|
||||
// Discord) read as whole ended the agent's turn a
|
||||
// few words in, with nothing to say why
|
||||
// stop_reason, no message_stop — or a Responses one
|
||||
// with no response.completed is a reply cut short,
|
||||
// not a finished one: a relay's (蓝猫 on Discord)
|
||||
// read as whole ended the agent's turn a few words
|
||||
// in, with nothing to say why, and a Responses reply
|
||||
// whole would say completed it never said
|
||||
serr = errEndedShort
|
||||
}
|
||||
}
|
||||
|
||||
@@ -134,6 +134,55 @@ func TestRelayStreamEndedShort(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
// relayResponses serves a translated request's model from a Responses
|
||||
// upstream answering with events, as they are, and returns the Chat
|
||||
// stream magpie made of it.
|
||||
func relayResponses(t *testing.T, events ...string) string {
|
||||
t.Helper()
|
||||
fresh(t)
|
||||
up := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
io.Copy(io.Discard, r.Body)
|
||||
w.Header().Set("Content-Type", "text/event-stream")
|
||||
for _, ev := range events {
|
||||
io.WriteString(w, "data: "+ev+"\n\n")
|
||||
}
|
||||
}))
|
||||
t.Cleanup(up.Close)
|
||||
if err := provider.Save(provider.Provider{ID: "up", Name: "UP", Key: "k", Models: []string{"gpt-6.1"}, Responses: up.URL + "/v1"}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
code, body := post(t, "/v1/chat/completions", `{"model":"up/gpt-6.1","stream":true,"messages":[{"role":"user","content":"hi"}]}`)
|
||||
if code != 200 {
|
||||
t.Fatalf("status %d: %s", code, body)
|
||||
}
|
||||
return body
|
||||
}
|
||||
|
||||
// A Responses stream that stops with no response.completed is a reply cut
|
||||
// short, as an Anthropic one with no message_stop is: the client is told
|
||||
// so rather than handed a finished one (the passthrough's word for it,
|
||||
// which the translated path gave only Anthropic's streams).
|
||||
func TestResponsesUpstreamEndedShort(t *testing.T) {
|
||||
body := relayResponses(t,
|
||||
`{"type":"response.created","response":{"id":"resp_1","status":"in_progress"}}`,
|
||||
`{"type":"response.output_item.added","output_index":0,"item":{"type":"message","id":"msg_1","role":"assistant","content":[]}}`,
|
||||
`{"type":"response.output_text.delta","item_id":"msg_1","output_index":0,"delta":"Let me look at the"}`)
|
||||
if chatFinish(body) == "stop" && !strings.Contains(body, "ended before it was complete") {
|
||||
t.Errorf("a cut reply finished as whole: %s", body)
|
||||
}
|
||||
if !strings.Contains(body, "ended before it was complete") {
|
||||
t.Errorf("no error for the cut reply: %s", body)
|
||||
}
|
||||
// a stream whose response.completed came said it was done
|
||||
body = relayResponses(t,
|
||||
`{"type":"response.created","response":{"id":"resp_1","status":"in_progress"}}`,
|
||||
`{"type":"response.output_item.done","output_index":0,"item":{"type":"message","id":"msg_1","role":"assistant","content":[{"type":"output_text","text":"Done."}]}}`,
|
||||
`{"type":"response.completed","response":{"id":"resp_1","status":"completed","output":[],"usage":{"input_tokens":5,"output_tokens":1}}}`)
|
||||
if got := chatFinish(body); got != "stop" || strings.Contains(body, "ended before") {
|
||||
t.Errorf("finish_reason %q: %s", got, body)
|
||||
}
|
||||
}
|
||||
|
||||
// The upstream's own stop reason is kept with the request, for a reply
|
||||
// that ended too soon to be told apart by: the relay's word, not magpie's.
|
||||
func TestRelayStopReasonRecorded(t *testing.T) {
|
||||
|
||||
Reference in New Issue
Block a user