Files
magpie/internal/gateway/limit.go
T
yetone 59d9f5c7d9 gateway, redact: compile their 275 package-level regexps on first use, not at every start
magpie is one binary, so every package's init runs on every launch,
including `magpie statusline`, which Claude Code runs on every message.
internal/gateway and internal/redact compiled 275 patterns at init:
3.7 MB + 2.3 MB and ~38k allocations per launch, most of them for
vendors and rules that launch never reaches.

New internal/lazyre: RE holds the source and compiles it through a
sync.Once on first use, with the *regexp.Regexp methods magpie calls
delegating to it (Of wraps one already compiled, for the user's own
privacy rules). A one-off Go AST rewrite turned every regexp.MustCompile
in a package-level var (outside func literals) into lazyre.New; the
struct fields, map and parameter that hold them took the new type. A
bad pattern now panics on first use instead of at start, so
TestAllCompile in gateway and redact compiles every registered one.

Measured on mote (M5 Pro), sandbox HOME with a copy of real accounts,
v0.1.3515 (273b9f5a9) vs this change:
- GODEBUG=inittrace=1: all init 13.0 MB / 106k allocs -> 7.4 MB / 70k;
  gateway 3.68 MB -> 70 KB, redact 2.31 MB -> 261 KB.
- `echo {} | magpie statusline`, /usr/bin/time -l, 3 runs each:
  instructions retired 260-265M -> 212-215M (-18%), peak footprint
  22.1-22.3 MB -> 18.6-19.2 MB.

Run: go vet ./... (mote); GOOS=linux and GOOS=windows go vet of
gateway, redact, lazyre; go test -race ./internal/lazyre (incl. a
bad-pattern test that MustAll panics); go test ./internal/redact (all);
go test ./internal/gateway -run 'TestAllCompile|OtherOff|WorkDir|
WorkPlace|RunNoise': ok. Broken by hand: TestBadPatternPanicsInMustAll
registers `(` and fails if MustAll does not panic.
Not run before the push: the whole internal/gateway package and the
full suite (a full suite of 273b9f5a9 was running on mote).
2026-11-10 12:34:14 +08:00

67 lines
2.1 KiB
Go

package gateway
import (
"encoding/json"
"strconv"
"strings"
"github.com/yetone/magpie/internal/lazyre"
)
// tooFewTokens reads a provider's floor on the reply's length from the 400
// it sends when a request asks for less ("max_tokens must be greater than
// 2"). Apps checking a model is up ask for a token or two, which most
// providers answer and some turn away. A > may come JSON-escaped, as
// \u003e: the error is read from the body magpie re-encoded for the agent,
// or a vendor encodes its own that way (#260: "Expected a value >= 16").
var tooFewTokens = lazyre.New(`(?i)max_(?:completion_|output_)?tokens.{0,60}?(greater than|more than|larger than|at least|(?:>|\\u003e)=?)\s*(\d+)`)
// tokenFloor is the least a provider said it takes, or 0 when the error
// isn't about that.
func tokenFloor(msg []byte) int {
m := tooFewTokens.FindSubmatch(msg)
if m == nil {
return 0
}
n, err := strconv.Atoi(string(m[2]))
if err != nil || n < 0 || n > 1024 {
return 0
}
if sign := string(m[1]); strings.EqualFold(sign, "at least") || strings.HasSuffix(sign, "=") {
return n
}
return n + 1
}
// withTokenFloor raises the reply's length the request asks for to floor,
// wherever the request's protocol keeps it; false when it asked for that
// much already, so the error was about something else.
func withTokenFloor(body []byte, floor int) ([]byte, bool) {
var q map[string]json.RawMessage
if floor <= 0 || json.Unmarshal(body, &q) != nil {
return nil, false
}
raise := func(m map[string]json.RawMessage, key string) bool {
var n int
if json.Unmarshal(m[key], &n) != nil || n >= floor {
return false
}
m[key], _ = json.Marshal(floor)
return true
}
raised := false
for _, k := range []string{"max_tokens", "max_completion_tokens", "max_output_tokens"} {
raised = raise(q, k) || raised
}
var gc map[string]json.RawMessage // Gemini's
if json.Unmarshal(q["generationConfig"], &gc) == nil && raise(gc, "maxOutputTokens") {
q["generationConfig"], _ = json.Marshal(gc)
raised = true
}
if !raised {
return nil, false
}
b, err := marshalJSON(q)
return b, err == nil
}