Files
magpie/internal/gateway/effort_accounts.go
T
yetone 5feadabef6 gateway: a long conversation's request costs about a third of the CPU it did, with the same bytes sent on (#1532, #1654)
The gateway reads one request's body a dozen times or more on its way:
modelOf, streamOf, conversationID, requestEffort, bodyEffort,
walkImages and swapImageBlocks (more than once through a group), turnOf's
parse, promptOf, chatToolNames, thinkingOffUnlessAsked, decodeRequest,
and for Responses pairToolItems, orphanedToolOutputs,
hasSealedAgentMessage and askedTier. Each read took a field or two with
json.Unmarshal, which checks the whole input and then steps through every
byte of every string one call at a time, so each read cost as much as
decoding the whole conversation: 74-77% of a request's CPU in pprof, most
of it checkValid and stateInString.

decodeJSON (fastjson.go) is json.Unmarshal for these reads. It checks the
body once with its own validator (json.Valid's grammar and 10000 depth,
8 string bytes at a time), splits objects and arrays at their members
without decoding them, and decodes only what dst has a place for:
strings, booleans, json.RawMessage (copied, as encoding/json does),
structs, pointers, slices and string-keyed maps by their parts, and
everything else (numbers, interfaces, types that decode themselves) by
encoding/json itself. Whatever it doesn't take on exactly as
json.Unmarshal would goes to json.Unmarshal with dst zeroed: invalid
input, a dst already holding something, an embedded field, a ",string"
option, two fields of one name, a key given twice, a value of the wrong
type. A list or object where dst takes a string (a "string or parts"
read) is answered by json.Unmarshal of its opening and close, which gives
the same error at the same offset without reading the rest. The request
paths' json.Unmarshal calls in gateway.go, decide.go, affinity.go,
image_input.go, textcalls.go, anthropic.go, ir.go, prompt.go, chat.go,
chattidy.go and responses.go, and hasSealedAgentMessage and askedTier,
now call it. Nothing that writes a body changed.

Numbers, M4 Pro under load 10-20 from other sessions, BenchmarkLargeRequest
(new: a 2 MB agent conversation with 30 tools, tool calls and results,
through a fake vendor), 20 requests each:

                    CPU in the request's handler    time per request
                    (pprof, per request)            (ns/op)
  anthropic         154ms -> 45ms                   208-212ms -> 52ms
  anthropic, group  178ms -> 51ms                   249-262ms -> 65-67ms
  chat              122ms -> 35ms                   167-254ms -> 50-54ms
  responses         215ms -> 56ms                   294-452ms -> 70ms

TestLargeRequestEndpoints (64 MB padded bodies): 16.8-17.6s -> 2.9-4.8s
(skipping runs of spaces 8 bytes at a time took its last ~5s).

Tests:
- TestUpstreamBodiesUnchanged sends 18 requests (Anthropic, Chat and
  Responses; direct, through a group, translated to each other protocol,
  with images, thinking, escapes, odd spacing, a repeated key, and four
  2 MB conversations) and compares what the vendor gets with
  testdata/upstream_bodies, recorded on the code before this change
  (all 18 identical; three runs agreed). Breaking decodeJSON's \n
  unescape by hand turns the three translated cases holding one red.
- TestDecodeJSONIsUnmarshal / FuzzDecodeJSON compare decodeJSON with
  json.Unmarshal (dst DeepEqual, error nil-ness) for 19 types shaped like
  the gateway's, and jsonValid with json.Valid, over seeds, every cut
  and a changed byte at every place of each seed, and 2.5 minutes of
  fuzzing (~1.75M inputs). Breaking the validator's control-byte check
  by hand turns it red.
- go test -tags nogui -timeout 40m ./... on this commit rebased onto
  origin/main 498b77fbc, with #1667's fix below it: all 48 packages ok
  (gateway 394s).
gofmt -l clean; GOOS=linux and GOOS=windows go vet -tags nogui
./internal/gateway clean.

Not tried: real vendor traffic; Windows and Linux runs (vet only).
2026-10-12 03:28:16 +08:00

196 lines
6.3 KiB
Go

