From ff28dc6bd71f5deff7ec19dfc5aa4c1658395be1 Mon Sep 17 00:00:00 2001 From: yetone Date: Tue, 17 Nov 2026 20:30:43 +0800 Subject: [PATCH] gateway: turns of sessions sent together are ahead of a near cap from their check, and of a reading their round isn't in (#6958) TestCapHoldsUnderParallelSessions went red on ubuntu CI at 93% of a 90% cap (#6958). Five sessions' turns on one account each checked whether it was near its cap, and two gaps let a round of them past it: - A turn found not near was counted out on the account (lanes.out) only once its try took its lane. Turns checking in between saw none of the others. Now the check and that count are one step under nearCaps.check: a turn found not near is counted from its check (lanes.plan) until its lane counts it, or it leaves. The near path's wait for turns out (lanes.idle) waits for those too. The key's slot is taken before the check, as the near path takes it, so a counted turn never waits for a key slot that a near turn holds while it waits for the count to drop. - turnSpends took every turn come back as in the reading when the reading moved. A reply tells the usage as its turn begins, so the reading it brings lacks the round out then. At 20 turns come back, the reading said 82.5% while the account was at 90%. What a turn spent was halved (7.5 points over 10 turns, not 5), and the 5 turns since were never ahead of it. lanes.began now notes the turns come back as each try takes its lane, and ahead counts what that reading has (read). Turns come back since are ahead of it. nearChecked is a test hook after the check. TestCapHoldsWithAPauseAfterTheCheck runs the parallel test with a 15ms pause there, as a busy machine widens it. TestTurnSpendsAhead gains the case of a round out as the reading was told. Run at this change on f9492fd8e: - mote: go test -race -count=10 -run 'TestCapHolds|TestTurnSpendsAhead|TestLane|Near' ./internal/gateway: ok (31.7s) - mote: go vet ./internal/gateway: ok - mote: go test -timeout 45m ./internal/gateway: ok (982.9s) - mica (mote over its cores then): the cap tests -count=5: ok Rebased onto f1a4de736 (49e29de7b and 52d527f7b touch the gateway). At the pushed tree, on mote: the cap, turnSpends, lane and near tests -count=3 ok; go vet, GOOS=linux and GOOS=windows go vet ./internal/gateway ok; gofmt -l clean. Broken by hand, the pause test, 3 runs each: - On the old code, red 3 of 3: "used 97.5% of a 90% cap after 25 turns; want at most 91.5%". - With only the read count taken out (ahead given turns as read): red, 93.0%. - With only the planned count taken out of out and idle: red, 93.0%. - First cut, with the hook inside the check's lock: green with the count taken out too, because the lock held the next check for the pause. The hook now runs after the unlock, where the real gap is. Not tried: a real Codex account at its cap with parallel sessions. The reading's turns are those come back at the latest lane take, so a reading still on its way (lane taken, reply not begun yet) is taken as having them: a gap of one reply's first byte, not of a whole turn. --- internal/gateway/cap_near.go | 38 ++++++++++------ internal/gateway/cap_parallel_test.go | 33 +++++++++++--- internal/gateway/concurrency.go | 64 ++++++++++++++++++++++++--- internal/gateway/gateway.go | 52 +++++++++++++++++++++- 4 files changed, 160 insertions(+), 27 deletions(-) diff --git a/internal/gateway/cap_near.go b/internal/gateway/cap_near.go index de7c2756f..1e95ec1f5 100644 --- a/internal/gateway/cap_near.go +++ b/internal/gateway/cap_near.go @@ -29,6 +29,10 @@ import ( "github.com/yetone/magpie/internal/provider" ) +// nearChecked, for tests, is told each try's near-cap check, right after +// it, before the try is counted out on the account. +var nearChecked func(near bool) + // nearCapPoints is how many points under a cap an account takes one turn at a // time: as careful caps read again (carefulNear), a turn of a big model // on a small plan spending a few points. @@ -36,6 +40,9 @@ const nearCapPoints = carefulNear // nearCaps is each account's one turn near its cap, by candidate.who(). type nearCaps struct { + // check makes a turn's near-cap check and its count as out on the + // account (lanes.plan) one step (#6958) + check sync.Mutex mu sync.Mutex slots map[string]chan struct{} wait int // turns waiting for a slot, for tests @@ -109,7 +116,7 @@ func (s *Server) nearCapOf(c candidate, now time.Time) (used, ahead float64, nea } used, _ = al.For(c.model, now) out, _, turns := s.lanes.out(c.who()) - ahead = s.turnSpend.ahead(c.who(), used, turns, out) + ahead = s.turnSpend.ahead(c.who(), used, turns, s.lanes.inReading(c.who()), out) return used, ahead, al.NearCap(c.model, caps, nearCapPoints+ahead, now) } @@ -144,10 +151,11 @@ func capWatched(c candidate) (provider.Allowance, provider.WindowCaps, bool) { } // turnSpends learns what a turn spends on each account, by candidate.who(): -// as its usage moves up, by how much, over the turns that came back since -// it last moved. A reply tells the usage as its turn begins, so turns out -// at the vendor, and those come back since the usage last moved, are in -// no reading yet: what they will spend is ahead of the reading. +// as its usage moves up, by how much, over the turns that reading has +// that the one before it hadn't. A reply tells the usage as its turn +// begins, so turns out at the vendor, and those come back since the turn +// whose reply told it began, are in no reading yet: what they will spend +// is ahead of the reading. type turnSpends struct { mu sync.Mutex m map[string]turnSpend @@ -155,7 +163,7 @@ type turnSpends struct { type turnSpend struct { used float64 // the usage last known - turns int // turns come back when it last moved + turns int // turns come back that reading has per float64 // what a turn spent then, at most maxTurnSpend } @@ -163,25 +171,29 @@ type turnSpend struct { // moved by what the vendor's own app spent too is not one turn's. const maxTurnSpend = 2 * nearCapPoints -// ahead notes who's usage, used, with turns come back, and answers what -// out turns at the vendor and those come back since the usage last moved -// will spend. -func (t *turnSpends) ahead(who string, used float64, turns, out int) float64 { +// ahead notes who's usage, used, with turns come back and read of them +// in that reading at most (lanes.inReading), and answers what out turns +// at the vendor and those come back that no reading has yet will spend. +// Counting every turn come back as read, the turns of five sessions sent +// together, out as the reading was told, were never ahead of it, and the +// account went past its cap by a round of them (#6958). +func (t *turnSpends) ahead(who string, used float64, turns, read, out int) float64 { t.mu.Lock() defer t.mu.Unlock() if t.m == nil { t.m = map[string]turnSpend{} } + read = min(read, turns) s, ok := t.m[who] switch { case !ok || used < s.used: // first known, or renewed: what a turn spent stands - s.used, s.turns = used, turns + s.used, s.turns = used, read case used > s.used: - if n := turns - s.turns; n > 0 { + if n := read - s.turns; n > 0 { s.per = min((used-s.used)/float64(n), maxTurnSpend) } - s.used, s.turns = used, turns + s.used, s.turns = used, read } t.m[who] = s return s.per * float64(out+max(turns-s.turns, 0)) diff --git a/internal/gateway/cap_parallel_test.go b/internal/gateway/cap_parallel_test.go index f8c639669..104620128 100644 --- a/internal/gateway/cap_parallel_test.go +++ b/internal/gateway/cap_parallel_test.go @@ -131,32 +131,39 @@ func TestCapHoldsUnderParallelSessions(t *testing.T) { // back since it last moved; a renewed window keeps what a turn spent. func TestTurnSpendsAhead(t *testing.T) { var ts turnSpends - if got := ts.ahead("a", 60, 0, 3); got != 0 { + if got := ts.ahead("a", 60, 0, 0, 3); got != 0 { t.Fatalf("nothing learned yet: ahead %v; want 0", got) } // two turns came back, the reading not moved: still nothing learned - if got := ts.ahead("a", 60, 2, 3); got != 0 { + if got := ts.ahead("a", 60, 2, 2, 3); got != 0 { t.Fatalf("ahead %v; want 0", got) } // it moved 3 points over those two: 1.5 a turn, none since - if got := ts.ahead("a", 63, 2, 4); got != 6 { + if got := ts.ahead("a", 63, 2, 2, 4); got != 6 { t.Fatalf("ahead %v; want 4 turns out at 1.5", got) } // one more came back unread, three out - if got := ts.ahead("a", 63, 3, 3); got != 6 { + if got := ts.ahead("a", 63, 3, 3, 3); got != 6 { t.Fatalf("ahead %v; want 4 turns at 1.5", got) } // renewed: what a turn spends stands, counted from here - if got := ts.ahead("a", 2, 3, 1); got != 1.5 { + if got := ts.ahead("a", 2, 3, 3, 1); got != 1.5 { t.Fatalf("ahead %v; want one turn at 1.5", got) } // a jump the vendor's own app made too is not taken as one turn's - if got := ts.ahead("a", 40, 4, 1); got != maxTurnSpend { + if got := ts.ahead("a", 40, 4, 4, 1); got != maxTurnSpend { t.Fatalf("ahead %v; want %v", got, maxTurnSpend) } - if got := ts.ahead("b", 50, 0, 2); got != 0 { + if got := ts.ahead("b", 50, 0, 0, 2); got != 0 { t.Fatalf("another account: ahead %v; want 0", got) } + // #6958: five turns out as the reading was told came back after it. + // Its 7.5 points are those five's before them, not ten's, and the + // five come back since are in no reading yet + ts.ahead("c", 60, 0, 0, 5) + if got := ts.ahead("c", 67.5, 10, 5, 0); got != 7.5 { + t.Fatalf("ahead %v; want the 5 turns no reading has, at 1.5", got) + } } // A turn near its cap waits for the turns out on its account, not for a @@ -195,3 +202,15 @@ func TestLaneIdleLeavesItsOwnSlot(t *testing.T) { t.Fatalf("ended %v, turns %d; want the other's return noted", ended, turns) } } + +// #6958: the same five sessions, with each try's pause after its near-cap +// check widened, as a busy machine widens it (ubuntu CI: 93% of a 90% +// cap). A turn found not near is counted out on the account from its +// check, before its try takes its lane, and the reading the account is +// checked by has only the turns come back before the reply that told it +// began, not those of the round under way then. +func TestCapHoldsWithAPauseAfterTheCheck(t *testing.T) { + nearChecked = func(bool) { time.Sleep(15 * time.Millisecond) } + t.Cleanup(func() { nearChecked = nil }) + TestCapHoldsUnderParallelSessions(t) +} diff --git a/internal/gateway/concurrency.go b/internal/gateway/concurrency.go index 00596c21e..5b0f88a28 100644 --- a/internal/gateway/concurrency.go +++ b/internal/gateway/concurrency.go @@ -41,6 +41,55 @@ type lanes struct { ended map[string]time.Time turns map[string]int // how many turns each has had come back idles int // turns waiting in idle, for tests + // planned is each's turns found not near a usage cap that haven't + // taken their lane yet: out on it already, for out and idle (#6958) + planned map[string]int + // read is how many turns had come back on each when one of its turns + // last took its lane: a reply tells the usage as its turn begins, so + // the reading it brings has those turns and none come back since + // (cap_near.go, #6958) + read map[string]int +} + +// began notes that one of who's turns took its lane now. +func (l *lanes) began(who string) { + l.mu.Lock() + defer l.mu.Unlock() + if l.read == nil { + l.read = map[string]int{} + } + l.read[who] = l.turns[who] +} + +// inReading is how many of who's turns come back the reading last told +// has at most: those come back as one of its turns last took its lane. +func (l *lanes) inReading(who string) int { + l.mu.Lock() + defer l.mu.Unlock() + return l.read[who] +} + +// plan counts a turn out on who before it takes its lane, and gives back +// the func that stops counting it: called once its lane counts it, or as +// it leaves. +func (l *lanes) plan(who string) func() { + l.mu.Lock() + if l.planned == nil { + l.planned = map[string]int{} + } + l.planned[who]++ + l.mu.Unlock() + var once sync.Once + return func() { + once.Do(func() { + l.mu.Lock() + if l.planned[who]--; l.planned[who] <= 0 { + delete(l.planned, who) + } + l.signalLocked() + l.mu.Unlock() + }) + } } // signalLocked wakes every request waiting in a lane to look for another @@ -460,13 +509,15 @@ func (l *lanes) releaser(who string, ln *lane) func() { } } -// out is how many of who's turns are out at the vendor now, when one last -// came back, and how many have come back. +// out is how many of who's turns are out at the vendor now, those found +// not near its cap on their way to their lane among them (plan), when one +// last came back, and how many have come back. func (l *lanes) out(who string) (busy int, ended time.Time, turns int) { l.mu.Lock() defer l.mu.Unlock() + busy = l.planned[who] if ln := l.m[who]; ln != nil { - busy = ln.busy + busy += ln.busy } return busy, l.ended[who], l.turns[who] } @@ -476,8 +527,11 @@ func (l *lanes) out(who string) (busy int, ended time.Time, turns int) { func (l *lanes) idle(ctx context.Context, who string, own int) error { for { l.mu.Lock() - ln := l.m[who] - if ln == nil || ln.busy <= own { + busy := l.planned[who] + if ln := l.m[who]; ln != nil { + busy += ln.busy + } + if busy <= own { l.mu.Unlock() return nil } diff --git a/internal/gateway/gateway.go b/internal/gateway/gateway.go index 03793590a..b2650b23b 100644 --- a/internal/gateway/gateway.go +++ b/internal/gateway/gateway.go @@ -3741,6 +3741,14 @@ func (s *Server) serve(w http.ResponseWriter, r *http.Request, from provider.Pro }() nearBehind := map[string]bool{} // accounts near their cap moved behind the rest once var nearInKey time.Duration // the key's slot waited for before an account's turn near its cap + // onWay takes back a turn counted out on its account from its + // near-cap check (lanes.plan) once its lane counts it, or it leaves + var onWay func() + defer func() { + if onWay != nil { + onWay() + } + }() for i := 0; i < len(cands); i++ { if failedRow != nil { failedRow() @@ -3807,7 +3815,38 @@ func (s *Server) serve(w http.ResponseWriter, r *http.Request, from provider.Pro failTo(w, kept, from, call.Status, cmp.Or(msg, call.Error)) break } - if used, ahead, near := s.nearCapOf(c, time.Now()); near && aff.Why != "strict" && (len(cands) > 1 || userCapped(c)) && capHeld(c.p, c.p, c.model, time.Now()) == nil { + if onWay != nil { + onWay() + onWay = nil + } + var nearUsed, nearAhead float64 + var near bool + if _, _, watched := capWatched(c); watched { + // a turn found not near its cap is out on the account from + // its check, not from its lane, and the check and that count + // are one step: turns of sessions sent together each checked + // before any took its lane, saw none of the others, and went + // past the cap together (#6958: 93% of a 90% cap). The key's + // slot is taken first, as the near path below takes it, so a + // turn counted out never waits for a key slot a turn near the + // cap holds while it waits for the count to drop + waited, err := keySlot(r.Context()) + nearInKey += waited + if err != nil { + call.Status, call.Error = canceled(r.Context()) + break + } + s.nearCap.check.Lock() + nearUsed, nearAhead, near = s.nearCapOf(c, time.Now()) + if !near { + onWay = s.lanes.plan(c.who()) + } + s.nearCap.check.Unlock() + if nearChecked != nil { + nearChecked(near) + } + } + if near && aff.Why != "strict" && (len(cands) > 1 || userCapped(c)) && capHeld(c.p, c.p, c.model, time.Now()) == nil { // within nearCapPoints of its usage cap, the account takes one // turn at a time (dyzdyz010 on Discord): busy, the turn goes to // the next one first, this one kept behind them, else waits for @@ -3878,7 +3917,7 @@ func (s *Server) serve(w http.ResponseWriter, r *http.Request, from provider.Pro held = true } _, ended, _ := s.lanes.out(c.who()) - nearCapAgain(r.Context(), c, used, ahead, held, ended) + nearCapAgain(r.Context(), c, nearUsed, nearAhead, held, ended) nearDone = done if h := capHeld(c.p, c.p, c.model, time.Now()); h != nil { nearDone() @@ -4439,6 +4478,15 @@ func (s *Server) serve(w http.ResponseWriter, r *http.Request, from provider.Pro return true, time.Time{} }) } + if err == nil { + // the reply's reading has the turns come back by now + // (turnSpends), and its lane counts it + s.lanes.began(c.who()) + if onWay != nil { + onWay() + onWay = nil + } + } 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