gateway: requests that come together spread over a pool's accounts (#5242)

Moody-Sin and Tericerice (#5242, magpie 0.1.3072 on Linux): an
antigravity provider with three accounts and affinity turn sent four
requests at once all to one account, under In turn and By pace alike,
each request with its own X-Magpie-Session.

Cause:
- Nothing counted the requests in flight when a request was planned.
  Pace (internal/routes/strategies.go:348) goes by pace, wallet and
  Tokens, all of which move only once a reply ends; a key's lane counts
  a request only once its try starts, after planning. Requests that came
  together were planned on the same figures and all went to the first.
- In turn's next turn (affinity.go:685 "new-turn" → after(), :937) reads
  a stick that moves only when an answer comes back, so a burst of turns
  of conversations already answered all went to the one next account.
- conversationID (gateway.go:9160 on origin/main) ignored
  X-Magpie-Session, so callers that named their own sessions but opened
  alike were one conversation and kept together.

Fix:
- burst.go: burstSpread, called in serve once the candidates are planned
  (gateway.go:3013), counts each request on the account it goes to until
  it ends, and puts first, among the accounts routing would as soon pick
  (burstAlike: In turn any ready one; By pace a pace within a tenth, no
  wallet told apart, none near its cap; Least used within a point), the
  one with the fewest in flight. A kept conversation (session, turn's
  stick, strict), a pin, a lead's account, a checkpoint and a new
  conversation leastHeld spread are counted where they are, not moved.
  Fallbacks, reserved, aside, resting, held, barred and capped accounts,
  other routings (Smart, In order, ...) and a group in a group keep
  their order. In a group, a member routed its own way is alike only to
  its own provider's. The one step covers direct models, groups, plugin
  providers and a remote magpie.
- affinityID: the stick key (stickKey), a group rule's key (ruleKey) and
  the sealed lead's stick read X-Magpie-Session after an agent's own
  session header. conversationID, which Kilo and a plugin are sent as the
  conversation, is unchanged, so the caller's session never goes
  upstream.
- docs/subsystems/gateway-routing.md says both.

Not done: putting a markedly slower account behind by its TTFT. A first
token's wait goes with the prompt's size and the vendor's queue more than
with the account, so a small sample would move turns away from a fine
account and off its cache; it needs its own design.

Run (mote, mote-run):
- go test ./internal/gateway -run 'TestABurst|TestBurst|TestMagpieSession|
  Kilo|Sealed|Rule|Stick|Affinity|Conversation': ok
- go test ./internal/gateway ./internal/routes: ok (654s, 0.3s)
- GOOS=linux go vet -tags nogui ./..., GOOS=windows go vet ./...: ok; gofmt -l: clean
New tests (burst_spread_test.go): six at once over three keys, rotate
and pace × affinity turn/off/auto × x-session-id / X-Magpie-Session /
same body × fresh and warm; over a group of three providers and of one
provider's keys; behind a remote magpie; over a plugin's three accounts
(fake plugin, streaming); a kept session stays on one account; paces
{10, 9.5} spread and {10, 5} don't; three X-Magpie-Sessions in turn get
an account each under session affinity, and conversationID never
returns X-Magpie-Session.

On the old code every pace case went 6 of 6 to k1, and rotate's warm
cases 6 of 6 to the next account.

Broken by hand:
- reorder forced false: every pace case, rotate's warm cases, the group
  pace cases, the remote and the plugin tests red.
- !aff.Kept dropped: TestABurstKeepsAKeptConversation red
  (map[k1:2 k2:2 k3:2]).
- affinityID without X-Magpie-Session: TestMagpieSessionIsTheConversation
  red (map[k1:3]); the burst tests stay green, as the count covers them.

Not tried: real Antigravity accounts, a run on Linux, a real remote
magpie on another machine.
This commit is contained in:
yetone
2026-11-06 07:05:37 +08:00
parent 5ae0ed1ab0
commit a754660b2a
6 changed files with 579 additions and 4 deletions
File diff suppressed because one or more lines are too long
+1 -1
View File
@@ -522,7 +522,7 @@ func strictOnly(cs []candidate, pl planned, at int) ([]candidate, planned) {
// the session's as before, so what is kept of it, and Codex's leadFirst,
// which reads a lead's stick by its thread id, are as they were.
func stickKey(scope string, in http.Header, body []byte) string {
key := scope + "|" + conversationID(in, body)
key := scope + "|" + affinityID(in, body)
if sub := subOf(in); sub != "" {
key += "|agent:" + sub
}
+144
View File
@@ -0,0 +1,144 @@
package gateway
import (
"math"
"slices"
"strings"
"sync"
"github.com/yetone/magpie/internal/provider"
)
// inFlight counts, for each key or account (candidate.who), the requests
// routed to it that haven't ended. Routing weighs what each has served
// (Tokens) and its allowance, both of which move only once a reply ends,
// and a key's lane counts a request only once its try begins: requests
// that came together were all planned on the same figures and all went to
// the one first (#5242, Moody-Sin and Tericerice: four at once to one of
// three Antigravity accounts, In turn and By pace alike).
var inFlight = struct {
sync.Mutex
m map[string]int
}{m: map[string]int{}}
// burstSpread puts first, of those alike to cs[0] under routing (burstAlike),
// the one with the fewest requests in flight, the order kept between those
// with as few, and counts the request on whichever is first then, in one
// hold of the count, so requests planned at the same moment each see the
// ones before them. The count is given back by the func it returns, when
// the request ends. reorder false counts it where it is: a conversation
// kept on its account, a request pinned to one, a new conversation that
// leastHeld spread. sameMember keeps a group's rule's member first.
func burstSpread(routing string, g *provider.Group, sameMember, reorder bool, cs []candidate, pl planned) ([]candidate, planned, func()) {
if len(cs) == 0 {
return cs, pl, func() {}
}
inFlight.Lock()
defer inFlight.Unlock()
if reorder && len(cs) > 1 && len(pl.order) >= len(cs) {
best := 0
for i := 1; i < len(cs); i++ {
if burstAlike(routing, g, sameMember, cs, pl.order, i) && inFlight.m[cs[i].who()] < inFlight.m[cs[best].who()] {
best = i
}
}
if best > 0 {
cs = append(append([]candidate{cs[best]}, cs[:best]...), cs[best+1:]...)
pl.order = append(append([]Weighed{pl.order[best]}, pl.order[:best]...), pl.order[best+1:]...)
if routingOf(routing) == provider.Rotate {
for j := range pl.order {
pl.order[j].Turn = j == 0
}
}
}
}
who := cs[0].who()
inFlight.m[who]++
var once sync.Once
return cs, pl, func() {
once.Do(func() {
inFlight.Lock()
if inFlight.m[who]--; inFlight.m[who] <= 0 {
delete(inFlight.m, who)
}
inFlight.Unlock()
})
}
}
// burstAlike says whether cs[i] is one routing would as soon send the
// request to as cs[0]: ready as cs[0] is, on the same footing (a fallback
// as a fallback, a key fit for the protocol as well, through the same
// remote magpie), and alike by what its routing goes by — any of a round
// In turn; By pace, both on a pace alike within a tenth with no wallet
// told apart and neither near its cap; Least used, used within a point.
// Other routings pick for their own reasons and keep their order. In a
// group, one of a provider routed its own way is alike only to its own
// provider's, by its provider's routing; a group in the group keeps its
// own order.
func burstAlike(routing string, g *provider.Group, sameMember bool, cs []candidate, order []Weighed, i int) bool {
a, b := order[0], order[i]
c0, ci := cs[0], cs[i]
if a.Rest != nil || a.Aside || a.Reserve > 0 || c0.capped != nil || ci.capped != nil {
return false
}
if b.Rest != nil || b.Aside || b.Reserve > 0 || b.Barred || b.Held || standsIn(order, i) || lastBehind(order, i) || busyBehind(order, i) {
return false
}
if a.Fallback != b.Fallback || a.Fit != b.Fit || a.Speaks != b.Speaks || c0.noURL != ci.noURL || !slices.Equal(a.Via, b.Via) {
return false
}
if sameMember && c0.member != ci.member {
return false
}
if g != nil {
if strings.HasPrefix(c0.member, provider.GroupPrefix) || strings.HasPrefix(ci.member, provider.GroupPrefix) {
return false
}
if ownRouting(c0.p, *g) || ownRouting(ci.p, *g) {
if c0.p.ID != ci.p.ID {
return false
}
routing = c0.p.Routing
}
}
switch routingOf(routing) {
case provider.Rotate:
return true
case provider.Pace:
return a.Learns == b.Learns && burstTier(a) == 0 && burstTier(b) == 0 && paceAlike(a.Pace, b.Pace) && sameBalance(a, b)
case provider.LeastUsed:
return a.Known == b.Known && burstTier(a) == burstTier(b) && math.Abs(a.Used-b.Used) < 1 && sameBalance(a, b)
}
return false
}
// burstTier is routes.seatTier of a weighed seat: 0 with room, 1 near
// its cap, 2 all but used up; 0 for an account set to spend its credits
// first, and for a week alone that low.
func burstTier(w Weighed) int {
switch {
case w.CreditsFirst:
return 0
case w.Used >= usedShare:
return 2
case w.Used >= lowShare && !w.WeekLow:
return 1
}
return 0
}
// paceAlike says whether two paces are in a band of routes.Pace: within a
// tenth of each other, or neither one's (a key has none).
func paceAlike(a, b float64) bool {
hi, lo := max(a, b), min(a, b)
return hi <= 0 || lo >= 0.9*hi
}
// sameBalance says whether two seats told the same of a wallet, or none.
func sameBalance(a, b Weighed) bool {
if a.Balance == nil || b.Balance == nil {
return a.Balance == nil && b.Balance == nil
}
return *a.Balance == *b.Balance
}
+400
View File
@@ -0,0 +1,400 @@
package gateway
import (
"context"
"encoding/json"
"fmt"
"io"
"net/http"
"net/http/httptest"
"os"
"path/filepath"
"slices"
"strings"
"sync"
"testing"
"time"
"github.com/yetone/magpie/internal/plugin"
"github.com/yetone/magpie/internal/provider"
"github.com/yetone/magpie/internal/routes"
"github.com/yetone/magpie/internal/testenv"
)
// #5242 (Moody-Sin, Tericerice): requests sent at the same moment to a
// provider with three accounts, routed to spread load, all went to one
// account, in turn and in pace, with affinity turn and off, and even when
// each request named a session of its own.
func TestABurstSpreadsOverAccounts(t *testing.T) {
const n = 6
for _, routing := range []string{provider.Rotate, provider.Pace} {
for _, aff := range []string{provider.AffinityTurn, provider.AffinityOff, ""} {
for _, how := range []string{"x-session-id", SessionHeader, "same body"} {
for _, warm := range []bool{false, true} {
t.Run(fmt.Sprintf("%s/%s/%s/warm=%v", routing, aff, how, warm), func(t *testing.T) {
fresh(t)
h := &held{want: n, all: make(chan struct{}), tried: map[string]int{}}
serveOn(t, "ag", "k1", []string{"m1"}, h, "k2", "k3")
if err := provider.SetRouting("ag", routing); err != nil {
t.Fatal(err)
}
if err := provider.SetAffinity("ag", aff); err != nil {
t.Fatal(err)
}
routes.Forget("ag")
s := New()
if warm {
// the reporters' rounds: the same request answered
// before, so its conversation is held on an account
h.want = 1
burstPost(t, s, how, 0)
h.mu.Lock()
h.want, h.in, h.all, h.tried = n, 0, make(chan struct{}), map[string]int{}
h.mu.Unlock()
}
var wg sync.WaitGroup
for i := range n {
wg.Add(1)
go func() {
defer wg.Done()
burstPost(t, s, how, i)
}()
}
wg.Wait()
h.mu.Lock()
defer h.mu.Unlock()
for _, k := range []string{"k1", "k2", "k3"} {
if h.tried[k] == 0 {
t.Errorf("%s got none of %d requests sent at once: %v", k, n, h.tried)
}
}
})
}
}
}
}
}
// burstPost sends the reporters' request: the same body every time, with a
// session of its own in a header, or none.
func burstPost(t *testing.T, s *Server, how string, i int) {
t.Helper()
rec := httptest.NewRecorder()
req := httptest.NewRequest("POST", "/v1/chat/completions", strings.NewReader(`{"model":"ag/m1","messages":[{"role":"user","content":"hi"}]}`))
if how != "same body" {
req.Header.Set(how, fmt.Sprintf("s-%d", i))
}
s.Handler().ServeHTTP(rec, req)
if rec.Code != 200 {
t.Errorf("%d %s", rec.Code, rec.Body.String())
}
}
// #5242 through a routing group: its members' keys weighed together, and
// a group of one provider's three keys, routed In turn and By pace.
func TestABurstSpreadsOverAGroup(t *testing.T) {
const n = 6
for _, routing := range []string{provider.Rotate, provider.Pace} {
for _, shape := range []string{"three providers", "one provider's keys"} {
t.Run(routing+"/"+shape, func(t *testing.T) {
fresh(t)
h := &held{want: n, all: make(chan struct{}), tried: map[string]int{}}
members := []string{"ag/m1"}
if shape == "three providers" {
serveOn(t, "pa", "k1", []string{"m1"}, h)
serveOn(t, "pb", "k2", []string{"m1"}, h)
serveOn(t, "pc", "k3", []string{"m1"}, h)
members = []string{"pa/m1", "pb/m1", "pc/m1"}
} else {
serveOn(t, "ag", "k1", []string{"m1"}, h, "k2", "k3")
}
if err := provider.SaveGroup(provider.Group{ID: "g", Name: "G", Members: members, Routing: routing, Affinity: provider.AffinityTurn}); err != nil {
t.Fatal(err)
}
s := New()
var wg sync.WaitGroup
for i := range n {
wg.Add(1)
go func() {
defer wg.Done()
rec := httptest.NewRecorder()
req := httptest.NewRequest("POST", "/v1/chat/completions", strings.NewReader(`{"model":"`+provider.GroupPrefix+`g","messages":[{"role":"user","content":"hi"}]}`))
req.Header.Set(SessionHeader, fmt.Sprintf("s-%d", i))
s.Handler().ServeHTTP(rec, req)
if rec.Code != 200 {
t.Errorf("%d %s", rec.Code, rec.Body.String())
}
}()
}
wg.Wait()
h.mu.Lock()
defer h.mu.Unlock()
for _, k := range []string{"k1", "k2", "k3"} {
if h.tried[k] == 0 {
t.Errorf("%s got none of %d requests sent at once: %v", k, n, h.tried)
}
}
})
}
}
}
// #5242 through a remote magpie: the sessions each request names go on
// to it, and it spreads them over its provider's keys.
func TestABurstSpreadsBehindARemoteMagpie(t *testing.T) {
const n = 6
fresh(t)
h := &held{want: n, all: make(chan struct{}), tried: map[string]int{}}
serveOn(t, "ag", "k1", []string{"m1"}, h, "k2", "k3")
if err := provider.SetRouting("ag", provider.Pace); err != nil {
t.Fatal(err)
}
if err := provider.SetAffinity("ag", provider.AffinityTurn); err != nil {
t.Fatal(err)
}
there := New().Handler()
remote := httptest.NewServer(there)
t.Cleanup(remote.Close)
if err := provider.Save(provider.Provider{ID: "office", Name: "Office", Preset: provider.RemoteMagpiePreset, Key: "rk", Models: []string{"ag/m1"},
Chat: remote.URL + "/v1", Responses: remote.URL + "/v1", Anthropic: remote.URL}); err != nil {
t.Fatal(err)
}
s := New()
var wg sync.WaitGroup
for i := range n {
wg.Add(1)
go func() {
defer wg.Done()
rec := httptest.NewRecorder()
req := httptest.NewRequest("POST", "/v1/chat/completions", strings.NewReader(`{"model":"office/ag/m1","messages":[{"role":"user","content":"hi"}]}`))
req.Header.Set(SessionHeader, fmt.Sprintf("s-%d", i))
s.Handler().ServeHTTP(rec, req)
if rec.Code != 200 {
t.Errorf("%d %s", rec.Code, rec.Body.String())
}
}()
}
wg.Wait()
h.mu.Lock()
defer h.mu.Unlock()
for _, k := range []string{"k1", "k2", "k3"} {
if h.tried[k] == 0 {
t.Errorf("%s got none of %d requests sent at once: %v", k, n, h.tried)
}
}
}
// #5242 for a provider a plugin serves: three accounts of the fake plugin
// (as Factory) through a real plugin host, By pace, sent six at once.
func TestABurstSpreadsOverAPluginsAccounts(t *testing.T) {
const n = 6
bun := testenv.Bun(t)
fresh(t)
t.Setenv("MAGPIE_BUN", bun)
t.Setenv("FAKE_ID", "factory")
t.Cleanup(plugin.Settle)
h := &held{want: n, all: make(chan struct{}), tried: map[string]int{}}
up := testenv.FakeVendor(t, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
io.ReadAll(r.Body)
who := strings.TrimPrefix(r.Header.Get("Authorization"), "Bearer fresh-r-")
h.mu.Lock()
h.tried[who]++
if h.in++; h.in == h.want {
close(h.all)
}
h.mu.Unlock()
select {
case <-h.all:
case <-time.After(5 * time.Second):
}
w.Header().Set("Content-Type", "text/event-stream")
fmt.Fprint(w, `data: {"id":"c","object":"chat.completion.chunk","model":"fake-1","choices":[{"index":0,"delta":{"role":"assistant","content":"ok"},"finish_reason":"stop"}]}`+"\n\n")
fmt.Fprint(w, "data: [DONE]\n\n")
}))
defer up.Close()
dir := filepath.Dir(provider.Path())
if err := os.MkdirAll(dir, 0o700); err != nil {
t.Fatal(err)
}
mig, _ := json.Marshal(map[string]any{"factory": map[string]any{"state": provider.MovePlugin}})
if err := os.WriteFile(filepath.Join(dir, "migrations.json"), mig, 0o600); err != nil {
t.Fatal(err)
}
ctx, cancel := context.WithTimeout(context.Background(), 2*time.Minute)
defer cancel()
abs, _ := filepath.Abs("../plugin/testdata/fake/index.js")
if _, err := plugin.Add(ctx, abs); err != nil {
t.Fatal(err)
}
if _, err := plugin.Providers(ctx); err != nil {
t.Fatal(err)
}
teams := []string{"a", "b", "c"}
for _, team := range teams {
st, err := provider.StartPluginSignIn("factory", 1, map[string]string{"where": "work", "team": team})
if err != nil {
t.Fatal(err)
}
if err := provider.SubmitSignInCallback(st.ID, "good"); err != nil {
t.Fatal(err)
}
}
if _, err := plugin.Providers(ctx); err != nil {
t.Fatal(err)
}
if ls := provider.Logins("factory"); len(ls) != len(teams) {
t.Fatalf("accounts %+v", ls)
}
for _, team := range teams {
if err := provider.SetLoginOn("factory", team+"@fake", true); err != nil {
t.Fatal(err)
}
}
if err := provider.SetRouting("factory", provider.Pace); err != nil {
t.Fatal(err)
}
if err := provider.SetAffinity("factory", provider.AffinityTurn); err != nil {
t.Fatal(err)
}
s := New()
var wg sync.WaitGroup
for i := range n {
wg.Add(1)
go func() {
defer wg.Done()
rec := httptest.NewRecorder()
req := httptest.NewRequest("POST", "/v1/chat/completions", strings.NewReader(`{"model":"factory/fake-1","stream":true,"messages":[{"role":"user","content":"hi"}]}`))
req.Header.Set(SessionHeader, fmt.Sprintf("s-%d", i))
s.Handler().ServeHTTP(rec, req)
if rec.Code != 200 {
t.Errorf("%d %s", rec.Code, rec.Body.String())
}
}()
}
wg.Wait()
h.mu.Lock()
defer h.mu.Unlock()
for _, team := range teams {
if h.tried[team] == 0 {
t.Errorf("%s@fake got none of %d requests sent at once: %v", team, n, h.tried)
}
}
}
// Spreading a burst leaves a conversation its affinity keeps where it is:
// one session, Stays: Session, answered once, then sent six at once.
func TestABurstKeepsAKeptConversation(t *testing.T) {
const n = 6
for _, routing := range []string{provider.Rotate, provider.Pace} {
t.Run(routing, func(t *testing.T) {
fresh(t)
h := &held{want: 1, all: make(chan struct{}), tried: map[string]int{}}
serveOn(t, "ag", "k1", []string{"m1"}, h, "k2", "k3")
if err := provider.SetRouting("ag", routing); err != nil {
t.Fatal(err)
}
if err := provider.SetAffinity("ag", provider.AffinitySession); err != nil {
t.Fatal(err)
}
s := New()
burstPost(t, s, SessionHeader, 0)
var first string
for k := range h.tried {
first = k
}
h.mu.Lock()
h.want, h.in, h.all, h.tried = n, 0, make(chan struct{}), map[string]int{}
h.mu.Unlock()
var wg sync.WaitGroup
for range n {
wg.Add(1)
go func() {
defer wg.Done()
burstPost(t, s, SessionHeader, 0)
}()
}
wg.Wait()
h.mu.Lock()
defer h.mu.Unlock()
if h.tried[first] != n {
t.Errorf("the session's %d requests left %s, the account it is kept on: %v", n, first, h.tried)
}
})
}
}
// By pace a burst goes on to another account only while its pace is alike
// (within a tenth): one with markedly more of its week left per hour
// takes them all, as pace says.
func TestBurstSpreadsOnlyOverAlikePaces(t *testing.T) {
cs := []candidate{{p: provider.Provider{ID: "ag", Key: "k1"}, rest: "ag#1"}, {p: provider.Provider{ID: "ag", Key: "k2"}, rest: "ag#2"}}
for _, tc := range []struct {
paces [2]float64
spread bool
}{{[2]float64{10, 9.5}, true}, {[2]float64{10, 5}, false}, {[2]float64{0, 0}, true}} {
inFlight.Lock()
inFlight.m = map[string]int{}
inFlight.Unlock()
pl := planned{order: []Weighed{{Pace: tc.paces[0]}, {Pace: tc.paces[1]}}}
var gone []string
var releases []func()
for range 2 {
got, _, release := burstSpread(provider.Pace, nil, false, true, slices.Clone(cs), pl)
gone, releases = append(gone, got[0].who()), append(releases, release)
}
for _, r := range releases {
r()
}
if spread := gone[0] != gone[1]; spread != tc.spread {
t.Errorf("paces %v: went to %v, spread %v, want %v", tc.paces, gone, spread, tc.spread)
}
inFlight.Lock()
left := len(inFlight.m)
inFlight.Unlock()
if left != 0 {
t.Errorf("%d still counted in flight after each ended", left)
}
}
}
// The session a caller names in X-Magpie-Session is its conversation's, as
// the agent's own session header is: two sessions that open alike are two
// conversations, the second not kept on the first's account (#5242's
// second run: each request named a session of its own, and every one was
// taken for the first's conversation by its first message).
func TestMagpieSessionIsTheConversation(t *testing.T) {
fresh(t)
h := &held{want: 1, all: make(chan struct{}), tried: map[string]int{}}
serveOn(t, "ag", "k1", []string{"m1"}, h, "k2", "k3")
if err := provider.SetRouting("ag", provider.Pace); err != nil {
t.Fatal(err)
}
if err := provider.SetAffinity("ag", provider.AffinitySession); err != nil {
t.Fatal(err)
}
s := New()
for i := range 3 {
burstPost(t, s, SessionHeader, i)
}
for _, k := range []string{"k1", "k2", "k3"} {
if h.tried[k] != 1 {
t.Errorf("three sessions, one after another, kept for the session: %v", h.tried)
break
}
}
// an agent's own session header still names it first
in := http.Header{}
in.Set(SessionHeader, "magpie-s")
in.Set("session_id", "agent-s")
if got := affinityID(in, nil); got != "agent-s" {
t.Errorf("conversation %q, want the agent's own agent-s", got)
}
// what a vendor or plugin is sent as the conversation never is the caller's
in.Del("session_id")
if got := conversationID(in, nil); got == "magpie-s" {
t.Errorf("conversationID %q: X-Magpie-Session would go upstream", got)
}
if got := affinityID(in, nil); got != "magpie-s" {
t.Errorf("affinityID %q, want magpie-s", got)
}
}
+31 -1
View File
@@ -2540,7 +2540,7 @@ func (s *Server) serve(w http.ResponseWriter, r *http.Request, from provider.Pro
}
conv := conversationID(r.Header, body)
sealedLead = leadProvider(scope, parent)
sealers = []string{sealedLead, leadProvider(scope, conv)}
sealers = []string{sealedLead, leadProvider(scope, affinityID(r.Header, body))}
readable := func() bool {
return isGroup && slices.ContainsFunc(ms, func(m provider.Member) bool { return s.sealedReader(m.Provider, m.Model, sealers) }) || !isGroup && s.sealedReader(p, model, sealers)
}
@@ -3000,6 +3000,18 @@ func (s *Server) serve(w http.ResponseWriter, r *http.Request, from provider.Pro
// grown conversation is refused again, and the member that answered
// is asked first (#3453)
cands, pl = behindOverflow(stuck, cands, pl, len(body))
// requests that came together go to as many keys or accounts as are
// alike for them, each counted where it goes until it ends (#5242);
// one kept, pinned, sealed to its account, or a new conversation
// leastHeld spread is counted where it is
poolRouting, poolGroup := p.Routing, (*provider.Group)(nil)
if isGroup {
poolRouting, poolGroup = g.Routing, &g
}
leastHeldIt := aff.Why == "first" && (rotate || spread)
reorder := !aff.Kept && aff.Why != "strict" && pin == "" && leadAccount == "" && checkpoint == nil && !leastHeldIt
cands, pl, unburst := burstSpread(poolRouting, poolGroup, hit != nil && hit.Use != "", reorder, cands, pl)
defer unburst()
// of those resting, only the one back soonest is asked (#1799); the
// whole list still finds a Codex account to spend a reset on
all := cands
@@ -9157,6 +9169,24 @@ func nativeSessionOf(in http.Header) string {
// (conversationOpening). One message is hashed as the request has it, as
// it always was; several are hashed as writeOpening reads them, so the
// cache mark an agent moves on from turn to turn doesn't move the id.
// affinityID is the conversation a turn's account is kept for: an agent's
// own session (conversationID), else the caller's X-Magpie-Session, else
// the conversation's hash. Two callers that send the same opening with
// their own X-Magpie-Session are two conversations (#5242). It is magpie's
// own key and never goes upstream: conversationID, which a vendor or a
// plugin is sent (Kilo, ConversationHeader), doesn't read X-Magpie-Session.
func affinityID(in http.Header, body []byte) string {
for _, h := range sessionHeaders {
if v := strings.TrimSpace(in.Get(h)); v != "" {
return v
}
}
if v := strings.TrimSpace(in.Get(SessionHeader)); v != "" {
return v
}
return conversationID(in, body)
}
func conversationID(in http.Header, body []byte) string {
for _, h := range sessionHeaders {
if v := strings.TrimSpace(in.Get(h)); v != "" {
+1 -1
View File
@@ -139,7 +139,7 @@ var turnRules = struct {
// ruleKey is the conversation a group's rules keep a turn's decision for:
// the agent's session and the conversation's first words (firstWords).
func ruleKey(g provider.Group, in http.Header, req *Request) string {
return provider.GroupPrefix + g.ID + "|" + conversationID(in, nil) + "|" + firstWords(req)
return provider.GroupPrefix + g.ID + "|" + affinityID(in, nil) + "|" + firstWords(req)
}
// firstWords tells an agent's subagents from it: they share its session