package gateway
// An account's plan may not take every reasoning level its model has: a
// Free ChatGPT account turns gpt-6-luna at high and above away with a 400,
// which a Plus one beside it answers (#520). Such an account is asked
// after its provider's others that may take the level — by its own model
// list's levels, or what it answered last — and one that refuses the level
// is not the request's fault: the next is asked, and it doesn't rest. When
// none that is left takes it, the agent is told so, not the level lowered
// behind its back.
import (
"encoding/json"
"fmt"
"regexp"
"slices"
"strings"
"sync"
"time"
)
// effortRemember is how long an account's refusal of a level is kept: a
// plan upgraded is asked again after it.
const effortRemember = time.Hour
var effortRefusals = struct {
sync.Mutex
m map[string]effortRefusal // who|model → what it said
}{m: map[string]effortRefusal{}}
type effortRefusal struct {
refused []string // levels it turned away
takes []string // the levels it said it takes, when it said
at time.Time
}
func effortKey(c candidate) string { return c.who() + "|" + c.model }
// noteEffortRefused remembers c turning e away, with the levels it said
// it takes.
func noteEffortRefused(c candidate, e string, takes []string) {
effortRefusals.Lock()
defer effortRefusals.Unlock()
k := effortKey(c)
n := effortRefusals.m[k]
if time.Since(n.at) > effortRemember {
n = effortRefusal{}
}
if !slices.Contains(n.refused, e) {
n.refused = append(n.refused, e)
}
if len(takes) > 0 {
n.takes = takes
}
n.at = time.Now()
effortRefusals.m[k] = n
}
// takesEffort says whether c's account may be asked for reasoning e on its
// model, as far as magpie knows: not when it turned e away within the hour,
// or its own model list gives the model levels without e.
func takesEffort(c candidate, e string) bool {
if e == "" || c.p.Account == nil {
return true
}
effortRefusals.Lock()
n, ok := effortRefusals.m[effortKey(c)]
effortRefusals.Unlock()
if ok && time.Since(n.at) <= effortRemember {
if slices.Contains(n.refused, e) || len(n.takes) > 0 && !slices.Contains(n.takes, e) {
return false
}
if slices.Contains(n.takes, e) {
return true
}
}
if levels, ok := c.p.Account.Levels(c.model); ok && !slices.Contains(levels, e) {
return false
}
return true
}
// effortMate is the first of left that is another account of c's member —
// its provider and model, at its fixed effort — that may take e, or -1.
func effortMate(left []candidate, c candidate, e string) int {
return slices.IndexFunc(left, func(x candidate) bool {
return x.p.Account != nil && x.p.ID == c.p.ID && x.model == c.model && x.effort == c.effort &&
x.who() != c.who() && takesEffort(x, e)
})
}
var (
// unsupportedEffort is OpenAI's "Unsupported value: 'high' is not
// supported with the 'gpt-6-luna' model. Supported values are: …"
unsupportedEffort = regexp.MustCompile(`(?i)unsupported value:?\s*['"\x60]?([a-z]+)['"\x60]?\s+is not supported`)
// effortNamed is a refusal naming the reasoning effort itself
effortNamed = regexp.MustCompile(`(?i)reasoning[._ ]?effort`)
effortDenied = regexp.MustCompile(`(?i)not supported|unsupported|not available|isn'?t available|not allowed|invalid value|upgrade|your plan`)
supportedAre = regexp.MustCompile(`(?i)supported values are:?\s*([^.]*)`)
quotedLevel = regexp.MustCompile(`['"\x60]([a-z]+)['"\x60]`)
)
// effortRefused reads a vendor's 400 as the reasoning level sent turned
// away, and the levels it says it takes, if it says. A refusal of some
// other field's value — text.verbosity's 'high' — isn't one.
func effortRefused(body []byte, sent string) (takes []string, ok bool) {
if sent == "" || len(body) == 0 {
return nil, false
}
s := string(body)
var e struct {
Param string `json:"param"`
Error struct {
Param string `json:"param"`
} `json:"error"`
}
if i := strings.IndexByte(s, '{'); i >= 0 && json.Unmarshal([]byte(s[i:]), &e) == nil {
param := e.Error.Param
if param == "" {
param = e.Param
}
if param != "" && !effortNamed.MatchString(param) {
return nil, false
}
}
m := unsupportedEffort.FindStringSubmatch(s)
switch {
case m != nil && strings.EqualFold(m[1], sent):
case m == nil && effortNamed.MatchString(s) && effortDenied.MatchString(s):
default:
return nil, false
}
if sm := supportedAre.FindStringSubmatch(s); sm != nil {
for _, q := range quotedLevel.FindAllStringSubmatch(sm[1], -1) {
if l := strings.ToLower(q[1]); slices.Contains(effortRank, l) && !slices.Contains(takes, l) {
takes = append(takes, l)
}
}
}
return takes, true
}
// modelTakes says whether c's model is known to have level e, or its
// levels aren't known: a level the model has, turned away, is the
// account's plan, not the request.
func modelTakes(c candidate, e string) bool {
levels := c.p.Efforts(c.model)
return len(levels) == 0 || slices.Contains(levels, e)
}
// effortError is what the agent is told when the account left turned the
// level away and none that takes it could answer.
func effortError(c candidate, e string, takes []string, vendor string) string {
msg := fmt.Sprintf("%s doesn't take reasoning effort %q on %s", c.label(), e, c.model)
if len(takes) > 0 {
msg += " (it takes " + strings.Join(takes, ", ") + ")"
}
msg += ", and no other account that does could answer; pick a lower effort or another account"
if vendor != "" {
msg += ": " + vendor
}
return msg
}
// askedTier is the service tier a Responses request asks for.
func askedTier(body []byte) string {
var q struct {
Tier string `json:"service_tier"`
}
decodeJSON(body, &q)
return q.Tier
}
// takesTier says whether c's account may be asked for service tier t on
// its model: not when its own model list says which tiers the model has
// and t isn't one.
func takesTier(c candidate, t string) bool {
if c.p.Account == nil {
return true
}
tiers, ok := c.p.Account.Tiers(c.model)
return !ok || slices.Contains(tiers, t)
}
// tierMate is the first of left that is another account of c's member
// whose list offers tier t on the model, or -1.
func tierMate(left []candidate, c candidate, t string) int {
return slices.IndexFunc(left, func(x candidate) bool {
if x.p.Account == nil || x.p.ID != c.p.ID || x.model != c.model || x.effort != c.effort || x.who() == c.who() {
return false
}
tiers, ok := x.p.Account.Tiers(x.model)
return ok && slices.Contains(tiers, t)
})
}