gateway: a waiting request goes to an account back from rest (01huadalang)

01huadalang on Discord (11-01): three ZCode accounts, three requests at
once each. The first two got a 405 and rested, so every request went to
the third, and those over its three waited in its lane. Once the first two
were back, the waiting ones stayed on the third, behind its long turns,
until its requests were cut by hand. Same under Smart, In turn and Stays
off.

Cause: a request that queued in a lane (lanes.take) waited only for that
lane's turn. Nothing looked again when another lane gave a slot back or a
rest ended. With ZCode's maxAccounts 2, the third took a seat while the
first two rested and was a reserve again once they were back, but the
requests already waiting for it stayed. laneMate also gave way to a mate
resting, because ready() checks only lane and RPM room.

Change:
- lanes.take takes a move func. While waiting (lanes.await), it looks
  again when any lane gives a slot back, when a rest is lifted (Unrest,
  UnrestAll signal lanes.freed), when the soonest rest among the others
  ends, and at least every 5s (laneRecheck). waitMate finds the first
  candidate after it in the planned order (then those probeOne left out
  for resting) of the same provider, or any member of a group, that has
  a free slot with no queue (tryTake), minute room, isn't resting, didn't
  give way, and isn't a reserve as keepAtOnce stands now. The request
  then leaves its queue (errMoved) and serve runs that candidate with the
  slot already taken for it. A fallback provider is never one. Strict
  stays leave no other candidate, so nothing changes there.
- laneMate skips resting mates.
- docs/subsystems/gateway-routing.md Limits row says so.

Tests:
- TestWaitingRequestGoesToAccountBackFromRest: 3 keys, cap 3, MaxAccounts
  2, k1 and k2 resting (405), 9 requests. 3 go to k3, 6 wait for it, and
  none reach the resting two. Then the rests are lifted (Unrest) or run
  out (300ms), and the six go to k1 and k2 while k3's three are still
  out (9 at once). Run under Smart and Rotate, with Stays default and
  off.
- TestWaitingRequestTakesSlotGivenBackElsewhere: 2 keys, cap 1. A third
  request waiting for one key goes to the other when that one's request
  ends, under default, order, rotate and usage routing.
- TestFullMemberGivesWay updated. c, waiting for first, now goes to second
  once second's b ends. d (first's fallback is second) still waits for
  first.

Run on mote (mote-run), rebased on e65bc8473:
- go test -count=1 -timeout 45m ./internal/gateway: every test ok
  except TestCodexPoolSaysTheClientsVersion (608s; #4807, below)
- go vet ./internal/gateway, GOOS=linux (-tags nogui), GOOS=windows: ok
- gofmt -l: clean
- go test -race -count=10 on the three tests above: ok
- That red is #4807, also the only red in an earlier full run (it passes alone,
  here and on origin/main e65bc8473; another test's Codex version reaches
  it).

Rebased again on 6b3a6d42c (VS Code agent host, gateway.go): at this
head, vet for darwin, linux and windows ok, gofmt clean, and go test -run
'Lane|Waiting|FullMember|AtOnce|VSCode|Vscode|AgentHost|Concurrency|
Queue|Rest|Probe|Affinity' ./internal/gateway ok (44s).

Broken by hand:
- On origin/main's code, the new tests and the updated
  TestFullMemberGivesWay are red. The rest test fails at "six waiting for
  k3" because laneMate handed requests to the resting keys.
- With waitMate's move ignored (if ok && false), every case is red at
  "the waiting ones at k1 and k2", and so is TestWaitingRequestTakesSlot-
  GivenBackElsewhere.
- With the rest's end ignored for the recheck timer (only laneRecheck),
  the four "ran out" cases are red.
- Two test races were found under -race and fixed in the test: the rest
  was timed from before the nine were sent, and the concurrency count was
  read before the ninth reached the fake vendor.

