From f2b0780fa29fc9ff5692af8e22cd48e73c648d44 Mon Sep 17 00:00:00 2001 From: yetone Date: Tue, 13 Oct 2026 16:14:23 +0800 Subject: [PATCH] gateway: a held rule fails over within the member it chose, and a fallback outside it isn't kept for the turn (#1946, XcodeFish) A group of coding-fast and coding-quality, its rule sending turns to coding-quality: when coding-quality's member failed mid-turn the request went to coding-fast's members before coding-quality's other one, and the turn then stayed on coding-fast. Within a turn the rule is held, and when affinity kept a member the rule's order wasn't applied at all (gateway.go and nestedRules skipped `hit.Held && aff.Kept`), so the failover order was the kept one, then the parent's own order. ruleOver (rules.go), used at the group's rule and every nested group's: - the kept one stays first while it is of the rule's member that goes first (the one it names, or a Then's while that is resting); the rule's other members follow it, ahead of the group's others; - one kept outside that member, which took over when it failed, isn't held: once a member of the rule's target is out of its rest, the next request of the turn goes back to it (Affinity.Why "rule"). While all of it rests, the fallback stays. No new option. docs/subsystems/gateway-routing.md says so. Run (before the rebase onto origin/main): go test -tags nogui -count=1 ./internal/gateway/: green but for TestKimiHeldBurstTellsNoSpeed at load average ~139 (passes 3 of 3 alone; filed as #1963, not on this path), gofmt -l, GOOS=linux and GOOS=windows go vet -tags nogui ./internal/gateway/. TestHeldRuleFailsOverWithinItsMember fails on the old code (tried [kq1 kf1], the reporter's order), and with the go-back part disabled by hand (round 3 kept on f1). After the rebase: gofmt, both vets, and go test -run 'Rule|Group|Affin|Nested|Stick|Turn|Classif|Decide|Pause' ./internal/gateway/ green. --- docs/subsystems/gateway-routing.md | 1 + internal/gateway/gateway.go | 13 +--- internal/gateway/rules.go | 68 +++++++++++++++-- internal/gateway/rules_failover_test.go | 97 +++++++++++++++++++++++++ 4 files changed, 163 insertions(+), 16 deletions(-) create mode 100644 internal/gateway/rules_failover_test.go diff --git a/docs/subsystems/gateway-routing.md b/docs/subsystems/gateway-routing.md index 4f6986f97..2a4d10a7a 100644 --- a/docs/subsystems/gateway-routing.md +++ b/docs/subsystems/gateway-routing.md @@ -58,6 +58,7 @@ foreign sealed history or repair ChatGPT's response protection. - A model set for Codex's subagents (`settings.CodexSubagentModel`, the Agents page's Codex "subagent model", willz on Discord) is put on a Codex subagent's request (`x-openai-subagent` read as `kind:collab_spawn`) before this check, whatever model its lead's `spawn_agent` asked for (`codexSubagentPick` in [`codex_subagent.go`](../../internal/gateway/codex_subagent.go)): in `codexBackend` for one of Codex's own bare models, which then goes through `serveAgent`, and in `serve` for any other. Any model magpie serves can be set (`provider.SetCodexSubagentModel`, #1633): a task handed as text (a lead magpie served on a chat provider, or multi-agent V1) is read by any model. A request carrying a task the ChatGPT backend sealed (`sealedTaskIn`: a sealed agent message that isn't a `MESSAGE`, which `withoutSealedMessages` leaves out) is put only on a ChatGPT account's model; set to another, the subagent stays on the model asked for, which the sealed gate below handles as with nothing set. When magpie doesn't serve the model set now, or a gateway key held to some models may not use it, the subagent goes on the model asked for too. The route trace keeps both models and the reason it stayed (`Route.Subagent`), and the Routing page's `kindWhy` says it. The lead's turns, titles and every other kind are never moved. - Rules and image inputs are handled here too. - A rule is decided as a user's turn begins and held for the rest of it (`ruleFor`, [`rules.go`](../../internal/gateway/rules.go)). What counts as the user's own words is one helper, `userWords`/`userSaid` in [`prompt.go`](../../internal/gateway/prompt.go), which the turn count (`turnIn`), the classifier's question (`userText`), the conversation's key (`firstWords`, in `ruleKey` and the affinity scope), Copilot's Auto (`lastUserText`) and the prompt breakdown's turns (`userSays`) all go by. It drops `` blocks (a `source=` attribute too) and any text that begins as an agent writes for the model alone: Codex's ``, ``, ``, ``, `` and `# AGENTS.md instructions for …`; Claude Code's and ZCode's ``, ``, agent lists ("Available agent types …", "New agent types are now available …"), TodoWrite and task-tool nudges and rewind notices; ZCode's ``; the Codex app's ``. The Codex app's context before `## My request (for Codex):` is dropped and what follows it kept (the `injected` list beside `agentsFor`). A user message with nothing of the user's in it (and no image or file) begins no turn: after an answer or a tool round it carries the turn on (`within`), so the turn's rule and stick hold and the classifier isn't asked; right after the user's words it leaves their turn as it began. The classifier is asked about the last user message that has words of the user's, only those words. `firstWords` hashes the words of the first user message that has any, so an instruction file or notice the agent changes beside them doesn't move the conversation to a new key and lose its stick mid-turn (#1826: ZCode's TodoWrite nudge classified as a new, harder turn, and three keys for one ZCode session). `TestTurnInSkipsWhatTheAgentPutIn`, `TestUserTextSkipsWhatTheAgentPutIn`, `TestFirstWordsAreWhatTheUserSaid`, `TestIntentHoldsPastWhatTheAgentPutIn`. + - A rule's members go first (`ruleOver`, `applyRule`): the member it names, then those the matching rules after it name (`ruleOrder`), each not resting, then the group's others to fail over to. That holds within the turn too, at the group's rule and at each nested group's (`nestedRules`): the one the turn stays on (affinity) stays first while it is of the rule's member that goes first, and the member's others follow it ahead of the group's others, so a failure fails over within the member the rule chose before going outside it. One the turn was kept on outside that member, which took over when the member failed, isn't held there: once one of the member is out of its rest, the turn's next request goes back to it (`Affinity.Why` `rule`). Before #1946 (XcodeFish) a held rule's order wasn't applied to a kept turn at all: a coding-quality member failing mid-turn failed over to coding-fast, the parent's first, and the turn stayed there. `TestHeldRuleFailsOverWithinItsMember`. - A classifier that can't say which kind a turn is (an error, no answer within `classifyTimeout`, an answer that isn't a number, or resting `classifyRest` after a failure) leaves a turn whose conversation had an intent, still one of this turn's, with that intent (`Classified.Fallback` is `previous`, its `Error` kept), so the turn goes where the turn before went rather than to the group's first member; with no intent before, no rule with an intent matches, as before. The Routing page says the turn kept it (`classWhy`). The turn's decision itself (`turnRules`) is kept in memory only: after a restart a turn under way waits for the next one and the stick holds it meanwhile. `TestIntentClassifierFailsKeepsThePreviousIntent`, `routing-intent-fallback.test.cjs`. - The classifier's requests are magpie's own (#1839). Asked in words, they go out with `RouterAgent`'s User-Agent (`magpie-router/1`), so their records' agent is magpie and `callKind` marks them `routing`; a decision model's (Jev, System One) record is written with `Kind: "routing"` too. They go to the same key or account as any other request and count in its totals, while `usage.Group.Own` (`Record.ByMagpie`: agent `magpie` or one of its `magpie-` User-Agents, with search's and image description's) says how many of an account's, key's or model's calls, tokens and cost were magpie's own. A classifier set to a subscription's model (`modelRef.Sub`, or a group whose first member is one) asks that subscription as every turn begins, twice when it picks both intent and effort in words; the Routing page says so beside it (`classifierSub` in `routing.js`). `TestIntentRoutesATurn`, `TestJevPicksTheIntent`, `TestSummaryCountsMagpiesOwnCallsApart`, `TestByMagpie`, `TestServedRefSaysASubscription`, `own-requests.test.cjs`. - A rule by folder (`Rule.Folders`, `folders=~/work/acme,~/oss`; Cario0x on X: routing by the project being worked on) matches when the folder the agent works in is one of them or inside one (`provider.FolderUnder`, [`rulefolder.go`](../../internal/provider/rulefolder.go)): at a path's boundary, so `/a/b` is not under `/a/bc`; `~` is the home folder; a Windows drive is one with its WSL mount (`C:\work` is `/mnt/c/work`) and a `\\wsl$\` or `\\wsl.localhost\` share is the distro's own path; case doesn't count on macOS and Windows, nor ever for a drive. A rule outside folders (`Rule.ExceptFolders`, `except-folders=~/big-task`; #1606, Ti800) matches when the folder is in none of them, and an agent that says none isn't known to be in one, so it matches; a rule may have both (`Rule.ByFolder`, `inFolders`). The folder is read from the request only when a rule of the group has folders or except-folders (`workDir` in [`workdir.go`](../../internal/gateway/workdir.go)), in each agent's own words, taken from captured requests: Claude Code's ` - Primary working directory: ` (its `<`/`>` as entities; ` (was )` after a change dropped), Codex's `` ``, Pi's `` in the system prompt, and OpenCode's `Working directory:` inside its `` block. Only the system prompt and the user's and system messages' text count, never the model's words or a tool's result, and the last said wins. An agent that says none has no folder, and no `folders=` rule matches it (unknown, never empty). The same reading tells a plugin's fetch where its agent works ([provider-plugins](provider-plugins.md#where-the-agent-works-for-a-plugins-fetch)). A pause rule may hold by folder too (below). The trace's `RuleHit.Folder` is the folder read, and the Routing page tells it beside the rule's `folder …` condition. `TestFolderUnder`, `TestRuleMatchesByFolder`, `TestParseRuleFolders`, `TestWorkDirOfEachAgent`, `TestRuleByFolder`, `TestRuleMatchesExceptFolders`, `routing-folder.test.cjs`. Rules by folder are never in a shared group (`ShareGroup` drops every `ByFolder` rule). diff --git a/internal/gateway/gateway.go b/internal/gateway/gateway.go index a083d2629..f1e64636e 100644 --- a/internal/gateway/gateway.go +++ b/internal/gateway/gateway.go @@ -1808,16 +1808,11 @@ func (s *Server) serve(w http.ResponseWriter, r *http.Request, from provider.Pro } cands, pl, leadAccount = leadFirst(leadScope, parent, cands, pl) } - if hit != nil && hit.Use != "" && !(hit.Held && aff.Kept) { + if hit != nil && hit.Use != "" { // the rule's member first, over whoever answered last, as a turn - // begins; within it, whoever answered last stays — the rule's - // member, or who took over when it failed - was := cands[0] - var ok bool - cands, pl, ok = applyRule(hit, ms, cands, pl) - if ok && aff.Kept && cands[0].rest != was.rest { - aff.Kept, aff.Why = false, "rule" - } + // begins; within it, whoever answered last stays while it is of + // the rule's member, the member's others behind it (#1946) + cands, pl = ruleOver(hit, ms, cands, pl, aff) } // the rules of the groups in the group, down the one that goes first var nested []NestedRule diff --git a/internal/gateway/rules.go b/internal/gateway/rules.go index 082ad0d64..0442d6e74 100644 --- a/internal/gateway/rules.go +++ b/internal/gateway/rules.go @@ -449,15 +449,10 @@ func (s *Server) nestedRules(at string, req *Request, agent string, ask classifi h := ruleFor(at, sub, subMs, req, agent, ask) keys = append(keys, at) out = append(out, NestedRule{Group: sub.ID, Name: sub.Name, Rule: h}) - if h == nil || h.Use == "" || h.Held && aff != nil && aff.Kept { + if h == nil || h.Use == "" { continue } - was := cands[0] - var ok bool - cands, pl, ok = applyRule(h, subMs, cands, pl) - if ok && aff != nil && aff.Kept && cands[0].rest != was.rest { - aff.Kept, aff.Why = false, "rule" - } + cands, pl = ruleOver(h, subMs, cands, pl, aff) } return out, keys, cands, pl } @@ -553,6 +548,65 @@ func ruleFirst(ms []provider.Member, cs []candidate, pl planned) (out []candidat return out, pl, lead } +// ruleOver puts a rule's members first, over whoever answered the +// conversation last as a turn begins. Within the turn the rule held (#1946), +// the one the turn stays on stays first while it is of the rule's member +// that goes first — the one it names or, that resting, the one a rule after +// it does — and the rule's other members follow it, ahead of the group's +// others, so a failure fails over within the member the rule chose before +// going outside it. One kept outside it, which took over when it failed, +// isn't held there: the turn goes back to the rule's member once one of it +// is ready again, its rest over. +func ruleOver(hit *RuleHit, ms []provider.Member, cs []candidate, pl planned, aff *Affinity) ([]candidate, planned) { + kept := aff != nil && aff.Kept + if hit.Held && kept && len(cs) > 1 { + ordered := ruleOrder(hit, ms) + place := func(i int) int { // which of the rule's members cs[i] is of: 0 its own, then the Then's + for _, m := range ordered { + if !ofMember(cs[i], m) { + continue + } + if named(m, hit.Use) { + return 0 + } + for j, id := range hit.Then { + if named(m, id) { + return j + 1 + } + } + } + return -1 + } + best := -1 + for i := range cs { + if p := place(i); p >= 0 && pl.order[i].Rest == nil && (best < 0 || p < best) { + best = p + } + } + if p := place(0); best < 0 || p == best { + // it stays: the rule's members after it, then the group's + sub := pl + sub.order = pl.order[1:] + rest, sub, _ := ruleFirst(ordered, cs[1:], sub) + cs = append([]candidate{cs[0]}, rest...) + pl.order = append([]Weighed{pl.order[0]}, sub.order...) + if p >= 0 { + hit.Unready = p > 0 + if p > 0 { + hit.Instead = hit.Then[p-1] + } + } + return cs, pl + } + } + was := cs[0] + cs, pl, ok := applyRule(hit, ms, cs, pl) + if ok && kept && cs[0].rest != was.rest { + aff.Kept, aff.Why = false, "rule" + } + return cs, pl +} + // applyRule puts a rule's members first (ruleOrder) and says in the hit // whether the one it names leads; it reports whether any of them was ready. func applyRule(hit *RuleHit, ms []provider.Member, cs []candidate, pl planned) ([]candidate, planned, bool) { diff --git a/internal/gateway/rules_failover_test.go b/internal/gateway/rules_failover_test.go new file mode 100644 index 000000000..90d4c3222 --- /dev/null +++ b/internal/gateway/rules_failover_test.go @@ -0,0 +1,97 @@ +package gateway + +import ( + "strings" + "testing" + + "github.com/yetone/magpie/internal/provider" +) + +// #1946 (XcodeFish): a group of two groups, coding-fast and +// coding-quality, its rule sending every turn to coding-quality. When +// coding-quality's member failed mid-turn, the request went to coding-fast +// before coding-quality's other member, and the turn stayed there: the +// rule held for the turn, the one the turn stayed on was kept whoever it +// was, and the rule's order wasn't applied at all. +func TestHeldRuleFailsOverWithinItsMember(t *testing.T) { + fresh(t) + k := &keyed{fail: map[string]int{}} + for _, id := range []string{"f1", "f2", "q1", "q2"} { + serveOn(t, id, "k"+id, []string{"m"}, k) + } + for _, g := range []provider.Group{ + {Name: "Coding Fast", Members: []string{"f1/m", "f2/m"}, Routing: provider.Ordered}, + {Name: "Coding Quality", Members: []string{"q1/m", "q2/m"}, Routing: provider.Ordered}, + {Name: "Coding", Members: []string{"group/coding-fast", "group/coding-quality"}, Routing: provider.Ordered, + Rules: []provider.Rule{{Use: "group/coding-quality", Tokens: 1}}}, + } { + if err := provider.SaveGroup(g); err != nil { + t.Fatal(err) + } + } + s := New() + body := func(rounds int) string { + ms := []string{`{"role":"user","content":"fix the bug"}`} + for range rounds { + ms = append(ms, `{"role":"assistant","content":null,"tool_calls":[{"id":"c","type":"function","function":{"name":"ls","arguments":"{}"}}]}`, + `{"role":"tool","tool_call_id":"c","content":"file.txt"}`) + } + return `{"model":"group/coding","messages":[` + strings.Join(ms, ",") + `]}` + } + send := func(session string, rounds int, want string) Route { + t.Helper() + k.tried = nil + code, out := postAs(t, s, session, body(rounds)) + r := lastRoute(s) + if code != 200 || !strings.Contains(out, "from k"+want) { + t.Fatalf("%s round %d: %d %s, tried %v, affinity %+v", session, rounds, code, out, k.tried, r.Affinity) + } + return r + } + order := func(r Route) string { + var out []string + for _, w := range r.Order { + out = append(out, w.Provider) + } + return strings.Join(out, " ") + } + + // the turn begins on coding-quality + if r := send("one", 0, "q1"); order(r) != "q1 q2 f1 f2" { + t.Fatalf("turn start: %s", order(r)) + } + // q1 fails in a tool round: q2, coding-quality's other, takes it + k.fail["kq1"] = 500 + r := send("one", 1, "q2") + if strings.Join(k.tried, " ") != "kq1 kq2" || !r.Rule.Held || r.Rule.Unready { + t.Fatalf("failover: tried %v order %s rule %+v", k.tried, order(r), r.Rule) + } + // q2 is kept for the turn, q1 back or not: it is of the rule's member + delete(k.fail, "kq1") + s.UnrestAll("q1") + if r := send("one", 2, "q2"); !r.Affinity.Kept || r.Affinity.Why != "turn" || order(r) != "q2 q1 f1 f2" { + t.Fatalf("kept within the member: %s %+v", order(r), r.Affinity) + } + + // coding-quality failing whole, coding-fast answers the round + send("two", 0, "q1") + k.fail["kq1"], k.fail["kq2"] = 500, 500 + send("two", 1, "f1") + if strings.Join(k.tried, " ") != "kq1 kq2 kf1" { + t.Fatalf("tried %v", k.tried) + } + // both resting, the turn stays on f1 + delete(k.fail, "kq1") + delete(k.fail, "kq2") + if r := send("two", 2, "f1"); !r.Affinity.Kept { + t.Fatalf("resting: %s %+v", order(r), r.Affinity) + } + // their rests over, the turn goes back to coding-quality, not kept on + // the fallback + s.UnrestAll("q1") + s.UnrestAll("q2") + r = send("two", 3, "q1") + if r.Affinity.Kept || r.Affinity.Why != "rule" || order(r) != "q1 q2 f1 f2" || !r.Rule.Held { + t.Fatalf("back to the rule's member: %s %+v %+v", order(r), r.Affinity, r.Rule) + } +}