diff --git a/internal/gateway/effort_keep_test.go b/internal/gateway/effort_keep_test.go new file mode 100644 index 000000000..4d31d1a6b --- /dev/null +++ b/internal/gateway/effort_keep_test.go @@ -0,0 +1,125 @@ +package gateway + +import ( + "net/http/httptest" + "strings" + "testing" + "time" + + "github.com/yetone/magpie/internal/provider" +) + +// A group whose effort is auto keeps a conversation's reasoning from one +// turn to the next while the vendor's cache of it is warm (#617): a turn +// the decision model takes to be harder goes up, one it takes to be easier +// keeps the higher level (the trace shows the pick it wanted), its tool +// rounds with it, and once the conversation went unanswered past +// cacheCold the easier pick is taken. +func TestAutoEffortKeepsTheCache(t *testing.T) { + now := time.Date(2026, 10, 3, 17, 27, 0, 0, time.Local) + ruleClock = func() time.Time { return now } + t.Cleanup(func() { ruleClock = time.Now }) + s, a, _, j := jevved(t, provider.EffortAuto) + if err := provider.SetModelEfforts("a/small", []string{"low", "medium", "high", "xhigh"}); err != nil { + t.Fatal(err) + } + var said []string + turn := func(score float64, words string, tools int, wantPick, wantWanted, wantSent string) { + t.Helper() + j.score = score + if tools == 0 { + said = append(said, words) + } + _, r := postOK(t, s, "pi", chat(said[0], said[1:], tools, `,"reasoning_effort":"medium"`)) + sent := sentBody(t, a)["reasoning_effort"] + if r.Rule == nil || r.Rule.Pick != wantPick || r.Rule.Wanted != wantWanted || sent != wantSent { + t.Fatalf("%q (%d tool rounds): pick %+v, sent %v; want pick %q wanted %q sent %q", words, tools, r.Rule, sent, wantPick, wantWanted, wantSent) + } + } + turn(2, "add a retry to the fetcher", 0, "high", "", "high") + now = now.Add(30 * time.Second) + turn(3, "now it deadlocks under load, find out why", 0, "xhigh", "", "xhigh") // up: taken + now = now.Add(30 * time.Second) + turn(2, "rename the helper", 0, "xhigh", "high", "xhigh") // down: kept for the cache + now = now.Add(10 * time.Second) + turn(2, "rename the helper", 2, "xhigh", "high", "xhigh") // its tool rounds too + now = now.Add(cacheCold + time.Minute) + turn(1, "and the test name", 0, "medium", "", "medium") // the cache went cold: the pick is taken +} + +// Where an effort change goes as a configuration_update (Responses on a +// GPT-6 model through a ChatGPT account, MAGPIE_EFFORT_UPDATES=on), the +// easier pick isn't held back: the update carries it and the top-level +// effort, and the cache with it, stays the thread's first. +func TestAutoEffortGoesAsUpdate(t *testing.T) { + t.Setenv("MAGPIE_EFFORT_UPDATES", "on") + f := &fake{t: t, ctype: "none", reply: effortReply} + effortCodexAccount(t, f) + j := &jevUp{choice: noIntent, sure: 0.9} + srv := httptest.NewServer(j) + t.Cleanup(srv.Close) + if err := provider.Save(provider.Provider{ID: "ts", Name: "TypeSafe", Key: "kts", Decide: srv.URL + "/v1"}); err != nil { + t.Fatal(err) + } + if err := provider.SaveGroup(provider.Group{ID: "core", Name: "Core", Members: []string{"codex/gpt-6-luna"}, Effort: provider.EffortAuto, Classifier: "ts/jev-latest"}); err != nil { + t.Fatal(err) + } + if err := provider.SetModelEfforts("codex/gpt-6-luna", []string{"low", "medium", "high", "xhigh"}); err != nil { + t.Fatal(err) + } + s := New() + var said []string + for i, c := range []struct { + score float64 + words string + wantEffort string + wantInput string + wantWanted string + wantPicked string + }{ + {3, "find the deadlock", "xhigh", "user", "", "xhigh"}, + {2, "rename the helper", "xhigh", "user,assistant,u:high,user", "high", "xhigh"}, + } { + j.score = c.score + said = append(said, c.words) + body := strings.Replace(effortTurn("pi", "medium", said...), `"codex/gpt-6-luna"`, `"group/core"`, 1) + rec := httptest.NewRecorder() + s.Handler().ServeHTTP(rec, httptest.NewRequest("POST", "/v1/responses", strings.NewReader(body))) + if rec.Code != 200 { + t.Fatalf("turn %d: %d %s", i, rec.Code, rec.Body) + } + effort, _, input := sentShape(t, f.got) + r := lastRoute(s) + if effort != c.wantEffort || strings.Join(input, ",") != c.wantInput || r.Rule == nil || r.Rule.Pick != c.wantPicked || r.Rule.Wanted != c.wantWanted { + t.Fatalf("turn %d: sent %q %v, rule %+v", i, effort, input, r.Rule) + } + } +} + +// keepsEffort keeps a turn before's level only against a lower pick, while +// the cache is warm and the conversation wasn't compacted. +func TestKeepsEffort(t *testing.T) { + at := time.Date(2026, 10, 3, 19, 13, 0, 0, time.Local) + tr := turnRule{effort: "xhigh", at: at, size: 230_000} + for _, c := range []struct { + name string + tr turnRule + pick string + tokens int + now time.Time + want bool + }{ + {"lower, warm", tr, "high", 234_000, at.Add(33 * time.Second), true}, + {"higher", turnRule{effort: "medium", at: at}, "high", 1000, at.Add(time.Second), false}, + {"same", tr, "xhigh", 234_000, at.Add(time.Second), false}, + {"cold", tr, "high", 234_000, at.Add(cacheCold + time.Second), false}, + {"answered since: warm", turnRule{effort: "xhigh", at: at, answered: at.Add(4 * time.Minute)}, "low", 1000, at.Add(6 * time.Minute), true}, + {"compacted", tr, "high", 40_000, at.Add(time.Second), false}, + {"nothing before", turnRule{at: at}, "high", 1000, at.Add(time.Second), false}, + {"no pick", tr, "", 234_000, at.Add(time.Second), false}, + } { + if got := keepsEffort(c.tr, c.pick, c.tokens, c.now); got != c.want { + t.Errorf("%s: %v, want %v", c.name, got, c.want) + } + } +} diff --git a/internal/gateway/gateway.go b/internal/gateway/gateway.go index 7756ecf84..78c8f0560 100644 --- a/internal/gateway/gateway.go +++ b/internal/gateway/gateway.go @@ -1239,13 +1239,13 @@ func (s *Server) serve(w http.ResponseWriter, r *http.Request, from provider.Pro } // the effort a group's decision model picked for the turn: the // outermost group's that did - effort := "" + effort, wanted := "", "" if hit != nil { - effort = hit.Pick + effort, wanted = hit.Pick, hit.Wanted } for _, n := range nested { if effort == "" && n.Rule != nil { - effort = n.Rule.Pick + effort, wanted = n.Rule.Pick, n.Rule.Wanted } } // A vision rule may choose a vision model even when the group has @@ -1382,8 +1382,14 @@ func (s *Server) serve(w http.ResponseWriter, r *http.Request, from provider.Pro } else if effort != "" { // the level this model has nearest to the one picked; one whose // levels aren't known isn't asked for more than high, which - // every vendor with levels takes - if b := withEffort(from, attemptBody, fitLevel(withinLevels(effort, levels), c.p.Efforts(c.model))); !bytes.Equal(b, attemptBody) { + // every vendor with levels takes. The conversation kept a + // higher one for its cache (keepsEffort) unless an effort + // update carries the turn's own without losing it. + pick := effort + if wanted != "" && from == provider.Responses && plainFor != c.who()+"|"+c.model && takesEffortUpdates(c.p, c.model) { + pick = wanted + } + if b := withEffort(from, attemptBody, fitLevel(withinLevels(pick, levels), c.p.Efforts(c.model))); !bytes.Equal(b, attemptBody) { attemptBody, picked = b, true } } else if e := agentEffort(from, attemptBody); e != "" && e != "none" { diff --git a/internal/gateway/rules.go b/internal/gateway/rules.go index d094a1e7c..900c43f94 100644 --- a/internal/gateway/rules.go +++ b/internal/gateway/rules.go @@ -53,6 +53,11 @@ type RuleHit struct { // Pick: the reasoning the group's decision model picked for the turn, // which its requests ask their model for (provider.EffortAuto) Pick string `json:"pick,omitempty"` + // Wanted: the reasoning the decision model picked for the turn when + // the conversation kept a higher one (Pick) for the vendor's cache of + // it (#617) — sent instead where the change goes as an effort update + // that keeps the cache (takesEffortUpdates) + Wanted string `json:"wanted,omitempty"` // Compact: the request is the agent compacting its conversation, looked // at on its own; Small, the members of rules it matched that take less // than it is long, passed over @@ -88,6 +93,11 @@ type turnRule struct { // intent is what the classifier said the turn's first message is intent string effort string // the reasoning it picked for the turn + wanted string // what it would have picked, kept from (RuleHit.Wanted) + // answered is when the vendor last answered the conversation: its + // cache of it is read from then (ruleAnswered) + answered time.Time + size int // how long magpie took the conversation's last request to be (estimate) } var turnRules = struct { @@ -136,7 +146,8 @@ func ruleFor(key string, g provider.Group, ms []provider.Member, req *Request, a } turn, within := turnIn(req) now := ruleClock() - q := provider.RuleRequest{Tokens: estimate(req), Thinking: req.Thinking, Effort: req.Effort, Agent: agent, At: now} + size := estimate(req) + q := provider.RuleRequest{Tokens: size, Thinking: req.Thinking, Effort: req.Effort, Agent: agent, At: now} for _, m := range req.Messages { if slices.ContainsFunc(m.Parts, func(p Part) bool { return p.Kind == Image }) { q.Images = true @@ -203,16 +214,16 @@ func ruleFor(key string, g provider.Group, ms []provider.Member, req *Request, a hit.Waits = true } if !hit.Waits && hit.Effort != "" { - hit.Pick = tr.effort + hit.Pick, hit.Wanted = tr.effort, tr.wanted } if grown, ok := outgrown(g, ctx, hit, q); ok { hit = grown - turnRules.m[key] = turnRule{turn: turn, use: hit.Use, n: hit.N, at: now, input: tr.input, intent: q.Intent, effort: tr.effort} + turnRules.m[key] = turnRule{turn: turn, use: hit.Use, n: hit.N, at: now, input: tr.input, intent: q.Intent, effort: tr.effort, wanted: tr.wanted, answered: tr.answered, size: size} return hit } if had { if cur, ok := turnRules.m[key]; ok { - cur.at = now + cur.at, cur.size = now, size turnRules.m[key] = cur } } @@ -257,17 +268,20 @@ func ruleFor(key string, g provider.Group, ms []provider.Member, req *Request, a } q.Intent = c.Intent hit.Classified, hit.Pick = c, c.Effort + if effort && had && keepsEffort(tr, c.Effort, size, now) { + hit.Pick, hit.Wanted = tr.effort, c.Effort + } } if i := provider.MatchRule(g.Rules, q); i >= 0 { hit.N, hit.Use, hit.When = i+1, g.Rules[i].Use, g.Rules[i].Conditions() } turnRules.Lock() defer turnRules.Unlock() - input := tr.input + input, answered := tr.input, tr.answered if cur, ok := turnRules.m[key]; ok { - input = cur.input // answered while the classifier was asked + input, answered = cur.input, cur.answered // answered while the classifier was asked } - turnRules.m[key] = turnRule{turn: turn, use: hit.Use, n: hit.N, at: now, input: input, intent: q.Intent, effort: hit.Pick} + turnRules.m[key] = turnRule{turn: turn, use: hit.Use, n: hit.N, at: now, input: input, intent: q.Intent, effort: hit.Pick, wanted: hit.Wanted, answered: answered, size: size} if len(turnRules.m) > 4096 { for k, tr := range turnRules.m { if now.Sub(tr.at) > stickKeep { @@ -340,11 +354,42 @@ func ruleAnswered(key string, u Usage) { turnRules.Lock() defer turnRules.Unlock() if tr, ok := turnRules.m[key]; ok { - tr.input = n + tr.input, tr.answered = n, ruleClock() turnRules.m[key] = tr } } +// keepsEffort is whether a new turn of a conversation keeps the reasoning +// its turn before was asked for, rather than the lower one the decision +// model picked now (#617). The reasoning is part of what the vendor caches +// a conversation under: a turn asking for another reads none of it back — +// with group effort "auto", 40 of 42 changes between a Pi session's turns +// on gpt-6.1-sol read 0 cached tokens, against 4 of 834 without one. So +// while the cache is warm the effort only goes up — a hard turn still gets +// the reasoning it needs, and a conversation pays for at most one miss per +// level — and a lower pick waits for a turn the cache is lost to anyway: +// one after cacheCold without an answer, or after the agent compacted the +// conversation (it is now under half as long as its last request). +func keepsEffort(tr turnRule, pick string, tokens int, now time.Time) bool { + if tr.effort == "" || pick == "" || pick == tr.effort { + return false + } + if slices.Index(effortRank, pick) > slices.Index(effortRank, tr.effort) { + return false // up: the turn wants more than the conversation had + } + last := tr.at + if tr.answered.After(last) { + last = tr.answered + } + if now.Sub(last) > cacheCold { + return false + } + if tr.size > 0 && tokens < tr.size/2 { + return false + } + return true +} + // nestedRules looks at the rules of each group in the group that the one // going first is of, outermost first: a group's rules pick among its own // members as the group's do, keeping what they decided for the turn by