From a0a4d55ef7b0983ff1e69e76b08f4f2ca2e6e537 Mon Sep 17 00:00:00 2001 From: yetone Date: Fri, 16 Oct 2026 01:36:49 +0800 Subject: [PATCH] gateway: a passed-through reply whose reasoning loops before it says anything is asked again once, and its tries counted (#2436) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit lqisgod's five looped replies (pi → WorkBuddy, Chat in and out) each ended at once with empty tries and status 200. The once-only re-ask of a reasoning loop (loopReasks) lived only in streamTranslated's onLoop, so a same-protocol passthrough had holdWriter.reask nil and cutLoop ran on the first trip. A re-ask that did happen in place wasn't counted in the usage record's tries either (tries came from route.Tries alone). Now holdWriter lets such a try go (mayReloop/letGoLoop) when its reasoning looped, nothing has spoken (loopGuard.spoke: no text or call), the request has its re-ask left and its context is alive, and either nothing of the try reached the agent (held bytes dropped, any protocol) or the agent speaks Chat (bytes written up to the end of the tripping event, the next try's chunks follow). The fallback loop records the try as failLoop with reloopedError and asks the same provider again after retryPause. In-place re-asks add to tries too. An Anthropic or Responses stream whose reasoning already reached the agent still ends with the loop error: a second message_start/response.created can't follow. The plugin host's fetch goes through the same holdWriter (TestLoopEndsWorkBuddysReply's plugin subtests). Tests: loop_guard_test.go's chat case now expects 2 asks and an answer; every passed-through `data:` line is valid JSON; the usage record has Tries == asks and no error. docs/subsystems/gateway-routing.md updated. Broken by hand, each red: - hw.reloop = false (old behaviour): TestLoopEndsTheReplyOnEveryProtocol, TestLoopEndsWorkBuddysReply, TestReasoningLoopIsAskedAgain fail. - reasked not added to tries: the same three fail with "usage record's tries 0, the vendor asked 2 times". - spoke never set: TestLoopAfterTextIsNotAskedAgain fails. Run: gofmt -l clean; go vet -tags nogui ./internal/gateway ./internal/usage with GOOS=darwin, linux, windows ok; go test -run Loop ./internal/gateway ok. Not tried: a real WorkBuddy account looping (the loop can't be forced). Full suite: go test -tags nogui -count=1 -timeout 45m ./... on base b03031738, every package ok, no FAIL line. --- docs/subsystems/gateway-routing.md | 2 +- internal/gateway/fallback.go | 60 +++++++++++++++++++++++++++-- internal/gateway/gateway.go | 28 +++++++++++++- internal/gateway/loop_guard.go | 7 ++++ internal/gateway/loop_guard_test.go | 50 +++++++++++++++++------- internal/gateway/routing.go | 5 +++ 6 files changed, 132 insertions(+), 20 deletions(-) diff --git a/docs/subsystems/gateway-routing.md b/docs/subsystems/gateway-routing.md index 2cb4d9d07..7a1b91a8c 100644 --- a/docs/subsystems/gateway-routing.md +++ b/docs/subsystems/gateway-routing.md @@ -109,7 +109,7 @@ recorded as a prediction failure (`noPrediction`). - A vendor's error keeps its `code` and `param` on its way to an OpenAI-shaped client (`writeVendorError`), where `writeError` used to set both to null: a status error relayed or translated, and a request refused inside a Responses stream. A Responses stream's `error` event or failed response whose error is of type `invalid_request_error` is the request at fault (`requestRefused`, read by its type, not its words): its `Event` carries status 400 and the vendor's error (`Event.Said`), so a client answered whole gets the vendor's 400 with its code and param (the whole-translated path wrote 502 `api_error`), a reply cut by it isn't resumed (`continuation.again`), and a translated stream's error says the vendor's type, code and param (`saidError`), so `holdWriter` reads it as the 400 it is. Before, the hold read magpie's `api_error` as a 502: the same request was sent three times, then to the other accounts, and every one rested (magpie-releases#18: the ChatGPT backend answers `access_programs` naming a program the workspace hasn't got with a 200 stream whose error is `access_program_not_enabled`). Asked once, nobody rests ([`codex_access_programs_test.go`](../../internal/gateway/codex_access_programs_test.go)). - An error that reaches the agent in a stream already begun can't carry its status, so `streamError` says it in the words (`saysPassing`, #2372, zminds): for a status that may pass (408, 429, 5xx) whose text names none of the words a text-judging agent retries on (Pi decides by its `errorMessage` alone), it appends `(: you can retry your request)`; a request's own fault (400, 401, 404 …) and a text that already says so are left as they were. `TestStreamErrorSaysItPasses` holds Pi's own lists; `TestGroupLastFailureInStreamSaysItPasses` runs a group whose last member fails after the keepalive. - 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. +- 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 reply passed through in the agent's own protocol is asked again once too, at the fallback loop (`holdWriter.mayReloop`, `letGoLoop`; #2436, lqisgod: pi's Chat stream to WorkBuddy was cut at once): when nothing of the try has reached the agent yet, in any protocol, its held bytes are dropped; when its reasoning is already passing, only a Chat stream goes on, written up to the end of the tripping event, with the next try's chunks after it. An Anthropic or Responses stream already passing still ends with the error, since a second `message_start` or `response.created` can't follow. Each re-ask, in place or at the fallback loop, counts in the usage record's tries. A loop in the text, or after a text or call, is ended at once (`TestLoopAfterTextIsNotAskedAgain`). 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. - A Chat request's earlier turns carry the assistant's thinking back in the spelling its own client used: `reasoning_content` (DeepSeek's, which OpenCode and most clients send), `reasoning` (OpenRouter's) or `reasoning_details` (OpenRouter's structured one). A request translated to a non-Chat upstream reads whichever of the three the turn has, in that order, as the turn's thinking (`messageReasoning`, `reasoningText`, read by `parseChat` in [chat.go](../../internal/gateway/chat.go)); the passthrough has read all three since `mistralThinking` (#494), which was the one place that did. Before that the parse layer read `reasoning_content` alone, so a tool-calling session whose client spelled it another way went on from its second turn without the model's own reasoning. - 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. - A turn's end is told to the app for the "Task done alert" notification (itieniu on X, `turndone.go`). The trace follows each agent session's turn (`turns`, keyed by agent and session): a request is of the turn unless it has a `Kind` or is a Claude Code subagent's (`agentTurnOf`), and its reply is scanned on the way to the agent for a tool call in any wire format (`toolScan`, a JSON value such as `"type":"tool_use"` or `"finish_reason":"tool_calls"`, never a key or text). The turn is done when no request of it is going, the last reply was whole, under 400 and called no tool, and nothing more came for `turnQuiet` (4s); a session idle past `turnStale` (30m) starts over. Only a turn that ran at least `settings.TurnDoneAlert` seconds is told (`TurnDone`, set by the GUI; nil under `magpie serve`, so nothing is followed). The ChatGPT backend path (`codexBackend`) is followed the same way. `TestTurnDoneSaidAtTheTurnsEnd`, `TestTurnDoneCodexBackend`, `TestToolScan`, `turn-done.test.cjs`. diff --git a/internal/gateway/fallback.go b/internal/gateway/fallback.go index f3c0b9419..3faeefb0d 100644 --- a/internal/gateway/fallback.go +++ b/internal/gateway/fallback.go @@ -1534,6 +1534,13 @@ type holdWriter struct { // reply is asked again instead of ended: the guard then reads the // next try's afresh reask func(loopTrip) bool + // reasked is how many times reask asked the reply again in place, + // tries of the request its route doesn't list (#2436) + reasked int + // reloop: a reply passed through, whose reasoning loops before it + // said anything, may be let go for the request to ask it again + // (loopReasks, #2436); relooped says it was + reloop, relooped bool // wantWhole: a reply wanted only whole, a compaction's summary (#2274): its // stream is held to its end, never let through at its first content, @@ -1634,7 +1641,7 @@ func (h *holdWriter) Write(b []byte) (int, error) { if h.slow { return 0, errSlowStart } - if h.looped != "" { + if h.looped != "" || h.relooped { return 0, errLooped } if h.status == 0 { @@ -1642,10 +1649,15 @@ func (h *holdWriter) Write(b []byte) (int, error) { } if h.loop != nil && !h.whole && h.status < 400 { if t, ok := h.loop.feed(b); ok { - if h.reask == nil || !h.reask(t) { + switch { + case h.reask != nil && h.reask(t): + h.reasked++ + h.loop = &loopGuard{} + case h.reask == nil && h.mayReloop(t): + return h.letGoLoop(b) + default: return h.cutLoop(b, t) } - h.loop = &loopGuard{} } } h.see(b) @@ -1709,6 +1721,46 @@ func (h *holdWriter) cutLoop(b []byte, t loopTrip) (int, error) { return 0, errLooped } +// mayReloop says whether a reply passed through, found stuck in a loop +// (t), is let go for the request to ask it again (letGoLoop) rather than +// ended: its reasoning looped before it said a text or a call, the +// request has an ask left (reloop), and the next try's stream can follow +// what the agent has. Nothing of it sent, any can; sent, only a Chat +// stream, whose chunks are deltas the agent adds up: a second stream's +// follow the first's as they would its own. An Anthropic or Responses +// stream begun can't be followed by another's message_start or +// response.created, so it ends with the loop's error, as before. +func (h *holdWriter) mayReloop(t loopTrip) bool { + if !h.reloop || !t.reasoning || h.loop.spoke || h.alive == nil || h.ctx != nil && h.ctx.Err() != nil { + return false + } + return !h.passing || h.alive.proto == provider.Chat +} + +// letGoLoop lets a reply go whose reasoning looped before it said a word +// (mayReloop), for the request to ask it again: the vendor's request is +// let go, and the try's writes after it fail. Held, none of it reaches +// the agent; passing, its events go up to the end of the one the loop was +// found in, for the next try's stream to begin on a whole event. +func (h *holdWriter) letGoLoop(b []byte) (int, error) { + if h.passing { + b = b[:max(len(b)-len(h.loop.pending), 0)] + h.sent(b) + h.w.Write(b) + h.flush() + // the next try's stream follows this one: its 200 and headers + // are not sent again + h.alive.sent = true + } else { + h.held.Reset() + } + h.relooped = true + if h.stop != nil { + h.stop() + } + return 0, errLooped +} + // sseStart reports whether a body that begins with head is server-sent // events, by the field its first line begins with, and whether head is // enough to tell. @@ -2316,7 +2368,7 @@ func (h *holdWriter) watch() func() { // comments only (keepAlive), none of the try, which another account may // still answer instead; passed, a comment goes between two lines of it. func (h *holdWriter) keepQuiet() { - if h.slow || h.ended || h.alive == nil || h.alive.proto == provider.Gemini || h.ctx != nil && h.ctx.Err() != nil { + if h.slow || h.relooped || h.ended || h.alive == nil || h.alive.proto == provider.Gemini || h.ctx != nil && h.ctx.Err() != nil { return } if !h.heard.IsZero() && time.Since(h.heard) >= keepaliveLongest { diff --git a/internal/gateway/gateway.go b/internal/gateway/gateway.go index 060518117..e49b3c1ad 100644 --- a/internal/gateway/gateway.go +++ b/internal/gateway/gateway.go @@ -2201,6 +2201,10 @@ func (s *Server) serve(w http.ResponseWriter, r *http.Request, from provider.Pro rounds := 0 // the rounds they were asked again in var waitFrom time.Time // when every member had first failed so refusals := 0 // the tries the safety filter refused so + // a reply passed through whose reasoning looped before it said a word, + // asked again (loopReasks); reasked, the times a translated one was + // asked again in place, tries the route doesn't list (#2436) + reloops, reasked := 0, 0 // ended is when the last try's reply ended: the request's ms end there, // not after what magpie writes down of it once it has (#1939: sticks // and the provider's last answer, saved to disk, took seconds on a busy @@ -2264,6 +2268,7 @@ func (s *Server) serve(w http.ResponseWriter, r *http.Request, from provider.Pro // a reply stuck in a loop is ended, not let run to its limit // (#1359) hw.loop = &loopGuard{} + hw.reloop = reloops < loopReasks } // a member of a group in the group is timed by the innermost // group that sets a FirstToken (#2246), else by the group asked for @@ -2575,6 +2580,7 @@ func (s *Server) serve(w http.ResponseWriter, r *http.Request, from provider.Pro break } hw.settle() + reasked += hw.reasked if hw.passing { clientResponseID = call.Usage.ResponseID } @@ -2671,6 +2677,26 @@ func (s *Server) serve(w http.ResponseWriter, r *http.Request, from provider.Pro skipped = append(skipped, c.label()+": "+call.Error) continue } + if hw.relooped { + // its reasoning ran into a loop before it said a word (#1359), + // and it was let go: asked again, once, of the same one, as a + // translated reply is in place; asked again, it mostly doesn't + // loop. The agent keeps what it has, and the next try's stream + // follows it. Nobody rests: the model looped, not the account + // (#2436: pi's Chat to WorkBuddy was ended at once) + reloops++ + call.Error = c.p.Name + ": " + reloopedError + try.Status, try.Error, try.Fail = call.Status, call.Error, failLoop + call.TTFT, call.FirstText, call.Flow, call.FirstReasoning = 0, 0, 0, 0 + watched.attempt(call, try, c.p.ID, sent, hw, capture) + s.trace.update(tr, func(t *Route) { t.Tries[len(t.Tries)-1] = try }) + select { + case <-time.After(retryPause): + case <-r.Context().Done(): + } + i-- + continue + } watched.attempt(call, try, c.p.ID, sent, hw, capture) if autoPicks(c) && repicked < 2 && !hw.passing && hw.code() == http.StatusBadRequest && (provider.CopilotRefusal(hw.errBody()) || wrongEndpoint(hw.code(), hw.errBody())) { @@ -3242,7 +3268,7 @@ func (s *Server) serve(w http.ResponseWriter, r *http.Request, from provider.Pro tries := 0 // the request's tries, as its route lists them s.trace.update(tr, func(t *Route) { t.Done, t.Status, t.Error, t.Millis = true, call.Status, call.Error, call.Millis - tries = len(t.Tries) + tries = len(t.Tries) + reasked if t.TitleLink != nil && isTitleKind(t.Kind) && call.Status < 400 && call.Error == "" && !call.ResponseTruncated { link := *t.TitleLink link.Reply = replyDigest diff --git a/internal/gateway/loop_guard.go b/internal/gateway/loop_guard.go index e910ac864..85e4359ec 100644 --- a/internal/gateway/loop_guard.go +++ b/internal/gateway/loop_guard.go @@ -33,6 +33,9 @@ type loopGuard struct { pending []byte // what came of an event not yet whole think unitRun text unitRun + // spoke: the reply has said something the agent acts on, a text or a + // call, which a reply asked again would say twice + spoke bool } const ( @@ -121,6 +124,10 @@ func (g *loopGuard) feed(b []byte) (loopTrip, bool) { return t, true } } + if !g.spoke { + content, said, reasoning, _ := timingKind(ev) + g.spoke = said || content && !reasoning + } if text != "" { if t, ok := g.text.add(text); ok { return t, true diff --git a/internal/gateway/loop_guard_test.go b/internal/gateway/loop_guard_test.go index f6c403259..0592fa86e 100644 --- a/internal/gateway/loop_guard_test.go +++ b/internal/gateway/loop_guard_test.go @@ -380,16 +380,16 @@ func (v *loopingVendor) ServeHTTP(w http.ResponseWriter, r *http.Request) { // loopAsks are a streamed request on each of the agents' protocols, and // how each one's stream says it ended well, and with magpie's error; asks -// is how many times the vendor is asked when every reply loops: a reply -// translated to the agent's protocol is asked again once (loopReasks), a -// Chat stream passed through as it comes is not. +// is how many times the vendor is asked when every reply loops: once, and +// again once (loopReasks), whether magpie translates the reply to the +// agent's protocol or passes a Chat stream through as it comes (#2436). var loopAsks = []struct { name, path, body string done, failed string asks int }{ {"chat", "/v1/chat/completions", `{"model":"ds/deepseek-v4-max","stream":true,"messages":[{"role":"user","content":"add TOML"}]}`, - "data: [DONE]", `data: {"error":{"message":"magpie ended this reply`, 1}, + "data: [DONE]", `data: {"error":{"message":"magpie ended this reply`, 2}, {"anthropic", "/v1/messages", `{"model":"ds/deepseek-v4-max","max_tokens":32000,"stream":true,"messages":[{"role":"user","content":"add TOML"}]}`, `"type":"message_stop"`, "event: error\ndata: {\"error\":{", 2}, {"responses", "/v1/responses", `{"model":"ds/deepseek-v4-max","stream":true,"input":"add TOML"}`, @@ -500,6 +500,11 @@ func loopCut(t *testing.T, v *loopingVendor, got, done, failed, provider string, if rec.ErrType != loopErrType || !strings.Contains(rec.Error, "stuck in a loop") || rec.Provider != provider { t.Fatalf("usage record %+v", rec) } + // a reply asked again counts its tries, in place or not (#2436: five + // reply_loop rows, tries empty) + if want := asks; asks == 1 && rec.Tries != 0 || asks > 1 && rec.Tries != want { + t.Fatalf("usage record's tries %d, the vendor asked %d times", rec.Tries, asks) + } } // loopLines counts the lines of the reporter's loop in what the agent got, @@ -557,22 +562,19 @@ func TestLoopEndsWorkBuddysReply(t *testing.T) { } // A reply whose reasoning loops before it says anything is asked again -// once, in place, when magpie translates it to the agent's protocol: the -// agent keeps the reasoning it has, the next try's follows it, and the -// reply ends whole, the loop no error (cdredfox on X: WorkBuddy's DeepSeek -// v4 flash now and then looping in a long turn, the agent's turn ended). -// A Chat stream passed through as it comes is ended with the loop's error, -// as before: its events aren't magpie's to splice. +// once: the agent keeps the reasoning it has, the next try's follows it, +// and the reply ends whole, the loop no error (cdredfox on X: WorkBuddy's +// DeepSeek v4 flash now and then looping in a long turn, the agent's turn +// ended). Translated to the agent's protocol, it is asked again in place; +// a Chat stream passed through as it comes is let go at the end of the +// event the loop was found in, and the next try's stream follows it +// (#2436: pi's Chat to WorkBuddy was ended at once, its tries empty). func TestReasoningLoopIsAskedAgain(t *testing.T) { for _, x := range loopAsks { t.Run(x.name, func(t *testing.T) { v := &loopingVendor{loops: 1, letGo: make(chan bool, 4)} gw := deepseekOn(t, v) got := askStream(t, gw+x.path, x.body) - if x.asks == 1 { - loopCut(t, v, got, x.done, x.failed, "ds", 1) - return - } if !strings.Contains(got, x.done) || strings.Contains(got, "magpie ended this reply") || !strings.Contains(got, "parse() now takes .toml") { t.Fatalf("the reply asked again didn't end whole:\n%s", got[max(len(got)-1500, 0):]) } @@ -590,6 +592,26 @@ func TestReasoningLoopIsAskedAgain(t *testing.T) { if a, b := <-v.letGo, <-v.letGo; a == b { t.Fatalf("let go: %v and %v, want the looping try let go and the next not", a, b) } + if x.name == "chat" { + // both tries' chunks, each whole: the first ends on an + // event's end, not halfway through one + for _, ln := range strings.Split(got, "\n") { + if d, ok := strings.CutPrefix(ln, "data: "); ok && d != "[DONE]" && !json.Valid([]byte(d)) { + t.Fatalf("a chunk spliced halfway: %q", ln) + } + } + } + var rec usage.Record + for i := 0; i < 50; i++ { + if recs := usage.Load(time.Time{}); len(recs) > 0 { + rec = recs[len(recs)-1] + break + } + time.Sleep(20 * time.Millisecond) + } + if rec.Tries != 2 || rec.Error != "" || rec.ErrType != "" { + t.Fatalf("usage record %+v, want an answer in 2 tries", rec) + } }) } } diff --git a/internal/gateway/routing.go b/internal/gateway/routing.go index 48d165993..1d81d5708 100644 --- a/internal/gateway/routing.go +++ b/internal/gateway/routing.go @@ -238,6 +238,11 @@ const ( // (#1359), told apart from what vendors call their errors. const loopErrType = usage.LoopErrType +// reloopedError is a try's error once its reasoning was found stuck in a +// loop before it said anything, and it was let go for the request to ask +// again (#2436). +const reloopedError = "the model's reasoning was stuck in a loop before it said anything; asked again" + // proxyDown is the error Go gives when the proxy itself can't be reached, // over HTTP (proxyconnect) or SOCKS (socks connect). var proxyDown = regexp.MustCompile(`proxyconnect |socks connect `)