From 075dc3247485b844a748e9515f9e093ce7f3d1bc Mon Sep 17 00:00:00 2001 From: ggbdpq Date: Tue, 20 Oct 2026 02:12:28 +0800 Subject: [PATCH] gateway: a plugin's cut-short tool call is retried, not rested for a minute (#2873) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit A plugin that reads a model's text-form tool calls ends a turn whose upstream stream died mid-call as a failure, so the gateway can act (magpie-community/plugins#38: the turn ends as an error "the gateway can retry or fail over"). The gateway did neither: the error was classified as an unknown failure, the account was rested for a minute of backoff, and the failure was passed to the client — the retry the plugin engineered never happened, and the user's next attempt met the backoff too (#2873's routing record: status 200, usage null, fail "other", rest "backoff", 60s). What changed: the contract's own error wording ("the model's tool call, written as text, was cut short", shared by the plugins that read text-form calls — packages/trae, packages/qoder's CUT_SHORT) is classified as a failure of its own, "cut". Nobody rests for it and no failure is counted: the same member is asked again once — the plugin's parser reads the same but the cut doesn't come again — then the next member as any failure's is; the last member left keeps its usual same-member retries, and the agent is told only after the retries run out. Why: a cut is transient and nobody's fault — the account is as good as it was, and a minute of backoff only pushed the user's next attempt off the same account the plugin had proven works. Run: the new tests (plugin_cutshort_test.go) fail on the unfixed tree — the failing account is tried once, rested, and its mate answers; with the fix the same member answers on its second try, nobody rests, and every member cutting still ends the turn with nobody rested. Full gateway package green (316s), targeted family green under -race, vet and gofmt clean, builds fine on darwin and windows; the linux cross-build fails in the wails GUI dependency exactly as it does on the unfixed base (needs a native linux build), and the gateway package itself builds for linux. Landing record (yetone): Run at the pushed batch head (tree a6b084d0b, on origin/main 616405061), go1.26.8: - go test -count=1 -timeout 45m on Linux (wsl-run) of internal/gateway, internal/redact, internal/provider and internal/plugin (this batch's packages and those main changed since the full run): all ok. gofmt -l clean; go vet ./... (darwin), GOOS=linux and GOOS=windows go vet -tags nogui ./... clean. internal/gui on macOS (mote-run): TestSettingsSaveKeepsWhatItDoesNotSend (#4514) and TestMainWindowCorners (#3949), both red at main too. - The full go test ./... -timeout 45m -count=1 ran one rebase earlier, at tree 66a7a4c17 on origin/main 3a3bdb9f2 (main then gained 5bfa9f076's group stand-in, b19d08593, f856d381a and 616405061). It ran on Linux (wsl-run): 82 packages ok. internal/agent has 4 reds, all red at origin/main on that box as well: TestInstalledVersion, TestGrokInstalled, TestOmpDetectedWithPiDir and TestCopilotFolderFromAnIDEPluginIsNotTheCLI (#4033, #3548). The root package and internal/cli need gtk4 to build, so they ran on macOS (mote-run): ok. TestColdTurnsTaken (#4510) was red there once. An earlier full run at base d307aa648 was red once in TestUnroutedHeldReportSaved (#4300), which passes 5 of 5 alone at both the head and main. - Each landed patch's diff matches the head ggbdpq posted last on its issue (patch-id). - No GUI file is touched, so no GUI test file was run. Broken by hand: the cut-short path made to fall through to the old failure: TestPluginCutShortIsRetriedNotRested and TestPluginCutShortEveryMemberCutEndsTheTurn go red; restored, green. Not tried: a real plugin whose model cuts a text-form tool call short; the words matched are the plugin's own. Landing record (yetone): Run at tree 7d7955eb9 (this batch on origin/main 3cfba2e37), go1.26.8: - go test -count=1 -timeout 45m on Linux (wsl-run) of internal/gateway, internal/redact, internal/provider, internal/agent and internal/usage (this batch's packages, plus those main changed since the full run): all ok except internal/agent's TestInstalledVersion, TestGrokInstalled and TestOmpDetectedWithPiDir, red at origin/main on that box too (#4033, #3548). gofmt -l clean; go vet ./... (darwin), GOOS=linux and GOOS=windows go vet -tags nogui ./... clean. On macOS (mote-run), the root package and internal/cli ok; internal/gui red in TestSettingsSaveKeepsWhatItDoesNotSend (#4514), TestMainWindowCorners (#3949) and TestColdTurnsTaken (#4510), the first two red at main too. - The full go test ./... -timeout 45m -count=1 ran two rebases earlier, at tree 66a7a4c17 on origin/main 3a3bdb9f2, on Linux (wsl-run): 82 packages ok, internal/agent's 4 reds as above, plus TestCopilotFolderFromAnIDEPluginIsNotTheCLI (#4033, red at main). The root package, internal/cli and internal/gui need gtk4 to build, so they ran on macOS as above. An earlier full run at base d307aa648 was red once in TestUnroutedHeldReportSaved (#4300), which passes 5 of 5 alone at both the head and main. - Each landed patch's diff matches the head ggbdpq posted last on its issue (patch-id). - No GUI file is touched, so no GUI test file was run. - Rebased after these runs onto origin/main c1457f2ee. Its two commits since 3cfba2e37 (3f2faef62 gui, c1457f2ee agent) touch neither internal/gateway nor internal/redact, nor any file this batch changes, and were not run again here. Broken by hand: the cut-short path made to fall through to the old failure: TestPluginCutShortIsRetriedNotRested and TestPluginCutShortEveryMemberCutEndsTheTurn go red; restored, green. Not tried: a real plugin whose model cuts a text-form tool call short; the words matched are the plugin's own. Generated-by: GLM-5.3-Flash (ZCode) --- internal/gateway/continuation.go | 6 ++ internal/gateway/gateway.go | 25 +++++ internal/gateway/plugin_cutshort_test.go | 127 +++++++++++++++++++++++ internal/gateway/routing.go | 26 +++++ 4 files changed, 184 insertions(+) create mode 100644 internal/gateway/plugin_cutshort_test.go diff --git a/internal/gateway/continuation.go b/internal/gateway/continuation.go index 830b432a7..74f241da0 100644 --- a/internal/gateway/continuation.go +++ b/internal/gateway/continuation.go @@ -61,6 +61,12 @@ func emptyRetries(w http.ResponseWriter, ctx context.Context) int { // than ended with the loop's error. const loopReasks = 1 +// cutReasks is how many times a try a plugin ended on its upstream's +// stream dying mid-call (plugins#38) is asked again where it stood, before +// the next member is (#2873): the parser reads the same, the cut doesn't +// come again. +const cutReasks = 1 + // errStreamCut ends a reply's read once its error event is in hand, // without waiting on a vendor that keeps the connection open after it. var errStreamCut = errors.New("stream cut mid-reply") diff --git a/internal/gateway/gateway.go b/internal/gateway/gateway.go index 144f1742c..31c60b225 100644 --- a/internal/gateway/gateway.go +++ b/internal/gateway/gateway.go @@ -2765,6 +2765,9 @@ func (s *Server) serve(w http.ResponseWriter, r *http.Request, from provider.Pro // 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 + // the try whose plugin ended the turn on its upstream's stream dying + // mid-call (plugins#38), asked again where it stood (cutReasks, #2873) + cuts := 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 @@ -3892,6 +3895,28 @@ func (s *Server) serve(w http.ResponseWriter, r *http.Request, from provider.Pro skipped = append(skipped, c.label()+": "+call.Error) continue } + if !last && hw.failed() && failure(hw.code(), hw.errBody()) == failCut { + // a plugin ended the turn on purpose, its upstream's stream + // having died mid-call (plugins#38: "the gateway can retry or + // fail over"). Nobody rests: the parser reads the same but the + // cut doesn't come again, so the same one is asked again once, + // then the next member as any failure's is (#2873) + try.Fail = failCut + if other == nil { + other = &Try{Status: call.Status, Error: call.Error} + } + s.trace.update(tr, func(t *Route) { t.Tries[len(t.Tries)-1] = try }) + skipped = append(skipped, c.label()+": "+call.Error) + if cuts < cutReasks { + cuts++ + select { + case <-time.After(retryPause): + case <-r.Context().Done(): + } + i-- + } + continue + } if !last && hw.failed() { if f := failure(hw.code(), hw.errBody()); other == nil && f != failQuota && f != failCredit { other = &Try{Status: call.Status, Error: call.Error} diff --git a/internal/gateway/plugin_cutshort_test.go b/internal/gateway/plugin_cutshort_test.go new file mode 100644 index 000000000..a1ddf66bc --- /dev/null +++ b/internal/gateway/plugin_cutshort_test.go @@ -0,0 +1,127 @@ +package gateway + +import ( + "strings" + "testing" + + "github.com/yetone/magpie/internal/provider" +) + +// A plugin that reads a model's text-form tool calls ends a turn whose +// stream died mid-call as a failure, so the gateway retries or fails over +// (magpie-community/plugins#38, #2873): a 200 whose stream stops with an +// error event, the call it was reading unsent. The words are the +// contract's own, shared by the plugins that read text-form calls +// (packages/trae, packages/qoder's CUT_SHORT). +const cutShortSaid = "Trae CN: the model's tool call, written as text, was cut short; it is not sent on as the answer" + +var cutShortStream = sse( + `data: {"id":"c","object":"chat.completion.chunk","model":"m","choices":[{"index":0,"delta":{"role":"assistant","content":""}}]}`, + `data: {"error":{"message":"`+cutShortSaid+`","type":"api_error","code":null}}`, + `data: [DONE]`) + +func chatStreamSaid(said string) string { + return sse( + `data: {"id":"c","object":"chat.completion.chunk","model":"m","choices":[{"index":0,"delta":{"role":"assistant","content":"`+said+`"},"finish_reason":"stop"}]}`, + `data: [DONE]`) +} + +// A plugin account whose upstream cut the call short mid-stream is asked +// again — the parser reads the same, the cut doesn't come again — and its +// second answer is the reply; the next member isn't needed, and nobody +// rests: the account did nothing wrong a minute of backoff would mend +// (#2873: the routing record showed fail "other" and a 60s backoff, and +// the retry the plugin engineered never happened). +func TestPluginCutShortIsRetriedNotRested(t *testing.T) { + fresh(t) + a := &scripted{replies: []reply{ + {200, "text/event-stream", cutShortStream}, + {200, "text/event-stream", chatStreamSaid("from a")}, + }} + b := &scripted{replies: []reply{{200, "text/event-stream", chatStreamSaid("from b")}}} + scriptedOn(t, "a", provider.Chat, a) + scriptedOn(t, "b", provider.Chat, b) + if err := provider.SaveGroup(provider.Group{Name: "G", Members: []string{"a/m", "b/m"}, Routing: provider.Ordered}); err != nil { + t.Fatal(err) + } + s := New() + code, body := postAs(t, s, "", `{"model":"group/g","stream":true,"messages":[{"role":"user","content":"hi"}]}`) + if code != 200 || !strings.Contains(body, "from a") || strings.Contains(body, "from b") || a.n != 2 || b.n != 0 { + t.Fatalf("%d %s (a %d, b %d)", code, body, a.n, b.n) + } + r := s.trace.routes[len(s.trace.routes)-1] + if len(r.Tries) != 2 || r.Tries[0].Fail != failCut || r.Tries[0].Rest != nil || r.Tries[1].Status != 200 { + t.Fatalf("tries: %+v", r.Tries) + } + if s.resting("a") || s.resting("b") || len(routed.failures) != 0 { + t.Fatalf("a cut is nobody's fault: a resting %v, b %v, failures %v", s.resting("a"), s.resting("b"), routed.failures) + } + + // the next request finds the account as good as it was: asked first + // again, and answering + code, body = postAs(t, s, "", `{"model":"group/g","stream":true,"messages":[{"role":"user","content":"hi"}]}`) + if code != 200 || !strings.Contains(body, "from a") || b.n != 0 { + t.Fatalf("next request: %d %s (a %d, b %d)", code, body, a.n, b.n) + } +} + +// Every member's stream may cut, and the turn still ends: the same one is +// asked again once, the members after it as any failure's are, and the +// agent is told after the retries run out — with nobody resting, so the +// user's next attempt isn't met by a minute of backoff (#2873). +func TestPluginCutShortEveryMemberCutEndsTheTurn(t *testing.T) { + fresh(t) + a := &scripted{replies: []reply{{200, "text/event-stream", cutShortStream}}} + b := &scripted{replies: []reply{{200, "text/event-stream", cutShortStream}}} + scriptedOn(t, "a", provider.Chat, a) + scriptedOn(t, "b", provider.Chat, b) + if err := provider.SaveGroup(provider.Group{Name: "G", Members: []string{"a/m", "b/m"}, Routing: provider.Ordered}); err != nil { + t.Fatal(err) + } + s := New() + code, body := postAs(t, s, "", `{"model":"group/g","stream":true,"messages":[{"role":"user","content":"hi"}]}`) + // a streaming agent is told of the failure as its stream's error event + if code != 200 || !strings.Contains(body, "cut short") { + t.Fatalf("%d %s", code, body) + } + if a.n != 2 || b.n != 1+lastRetries { + t.Fatalf("a asked %d, b %d", a.n, b.n) + } + r := s.trace.routes[len(s.trace.routes)-1] + if s.resting("a") || s.resting("b") || len(routed.failures) != 0 { + t.Fatalf("nobody rests for a cut: a %v, b %v, failures %v", s.resting("a"), s.resting("b"), routed.failures) + } + for i, try := range r.Tries { + if try.Rest != nil { + t.Fatalf("try %d rested: %+v", i, try) + } + } +} + +// A plugin's other errors keep their own lanes: the contract's unreadable +// call (#2414), a model its vendor doesn't serve, a sign-in it turned +// away — none is a cut, and each rests or fails over as it did. +func TestPluginCutShortLeavesOtherErrorsAlone(t *testing.T) { + for _, x := range []struct { + status int + body string + want string + }{ + // the contract's UNREADABLE: the block is whole but can't be read + // — the model's doing, told apart from a stream that died + {502, `{"error":{"message":"Trae CN: the model's tool call, written as text, can't be read; it is not sent on as the answer","type":"api_error"}}`, failOther}, + // a plugin whose vendor doesn't serve the model asked for + {400, `{"error":{"message":"the model fake-x does not exist"}}`, failOther}, + // a sign-in its vendor turned away + {401, `{"error":{"message":"token expired"}}`, failOther}, + // the vendor's own cut-short words, a reply of its own kind + {502, `{"error":{"message":"upstream connect error"}}`, failOther}, + } { + if got := failure(x.status, []byte(x.body)); got != x.want { + t.Errorf("failure(%d, %s) = %s, want %s", x.status, x.body, got, x.want) + } + } + if got := failure(502, []byte(`{"error":{"message":"`+cutShortSaid+`"}}`)); got != failCut { + t.Errorf("the contract's cut-short error is %s, want %s", got, failCut) + } +} diff --git a/internal/gateway/routing.go b/internal/gateway/routing.go index 9001e28d1..1a71e36cd 100644 --- a/internal/gateway/routing.go +++ b/internal/gateway/routing.go @@ -350,6 +350,13 @@ var ( // RESOURCE_EXHAUSTED. A 5xx's words don't: a relay's 500 "当前模型 … // 负载已经达到上限,请稍后重试" is its load's limit, not the plan's (#1418). quotaCodes = regexp.MustCompile(`(?i)limit reached\|\d{10}\b|usage_limit_reached|RESOURCE_EXHAUSTED`) + // cutWords: a plugin's own error for the turn its upstream's stream + // died mid-call: the model wrote its tool call as text, the text + // stopped before the call was whole, and the plugin ends the turn as a + // failure "the gateway can retry or fail over" — its words, shared by + // the plugins that read text-form calls (magpie-community/plugins#38, + // packages/trae and packages/qoder's CUT_SHORT; #2873) + cutWords = regexp.MustCompile(`(?i)tool call, written as text, was cut short`) ) // Why a candidate failed, as rest tells it. @@ -416,6 +423,12 @@ const ( // 403 11140, "账号存在异常行为,已被限制使用", #1849) — the next is // asked, and it rests restrictedRest, until the vendor lifts it failRestricted = "restricted" + // failCut: a plugin ended the turn on purpose — its upstream's stream + // died mid-call, and the tool call it was reading, written as text, + // can't go on as the answer (plugins#38: the turn ends as an error + // "the gateway can retry or fail over"). The cut isn't the account's + // doing: the request is asked again, and nobody rests (#2873) + failCut = "cut" ) // loopErrType is the usage log's ErrType for a reply ended for looping @@ -467,6 +480,13 @@ func failure(status int, body []byte) string { // the words are matched decoded, too body = wordsOf(body) switch { + case cutWords.Match(body): + // a plugin ended the turn on purpose: its upstream's stream died + // mid-call, and the call it was reading isn't the answer + // (plugins#38). The cut is transient and nobody's fault — the next + // answer mostly isn't one — so the request is asked again, and + // nobody rests (#2873) + return failCut case restrictedSaid(status, body): return failRestricted case overflowed(status, body): @@ -1137,6 +1157,12 @@ func (s *Server) restAfterMarked(c candidate, status int, header http.Header, bo now := time.Now() d := fallbackCooldown why := failureOf(c, status, body) + if why == failCut { + // a plugin ended the turn on purpose, its upstream's stream having + // died mid-call (plugins#38): the account is as good as it was, the + // request is asked again, and no rest and no failure counted (#2873) + return Rest{Why: why, Status: status, By: "off", Until: now} + } if header.Get(zdrHeader) != "" || zdrRefused(status, body) { // Command Code's Zero Data Retention setting refused the request: // the model and the account are as good as they were, and answer