gateway: a held stream lets through only text, reasoning or a call, so a 200 that only framed a reply fails over (#1418)

Aliceonly's trace on #1418: sub2api answered 502 "Upstream HTTP/2 stream
failed", then Codex account A answered 200, sent only the frames before a
reply, and failed server_is_overloaded 37s in. Five candidates after it
were never asked, and Codex ended the turn. The stream had been let
through (h.passing), so holdWriter.failed() was false and neither the next
candidate nor a replan was tried.

Two ways a frames-only stream went through:
- streamEvent's default was eventContent: any event it didn't know (and an
  item of a type said() didn't know) counted as the reply begun. Now only
  the events of each protocol that carry text, reasoning, a call or a
  reply's end (replyEvent) count; anything else is eventLead, held as a
  ping is. An unknown item counts only when it is a call or a tool's
  (web_search_call, server_tool_use, mcp_*). A stream that ends well is
  still released whole, so this can only delay, never drop, a reply.
- a reply under a Content-Type that says neither JSON nor a stream, once
  the agent had a stream's headers, went straight through when its first
  bytes were SSE (sseStart -> pass()). It is now held as a stream from
  there and read event by event.

Which event Codex's backend actually sent isn't in the trace; the test
uses a keepalive, response.rate_limits.updated and an unknown item type.

Run: go test ./internal/gateway -count=1, green (428s).
TestFramesThenOverloadedGoesToTheNext (new: 502, then 200 frames + unknown
events + server_is_overloaded, then a third member) and
TestStreamEventUnknownOnlyFrames (new) fail on the old fallback.go: the
overloaded stream reaches the agent and c is never asked.
TestHeldUnsureStreamPasses/KeptAlive now expect the stream held until its
first word, and TestHeldUnsureStreamFailsHeld (new) a failure among held
frames; all fail on the old code. Not tried against the real ChatGPT
backend.
This commit is contained in:
yetone
2026-10-13 07:30:06 +08:00
parent 4a6c81e038
commit a68d2ac944
4 changed files with 150 additions and 20 deletions
+1 -1
View File
@@ -56,7 +56,7 @@ served by a plugin are in [Provider and plugin ownership](provider-plugins.md).
- A usage record carries its prompt's cache beside `in` and `out` (#1839): `cache_read` (tokens read from the vendor's cache) and `cache_write` (cache creation, Anthropic's `cache_creation_input_tokens`; `cache_write_1h` the part written for an hour). `in` holds neither. Both are written on every record, 0 too, so a prompt that missed the cache reads as that. A record from before then has neither and reads as 0. Every route fills them: Anthropic's messages, Chat (OpenAI's `prompt_tokens_details.cached_tokens`, DeepSeek's `prompt_cache_hit_tokens`), Responses (`input_tokens_details.cached_tokens`) and Gemini (`cachedContentTokenCount`), passed through or translated, whole or streamed, a plugin's fetch, and the Claude subscription bridge. System One's decision calls report no cache. `TestUsageRecordsCacheTokensOnEveryRoute`, `TestPluginUsageRecordsCacheTokens`, `TestClaudeSubscriptionUsageKeepsCacheTokens`, `TestRecordAlwaysCarriesCacheTokens`.
- 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 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), a Gemini or Code Assist one whose last chunk has no candidate's `finishReason` (`geminiEnds`, #1643: `usageMetadata` is no end, Vertex AI sends it on every chunk; a chunk with no candidate at all is the empty reply's to answer, #667), and a relayed Gemini one told the same way (#1644; it ends in Gemini's own `{"error":{"code":502,…,"status":"UNAVAILABLE"}}` data line from `streamFailure`, `TestGeminiRelayEndedShort`) — ends the turn with "the reply ended before it was complete" (`errEndedShort`, `TestResponsesUpstreamEndedShort`, `TestGeminiUpstreamEndedShort`), asked again in place where the upstream goes on from a prefill (`continuation.go`). A client that asked for no stream is told the same 502 of such a cut (`translate`, `TestNonStreamEndedShort`, `TestGeminiNonStreamEndedShort`), rather than handed what came as its whole reply.
- 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 reply under a type that says neither JSON nor a stream is held as a stream when its first bytes are one (`sseStart`), read event by event like one that says so, so an error among its frames still goes to the next candidate (#1418: it went through at once); 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, and any event `streamEvent` doesn't know to carry text, reasoning, a call or a reply's end (`replyEvent`), or an item not known that isn't a call or a tool's (`streamPart.said`): `eventLead`; Aliceonly on #1418: an unknown event was taken for content and let a frames-only 200 through, and its `server_is_overloaded` reached Codex with five candidates left) 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), a Gemini or Code Assist one whose last chunk has no candidate's `finishReason` (`geminiEnds`, #1643: `usageMetadata` is no end, Vertex AI sends it on every chunk; a chunk with no candidate at all is the empty reply's to answer, #667), and a relayed Gemini one told the same way (#1644; it ends in Gemini's own `{"error":{"code":502,…,"status":"UNAVAILABLE"}}` data line from `streamFailure`, `TestGeminiRelayEndedShort`) — ends the turn with "the reply ended before it was complete" (`errEndedShort`, `TestResponsesUpstreamEndedShort`, `TestGeminiUpstreamEndedShort`), asked again in place where the upstream goes on from a prefill (`continuation.go`). A client that asked for no stream is told the same 502 of such a cut (`translate`, `TestNonStreamEndedShort`, `TestGeminiNonStreamEndedShort`), rather than handed what came as its whole reply.
- 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` (`usage.LoopErrType`), and Usage counts them per model (`Totals.Loops`), as "{n} looped" beside the model's failures in the Overview's rows and the Requests ranking (#1858, `TestLoopsCountedPerModel`, `usage-loops.test.cjs`). 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. A window's renewal is its reset, or, when what it has left runs out sooner or it has no reset, that moment (`Limit.RunsOut`, from `QuotaWindow.RunsOutAt`; `Allowance.Renewal`): the WorkBuddy plugin (0.1.14) sends it on its Credits window as the soonest end of a package with credits left (cdredfox on X). Only Smart reads it; Weekly pace, the 90%/98% tiers and rests go by the window's share and reset as before. A row on the Routing page says the share used (the fullest window's, `Allowance.For`) with when that same window renews (`Allowance.Fullest`, the trace's `usedRenews`), not the biggest window's: a Factory account 32% into its week and 16% into its month reads "32% used · renews in 3 days" while Smart still ranks it by its month (#1778). A route from before `usedRenews` says when only for an account of one window. 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.
+44 -14
View File
@@ -1449,17 +1449,13 @@ func (h *holdWriter) Write(b []byte) (int, error) {
if sse, sure := sseStart(head); sure {
h.wholeUnsure = false
if sse {
// a stream under a type that doesn't say so: through as it
// comes, with what was held of its start
h.whole = false
h.held.Reset()
h.pass()
h.refusalAfter(head)
h.sent(head)
if _, err := h.w.Write(head); err != nil {
return 0, err
}
return len(b), nil
// a stream under a type that doesn't say so: held as a
// stream from here, its events read as they come, so an
// error before anything is said still goes to the next
// candidate. It went through at once before, and a 200
// that only framed a reply and then failed reached the
// agent (#1418)
h.whole, h.stream, h.since = false, true, time.Now()
}
}
}
@@ -2206,7 +2202,9 @@ func (p streamPart) thought() bool {
}
// said tells whether a part says anything an agent would show or act on:
// text, reasoning, a call. What isn't known is taken as saying something.
// text, reasoning, a call. Of what isn't known, a call or a tool's part
// (web_search_call, mcp_tool_use, server_tool_use, ...) says something;
// anything else only frames the reply until something does (#1418).
func (p streamPart) said() bool {
switch p.Type {
case "text", "output_text", "summary_text", "reasoning_text":
@@ -2235,7 +2233,7 @@ func (p streamPart) said() bool {
}
return false
}
return true
return strings.Contains(p.Type, "call") || strings.Contains(p.Type, "tool") || strings.HasPrefix(p.Type, "mcp_")
}
// streamEvent says what one server-sent event of a reply is, in any of the
@@ -2444,7 +2442,39 @@ func streamEvent(ev []byte) (kind, status int, msg string) {
}
return eventLead, 0, ""
}
return eventContent, 0, ""
if replyEvent(typ) {
return eventContent, 0, ""
}
// what isn't known to carry a reply only frames it: it lets the
// stream through no more than a ping does. Taken for content, a 200
// that sent only such frames went through, and the overloaded error
// after them reached Codex with five candidates never asked
// (Aliceonly on #1418). A stream that ends well is released whole
return eventLead, 0, ""
}
// replyEvent tells whether an event, past the cases streamEvent tells
// apart, is one of a protocol's events that carry a reply or end it:
// Anthropic's blocks and stop, Responses' text, refusal, items, parts,
// calls and audio, and its end.
func replyEvent(typ string) bool {
switch typ {
case "content_block_start", "content_block_delta", "message_delta", "message_stop",
"response.completed", "response.incomplete", "response.done":
return true
}
rest, ok := strings.CutPrefix(typ, "response.")
if !ok {
return false
}
for _, p := range []string{"output_text.", "refusal.", "output_item.", "content_part.", "audio", "output_audio"} {
if strings.HasPrefix(rest, p) {
return true
}
}
// a call's arguments or a hosted tool's progress: function_call_
// arguments, custom_tool_call_input, web_search_call, mcp_call, ...
return strings.Contains(rest, "_call") || strings.HasPrefix(rest, "mcp_")
}
// anthropicDeltaThinks tells whether an Anthropic content_block_delta is
+67
View File
@@ -300,3 +300,70 @@ func TestCodexHeardWithinItsIdleTimeout(t *testing.T) {
t.Fatalf("after %s (a %d, b %d):\n%s", took, a.n, b.n, body)
}
}
// Aliceonly's trace on #1418: sub2api answered 502 "Upstream HTTP/2
// stream failed", Codex account A a 200 that only framed a reply and then
// failed server_is_overloaded, and five candidates after it were never
// asked. An event streamEvent didn't know was taken for the reply's
// content and let the stream through, so its failure came after the
// reply had begun. Which event Codex's backend sent isn't in the trace;
// these stand in for any it may add. Now only text, reasoning or a call
// lets a stream through, and the third member answers.
func TestFramesThenOverloadedGoesToTheNext(t *testing.T) {
fresh(t)
unknown := []string{
`event: keepalive` + "\n" + `data: {"type":"keepalive"}`,
`event: response.rate_limits.updated` + "\n" + `data: {"type":"response.rate_limits.updated","rate_limits":{"allowed":true}}`,
`event: response.output_item.added` + "\n" + `data: {"type":"response.output_item.added","item":{"type":"compaction_summary","id":"cs_1"}}`,
}
a := &scripted{replies: []reply{{502, "", `{"error":{"message":"Upstream HTTP/2 stream failed"}}`}}}
b := &scripted{replies: []reply{{200, "text/event-stream", sse(append(append(slices.Clone(overloadedLead), unknown...), overloadedFailed)...)}}}
c := &scripted{replies: []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":[]}}`)}}}
responsesOn(t, "a", a)
responsesOn(t, "b", b)
responsesOn(t, "c", c)
if err := provider.SaveGroup(provider.Group{Name: "G", Members: []string{"a/m", "b/m", "c/m"}, Routing: provider.Ordered, Patience: provider.PatienceOff}); err != nil {
t.Fatal(err)
}
s := New()
code, body := sendTo(s, "/v1/responses", codexAsk)
if code != 200 || !strings.Contains(body, "hello") || strings.Contains(body, "server_is_overloaded") || strings.Contains(body, "keepalive") || c.n != 1 {
t.Fatalf("%d %q (a %d, b %d, c %d)", code, body, a.n, b.n, c.n)
}
r := s.trace.routes[len(s.trace.routes)-1]
if len(r.Tries) != 3 || r.Tries[1].Fail == "" {
t.Fatalf("tries: %+v", r.Tries)
}
}
// What only frames a reply, or isn't known, doesn't let a stream through;
// text, reasoning, a call or a reply's end does.
func TestStreamEventUnknownOnlyFrames(t *testing.T) {
for _, x := range []struct {
ev string
kind int
}{
{`data: {"type":"keepalive"}`, eventLead},
{`event: response.rate_limits.updated` + "\n" + `data: {"type":"response.rate_limits.updated"}`, eventLead},
{`data: {"type":"response.output_item.added","item":{"type":"compaction_summary"}}`, eventLead},
{`data: {"x":1}`, eventLead},
{`data: {}`, eventLead},
{`data: {"type":"response.output_item.added","item":{"type":"web_search_call","id":"ws"}}`, eventContent},
{`data: {"type":"response.output_item.added","item":{"type":"mcp_list_tools"}}`, eventContent},
{`data: {"type":"response.web_search_call.searching","item_id":"ws"}`, eventContent},
{`data: {"type":"response.function_call_arguments.delta","delta":"{"}`, eventContent},
{`data: {"type":"response.custom_tool_call_input.delta","delta":"x"}`, eventContent},
{`data: {"type":"response.output_text.annotation.added"}`, eventContent},
{`data: {"type":"response.refusal.delta","delta":"no"}`, eventContent},
{`event: content_block_start` + "\n" + `data: {"type":"content_block_start","index":0,"content_block":{"type":"server_tool_use","id":"s","name":"web_search"}}`, eventContent},
{`event: content_block_start` + "\n" + `data: {"type":"content_block_start","index":0,"content_block":{"type":"container_upload"}}`, eventLead},
{`event: message_stop` + "\n" + `data: {"type":"message_stop"}`, eventContent},
{`data: [DONE]`, eventContent},
} {
if k, _, _ := streamEvent([]byte(x.ev)); k != x.kind {
t.Errorf("streamEvent(%s) = %d, want %d", x.ev, k, x.kind)
}
}
}
+38 -5
View File
@@ -259,8 +259,11 @@ func TestWholeAsStreamResponsesCitations(t *testing.T) {
// A held try's reply under a type that says neither JSON nor a stream,
// once the agent has a stream's headers: its first bytes decide, however
// they are split, and a stream goes through whole, the bytes held of its
// start too.
// they are split. A stream is held as a stream from there, read event by
// event like one that says so: its frames stay held, a failure among them
// is the try's (#1418: it went straight through before, and an error
// after its frames reached the agent), and the first word of the reply
// lets it through, the bytes held of its start too.
func TestHeldUnsureStreamPasses(t *testing.T) {
for _, c := range []struct {
name string
@@ -285,8 +288,15 @@ func TestHeldUnsureStreamPasses(t *testing.T) {
t.Fatalf("wrote %d of %q: %v", n, w, err)
}
}
if c.stream && (!h.passing || h.whole || rec.Body.String() != all) {
t.Fatalf("passing %v, whole %v, agent has %q", h.passing, h.whole, rec.Body.String())
if c.stream {
if h.passing || h.whole || !h.stream || h.held.String() != all || rec.Body.Len() != 0 {
t.Fatalf("frames only: passing %v, whole %v, stream %v, held %q, agent has %q", h.passing, h.whole, h.stream, h.held.String(), rec.Body.String())
}
said := "data: " + chatOK + "\n\n"
h.Write([]byte(said))
if !h.passing || rec.Body.String() != all+said {
t.Fatalf("said: passing %v, agent has %q", h.passing, rec.Body.String())
}
}
if !c.stream && (h.passing || !h.whole || h.held.String() != all || rec.Body.Len() != 0) {
t.Fatalf("passing %v, whole %v, held %q, agent has %q", h.passing, h.whole, h.held.String(), rec.Body.String())
@@ -314,7 +324,30 @@ func TestHeldUnsureKeptAlive(t *testing.T) {
t.Fatalf("the agent has %q", got)
}
h.Write([]byte("data: {}\n\n"))
if got := rec.Body.String(); got != ": keepalive\ndata: {}\n\n" {
if got := rec.Body.String(); got != ": keepalive\n" {
t.Fatalf("a frame went: the agent has %q", got)
}
h.Write([]byte("data: " + chatOK + "\n\n"))
if got := rec.Body.String(); got != ": keepalive\ndata: {}\n\ndata: "+chatOK+"\n\n" {
t.Fatalf("the agent has %q", got)
}
}
// A held try's reply under a type that says neither JSON nor a stream,
// which begins as a stream, frames only, then fails: the failure is the
// try's, for the next candidate to answer, and nothing of it went to the
// agent (#1418, Aliceonly: the sseStart branch passed such a stream
// through at once).
func TestHeldUnsureStreamFailsHeld(t *testing.T) {
rec := httptest.NewRecorder()
h := newHoldWriter(rec, true)
h.alive = &keptAlive{proto: provider.Responses, sent: true}
h.Header().Set("Content-Type", "text/plain; charset=utf-8")
h.WriteHeader(http.StatusOK)
h.Write([]byte(strings.Join(overloadedLead, "\n\n") + "\n\n"))
h.Write([]byte("event: response.rate_limits.updated\ndata: {\"type\":\"response.rate_limits.updated\"}\n\n"))
h.Write([]byte(overloadedFailed + "\n\n"))
if h.passing || !h.failed() || rec.Body.Len() != 0 {
t.Fatalf("passing %v, failed %v, agent has %q", h.passing, h.failed(), rec.Body.String())
}
}