Not tried: real ZCode accounts or the ZCode plugin. The plugin's own 405
handling and maxAccounts are as before. Not run on Windows or Linux
machines; vet only.
This commit is contained in:
yetone
2026-11-02 04:17:24 +08:00
parent 6b3a6d42c0
commit 62ffc40169
6 changed files with 517 additions and 22 deletions
File diff suppressed because one or more lines are too long
+236 -14
View File
@@ -31,6 +31,48 @@ import (
type lanes struct {
mu sync.Mutex
m map[string]*lane
// freed is closed, and made afresh, each time a slot of any lane is
// given back or a rest is lifted (signal): a request waiting in one
// lane looks then for another with room (waitMate)
freed chan struct{}
}
// signalLocked wakes every request waiting in a lane to look for another
// with room. l.mu is held.
func (l *lanes) signalLocked() {
if l.freed != nil {
close(l.freed)
l.freed = nil
}
}
// signal is signalLocked, taking l.mu.
func (l *lanes) signal() {
l.mu.Lock()
l.signalLocked()
l.mu.Unlock()
}
// tryTake takes one of who's slots if one is free now and nobody waits
// for it: no limit, or room. false takes none.
func (l *lanes) tryTake(who string, limit int) (release func(), ok bool) {
l.mu.Lock()
defer l.mu.Unlock()
if l.m == nil {
l.m = map[string]*lane{}
}
ln := l.m[who]
if ln == nil {
ln = &lane{}
l.m[who] = ln
}
if limit > 0 && (ln.busy >= limit || len(ln.queue) > 0) {
l.drop(who, ln)
return nil, false
}
ln.limit = max(limit, 0)
ln.busy++
return l.releaser(who, ln), true
}
// lane is one key's or account's: how many are out, and who waits, first
@@ -53,11 +95,20 @@ type lane struct {
//
// A full one gives way first. Where the request has another key or
// account of the same provider, or another member of its routing group,
// with a slot free now, that one is asked first and the full one keeps its
// place after it (laneMate): a group spreads its requests over members
// with room before any waits. A fallback provider is never asked for want
// of a slot — it is another vendor, often a paid one — and a request whose
// keys and accounts are all full waits for the one routing chose.
// with a slot free now and not resting, that one is asked first and the
// full one keeps its place after it (laneMate): a group spreads its
// requests over members with room before any waits. A fallback provider is
// never asked for want of a slot — it is another vendor, often a paid one
// — and a request whose keys and accounts are all full waits in the queue
// of the one routing chose, but not for it alone: each time a slot of any
// lane is given back (lanes.freed), a rest of one of the others ends or is
// lifted, it looks again, and the first of the others in routing's order
// with a slot free, not resting and not held back as a reserve as its
// provider's accounts stand now (waitMate) takes it, its slot taken for
// it as it leaves the queue (errMoved). 01huadalang on Discord: three
// ZCode accounts at three at once, the first two resting after a 405; once
// they were back, the requests already waiting for the third waited on
// behind its long turns, in every routing, until its own were cut by hand.
// errQueueFull and errQueueWait turn a request away from a lane: its queue
// at its bound, or the request waited as long as it may.
@@ -66,12 +117,21 @@ var (
errQueueWait = errors.New("waited too long")
)
// errMoved is a request that left its lane's queue for another key or
// account with room (waitMate): nobody failed, and it is asked there.
var errMoved = errors.New("gave way to one with room")
// laneRecheck is how often a request waiting in a lane looks again for
// another with room with nothing given back meanwhile: a minute's room
// (MaxRPM) comes back with nothing said.
const laneRecheck = 5 * time.Second
// acquire waits for one of who's limit slots, in turn, with no bound on
// the queue or the wait. It answers the release, to call once the request
// is done with the vendor, and false with no slot taken when ctx ended
// first. A limit of 0 never waits; the request is only counted.
func (l *lanes) acquire(ctx context.Context, who string, limit int) (release func(), ok bool) {
release, _, err := l.take(ctx, who, limit, 0, 0)
release, _, err := l.take(ctx, who, limit, 0, 0, nil)
return release, err == nil
}
@@ -80,7 +140,11 @@ func (l *lanes) acquire(ctx context.Context, who string, limit int) (release fun
// error when it ended first, with no slot taken. waited is how long it
// stood in the queue: 0 when a slot was free at once or there is no
// limit, so a request that never queued never reads as queued (#2153).
func (l *lanes) take(ctx context.Context, who string, limit, queue int, wait time.Duration) (release func(), waited time.Duration, err error) {
// move, when not nil, is asked while it waits — at once, each time a slot
// of any lane is given back, at the time it names and every laneRecheck —
// whether the request goes to another key or account instead (waitMate,
// which takes that one's slot): true leaves the queue with errMoved.
func (l *lanes) take(ctx context.Context, who string, limit, queue int, wait time.Duration, move func() (bool, time.Time)) (release func(), waited time.Duration, err error) {
l.mu.Lock()
if l.m == nil {
l.m = map[string]*lane{}
@@ -122,13 +186,9 @@ func (l *lanes) take(ctx context.Context, who string, limit, queue int, wait tim
defer t.Stop()
timeout = t.C
}
select {
case <-ch:
err = l.await(ctx, ch, timeout, move)
if err == nil {
return l.releaser(who, ln), time.Since(queued), nil
case <-ctx.Done():
err = ctx.Err()
case <-timeout:
err = errQueueWait
}
waited = time.Since(queued)
l.mu.Lock()
@@ -144,9 +204,66 @@ func (l *lanes) take(ctx context.Context, who string, limit, queue int, wait tim
ln.busy--
ln.grant()
l.drop(who, ln)
l.signalLocked()
return nil, waited, err
}
// await waits for ch, the request's turn in its lane: nil then, else
// ctx's error, errQueueWait at timeout, or errMoved once move says it goes
// elsewhere.
func (l *lanes) await(ctx context.Context, ch chan struct{}, timeout <-chan time.Time, move func() (bool, time.Time)) error {
for {
var freed chan struct{}
var again <-chan time.Time
var t *time.Timer
if move != nil {
l.mu.Lock()
if l.freed == nil {
l.freed = make(chan struct{})
}
freed = l.freed
l.mu.Unlock()
select {
case <-ch:
return nil // its turn came first: it goes where it waited
default:
}
ok, next := move()
if ok {
return errMoved
}
d := laneRecheck
if !next.IsZero() {
d = min(d, max(time.Until(next), time.Millisecond))
}
t = time.NewTimer(d)
again = t.C
}
select {
case <-ch:
if t != nil {
t.Stop()
}
return nil
case <-ctx.Done():
if t != nil {
t.Stop()
}
return ctx.Err()
case <-timeout:
if t != nil {
t.Stop()
}
return errQueueWait
case <-freed:
case <-again:
}
if t != nil {
t.Stop()
}
}
}
// free says whether a request for who would be sent at once: no limit, or
// a slot free and nobody waiting for it.
func (l *lanes) free(who string, limit int) bool {
@@ -165,7 +282,10 @@ func (l *lanes) free(who string, limit int) bool {
// full, or has sent its MaxRPM in the last minute; -1 when it isn't
// full, gave way once already, or none has room. A reserve is never one
// (keepAtOnce): it is held back for its provider not to be used from more
// accounts at once than it lets be, and a full lane is not a failure.
// accounts at once than it lets be, and a full lane is not a failure. Nor
// is one resting: its lane is free because it is resting, and a request
// handed to it for want of a slot would only ask it again before its rest
// is out.
func (s *Server) laneMate(cands []candidate, i int, group bool, gave map[string]bool) int {
c := cands[i]
who := c.who()
@@ -177,6 +297,9 @@ func (s *Server) laneMate(cands []candidate, i int, group bool, gave map[string]
if m.who() == who || !group && m.p.ID != c.p.ID || m.reserve > 0 {
continue
}
if _, resting := restedUntil(m); resting {
continue
}
if s.ready(m) {
return j
}
@@ -184,6 +307,104 @@ func (s *Server) laneMate(cands []candidate, i int, group bool, gave map[string]
return -1
}
// restedUntil is when c's rest ends, and whether it rests now: its key's
// or account's, else its model's (restingOf, without reading a key's
// allowance again).
func restedUntil(c candidate) (time.Time, bool) {
r, ok := restOf(c.restKey())
if !ok && c.restID() != c.restKey() {
r, ok = restOf(c.restID())
}
return r.Until, ok
}
// waitMate is, for a request waiting in the full lane of cands[i], the
// first other candidate in routing's order that would take it now, with
// its slot taken for it (release): another key or account of cands[i]'s
// provider, or in a routing group any member, not tried yet by this
// request, not one that gave way (gave), not resting, with a slot free and
// room in its minute, and not held back as a reserve as its provider's
// accounts stand now (keepAtOnce over them as the rests are now, so a
// reserve that took a seat while the first rested gives it back once they
// are back). Those after i come first, then those of planned that probeOne
// left out for resting, back now. ok is false when none would; next is
// then when the soonest of those left out only for resting is back (zero
// for none), for the request to look again then. A fallback provider is
// never one, as with laneMate.
func (s *Server) waitMate(cands []candidate, i int, group bool, gave map[string]bool, planned []candidate) (mate candidate, release func(), next time.Time, ok bool) {
c := cands[i]
who := c.who()
seat := func(m candidate) string { return m.who() + "|" + m.model }
seen := map[string]bool{}
for _, m := range cands[:i+1] {
seen[seat(m)] = true
}
var pool []candidate
for _, m := range append(slices.Clone(cands[i+1:]), planned...) {
if !seen[seat(m)] {
seen[seat(m)] = true
pool = append(pool, m)
}
}
// the reserves of each provider of the pool with accounts at once, as
// its accounts' rests are now
reserves := map[string]map[string]bool{}
reserveNow := func(m candidate) bool {
k := m.p.ID + "|" + m.model
set, done := reserves[k]
if !done {
n := m.p.AtOnce()
if n > 0 {
var all []candidate
for _, o := range append(slices.Clone(cands), planned...) {
if o.p.ID == m.p.ID && o.model == m.model && !slices.ContainsFunc(all, func(a candidate) bool { return a.who() == o.who() }) {
all = append(all, o)
}
}
_, held := keepAtOnce(n, all, nil)
set = map[string]bool{}
for _, o := range held {
set[o.who()] = true
}
}
reserves[k] = set
}
return set[m.who()]
}
for _, m := range pool {
if m.who() == who || gave[m.who()] || !group && m.p.ID != c.p.ID {
continue
}
if until, resting := restedUntil(m); resting {
if next.IsZero() || until.Before(next) {
next = until
}
continue
}
if reserveNow(m) || !s.rpms.free(m.who(), m.p.RPMLimit()) {
continue
}
if rel, took := s.lanes.tryTake(m.who(), m.p.LaneLimit()); took {
m.reserve = 0
return m, rel, time.Time{}, true
}
}
return candidate{}, nil, next, false
}
// movedAhead is cands with m at i, ahead of the one there, which keeps its
// place after it, and m left out where it stood after i.
func movedAhead(cands []candidate, i int, m candidate) []candidate {
cs := slices.Clone(cands)
for j := i + 1; j < len(cs); j++ {
if cs[j].who() == m.who() && cs[j].model == m.model {
cs = slices.Delete(cs, j, j+1)
break
}
}
return slices.Insert(cs, i, m)
}
// dropReserves leaves out, of the candidates after i, the reserves of
// provider id (keepAtOnce).
func dropReserves(cands []candidate, i int, id string) []candidate {
@@ -219,6 +440,7 @@ func (l *lanes) releaser(who string, ln *lane) func() {
ln.busy--
ln.grant()
l.drop(who, ln)
l.signalLocked()
l.mu.Unlock()
})
}
+15 -4
View File
@@ -253,8 +253,10 @@ func TestLaneReleasedOnFailure(t *testing.T) {
}
// A full member of a routing group gives way to one with a slot free (no
// waiting while another member has room), while a provider's fallback is
// never asked for want of a slot: the request waits for its own.
// waiting while another member has room), and a request of the group
// waiting for one goes to another once that one has room again (waitMate),
// while a provider's fallback is never asked for want of a slot: the
// request waits for its own.
func TestFullMemberGivesWay(t *testing.T) {
fresh(t)
v1, up1 := slowUp(t)
@@ -292,11 +294,20 @@ func TestFullMemberGivesWay(t *testing.T) {
if r := g.reply(); r.tag != "b" || !strings.Contains(r.body, "from b") {
t.Fatalf("b = %+v", r)
}
time.Sleep(50 * time.Millisecond)
// second has room again: c, waiting for first, goes there (waitMate);
// d, which second is only the fallback of, waits on for first
within(t, "c at second", func() bool { return slices.Contains(v2.seen(), "c") })
if l := firstLane(); l.Waiting != 1 {
t.Fatalf("first's lane = %+v, want d alone waiting", l)
}
if slices.Contains(v2.seen(), "d") {
t.Fatal("d went to first's fallback for want of a slot")
}
for _, tag := range []string{"a", "c", "d"} {
close(v2.gate("c"))
if r := g.reply(); r.tag != "c" || !strings.Contains(r.body, "[DONE]") {
t.Fatalf("c = %+v", r)
}
for _, tag := range []string{"a", "d"} {
close(v1.gate(tag))
if r := g.reply(); r.tag != tag || !strings.Contains(r.body, "[DONE]") {
t.Fatalf("%s = %+v", tag, r)
+67 -3
View File
@@ -2811,7 +2811,20 @@ func (s *Server) serve(w http.ResponseWriter, r *http.Request, from provider.Pro
if from == provider.Gemini {
streams = strings.Contains(r.URL.Path, "streamGenerateContent")
}
gaveWay := map[string]bool{} // keys and accounts that gave way, full, to one free (laneMate)
gaveWay := map[string]bool{} // keys and accounts that gave way, full, to one free (laneMate, waitMate)
// the slot a request waiting in a full lane took of the key or account
// it went to instead (waitMate), for that one's try; given back if it
// isn't the one tried next, or when serve ends with it unused
var handed struct {
who string
release func()
waited time.Duration // how long it waited where it was, the first try's
}
defer func() {
if handed.release != nil {
handed.release()
}
}()
// a group's members that failed in a way that passes are asked again,
// once each has been, for up to its Patience (#1418): a member of a
// group in the group uses the innermost that sets Patience (#2410)
@@ -2870,7 +2883,13 @@ func (s *Server) serve(w http.ResponseWriter, r *http.Request, from provider.Pro
failedRow = nil
}
c := cands[i]
if j := s.laneMate(cands, i, isGroup, gaveWay); j > i {
if handed.release != nil && handed.who != c.who() {
handed.release()
handed.release = nil
}
if handed.release != nil {
// it holds a slot of this one already: no giving way
} else if j := s.laneMate(cands, i, isGroup, gaveWay); j > i {
// its key or account is full, and another of its provider's,
// or of its group, has a slot free: that one is asked first,
// this one keeps its place after it (#892)
@@ -3281,7 +3300,46 @@ func (s *Server) serve(w http.ResponseWriter, r *http.Request, from provider.Pro
// machine)
// a streaming agent waiting is kept alive meanwhile
queuedAlive := hw.keepQueued()
release, inLane, err := s.lanes.take(ctx, c.who(), c.p.LaneLimit(), c.p.QueueLimit, time.Duration(c.p.QueueWait)*time.Second)
var release func()
var inLane time.Duration
var err error
var mate candidate
if handed.release != nil {
// it left a full lane's queue for this one, whose slot it
// took as it did (waitMate): the wait there is its queue
release, handed.release = handed.release, nil
inLane, handed.waited = handed.waited, 0
} else {
// waiting, it goes to the first other key or account with
// room, not resting, once there is one (01huadalang on
// Discord: the requests already waiting for a third ZCode
// account waited on once the first two were back)
release, inLane, err = s.lanes.take(ctx, c.who(), c.p.LaneLimit(), c.p.QueueLimit, time.Duration(c.p.QueueWait)*time.Second, func() (bool, time.Time) {
m, rel, next, ok := s.waitMate(cands, i, isGroup, gaveWay, all)
if !ok {
return false, next
}
mate, handed.who, handed.release = m, m.who(), rel
return true, time.Time{}
})
}
if errors.Is(err, errMoved) {
// nothing was sent, and nobody failed: the one with room is
// asked now, this one keeps its place after it. The try
// never went out, so the route lists it no more
queuedAlive()
stop()
s.trace.update(tr, func(t *Route) { t.Tries = t.Tries[:len(t.Tries)-1] })
if firstBegan.Equal(began) {
// the first try's wait is the next one's queue, not a
// failed try's time
firstBegan, handed.waited = time.Time{}, inLane
}
gaveWay[c.who()] = true
cands = movedAhead(cands, i, mate)
i--
continue
}
var inMinute time.Duration
if err == nil && c.p.RPMLimit() > 0 {
// with a MaxRPM, it then waits for room in the minute, and
@@ -3314,6 +3372,12 @@ func (s *Server) serve(w http.ResponseWriter, r *http.Request, from provider.Pro
}
stop()
}
if handed.release != nil && handed.who == c.who() {
// answered without asking (verifyHeld, quotaHeld): the slot
// taken for it goes back
handed.release()
handed.release = nil
}
if laneErr != nil {
// its key's or account's queue was full, or it waited as long
// as it may: nobody failed, and nobody rests; the next is
+196
View File
@@ -0,0 +1,196 @@
package gateway
import (
"context"
"fmt"
"net/http/httptest"
"strings"
"testing"
"time"
"github.com/yetone/magpie/internal/provider"
)
// 01huadalang on Discord (11-01): three ZCode accounts at three requests
// at once each, the first two resting after a 405. Every request went to
// the third, and those over its three waited in its queue; once the first
// two were back, the waiting ones waited on behind the third's long turns,
// under Smart, In turn and with Stays off alike, until its requests were
// cut by hand. A request waiting in a full lane goes to the first other
// key or account with room that isn't resting (waitMate) as soon as there
// is one: one back from its rest, lifted by hand (Try now) or run out.
// While they rest, the full lane gives way to neither (laneMate): its lane
// is free only because it rests. With two accounts at once (ZCode's
// plugin's maxAccounts), the third, which took a seat while the first two
// rested, is a reserve again once they are back, and those waiting for it
// go to the two.
func TestWaitingRequestGoesToAccountBackFromRest(t *testing.T) {
for _, mode := range []string{"", provider.Rotate} {
for _, aff := range []string{"", provider.AffinityOff} {
for _, lift := range []string{"lifted", "ran out"} {
t.Run(fmt.Sprintf("routing=%q/stays=%q/%s", mode, aff, lift), func(t *testing.T) {
waitingGoesBack(t, mode, aff, lift == "lifted")
})
}
}
}
}
func waitingGoesBack(t *testing.T, mode, aff string, lift bool) {
fresh(t)
v, _ := slowUp(t)
rec := &atOnceKeys{next: v}
up := httptest.NewServer(rec)
t.Cleanup(up.Close)
three, two := 3, 2
if err := provider.Save(provider.Provider{ID: "zc", Name: "ZC", Key: "k1", Keys: []provider.KeyAccount{{Key: "k2"}, {Key: "k3"}}, Models: []string{"m"}, Chat: up.URL + "/v1",
Routing: mode, MaxConcurrency: &three, MaxAccounts: &two}); err != nil {
t.Fatal(err)
}
if aff != "" {
if err := provider.SetAffinity("zc", aff); err != nil {
t.Fatal(err)
}
}
key := func(k string) string { return "zc#" + provider.KeyID(k) }
// the first two rest after ZCode's 405
restFor := func(d time.Duration) {
restingUntil.Lock()
for _, k := range []string{"k1", "k2"} {
restingUntil.m[key(k)] = time.Now().Add(d)
restingUntil.note[key(k)] = Rest{Why: failOther, Status: 405, Key: key(k)}
}
restingUntil.Unlock()
}
restFor(time.Hour)
g := newLaneRig(t)
count := func(k string) int {
n := 0
for _, got := range rec.seen() {
if got == k {
n++
}
}
return n
}
waiting := func() int {
n := 0
for _, l := range g.s.Lanes() {
n += l.Waiting
}
return n
}
tags := []string{"a", "b", "c", "d", "e", "f", "g", "h", "i"}
for _, tag := range tags[:3] {
g.send(context.Background(), "/v1/chat/completions", "zc/m", tag)
}
within(t, "three out at k3", func() bool { return count("k3") == 3 })
for _, tag := range tags[3:] {
g.send(context.Background(), "/v1/chat/completions", "zc/m", tag)
}
within(t, "six waiting for k3", func() bool { return g.s.Lanes()[key("k3")].Waiting == 6 })
if n1, n2 := count("k1"), count("k2"); n1+n2 > 0 {
t.Fatalf("k1 asked %d, k2 %d while resting: a full lane gave way to one resting", n1, n2)
}
if lift {
g.s.Unrest(key("k1"))
g.s.Unrest(key("k2"))
} else {
// the rests now end in a moment, as if set so: the waiting ones
// look once more (as when they queued) and find them resting, so
// what moves them is the end itself, well before laneRecheck
restFor(300 * time.Millisecond)
g.s.lanes.signal()
}
// back: the six waiting go to the two, three each, at once, while
// the third's three are still out
within(t, "the waiting ones at k1 and k2", func() bool { return count("k1") == 3 && count("k2") == 3 && waiting() == 0 })
if n := count("k3"); n != 3 {
t.Fatalf("k3 asked %d, want its three only", n)
}
// rec counts a request before it reaches v: all nine at v at once
within(t, "nine at the vendor", func() bool { return len(v.seen()) == 9 })
for _, tag := range tags {
close(v.gate(tag))
}
for range tags {
if r := g.reply(); r.err != nil || !strings.Contains(r.body, "[DONE]") {
t.Fatalf("reply %+v", r)
}
}
if v.most != 9 {
t.Fatalf("most out at once = %d, want 9: three on each", v.most)
}
within(t, "every slot given back", func() bool { return len(g.s.Lanes()) == 0 })
}
// A request waiting for a key whose slots are all out goes to another key
// of its provider once one of that one's is given back, under every
// routing, rather than waiting for the one it first queued for. The lane
// it goes to has no queue of its own: who waits there goes first.
func TestWaitingRequestTakesSlotGivenBackElsewhere(t *testing.T) {
for _, mode := range []string{"", provider.Ordered, provider.Rotate, provider.LeastUsed} {
t.Run(fmt.Sprintf("routing=%q", mode), func(t *testing.T) {
fresh(t)
v, _ := slowUp(t)
rec := &atOnceKeys{next: v}
up := httptest.NewServer(rec)
t.Cleanup(up.Close)
one := 1
if err := provider.Save(provider.Provider{ID: "two", Name: "Two", Key: "k1", Keys: []provider.KeyAccount{{Key: "k2"}}, Models: []string{"m"}, Chat: up.URL + "/v1",
Routing: mode, MaxConcurrency: &one}); err != nil {
t.Fatal(err)
}
g := newLaneRig(t)
waiting := func() int {
n := 0
for _, l := range g.s.Lanes() {
n += l.Waiting
}
return n
}
g.send(context.Background(), "/v1/chat/completions", "two/m", "a")
within(t, "a out", func() bool { return len(v.seen()) == 1 })
g.send(context.Background(), "/v1/chat/completions", "two/m", "b")
within(t, "b out", func() bool { return len(v.seen()) == 2 })
g.send(context.Background(), "/v1/chat/completions", "two/m", "c")
within(t, "c waiting", func() bool { return waiting() == 1 })
// whichever key c waits for, the other one's request ends
// first: c goes there
keys := rec.seen()
waitsFor := ""
for who, l := range g.s.Lanes() {
if l.Waiting == 1 {
waitsFor = who
}
}
end, other := "a", keys[0] // c waits for b's key: a's ends
if waitsFor == "two#"+provider.KeyID(keys[0]) {
end, other = "b", keys[1] // c waits for a's key: b's ends
}
close(v.gate(end))
if r := g.reply(); r.tag != end {
t.Fatalf("reply %+v, want %s", r, end)
}
within(t, "c sent to "+other, func() bool { return len(v.seen()) == 3 })
if got := rec.seen(); got[2] != other {
t.Fatalf("keys asked %v: c went to %s, want %s, the one whose slot was given back", got, got[2], other)
}
if n := waiting(); n != 0 {
t.Fatalf("%d still waiting", n)
}
for _, tag := range []string{"a", "b", "c"} {
if tag != end {
close(v.gate(tag))
}
}
for range 2 {
if r := g.reply(); r.err != nil || !strings.Contains(r.body, "[DONE]") {
t.Fatalf("reply %+v", r)
}
}
within(t, "every slot given back", func() bool { return len(g.s.Lanes()) == 0 })
})
}
}
+2
View File
@@ -837,6 +837,7 @@ func (s *Server) Unrest(key string) bool {
}
unsink(key)
s.trace.lifted()
s.lanes.signal() // a request waiting in a full lane may go to it now (waitMate)
return ok
}
@@ -862,6 +863,7 @@ func (s *Server) UnrestAll(key string) int {
}
unsinkAll(key)
s.trace.lifted()
s.lanes.signal() // a request waiting in a full lane may go to it now (waitMate)
return n
}