mirror of
https://github.com/lukaszraczylo/traefik-llmgateway.git
synced 2026-11-26 10:06:31 +00:00
feat(router): smart routers and per-member rate limits (#9)
Add smart routers: virtual models that score each request and route it to admin-defined model tiers. A retryable failure moves the request to a higher tier. The classifier v2 extracts prose, finds the original ask in long tool loops, adds an uncertainty margin and reads tool-output failures. Sessions, outcome signals, bounded calibration, adaptive selection within a tier, gated saturation downgrade, a first-byte timeout and an opt-in timeout fallback are included. Every new feature is off by default. Add per-member group limits, a tokensPerMinute window that counts uncached input and output, rate-limit headers in three dialects, soft pacing before the hard limit, and a limitExemptKinds list so embedding and reranking traffic never counts toward or hits a limit. Fix yaegi named-result state that made smartContentSize grow between calls.
This commit is contained in:
@@ -0,0 +1,5 @@
|
||||
module llmgw-yaegi-bench
|
||||
|
||||
go 1.25.0
|
||||
|
||||
require github.com/traefik/yaegi v0.16.1
|
||||
@@ -0,0 +1,2 @@
|
||||
github.com/traefik/yaegi v0.16.1 h1:f1De3DVJqIDKmnasUF6MwmWv1dSEEat0wcpXhD2On3E=
|
||||
github.com/traefik/yaegi v0.16.1/go.mod h1:4eVhbPb3LnD2VigQjhYbEJ69vDRFdT2HQNrXx8eEwUY=
|
||||
@@ -0,0 +1,659 @@
|
||||
// Command yaegi-bench measures smart router classification throughput under
|
||||
// the Yaegi interpreter, the way Traefik loads the plugin. It copies the
|
||||
// plugin source into a temporary GOPATH, adds a small exported hook file that
|
||||
// loads the router fixtures and runs classifySmart in a loop, then times that
|
||||
// loop from outside the interpreter.
|
||||
//
|
||||
// The module is separate from the plugin (like tools/yaegi-check) so Yaegi
|
||||
// never becomes a plugin dependency. Run it with: make yaegi-bench
|
||||
package main
|
||||
|
||||
import (
|
||||
"bufio"
|
||||
"flag"
|
||||
"fmt"
|
||||
"io"
|
||||
"io/fs"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"sort"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/traefik/yaegi/interp"
|
||||
"github.com/traefik/yaegi/stdlib"
|
||||
)
|
||||
|
||||
// hookSource is written into the interpreted copy of the plugin package. It
|
||||
// returns a rank checksum so a loop that skips the work cannot look fast.
|
||||
const hookSource = `package %s
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"sort"
|
||||
"time"
|
||||
)
|
||||
|
||||
type benchFixture struct {
|
||||
ID string ` + "`json:\"id\"`" + `
|
||||
Request map[string]any ` + "`json:\"request\"`" + `
|
||||
Wire string ` + "`json:\"wire\"`" + `
|
||||
}
|
||||
|
||||
var (
|
||||
benchFixtures []benchFixture
|
||||
benchRouter *smartRouter
|
||||
benchSessions *routerSessions
|
||||
)
|
||||
|
||||
func BenchSetup(dir string, classifier string, mid int, top int) int {
|
||||
files, _ := filepath.Glob(filepath.Join(dir, "*.json"))
|
||||
sort.Strings(files)
|
||||
benchFixtures = nil
|
||||
for _, f := range files {
|
||||
raw, err := os.ReadFile(f)
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
var items []benchFixture
|
||||
if err := json.Unmarshal(raw, &items); err != nil {
|
||||
panic(err)
|
||||
}
|
||||
benchFixtures = append(benchFixtures, items...)
|
||||
}
|
||||
cfg := &SmartRouterConfig{Classifier: classifier, Tiers: []SmartRouterTier{
|
||||
{Name: "a", MinScore: 0, Models: []string{"p/a"}},
|
||||
{Name: "b", MinScore: mid, Models: []string{"p/b"}},
|
||||
{Name: "c", MinScore: top, Models: []string{"p/c"}},
|
||||
}}
|
||||
benchSessions = nil
|
||||
if classifier == "v2s" {
|
||||
cfg.Classifier = "v2"
|
||||
cfg.Session = &SmartRouterSessionConfig{Enabled: true}
|
||||
benchSessions = newRouterSessions(nil, nil, time.Now, nil)
|
||||
}
|
||||
rt, err := compileSmartRouter("bench", cfg, nil)
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
benchRouter = rt
|
||||
return len(benchFixtures)
|
||||
}
|
||||
|
||||
func BenchRanks() []string {
|
||||
var out []string
|
||||
for _, fx := range benchFixtures {
|
||||
endpoint := cacheEndpointChat
|
||||
if fx.Wire == "anthropic" {
|
||||
endpoint = cacheEndpointMessages
|
||||
}
|
||||
out = append(out, fx.ID+"="+string(rune('0'+classifySmart(benchRouter, fx.Request, endpoint).rank)))
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
// BenchHelperCheck replays the call sequences that exposed yaegi v0.16.1 leaking
|
||||
// named results between calls; it returns a description of the first mismatch.
|
||||
func BenchHelperCheck() string {
|
||||
small := []any{map[string]any{"type": "text", "text": "ab"}}
|
||||
big := []any{map[string]any{"type": "text", "text": "0123456789"}, map[string]any{"type": "image"}}
|
||||
for round := 0; round < 3; round++ {
|
||||
if c, im := smartContentSize(small, 0); c != 2 || im != 0 {
|
||||
return "smartContentSize(small) changed between calls"
|
||||
}
|
||||
if c, im := smartContentSize(big, 0); c != 10 || im != 1 {
|
||||
return "smartContentSize(big) changed between calls"
|
||||
}
|
||||
if c, im := smartMessagesSize(map[string]any{"messages": []any{map[string]any{"role": "user", "content": big}}}, cacheEndpointChat); c != 10 || im != 1 {
|
||||
return "smartMessagesSize changed between calls"
|
||||
}
|
||||
if _, _, tp := smartContentText([]any{map[string]any{"type": "tool_use"}}); !tp {
|
||||
return "smartContentText missed a tool part"
|
||||
}
|
||||
if _, _, tp := smartContentText(small); tp {
|
||||
return "smartContentText kept toolParts from the previous call"
|
||||
}
|
||||
if p1, _ := smartPasteKind("if (a) { b = c; } else { d = e; }\nx = y;\nfoo(bar);\nreturn z;\nint q = 1;\n"); !p1 {
|
||||
return "smartPasteKind missed a code paragraph"
|
||||
}
|
||||
if p2, _ := smartPasteKind("a plain sentence with no code in it at all, just words for a while"); p2 {
|
||||
return "smartPasteKind kept isPaste from the previous call"
|
||||
}
|
||||
if chunkFinishReason([]byte("{\"choices\":[{\"finish_reason\":\"length\"}]}")) != "length" || chunkFinishReason([]byte("{\"choices\":[{\"finish_reason\":null}]}")) != "" {
|
||||
return "chunkFinishReason changed between calls"
|
||||
}
|
||||
if !chunkHasOutput([]byte("{\"delta\":{\"content\":\"x\"}}")) || chunkHasOutput([]byte("{\"delta\":{\"content\":\"\"}}")) {
|
||||
return "chunkHasOutput changed between calls"
|
||||
}
|
||||
if !smartJSONEmpty([]byte("null")) || smartJSONEmpty([]byte("\"x\"")) {
|
||||
return "smartJSONEmpty changed between calls"
|
||||
}
|
||||
if u := withAnswerFlags(usage{}, "length", false); !u.finishLength || !u.emptyOutput {
|
||||
return "withAnswerFlags missed a flag"
|
||||
}
|
||||
if u := withAnswerFlags(usage{}, "stop", true); u.finishLength || u.emptyOutput {
|
||||
return "withAnswerFlags kept a flag from the previous call"
|
||||
}
|
||||
if msg := sessionHelperCheck(); msg != "" {
|
||||
return msg
|
||||
}
|
||||
if msg := learnHelperCheck(); msg != "" {
|
||||
return msg
|
||||
}
|
||||
if msg := banditHelperCheck(); msg != "" {
|
||||
return msg
|
||||
}
|
||||
if msg := classifierHelperCheck(); msg != "" {
|
||||
return msg
|
||||
}
|
||||
if msg := routerFeatureCheck(); msg != "" {
|
||||
return msg
|
||||
}
|
||||
if msg := firstByteHelperCheck(); msg != "" {
|
||||
return msg
|
||||
}
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
// firstByteHelperCheck replays the first-byte helpers with alternating inputs; a stale detector
|
||||
// position or a guard state kept from the previous call shows up as a mismatch.
|
||||
func firstByteHelperCheck() string {
|
||||
var d sseDataDetector
|
||||
if d.feed([]byte(": ping\n\n")) {
|
||||
return "sseDataDetector matched a comment"
|
||||
}
|
||||
if d.feed([]byte("id: data:1\n")) {
|
||||
return "sseDataDetector matched data inside another field"
|
||||
}
|
||||
if d.feed([]byte("da")) {
|
||||
return "sseDataDetector matched a partial prefix"
|
||||
}
|
||||
if !d.feed([]byte("ta: x")) {
|
||||
return "sseDataDetector missed a data line split across reads"
|
||||
}
|
||||
var e sseDataDetector
|
||||
if e.feed([]byte("event: m\n")) {
|
||||
return "sseDataDetector kept state from the previous detector"
|
||||
}
|
||||
if !e.feed([]byte("data: {}\n")) {
|
||||
return "sseDataDetector missed a data line"
|
||||
}
|
||||
if msg := fallbackRankCheck(); msg != "" {
|
||||
return msg
|
||||
}
|
||||
return firstByteErrCheck()
|
||||
}
|
||||
|
||||
// fallbackRankCheck alternates usable sets so a result kept from the previous call shows up as a mismatch.
|
||||
func fallbackRankCheck() string {
|
||||
has := func(set ...int) func(int) bool {
|
||||
return func(r int) bool {
|
||||
for _, s := range set {
|
||||
if s == r {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
}
|
||||
if routerFallbackRank(2, has(0, 1)) != 1 || routerFallbackRank(2, has(0)) != 0 || routerFallbackRank(2, has(2)) != -1 || routerFallbackRank(2, has(0, 1)) != 1 {
|
||||
return "routerFallbackRank changed between calls"
|
||||
}
|
||||
if routerFallbackRank(0, has(0, 1)) != -1 || routerFallbackRank(3, has(2)) != 2 {
|
||||
return "routerFallbackRank missed the lowest or highest edge"
|
||||
}
|
||||
counts := map[routerOutcomeKey]int64{{router: "r", reason: routerReasonFallback, outcome: routerOutcomeSlow}: 2, {router: "r", reason: smartReasonScore, outcome: routerOutcomeOK}: 5, {router: "o", reason: routerReasonFallback}: 9}
|
||||
if routerFallbackCount("r", counts) != 2 || routerFallbackCount("o", counts) != 9 || routerFallbackCount("r", counts) != 2 {
|
||||
return "routerFallbackCount changed between calls"
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
func firstByteErrCheck() string {
|
||||
if !isFirstByteTimeout(&firstByteTimeoutError{provider: "p"}) {
|
||||
return "isFirstByteTimeout missed its own type"
|
||||
}
|
||||
if isFirstByteTimeout(errFirstByteTimeout) {
|
||||
return "isFirstByteTimeout matched another error"
|
||||
}
|
||||
if got, err := parseFirstByteTimeout("r", "40s"); err != nil || got != 40*time.Second {
|
||||
return "parseFirstByteTimeout missed a valid value"
|
||||
}
|
||||
if _, err := parseFirstByteTimeout("r", "10ms"); err == nil {
|
||||
return "parseFirstByteTimeout accepted a value under the floor"
|
||||
}
|
||||
if none, err := parseFirstByteTimeout("r", ""); err != nil || none != 0 {
|
||||
return "parseFirstByteTimeout missed the empty value"
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
// routerFeatureCheck replays the v2 feature helpers with alternating inputs; yaegi v0.16.1 keeps
|
||||
// named results and struct fields from the previous call, so a stale answer shows up as a mismatch.
|
||||
func routerFeatureCheck() string {
|
||||
loop := func(ask, out string) smartFeatures {
|
||||
return extractSmartV2(map[string]any{
|
||||
"tools": []any{map[string]any{"type": "function"}},
|
||||
"messages": []any{
|
||||
map[string]any{"role": "user", "content": ask},
|
||||
map[string]any{"role": "assistant", "tool_calls": []any{map[string]any{"id": "c"}}},
|
||||
map[string]any{"role": "tool", "content": out},
|
||||
},
|
||||
}, cacheEndpointChat)
|
||||
}
|
||||
plain := func(ask string) smartFeatures {
|
||||
return extractSmartV2(map[string]any{"messages": []any{map[string]any{"role": "user", "content": ask}}}, cacheEndpointChat)
|
||||
}
|
||||
ok, bad := loop("format the new files", "ok"), loop("format the new files", "panic: boom")
|
||||
if !ok.routineToolStep() || bad.routineToolStep() || !ok.routineToolStep() {
|
||||
return "routineToolStep changed between calls"
|
||||
}
|
||||
rw, judge := plain("Summarize this in 3 bullets:\n\nThe design approach changed."), plain("Summarize the options and recommend one")
|
||||
if !rw.rewrite || judge.rewrite || !rw.rewrite {
|
||||
return "scanRewrite kept a flag from the previous call"
|
||||
}
|
||||
q, long := plain("ei, como faço pra pegar o ultimo item de uma lista?"), plain("what is the capital of france?")
|
||||
if !q.shortForeignQuestion() || long.shortForeignQuestion() || !q.shortForeignQuestion() {
|
||||
return "shortForeignQuestion changed between calls"
|
||||
}
|
||||
if g, n := plain("thanks a lot"), plain("and the leader?"); !g.isGreeting() || n.isGreeting() {
|
||||
return "isGreeting changed between calls"
|
||||
}
|
||||
if smartHead("abcdef", 3) != "abc" || smartHead("ab", 3) != "ab" || smartHead("abcdef", 2) != "ab" {
|
||||
return "smartHead changed between calls"
|
||||
}
|
||||
if !hasAnySmartTerm("the build hangs", smartTerseDebugCues) || hasAnySmartTerm("change it", smartTerseDebugCues) || !hasAnySmartTerm("the build hangs", smartTerseDebugCues) {
|
||||
return "hasAnySmartTerm changed between calls"
|
||||
}
|
||||
if !isSmartFailureAsk("review this for auth issues") || isSmartFailureAsk("review the pricing page") || !isSmartFailureAsk("it is flaky") {
|
||||
return "isSmartFailureAsk changed between calls"
|
||||
}
|
||||
run := func(out string) smartFeatures {
|
||||
return extractSmartV2(map[string]any{"messages": []any{
|
||||
map[string]any{"role": "user", "content": "format the files"},
|
||||
map[string]any{"role": "tool", "content": out},
|
||||
map[string]any{"role": "tool", "content": "ok"},
|
||||
}}, cacheEndpointChat)
|
||||
}
|
||||
if failed, passed := run("--- FAIL: TestX"), run("ok"); !failed.toolFail || passed.toolFail || !run("WARNING: DATA RACE").toolFail {
|
||||
return "noteToolResult kept toolFail from the previous call"
|
||||
}
|
||||
rt := &smartRouter{tiers: []smartTier{{}, {minScore: 300}, {minScore: 600}}}
|
||||
if smartScaled(rt, 100, 0) != 200 || smartScaled(rt, 100, 300) != 150 || smartScaled(rt, 100, 0) != 200 {
|
||||
return "smartScaled changed between calls"
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
// classifierHelperCheck compiles a router with a shadow classifier and then one without;
|
||||
// yaegi v0.16.1 would leak the named shadowV2 result from the first call into the second.
|
||||
func classifierHelperCheck() string {
|
||||
z := 3
|
||||
if _, shadow, _, err := compileSmartClassifier("r", &SmartRouterConfig{ShadowClassifier: smartClassifierV2, RiskZ: &z}); err != nil || !shadow {
|
||||
return "compileSmartClassifier missed the shadow classifier"
|
||||
}
|
||||
cls, shadow, riskZ, err := compileSmartClassifier("r", &SmartRouterConfig{})
|
||||
if err != nil || shadow {
|
||||
return "compileSmartClassifier kept shadowV2 from the previous call"
|
||||
}
|
||||
if cls != smartClassifierV1 || riskZ != defaultSmartRiskZ {
|
||||
return "compileSmartClassifier kept a result from the previous call"
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
// sessionHelperCheck replays the session helpers with known answers; yaegi v0.16.1 leaks
|
||||
// named results between calls, so each pure helper runs twice with different inputs.
|
||||
func sessionHelperCheck() string {
|
||||
cfg := &smartSessionCfg{idle: 1800, decayAsks: 3, regen: 120, toolStreak: 3}
|
||||
enc := smartSessionEncode(smartSession{pin: 2, loop: 1, streak: 1, calm: 2, lastScore: 300, msgCount: 7, askHash: 99, askAt: 5, seenAt: 6})
|
||||
if string(enc) != "v1|2|1|1|2|300|7|99|5|6" {
|
||||
return "smartSessionEncode changed between calls"
|
||||
}
|
||||
if got, ok := smartSessionDecode(enc); !ok || got.pin != 2 || got.seenAt != 6 || !got.found {
|
||||
return "smartSessionDecode missed a value"
|
||||
}
|
||||
if _, ok := smartSessionDecode([]byte("v1|1")); ok {
|
||||
return "smartSessionDecode kept ok from the previous call"
|
||||
}
|
||||
loopFeat := &smartFeatures{found: true, toolLoopTurn: true, msgCount: 9}
|
||||
loopSess := smartSession{found: true, pin: 1, loop: 2, askHash: 5, msgCount: 8, seenAt: 1}
|
||||
if rank, reason, _ := smartSessionRoute(cfg, 2, loopFeat, loopSess, smartVerdict{rank: 0}, 2, 5); rank != 2 || reason != "loop" {
|
||||
return "smartSessionRoute lost loop inheritance"
|
||||
}
|
||||
regenSess := smartSession{found: true, askHash: 9, askAt: 100, msgCount: 3, seenAt: 100}
|
||||
if rank, reason, _ := smartSessionRoute(cfg, 2, &smartFeatures{found: true, msgCount: 3}, regenSess, smartVerdict{}, 110, 9); rank != 1 || reason != "bump" {
|
||||
return "smartSessionRoute lost the regenerate bump"
|
||||
}
|
||||
if rank, reason, _ := smartSessionRoute(cfg, 2, &smartFeatures{found: true, msgCount: 5}, regenSess, smartVerdict{}, 110, 7); rank != 0 || reason != "score" {
|
||||
return "smartSessionRoute kept a bump from the previous call"
|
||||
}
|
||||
if s, changed := smartSessionOutcome(smartSession{found: true}, 0, 1, 2, true, false); !changed || s.pin != 1 {
|
||||
return "smartSessionOutcome missed an escalation"
|
||||
}
|
||||
if _, changed := smartSessionOutcome(smartSession{found: true}, 0, 0, 2, true, false); changed {
|
||||
return "smartSessionOutcome kept changed from the previous call"
|
||||
}
|
||||
if h := smartSessionHash("r", "u", "c", "s"); h != "f1968510ce9e8987eb3987daa6ba2c0d" || smartSessionHash("r", "u", "c", "t") == h {
|
||||
return "smartSessionHash changed between calls"
|
||||
}
|
||||
l := newSessionLRU()
|
||||
l.put("a", smartSession{found: true, pin: 1})
|
||||
if got, ok := l.get("a"); !ok || got.pin != 1 {
|
||||
return "sessionLRU lost an entry"
|
||||
}
|
||||
if _, ok := l.get("b"); ok {
|
||||
return "sessionLRU kept ok from the previous call"
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
// learnHelperCheck replays the calibration helpers with known answers, twice with different inputs.
|
||||
func learnHelperCheck() string {
|
||||
if lo, hi := smartWilsonBounds(5, 10, 1.96); lo < 0.236 || lo > 0.237 || hi < 0.763 || hi > 0.764 {
|
||||
return "smartWilsonBounds changed between calls"
|
||||
}
|
||||
if lo, hi := smartWilsonBounds(0, 0, 1.96); lo != 0 || hi != 1 {
|
||||
return "smartWilsonBounds kept bounds from the previous call"
|
||||
}
|
||||
c := &smartCalibCfg{maxLower: 150, step: 25, targetBadPct: 3, minSamples: 200}
|
||||
if got := smartCalibStep(0, 30, 200, c); got != 25 {
|
||||
return "smartCalibStep missed a step up"
|
||||
}
|
||||
if got := smartCalibStep(40, 0, 5000, c); got != 30 {
|
||||
return "smartCalibStep missed a relax step"
|
||||
}
|
||||
if got := smartCalibStep(10, 0, 100, c); got != 10 {
|
||||
return "smartCalibStep kept a step from the previous call"
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
// banditHelperCheck replays the bandit and saturation helpers with known answers, twice with different inputs.
|
||||
func banditHelperCheck() string {
|
||||
if got := smartThompsonScore(0, 0, 0, 0); got < 0.6666 || got > 0.6667 {
|
||||
return "smartThompsonScore changed between calls"
|
||||
}
|
||||
if got := smartThompsonScore(90, 100, 0, 1); got < 0.4466 || got > 0.4467 {
|
||||
return "smartThompsonScore kept a value from the previous call"
|
||||
}
|
||||
if smartBanditReward(true, 1, 1, 30) != 0 || smartBanditReward(false, 5, 1, 30) != 0.7 {
|
||||
return "smartBanditReward changed between calls"
|
||||
}
|
||||
if smartBanditReward(false, 0, 1, 30) != 1 {
|
||||
return "smartBanditReward kept a penalty from the previous call"
|
||||
}
|
||||
if !smartSaturated(4, 4) || smartSaturated(3, 4) || smartSaturated(9, 0) {
|
||||
return "smartSaturated changed between calls"
|
||||
}
|
||||
if smartUtil(2, 4) != 0.5 || smartUtil(9, 4) != 1 || smartUtil(1, 0) != 0 {
|
||||
return "smartUtil changed between calls"
|
||||
}
|
||||
perm := smartBanditOrder([]float64{0.2, 0.9, 0.5}, []bool{false, true, false}, -1)
|
||||
if len(perm) != 3 || perm[0] != 2 || perm[1] != 0 || perm[2] != 1 {
|
||||
return "smartBanditOrder missed the saturated-last order"
|
||||
}
|
||||
if !smartAllSaturated([]int{2, 3}, []int{2, 2}) || smartAllSaturated([]int{2, 1}, []int{2, 2}) {
|
||||
return "smartAllSaturated changed between calls"
|
||||
}
|
||||
if smartAllSaturated(nil, nil) || smartAllSaturated([]int{5}, []int{0}) {
|
||||
return "smartAllSaturated kept a result from the previous call"
|
||||
}
|
||||
perm = smartBanditOrder([]float64{0.2, 0.9}, []bool{false, false}, 0)
|
||||
if len(perm) != 2 || perm[0] != 0 || perm[1] != 1 {
|
||||
return "smartBanditOrder kept an order from the previous call"
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
func benchRank(fx benchFixture) int {
|
||||
endpoint := cacheEndpointChat
|
||||
if fx.Wire == "anthropic" {
|
||||
endpoint = cacheEndpointMessages
|
||||
}
|
||||
return classifySmart(benchRouter, fx.Request, endpoint).rank
|
||||
}
|
||||
|
||||
// BenchUnstable counts fixtures whose rank depends on call order, which is how
|
||||
// yaegi v0.16.1 leaking named results between calls shows up.
|
||||
func BenchUnstable() int {
|
||||
first := make([]int, len(benchFixtures))
|
||||
for i := 0; i < len(benchFixtures); i++ {
|
||||
first[i] = benchRank(benchFixtures[i])
|
||||
}
|
||||
bad := 0
|
||||
for i := len(benchFixtures) - 1; i >= 0; i-- {
|
||||
if benchRank(benchFixtures[i]) != first[i] {
|
||||
bad++
|
||||
}
|
||||
}
|
||||
return bad
|
||||
}
|
||||
|
||||
func BenchRun(n int) int {
|
||||
sum := 0
|
||||
for i := 0; i < n; i++ {
|
||||
fx := benchFixtures[i%%len(benchFixtures)]
|
||||
endpoint := cacheEndpointChat
|
||||
if fx.Wire == "anthropic" {
|
||||
endpoint = cacheEndpointMessages
|
||||
}
|
||||
if benchSessions != nil {
|
||||
f := extractSmartV2(fx.Request, endpoint)
|
||||
sc := benchSessions.open(benchRouter, fx.Request, &f, nil, nil)
|
||||
sum += classifySmartWith(benchRouter, fx.Request, endpoint, &f, sc).rank + 1
|
||||
if sc.dirty {
|
||||
benchSessions.put(sc.key, sc.next, time.Hour)
|
||||
}
|
||||
continue
|
||||
}
|
||||
sum += classifySmart(benchRouter, fx.Request, endpoint).rank + 1
|
||||
}
|
||||
return sum
|
||||
}
|
||||
`
|
||||
|
||||
var excludedDirs = map[string]bool{"tools": true, "integration": true, ".superpowers": true, "docs": true, ".git": true, "webui": true, "testdata": true}
|
||||
|
||||
type benchLayout struct {
|
||||
name string
|
||||
mid, top int
|
||||
}
|
||||
|
||||
func main() {
|
||||
minDPS := flag.Float64("min-dps", 2000, "fail when a v2 run decides fewer requests per second than this")
|
||||
dump := flag.Bool("ranks", false, "print each fixture's rank under yaegi, to diff against a native run")
|
||||
passes := flag.Int("passes", 3, "timed passes over the fixture set; the fastest counts")
|
||||
fixtures := flag.String("fixtures", "testdata/router_fixtures", "fixture directory, relative to the repo root")
|
||||
flag.Parse()
|
||||
root := "."
|
||||
if flag.NArg() > 0 {
|
||||
root = flag.Arg(0)
|
||||
}
|
||||
if err := run(root, *fixtures, *minDPS, *passes, *dump); err != nil {
|
||||
fmt.Fprintln(os.Stderr, "yaegi-bench: FAIL:", err)
|
||||
os.Exit(1)
|
||||
}
|
||||
}
|
||||
|
||||
func run(root, fixtureDir string, minDPS float64, passes int, dump bool) error {
|
||||
root, err := filepath.Abs(root)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
modulePath, err := readModulePath(filepath.Join(root, "go.mod"))
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
gopath, err := os.MkdirTemp("", "llmgw-yaegi-bench-*")
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer os.RemoveAll(gopath) //nolint:errcheck // best-effort cleanup of a temp dir
|
||||
pkgDir := filepath.Join(gopath, "src", modulePath)
|
||||
if err = copyTree(root, pkgDir); err != nil {
|
||||
return err
|
||||
}
|
||||
if err = os.Setenv("DO_NOT_TRACK", "1"); err != nil {
|
||||
return err
|
||||
}
|
||||
pkgName, err := readPackageName(pkgDir)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
hook := fmt.Sprintf(hookSource, pkgName)
|
||||
if err = os.WriteFile(filepath.Join(pkgDir, "zz_bench_hook.go"), []byte(hook), 0o600); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
i := interp.New(interp.Options{GoPath: gopath})
|
||||
if err = i.Use(stdlib.Symbols); err != nil {
|
||||
return err
|
||||
}
|
||||
if _, err = i.Eval(`import "` + modulePath + `"`); err != nil {
|
||||
return fmt.Errorf("import plugin under yaegi: %w", err)
|
||||
}
|
||||
setupV, err := i.Eval(pkgName + ".BenchSetup")
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
runV, err := i.Eval(pkgName + ".BenchRun")
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
setup := setupV.Interface().(func(string, string, int, int) int)
|
||||
loop := runV.Interface().(func(int) int)
|
||||
checkV, err := i.Eval(pkgName + ".BenchHelperCheck")
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if msg := checkV.Interface().(func() string)(); msg != "" {
|
||||
return fmt.Errorf("interpreter state leak: %s", msg)
|
||||
}
|
||||
unstableV, err := i.Eval(pkgName + ".BenchUnstable")
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
unstable := unstableV.Interface().(func() int)
|
||||
ranksV, err := i.Eval(pkgName + ".BenchRanks")
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
ranks := ranksV.Interface().(func() []string)
|
||||
|
||||
layouts := []benchLayout{{"deployed", 150, 350}, {"wide", 300, 600}}
|
||||
var failures []string
|
||||
for _, classifier := range []string{"v1", "v2", "v2s"} {
|
||||
for _, l := range layouts {
|
||||
n := setup(filepath.Join(root, fixtureDir), classifier, l.mid, l.top)
|
||||
if n == 0 {
|
||||
return fmt.Errorf("no fixtures under %s", fixtureDir)
|
||||
}
|
||||
if bad := unstable(); bad > 0 && classifier != "v2s" {
|
||||
return fmt.Errorf("%s %s: %d fixtures changed rank between a forward and a reverse pass", classifier, l.name, bad)
|
||||
}
|
||||
if dump {
|
||||
fmt.Printf("ranks %s %s %s\n", classifier, l.name, strings.Join(ranks(), " "))
|
||||
}
|
||||
loop(n)
|
||||
best := time.Duration(1<<63 - 1)
|
||||
sum := 0
|
||||
for p := 0; p < passes; p++ {
|
||||
start := time.Now()
|
||||
sum = loop(n)
|
||||
if d := time.Since(start); d < best {
|
||||
best = d
|
||||
}
|
||||
}
|
||||
dps := float64(n) / best.Seconds()
|
||||
fmt.Printf("yaegi %s %-8s fixtures=%d pass=%v decisions/s=%.0f rank-sum=%d\n", classifier, l.name, n, best.Round(time.Millisecond), dps, sum)
|
||||
if classifier != "v1" && dps < minDPS {
|
||||
failures = append(failures, fmt.Sprintf("%s %.0f < %.0f", l.name, dps, minDPS))
|
||||
}
|
||||
}
|
||||
}
|
||||
if len(failures) > 0 {
|
||||
sort.Strings(failures)
|
||||
return fmt.Errorf("below the throughput gate: %s", strings.Join(failures, "; "))
|
||||
}
|
||||
fmt.Println("yaegi-bench: OK")
|
||||
return nil
|
||||
}
|
||||
|
||||
func readModulePath(goModPath string) (string, error) {
|
||||
f, err := os.Open(goModPath)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
defer f.Close() //nolint:errcheck // read-side close
|
||||
sc := bufio.NewScanner(f)
|
||||
for sc.Scan() {
|
||||
if after, ok := strings.CutPrefix(strings.TrimSpace(sc.Text()), "module "); ok {
|
||||
return strings.TrimSpace(after), nil
|
||||
}
|
||||
}
|
||||
return "", fmt.Errorf("no module directive in %s", goModPath)
|
||||
}
|
||||
|
||||
func readPackageName(dir string) (string, error) {
|
||||
entries, err := os.ReadDir(dir)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
for _, e := range entries {
|
||||
name := e.Name()
|
||||
if e.IsDir() || !strings.HasSuffix(name, ".go") || strings.HasSuffix(name, "_test.go") {
|
||||
continue
|
||||
}
|
||||
raw, readErr := os.ReadFile(filepath.Join(dir, name))
|
||||
if readErr != nil {
|
||||
return "", readErr
|
||||
}
|
||||
for _, line := range strings.Split(string(raw), "\n") {
|
||||
if after, ok := strings.CutPrefix(strings.TrimSpace(line), "package "); ok {
|
||||
return strings.TrimSpace(after), nil
|
||||
}
|
||||
}
|
||||
}
|
||||
return "", fmt.Errorf("no package declaration in %s", dir)
|
||||
}
|
||||
|
||||
// copyTree copies src to dst without the directories the interpreter must not see.
|
||||
func copyTree(src, dst string) error {
|
||||
return filepath.WalkDir(src, func(path string, d fs.DirEntry, err error) error {
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
rel, relErr := filepath.Rel(src, path)
|
||||
if relErr != nil {
|
||||
return relErr
|
||||
}
|
||||
if d.IsDir() {
|
||||
if excludedDirs[rel] {
|
||||
return filepath.SkipDir
|
||||
}
|
||||
return os.MkdirAll(filepath.Join(dst, rel), 0o750)
|
||||
}
|
||||
return copyFile(path, filepath.Join(dst, rel))
|
||||
})
|
||||
}
|
||||
|
||||
func copyFile(src, dst string) error {
|
||||
in, err := os.Open(src)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer in.Close() //nolint:errcheck // read-side close
|
||||
out, err := os.Create(dst)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer out.Close() //nolint:errcheck // Close is checked below
|
||||
if _, err = io.Copy(out, in); err != nil {
|
||||
return err
|
||||
}
|
||||
return out.Close()
|
||||
}
|
||||
+252
-17
@@ -697,7 +697,7 @@ func run() error {
|
||||
return fmt.Errorf("marshal metrics escaping probe user name: %w", err)
|
||||
}
|
||||
|
||||
attemptAccountingOverride := `{"maxConcurrency":4,"concurrencyAutodetect":true,"failover":{"enabled":true},"breaker":{"failureThreshold":2,"openDuration":"3s","maxOpenDuration":"6s"},` +
|
||||
attemptAccountingOverride := `{"rateLimitHeaders":true,"limitExemptKinds":["embedding","reranking"],"maxConcurrency":4,"concurrencyAutodetect":true,"failover":{"enabled":true},"breaker":{"failureThreshold":2,"openDuration":"3s","maxOpenDuration":"6s"},` +
|
||||
`"providers":{"openai":{"type":"openai","baseUrl":"` + upstream.URL + `","apiKey":"sk-up","models":["` + testDataWantModel + `","` + builtinLookupModelID + `"]},` +
|
||||
`"brk":{"type":"openai","baseUrl":"` + brkUpstream.URL + `","apiKey":"sk-up","discovery":true,"discoveryInterval":"1ms"},` +
|
||||
// "warmretry" backs exerciseWarmFillRetry (production incident fix,
|
||||
@@ -724,6 +724,10 @@ func run() error {
|
||||
// — see its own const block doc comment above for why this
|
||||
// provider carries no failover candidate.
|
||||
`"` + eventsUpstreamErrorProviderName + `":{"type":"openai","baseUrl":"` + eventsUpstreamErrorUpstream.URL + `","apiKey":"sk-up","models":["` + eventsUpstreamErrorProviderModel + `"]},` +
|
||||
// routerProbeBadProvider/routerProbeOKProvider back exerciseSmartRouter:
|
||||
// they reuse the always-500 and always-200 upstreams above.
|
||||
`"` + routerProbeBadProvider + `":{"type":"openai","baseUrl":"` + eventsUpstreamErrorUpstream.URL + `","apiKey":"sk-up","models":["rp-bad"]},` +
|
||||
`"` + routerProbeOKProvider + `":{"type":"openai","baseUrl":"` + upstream.URL + `","apiKey":"sk-up","models":["rp-ok-a","rp-ok-b"]},` +
|
||||
// "anthropic" backs the /v1/messages passthrough probes
|
||||
// (exerciseMessagesRoute, below): a real anthropic-type provider,
|
||||
// interpreted end to end through
|
||||
@@ -781,7 +785,14 @@ func run() error {
|
||||
`"` + round3P1AGroupName + `":{"providers":["round3-shared"],"models":["` + round3ModelID + `"]},` +
|
||||
`"` + round3P1BGroupName + `":{"providers":["round3-shared"],"passthroughPaths":["v1/chat/completions"]},` +
|
||||
`"` + round3P2HomeGroupName + `":{"providers":["round3-alpha"]},` +
|
||||
`"` + round3P2FriendsGroupName + `":{"providers":["round3-shared"],"passthroughPaths":["v1/chat/completions"]}},` +
|
||||
`"` + round3P2FriendsGroupName + `":{"providers":["round3-shared"],"passthroughPaths":["v1/chat/completions"]},` +
|
||||
`"` + memberLimitsGroupName + `":{"memberLimits":{"requestsPerMinute":2,"pacing":{"startPct":50,"maxDelay":"20ms"}}},` +
|
||||
`"` + routerProbeDenyGroup + `":{"models":["` + routerProbeEscalating + `"]}},` +
|
||||
// smartRouters: routerProbeEscalating escalates a failing tier-0 to
|
||||
// tier-1; routerProbeHashed exercises hash selection (hash/fnv).
|
||||
`"smartRouters":{"` + routerProbeEscalating + `":{"tiers":[{"name":"` + routerProbeTier0 + `","minScore":0,"models":["` + routerProbeBadProvider + `/rp-bad"]},{"name":"` + routerProbeTier1 + `","minScore":300,"models":["` + routerProbeOKProvider + `/rp-ok-a"]}]},` +
|
||||
`"` + routerProbeHashed + `":{"selection":"hash","tiers":[{"name":"rp-h0","minScore":0,"models":["` + routerProbeOKProvider + `/rp-ok-a","` + routerProbeOKProvider + `/rp-ok-b"]}]},` +
|
||||
`"` + routerProbeSession + `":{"classifier":"v2","session":{"enabled":true},"tiers":[{"name":"` + routerProbeTier0 + `","minScore":0,"models":["` + routerProbeBadProvider + `/rp-bad"]},{"name":"` + routerProbeTier1 + `","minScore":300,"models":["` + routerProbeOKProvider + `/rp-ok-b"]}]}},` +
|
||||
// modelMeta (feature v0.23): a config-override entry for
|
||||
// testDataWantModel, so exerciseHandler's GET /v1/models
|
||||
// assertion below proves resolveModelMeta's config-override
|
||||
@@ -863,7 +874,11 @@ func run() error {
|
||||
// exerciseRateLimitEventAndRejections' own — group "default"
|
||||
// (allow-all), but with its own requestsPerMinute:1 limit so a
|
||||
// second call under this key alone 429s deterministically.
|
||||
`{"name":"events-probe","group":"default","apiKey":"` + eventsProbeUserAPIKey + `","limits":{"requestsPerMinute":1}}]}}`
|
||||
`{"name":"events-probe","group":"default","apiKey":"` + eventsProbeUserAPIKey + `","limits":{"requestsPerMinute":1}},` +
|
||||
`{"name":"exempt-probe","group":"default","apiKey":"` + limitExemptProbeAPIKey + `","limits":{"requestsPerMinute":1,"tokensPerMinute":50}},` +
|
||||
`{"name":"member-a","group":"` + memberLimitsGroupName + `","apiKey":"` + memberLimitsUserAAPIKey + `"},` +
|
||||
`{"name":"member-b","group":"` + memberLimitsGroupName + `","apiKey":"` + memberLimitsUserBAPIKey + `"},` +
|
||||
`{"name":"router-deny","group":"` + routerProbeDenyGroup + `","apiKey":"` + routerProbeDenyAPIKey + `"}]}}`
|
||||
if err = json.Unmarshal([]byte(attemptAccountingOverride), cfgVal.Interface()); err != nil {
|
||||
return fmt.Errorf("decode attempt-accounting harness override into the interpreted Config: %w", err)
|
||||
}
|
||||
@@ -1036,6 +1051,9 @@ func run() error {
|
||||
if err := exerciseUsageModelsSpan(handler); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := exerciseSmartRouter(handler); err != nil {
|
||||
return err
|
||||
}
|
||||
// exerciseRateLimitEventAndRejections (F3/F4, v0.3 dashboard task)
|
||||
// runs next, against its own dedicated requestsPerMinute:1 user
|
||||
// (eventsProbeUserAPIKey), so its two calls cannot perturb any earlier
|
||||
@@ -1043,6 +1061,12 @@ func run() error {
|
||||
if err := exerciseRateLimitEventAndRejections(handler); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := exerciseMemberLimits(handler); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := exerciseLimitExempt(handler); err != nil {
|
||||
return err
|
||||
}
|
||||
// exerciseUpstreamAndTimeoutEvents (F3 hook 2, coordinator request
|
||||
// 2026-09-23) runs LAST: each of its two assertions reads GET
|
||||
// /admin/api/events?limit=1 for the single newest entry right after
|
||||
@@ -1056,6 +1080,12 @@ func run() error {
|
||||
// instance (own config, own fake Redis, own upstream) rather than the
|
||||
// shared `handler` above — see that function's own doc comment for
|
||||
// why.
|
||||
if err := exerciseRouterV2(i, pkgName); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := exerciseRouterFirstByte(i, pkgName); err != nil {
|
||||
return err
|
||||
}
|
||||
return exerciseAdminRedesignStats(i, pkgName)
|
||||
}
|
||||
|
||||
@@ -1191,6 +1221,102 @@ const (
|
||||
round3PersonalModelID = "round3-shared/m1"
|
||||
)
|
||||
|
||||
// memberLimitsGroupName is a group whose memberLimits (requestsPerMinute:2)
|
||||
// give each of its two users, memberLimitsUserAAPIKey/UserBAPIKey, an own
|
||||
// counter; no other probe may reuse these keys.
|
||||
const (
|
||||
memberLimitsGroupName = "member-limits-group"
|
||||
memberLimitsUserAAPIKey = "sk-member-limits-a" // #nosec G101 -- test fixture literal, not a real credential
|
||||
memberLimitsUserBAPIKey = "sk-member-limits-b" // #nosec G101 -- test fixture literal, not a real credential
|
||||
)
|
||||
|
||||
// exerciseMemberLimits proves group memberLimits (auth.go's buildEntry,
|
||||
// member_limits.go's effectiveUserLimits) under the real interpreter: user A
|
||||
// is refused on the third request while user B, in the same group, still
|
||||
// has their own counter.
|
||||
func exerciseMemberLimits(handler http.Handler) error {
|
||||
body := `{"model":"` + testDataWantModel + `","messages":[{"role":"user","content":"hi"}]}`
|
||||
post := func(key string) *httptest.ResponseRecorder {
|
||||
req := httptest.NewRequest(http.MethodPost, "/v1/chat/completions", strings.NewReader(body))
|
||||
req.Header.Set("Authorization", "Bearer "+key)
|
||||
req.Header.Set("Content-Type", "application/json")
|
||||
rec := httptest.NewRecorder()
|
||||
handler.ServeHTTP(rec, req)
|
||||
return rec
|
||||
}
|
||||
steps := []struct {
|
||||
label string
|
||||
key string
|
||||
want int
|
||||
}{
|
||||
{"A 1st", memberLimitsUserAAPIKey, http.StatusOK},
|
||||
{"A 2nd", memberLimitsUserAAPIKey, http.StatusOK},
|
||||
{"A 3rd (over memberLimits requestsPerMinute:2)", memberLimitsUserAAPIKey, http.StatusTooManyRequests},
|
||||
{"B 1st (own counter)", memberLimitsUserBAPIKey, http.StatusOK},
|
||||
}
|
||||
for i, st := range steps {
|
||||
rec := post(st.key)
|
||||
if rec.Code != st.want {
|
||||
return fmt.Errorf("memberLimits harness, %s: status = %d, want %d, body=%s", st.label, rec.Code, st.want, rec.Body.String())
|
||||
}
|
||||
if got := rec.Header().Get("x-ratelimit-limit-requests"); got != "2" {
|
||||
return fmt.Errorf("memberLimits harness, %s: x-ratelimit-limit-requests = %q, want 2", st.label, got)
|
||||
}
|
||||
if i == 1 && rec.Header().Get("X-Llmgw-Paced-Ms") == "" {
|
||||
return fmt.Errorf("memberLimits harness, %s: X-Llmgw-Paced-Ms missing at 100%% of the limit", st.label)
|
||||
}
|
||||
}
|
||||
fmt.Println("yaegi-check: group memberLimits enforced per member user, with rate-limit headers and pacing, under the interpreter")
|
||||
return nil
|
||||
}
|
||||
|
||||
// limitExemptProbeAPIKey authenticates exerciseLimitExempt's own inline user,
|
||||
// limited to requestsPerMinute:1; no other probe may reuse it.
|
||||
const limitExemptProbeAPIKey = "sk-limit-exempt-probe" // #nosec G101 -- test fixture literal, not a real credential
|
||||
|
||||
// exerciseLimitExempt proves limitExemptKinds under the real interpreter:
|
||||
// embedding (the /v1/embeddings route) and reranking (a native passthrough
|
||||
// /rerank path) requests are never refused or given rate-limit headers,
|
||||
// while the same user's chat request is refused.
|
||||
func exerciseLimitExempt(handler http.Handler) error {
|
||||
post := func(path, body string) *httptest.ResponseRecorder {
|
||||
req := httptest.NewRequest(http.MethodPost, path, strings.NewReader(body))
|
||||
req.Header.Set("Authorization", "Bearer "+limitExemptProbeAPIKey)
|
||||
req.Header.Set("Content-Type", "application/json")
|
||||
rec := httptest.NewRecorder()
|
||||
handler.ServeHTTP(rec, req)
|
||||
return rec
|
||||
}
|
||||
chat := `{"model":"` + testDataWantModel + `","messages":[{"role":"user","content":"hi"}]}`
|
||||
if rec := post("/v1/chat/completions", chat); rec.Code != http.StatusOK {
|
||||
return fmt.Errorf("limitExempt harness, chat 1st: status = %d, want 200, body=%s", rec.Code, rec.Body.String())
|
||||
}
|
||||
exempt := []struct{ label, path, body string }{
|
||||
{"embeddings", "/v1/embeddings", `{"model":"` + testDataWantModel + `","input":"hi"}`},
|
||||
{"rerank passthrough", "/openai/v1/rerank", `{"query":"q","documents":["a"]}`},
|
||||
}
|
||||
for _, e := range exempt {
|
||||
for i := 0; i < 3; i++ {
|
||||
rec := post(e.path, e.body)
|
||||
if rec.Code != http.StatusOK {
|
||||
return fmt.Errorf("limitExempt harness, %s #%d: status = %d, want 200, body=%s", e.label, i+1, rec.Code, rec.Body.String())
|
||||
}
|
||||
for k := range rec.Header() {
|
||||
lk := strings.ToLower(k)
|
||||
// RateLimit-Policy stays: it carries the global maxConcurrency member.
|
||||
if strings.HasPrefix(lk, "x-ratelimit-") || strings.HasPrefix(lk, "anthropic-ratelimit-") || lk == "ratelimit" || lk == "x-llmgw-paced-ms" {
|
||||
return fmt.Errorf("limitExempt harness, %s #%d: unexpected header %s on an exempt response", e.label, i+1, k)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
if rec := post("/v1/chat/completions", chat); rec.Code != http.StatusTooManyRequests {
|
||||
return fmt.Errorf("limitExempt harness, chat 2nd: status = %d, want 429, body=%s", rec.Code, rec.Body.String())
|
||||
}
|
||||
fmt.Println("yaegi-check: limitExemptKinds exempts embedding and reranking requests from limits, under the interpreter")
|
||||
return nil
|
||||
}
|
||||
|
||||
// eventsProbeUserAPIKey authenticates exerciseRateLimitEventAndRejections'
|
||||
// own inline user (run()'s "users" override): group "default" (allow-all,
|
||||
// like every other probe user), but with its own requestsPerMinute:1
|
||||
@@ -1330,7 +1456,7 @@ func stampReleaseVersion(pkgDir string) error {
|
||||
// silently drift out of sync) every time `make pricing-sync`
|
||||
// regenerates the table against updated upstream data.
|
||||
func readBuiltinContextTokens(repoRoot, modelID string) (int, error) {
|
||||
data, err := os.ReadFile(filepath.Join(repoRoot, "pricing_data_gen.go"))
|
||||
data, err := os.ReadFile(filepath.Join(repoRoot, "pricing_data_gen.go")) //nolint:gosec // G703: repoRoot is the dev operator's own argv, joined with a fixed file name
|
||||
if err != nil {
|
||||
return 0, fmt.Errorf("read pricing_data_gen.go: %w", err)
|
||||
}
|
||||
@@ -3175,7 +3301,7 @@ func readProviderAttemptCounters(handler http.Handler, providerName string) (att
|
||||
// readModulePath returns the module path declared by goModPath's
|
||||
// "module" directive.
|
||||
func readModulePath(goModPath string) (string, error) {
|
||||
f, err := os.Open(goModPath)
|
||||
f, err := os.Open(goModPath) //nolint:gosec // G703: dev tool reading go.mod under the repo root given on its own command line
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
@@ -3220,7 +3346,7 @@ func readPackageName(dir string) (string, error) {
|
||||
|
||||
// scanPackageDecl reads path's leading "package X" line, if any.
|
||||
func scanPackageDecl(path string) (string, error) {
|
||||
f, err := os.Open(path)
|
||||
f, err := os.Open(path) //nolint:gosec // G703: dev tool reading Go files under the repo root given on its own command line
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
@@ -3246,7 +3372,7 @@ func copyRepoSource(repoRoot, destDir string) error {
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if err := os.MkdirAll(destDir, 0o750); err != nil {
|
||||
if err := os.MkdirAll(destDir, 0o750); err != nil { //nolint:gosec // G703: dev tool copying under paths from its own command line and temp dirs
|
||||
return err
|
||||
}
|
||||
for _, e := range entries {
|
||||
@@ -3270,7 +3396,7 @@ func copyRepoSource(repoRoot, destDir string) error {
|
||||
|
||||
// copyDir recursively copies src to dst.
|
||||
func copyDir(src, dst string) error {
|
||||
return filepath.WalkDir(src, func(path string, d fs.DirEntry, err error) error {
|
||||
return filepath.WalkDir(src, func(path string, d fs.DirEntry, err error) error { //nolint:gosec // G703: dev tool copying under paths from its own command line and temp dirs
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
@@ -3280,7 +3406,7 @@ func copyDir(src, dst string) error {
|
||||
}
|
||||
target := filepath.Join(dst, rel)
|
||||
if d.IsDir() {
|
||||
return os.MkdirAll(target, 0o750)
|
||||
return os.MkdirAll(target, 0o750) //nolint:gosec // G703: dev tool copying under paths from its own command line and temp dirs
|
||||
}
|
||||
return copyFile(path, target)
|
||||
})
|
||||
@@ -3288,16 +3414,16 @@ func copyDir(src, dst string) error {
|
||||
|
||||
// copyFile copies src to dst, creating dst's parent directory if needed.
|
||||
func copyFile(src, dst string) error {
|
||||
in, err := os.Open(src)
|
||||
in, err := os.Open(src) //nolint:gosec // G703: dev tool copying under paths from its own command line and temp dirs
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer in.Close() //nolint:errcheck // read-side close; nothing actionable on failure
|
||||
|
||||
if err = os.MkdirAll(filepath.Dir(dst), 0o750); err != nil {
|
||||
if err = os.MkdirAll(filepath.Dir(dst), 0o750); err != nil { //nolint:gosec // G703: dev tool copying under paths from its own command line and temp dirs
|
||||
return err
|
||||
}
|
||||
out, err := os.Create(dst)
|
||||
out, err := os.Create(dst) //nolint:gosec // G703: dev tool copying under paths from its own command line and temp dirs
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
@@ -3324,7 +3450,7 @@ type yamlLine struct {
|
||||
// in this harness module — the plugin module never parses YAML itself,
|
||||
// Traefik does that before handing the plugin its already-decoded Config.
|
||||
func extractTraefikYAMLTestData(path string) (map[string]any, error) {
|
||||
raw, err := os.ReadFile(path)
|
||||
raw, err := os.ReadFile(path) //nolint:gosec // G703: dev tool copying under paths from its own command line and temp dirs
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
@@ -3444,8 +3570,8 @@ func parseList(lines []yamlLine, pos *int, indent int) []any {
|
||||
}
|
||||
|
||||
// collectionOrScalar maps a "key: value" line's already-trimmed val to
|
||||
// an empty map/slice for "{}"/"[]", or to parseScalar(val) otherwise. It
|
||||
// does not recurse into a further nested block — no key in this file's
|
||||
// an empty map/slice for "{}"/"[]", a one-line "[a, b]" list of scalars,
|
||||
// or parseScalar(val) otherwise. It does not recurse into a further nested block — no key in this file's
|
||||
// testData needs a map/list value inside a list item's own fields, and
|
||||
// this harness parses only what .traefik.yml actually contains.
|
||||
func collectionOrScalar(val string) any {
|
||||
@@ -3454,9 +3580,15 @@ func collectionOrScalar(val string) any {
|
||||
return map[string]any{}
|
||||
case "[]":
|
||||
return []any{}
|
||||
default:
|
||||
return parseScalar(val)
|
||||
}
|
||||
if strings.HasPrefix(val, "[") && strings.HasSuffix(val, "]") {
|
||||
var items []any
|
||||
for _, part := range strings.Split(val[1:len(val)-1], ",") {
|
||||
items = append(items, parseScalar(strings.TrimSpace(part)))
|
||||
}
|
||||
return items
|
||||
}
|
||||
return parseScalar(val)
|
||||
}
|
||||
|
||||
// parseScalar converts a YAML scalar token to a bool, int64, float64, or
|
||||
@@ -3974,6 +4106,109 @@ func exerciseUpstreamAndTimeoutEvents(handler http.Handler) error {
|
||||
return nil
|
||||
}
|
||||
|
||||
const (
|
||||
routerProbeBadProvider = "routerprobe-bad"
|
||||
routerProbeOKProvider = "routerprobe-ok"
|
||||
routerProbeEscalating = "rp-auto"
|
||||
routerProbeHashed = "rp-hash"
|
||||
routerProbeSession = "rp-sess"
|
||||
routerProbeTier0 = "rp-t0"
|
||||
routerProbeTier1 = "rp-t1"
|
||||
routerProbeDenyGroup = "routerprobe-deny"
|
||||
routerProbeDenyAPIKey = "sk-router-deny" // #nosec G101 -- test fixture literal, not a real credential
|
||||
)
|
||||
|
||||
func routerProbeChat(handler http.Handler, model, key string) *httptest.ResponseRecorder {
|
||||
req := httptest.NewRequest(http.MethodPost, "/v1/chat/completions", strings.NewReader(
|
||||
`{"model":"`+model+`","messages":[{"role":"user","content":"hi"}]}`,
|
||||
))
|
||||
req.Header.Set("Authorization", "Bearer "+key)
|
||||
req.Header.Set("Content-Type", "application/json")
|
||||
rec := httptest.NewRecorder()
|
||||
handler.ServeHTTP(rec, req)
|
||||
return rec
|
||||
}
|
||||
|
||||
// exerciseSmartRouter drives the smart router under the interpreter: tier
|
||||
// escalation after a 500, hash selection (hash/fnv), the escalation metric,
|
||||
// and the *routerTargetError type assertion on a denied router.
|
||||
func exerciseSmartRouter(handler http.Handler) error {
|
||||
rec := routerProbeChat(handler, routerProbeEscalating, testDataUserAPIKey)
|
||||
if rec.Code != http.StatusOK {
|
||||
return fmt.Errorf("POST /v1/chat/completions (router %q, tier-0 upstream 500): status = %d, want 200 via escalation, body=%s", routerProbeEscalating, rec.Code, rec.Body.String())
|
||||
}
|
||||
if got := rec.Header().Get("X-Llmgw-Router-Tier"); got != routerProbeTier1 {
|
||||
return fmt.Errorf("router %q: X-Llmgw-Router-Tier = %q, want %q", routerProbeEscalating, got, routerProbeTier1)
|
||||
}
|
||||
|
||||
rec = routerProbeChat(handler, routerProbeHashed, testDataUserAPIKey)
|
||||
if rec.Code != http.StatusOK {
|
||||
return fmt.Errorf("POST /v1/chat/completions (router %q, hash selection): status = %d, want 200, body=%s", routerProbeHashed, rec.Code, rec.Body.String())
|
||||
}
|
||||
if got := rec.Header().Get("X-Llmgw-Routed-Model"); !strings.HasPrefix(got, routerProbeOKProvider+"/rp-ok-") {
|
||||
return fmt.Errorf("router %q: X-Llmgw-Routed-Model = %q, want a %s/rp-ok-* model", routerProbeHashed, got, routerProbeOKProvider)
|
||||
}
|
||||
|
||||
if err := exerciseRouterSession(handler); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
rec = routerProbeChat(handler, routerProbeEscalating, routerProbeDenyAPIKey)
|
||||
if rec.Code != http.StatusForbidden {
|
||||
return fmt.Errorf("POST /v1/chat/completions (router %q, every target denied): status = %d, want 403, body=%s", routerProbeEscalating, rec.Code, rec.Body.String())
|
||||
}
|
||||
var env struct {
|
||||
Error struct {
|
||||
Message string `json:"message"`
|
||||
} `json:"error"`
|
||||
}
|
||||
if err := json.Unmarshal(rec.Body.Bytes(), &env); err != nil || env.Error.Message == "" {
|
||||
return fmt.Errorf("denied router response is not an error envelope: err=%v body=%s", err, rec.Body.String())
|
||||
}
|
||||
|
||||
metricsReq := httptest.NewRequest(http.MethodGet, "/metrics", nil)
|
||||
metricsReq.Header.Set("Authorization", "Bearer "+attemptAccountingAdminAPIKey)
|
||||
metricsRec := httptest.NewRecorder()
|
||||
handler.ServeHTTP(metricsRec, metricsReq)
|
||||
want := `llmgateway_router_escalations_total{router="` + routerProbeEscalating + `",from_tier="` + routerProbeTier0 + `",to_tier="` + routerProbeTier1 + `"} 1`
|
||||
if !strings.Contains(metricsRec.Body.String(), want) {
|
||||
return fmt.Errorf("GET /metrics: missing %q; body=%s", want, metricsRec.Body.String())
|
||||
}
|
||||
|
||||
fmt.Println("yaegi-check: smart router escalated tier-0 500 to tier-1, hash selection served, denied router returned a 403 envelope, escalation metric incremented under the interpreter")
|
||||
return nil
|
||||
}
|
||||
|
||||
// exerciseRouterSession drives a session-enabled v2 router under the interpreter: the first
|
||||
// request escalates past the failing tier 0, so the pin makes the second one start at tier 1.
|
||||
func exerciseRouterSession(handler http.Handler) error {
|
||||
post := func(text string) *httptest.ResponseRecorder {
|
||||
req := httptest.NewRequest(http.MethodPost, "/v1/chat/completions", strings.NewReader(
|
||||
`{"model":"`+routerProbeSession+`","metadata":{"user_id":"yaegi-probe"},"messages":[{"role":"user","content":"`+text+`"}]}`,
|
||||
))
|
||||
req.Header.Set("Authorization", "Bearer "+testDataUserAPIKey)
|
||||
req.Header.Set("Content-Type", "application/json")
|
||||
rec := httptest.NewRecorder()
|
||||
handler.ServeHTTP(rec, req)
|
||||
return rec
|
||||
}
|
||||
first := post("hi")
|
||||
if first.Code != http.StatusOK || first.Header().Get("X-Llmgw-Router-Tier") != routerProbeTier1 || first.Header().Get("X-Llmgw-Router-Reason") != "score" {
|
||||
return fmt.Errorf("router %q first request: status=%d tier=%q reason=%q, want 200 %s score", routerProbeSession, first.Code, first.Header().Get("X-Llmgw-Router-Tier"), first.Header().Get("X-Llmgw-Router-Reason"), routerProbeTier1)
|
||||
}
|
||||
second := post("hello again")
|
||||
if second.Code != http.StatusOK || second.Header().Get("X-Llmgw-Router-Reason") != "session" {
|
||||
return fmt.Errorf("router %q second request: status=%d reason=%q, want 200 session", routerProbeSession, second.Code, second.Header().Get("X-Llmgw-Router-Reason"))
|
||||
}
|
||||
// The same ask again inside the regenerate window is a retry of an answer the user did not take.
|
||||
third := post("hello again")
|
||||
if third.Code != http.StatusOK || third.Header().Get("X-Llmgw-Router-Reason") != "bump" {
|
||||
return fmt.Errorf("router %q regenerate: status=%d reason=%q, want 200 bump", routerProbeSession, third.Code, third.Header().Get("X-Llmgw-Router-Reason"))
|
||||
}
|
||||
fmt.Println("yaegi-check: session router pinned the escalated tier, routed the next turn by the session and bumped a regenerate under the interpreter")
|
||||
return nil
|
||||
}
|
||||
|
||||
// latestEventKindAndStatus reads GET /admin/api/events?limit=1 as admin
|
||||
// and returns the single newest event's kind/status — the shared read
|
||||
// exerciseUpstreamAndTimeoutEvents' two assertions both drive, limit=1
|
||||
|
||||
@@ -0,0 +1,148 @@
|
||||
// This file adds the smart router first-byte deadline probe: a slow upstream, one that sends headers and a
|
||||
// keep-alive comment and then stalls, and a router whose every model is slow, interpreted under Yaegi.
|
||||
//
|
||||
// It builds its OWN Gateway so no other probe's traffic or state reaches it.
|
||||
package main
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"io"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/traefik/yaegi/interp"
|
||||
)
|
||||
|
||||
const (
|
||||
fbOK = "fb-ok"
|
||||
fbDead = "fb-dead"
|
||||
fbFall = "fb-fall"
|
||||
fbNoFall = "fb-nofall"
|
||||
fbTopAsk = "escalate-me"
|
||||
fbTimeout = "1s"
|
||||
// fbStall outlasts every probe request; handlers return as soon as the gateway cancels the attempt.
|
||||
fbStall = 20 * time.Second
|
||||
// fbBudget is far above one deadline and far below fbStall: an escalated answer arrives well inside it.
|
||||
fbBudget = 8 * time.Second
|
||||
fbChunk = "data: {\"id\":\"c1\",\"object\":\"chat.completion.chunk\",\"choices\":[{\"delta\":{\"content\":\"Hi\"}}]}\n\ndata: [DONE]\n\n"
|
||||
)
|
||||
|
||||
// fbSlowUpstream drains the request, then stalls until the client goes away. A stream request gets
|
||||
// headers and a comment line first, so only the first data event is late.
|
||||
func fbSlowUpstream() *httptest.Server {
|
||||
return httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
body, _ := io.ReadAll(r.Body)
|
||||
if strings.Contains(string(body), `"stream":true`) {
|
||||
w.Header().Set("Content-Type", "text/event-stream")
|
||||
w.WriteHeader(http.StatusOK)
|
||||
_, _ = w.Write([]byte(": keep-alive\n\n"))
|
||||
w.(http.Flusher).Flush()
|
||||
}
|
||||
select {
|
||||
case <-r.Context().Done():
|
||||
case <-time.After(fbStall):
|
||||
}
|
||||
}))
|
||||
}
|
||||
|
||||
// fbFastUpstream answers a plain or a stream request at once.
|
||||
func fbFastUpstream() *httptest.Server {
|
||||
return httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
body, _ := io.ReadAll(r.Body)
|
||||
if strings.Contains(string(body), `"stream":true`) {
|
||||
w.Header().Set("Content-Type", "text/event-stream")
|
||||
_, _ = w.Write([]byte(fbChunk))
|
||||
return
|
||||
}
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
_, _ = w.Write([]byte(rv2GoodBody))
|
||||
}))
|
||||
}
|
||||
|
||||
func fbConfig(slow, slow2, fast string) string {
|
||||
tiers := func(a, b string) string {
|
||||
return `"tiers":[{"name":"t0","minScore":0,"models":["` + a + `/m"]},{"name":"t1","minScore":300,"models":["` + b + `/m"]}]`
|
||||
}
|
||||
return `{"providers":{` + rv2ProviderJSON("fb-slow", slow) + `,` + rv2ProviderJSON("fb-slow2", slow2) + `,` + rv2ProviderJSON("fb-fast", fast) + `},` +
|
||||
`"groups":{"rv2g":{}},` +
|
||||
`"users":{"inline":[{"name":"rv2-user","group":"rv2g","apiKey":"` + rv2UserKey + `"}]},` +
|
||||
`"smartRouters":{` +
|
||||
`"` + fbOK + `":{"firstByteTimeout":"` + fbTimeout + `",` + tiers("fb-slow", "fb-fast") + `},` +
|
||||
`"` + fbDead + `":{"firstByteTimeout":"` + fbTimeout + `",` + tiers("fb-slow", "fb-slow2") + `},` +
|
||||
`"` + fbFall + `":{"firstByteTimeout":"` + fbTimeout + `","timeoutFallback":true,` + fbTopSlow + `},` +
|
||||
`"` + fbNoFall + `":{"firstByteTimeout":"` + fbTimeout + `",` + fbTopSlow + `}}}`
|
||||
}
|
||||
|
||||
// fbTopSlow is a router whose top tier is slow, a lower tier fast, and a keyword that routes to the top.
|
||||
const fbTopSlow = `"keywordRules":[{"tier":"t1","keywords":["` + fbTopAsk + `"]}],"tiers":[{"name":"t0","minScore":0,"models":["fb-fast/m"]},{"name":"t1","minScore":300,"models":["fb-slow/m"]}]`
|
||||
|
||||
func fbPost(handler http.Handler, model string, stream bool) (*httptest.ResponseRecorder, time.Duration) {
|
||||
return fbPostAsk(handler, model, "hi", stream)
|
||||
}
|
||||
|
||||
func fbPostAsk(handler http.Handler, model, ask string, stream bool) (*httptest.ResponseRecorder, time.Duration) {
|
||||
extra := ""
|
||||
if stream {
|
||||
extra = `,"stream":true`
|
||||
}
|
||||
req := httptest.NewRequest(http.MethodPost, "/v1/chat/completions", strings.NewReader(
|
||||
`{"model":"`+model+`","messages":[{"role":"user","content":"`+ask+`"}]`+extra+`}`,
|
||||
))
|
||||
req.Header.Set("Authorization", "Bearer "+rv2UserKey)
|
||||
req.Header.Set("Content-Type", "application/json")
|
||||
rec := httptest.NewRecorder()
|
||||
start := time.Now()
|
||||
handler.ServeHTTP(rec, req)
|
||||
return rec, time.Since(start)
|
||||
}
|
||||
|
||||
// exerciseRouterFirstByte checks that a slow first tier escalates to the next one for a plain request and for
|
||||
// a stream whose headers arrive at once, and that a router with no timely candidate answers 504.
|
||||
func exerciseRouterFirstByte(i *interp.Interpreter, pkgName string) error {
|
||||
slow, slow2, fast := fbSlowUpstream(), fbSlowUpstream(), fbFastUpstream()
|
||||
defer slow.Close()
|
||||
defer slow2.Close()
|
||||
defer fast.Close()
|
||||
|
||||
handler, err := newRouterV2Handler(i, pkgName, fbConfig(slow.URL, slow2.URL, fast.URL))
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
for _, stream := range []bool{false, true} {
|
||||
rec, took := fbPost(handler, fbOK, stream)
|
||||
if rec.Code != http.StatusOK || rec.Header().Get("X-Llmgw-Router-Tier") != "t1" || took > fbBudget {
|
||||
return fmt.Errorf("router %q stream=%v with a slow t0: status=%d tier=%q took=%s, want 200 t1 within %s (body %s)",
|
||||
fbOK, stream, rec.Code, rec.Header().Get("X-Llmgw-Router-Tier"), took, fbBudget, rec.Body.String())
|
||||
}
|
||||
}
|
||||
|
||||
rec, took := fbPost(handler, fbDead, false)
|
||||
if rec.Code != http.StatusGatewayTimeout || !strings.Contains(rec.Body.String(), "did not start responding in time") || took > fbBudget {
|
||||
return fmt.Errorf("router %q with every model slow: status=%d took=%s body=%s, want 504 within %s", fbDead, rec.Code, took, rec.Body.String(), fbBudget)
|
||||
}
|
||||
if err := exerciseTimeoutFallback(handler); err != nil {
|
||||
return err
|
||||
}
|
||||
fmt.Println("yaegi-check: a slow first tier escalated for a plain and a stream request, and a router with no timely model answered 504 under the interpreter")
|
||||
return nil
|
||||
}
|
||||
|
||||
// exerciseTimeoutFallback checks that a slow top tier falls back one tier down when the router opts in, for a
|
||||
// plain and a stream request, and that the same router without the flag still answers 504.
|
||||
func exerciseTimeoutFallback(handler http.Handler) error {
|
||||
for _, stream := range []bool{false, true} {
|
||||
rec, took := fbPostAsk(handler, fbFall, fbTopAsk, stream)
|
||||
if rec.Code != http.StatusOK || rec.Header().Get("X-Llmgw-Router-Tier") != "t0" || rec.Header().Get("X-Llmgw-Router-Downgraded") != "t1" || took > fbBudget {
|
||||
return fmt.Errorf("router %q stream=%v with a slow top tier: status=%d tier=%q downgraded=%q took=%s, want 200 t0 from t1 within %s (body %s)",
|
||||
fbFall, stream, rec.Code, rec.Header().Get("X-Llmgw-Router-Tier"), rec.Header().Get("X-Llmgw-Router-Downgraded"), took, fbBudget, rec.Body.String())
|
||||
}
|
||||
}
|
||||
rec, took := fbPostAsk(handler, fbNoFall, fbTopAsk, false)
|
||||
if rec.Code != http.StatusGatewayTimeout || rec.Header().Get("X-Llmgw-Router-Downgraded") != "" || took > fbBudget {
|
||||
return fmt.Errorf("router %q without timeoutFallback: status=%d downgraded=%q took=%s, want 504 within %s", fbNoFall, rec.Code, rec.Header().Get("X-Llmgw-Router-Downgraded"), took, fbBudget)
|
||||
}
|
||||
fmt.Println("yaegi-check: a slow top tier fell back one tier for a plain and a stream request, and stayed a 504 without timeoutFallback under the interpreter")
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,276 @@
|
||||
// This file adds the smart router v2 probes: calibration (live mode), adaptive
|
||||
// selection and the saturation downgrade, interpreted under Yaegi.
|
||||
//
|
||||
// They build their OWN Gateway (own config, own upstreams) so the learning
|
||||
// counters start at zero and the shared harness's traffic cannot skew them.
|
||||
// Calibration offsets and bandit arms refresh on the router learner's 60 s
|
||||
// ticker (routerLearnInterval, not configurable), so the probe seeds both from
|
||||
// real traffic, waits for one tick, and then asserts the routing change.
|
||||
package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"reflect"
|
||||
"strconv"
|
||||
"strings"
|
||||
"sync/atomic"
|
||||
"time"
|
||||
|
||||
"github.com/traefik/yaegi/interp"
|
||||
)
|
||||
|
||||
const (
|
||||
rv2UserKey = "sk-rv2-user" // #nosec G101 -- test fixture literal, not a real credential
|
||||
rv2AdminKey = "sk-rv2-admin" // #nosec G101 -- test fixture literal, not a real credential
|
||||
|
||||
rv2Calib = "rv2-calib"
|
||||
rv2Adapt = "rv2-adapt"
|
||||
rv2Sat = "rv2-sat"
|
||||
|
||||
// rv2Ask scores 151 under the default v1 weights: below the rv2-calib t1 minScore (200)
|
||||
// until calibration lowers that threshold by 100, and 51 points above the rv2-sat t1 minScore.
|
||||
rv2Ask = "write a function in python that reverses a linked list and explain the complexity"
|
||||
|
||||
rv2Seeds = 60
|
||||
rv2CalibDelta = 100
|
||||
rv2AdaptChecks = 25
|
||||
rv2LearnWait = 100 * time.Second
|
||||
rv2PollEvery = time.Second
|
||||
rv2HoldArrival = 5 * time.Second
|
||||
rv2GoodBody = `{"id":"c","object":"chat.completion","model":"m","choices":[{"index":0,"message":{"role":"assistant","content":"ok"},"finish_reason":"stop"}],"usage":{"prompt_tokens":3,"completion_tokens":2}}`
|
||||
rv2EmptyBody = `{"id":"c","object":"chat.completion","model":"m","choices":[{"index":0,"message":{"role":"assistant","content":""},"finish_reason":"stop"}],"usage":{"prompt_tokens":3,"completion_tokens":0}}`
|
||||
rv2HoldProvider = "rv2-hold"
|
||||
)
|
||||
|
||||
// rv2Upstream answers every request with body.
|
||||
func rv2Upstream(body string) *httptest.Server {
|
||||
return httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
_, _ = w.Write([]byte(body))
|
||||
}))
|
||||
}
|
||||
|
||||
// rv2Hold is an upstream that parks requests until released, so a provider shows in-flight load.
|
||||
type rv2Hold struct {
|
||||
srv *httptest.Server
|
||||
arrived chan struct{}
|
||||
release chan struct{}
|
||||
block atomic.Bool
|
||||
}
|
||||
|
||||
func newRV2Hold() *rv2Hold {
|
||||
h := &rv2Hold{arrived: make(chan struct{}, 4), release: make(chan struct{})}
|
||||
h.srv = httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
if h.block.Load() {
|
||||
h.arrived <- struct{}{}
|
||||
select {
|
||||
case <-h.release:
|
||||
case <-r.Context().Done():
|
||||
}
|
||||
}
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
_, _ = w.Write([]byte(rv2GoodBody))
|
||||
}))
|
||||
return h
|
||||
}
|
||||
|
||||
func rv2Post(handler http.Handler, model, text string) *httptest.ResponseRecorder {
|
||||
req := httptest.NewRequest(http.MethodPost, "/v1/chat/completions", strings.NewReader(
|
||||
`{"model":"`+model+`","messages":[{"role":"user","content":"`+text+`"}]}`,
|
||||
))
|
||||
req.Header.Set("Authorization", "Bearer "+rv2UserKey)
|
||||
req.Header.Set("Content-Type", "application/json")
|
||||
rec := httptest.NewRecorder()
|
||||
handler.ServeHTTP(rec, req)
|
||||
return rec
|
||||
}
|
||||
|
||||
func rv2Metrics(handler http.Handler) string {
|
||||
req := httptest.NewRequest(http.MethodGet, "/metrics", nil)
|
||||
req.Header.Set("Authorization", "Bearer "+rv2AdminKey)
|
||||
rec := httptest.NewRecorder()
|
||||
handler.ServeHTTP(rec, req)
|
||||
return rec.Body.String()
|
||||
}
|
||||
|
||||
// rv2Sample returns the value of the first metrics line that starts with prefix, and whether one exists.
|
||||
func rv2Sample(body, prefix string) (int, bool) {
|
||||
for _, line := range strings.Split(body, "\n") {
|
||||
if !strings.HasPrefix(line, prefix) {
|
||||
continue
|
||||
}
|
||||
v, err := strconv.Atoi(strings.TrimSpace(strings.TrimPrefix(line, prefix)))
|
||||
if err == nil {
|
||||
return v, true
|
||||
}
|
||||
}
|
||||
return 0, false
|
||||
}
|
||||
|
||||
func newRouterV2Handler(i *interp.Interpreter, pkgName, cfgJSON string) (http.Handler, error) {
|
||||
cfgVal, err := i.Eval(pkgName + ".CreateConfig()")
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("router v2 probe: call %s.CreateConfig() under yaegi: %w", pkgName, err)
|
||||
}
|
||||
if !cfgVal.CanInterface() {
|
||||
return nil, fmt.Errorf("router v2 probe: %s.CreateConfig() result cannot be used via reflect.Value.Interface", pkgName)
|
||||
}
|
||||
if err = json.Unmarshal([]byte(cfgJSON), cfgVal.Interface()); err != nil {
|
||||
return nil, fmt.Errorf("router v2 probe: decode its own config into the interpreted Config: %w", err)
|
||||
}
|
||||
newVal, err := i.Eval(pkgName + ".New")
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("router v2 probe: resolve %s.New under yaegi: %w", pkgName, err)
|
||||
}
|
||||
if newVal.Kind() != reflect.Func {
|
||||
return nil, fmt.Errorf("router v2 probe: %s.New is not a function (kind %s)", pkgName, newVal.Kind())
|
||||
}
|
||||
next := http.HandlerFunc(func(http.ResponseWriter, *http.Request) {})
|
||||
results := newVal.Call([]reflect.Value{
|
||||
reflect.ValueOf(context.Background()),
|
||||
reflect.ValueOf(next),
|
||||
cfgVal,
|
||||
reflect.ValueOf("llmgw-check-router-v2"),
|
||||
})
|
||||
if len(results) != 2 {
|
||||
return nil, fmt.Errorf("router v2 probe: %s.New returned %d values, want 2 (http.Handler, error)", pkgName, len(results))
|
||||
}
|
||||
if errVal := results[1]; !errVal.IsNil() {
|
||||
return nil, fmt.Errorf("router v2 probe: %s.New returned an error: %v", pkgName, errVal.Interface())
|
||||
}
|
||||
handler, ok := results[0].Interface().(http.Handler)
|
||||
if !ok || handler == nil {
|
||||
return nil, fmt.Errorf("router v2 probe: %s.New's returned value is not a usable http.Handler", pkgName)
|
||||
}
|
||||
return handler, nil
|
||||
}
|
||||
|
||||
func rv2ProviderJSON(name, url string) string {
|
||||
return `"` + name + `":{"type":"openai","baseUrl":"` + url + `","apiKey":"sk-up","models":["m"]}`
|
||||
}
|
||||
|
||||
func rv2Config(urls map[string]string) string {
|
||||
providers := make([]string, 0, len(urls))
|
||||
for name, url := range urls {
|
||||
providers = append(providers, rv2ProviderJSON(name, url))
|
||||
}
|
||||
return `{"providers":{` + strings.Join(providers, ",") + `},` +
|
||||
`"groups":{"rv2g":{}},` +
|
||||
`"users":{"inline":[{"name":"rv2-user","group":"rv2g","apiKey":"` + rv2UserKey + `"},{"name":"rv2-admin","group":"rv2g","apiKey":"` + rv2AdminKey + `","admin":true}]},` +
|
||||
`"admin":{"enabled":true},"metrics":{"enabled":true},` +
|
||||
`"concurrencyAutodetect":true,"maxConcurrency":1,` +
|
||||
`"smartRouters":{` +
|
||||
`"` + rv2Calib + `":{"calibration":{"mode":"live","step":` + strconv.Itoa(rv2CalibDelta) + `,"minSamples":50},"tiers":[{"name":"t0","minScore":0,"models":["rv2-low/m"]},{"name":"t1","minScore":200,"models":["rv2-hi/m"]}]},` +
|
||||
`"` + rv2Adapt + `":{"selection":"adaptive","adaptive":{"explorePct":0},"tiers":[{"name":"t0","minScore":0,"models":["rv2-good/m","rv2-flaky/m"]}]},` +
|
||||
`"` + rv2Sat + `":{"saturationDowngrade":true,"tiers":[{"name":"t0","minScore":0,"models":["rv2-fast/m"]},{"name":"t1","minScore":100,"models":["` + rv2HoldProvider + `/m"]}]}}}`
|
||||
}
|
||||
|
||||
// exerciseRouterV2 runs the calibration, adaptive-selection and saturation-downgrade probes against one
|
||||
// dedicated interpreted Gateway.
|
||||
func exerciseRouterV2(i *interp.Interpreter, pkgName string) error {
|
||||
good, empty := rv2Upstream(rv2GoodBody), rv2Upstream(rv2EmptyBody)
|
||||
hold := newRV2Hold()
|
||||
defer good.Close()
|
||||
defer empty.Close()
|
||||
defer hold.srv.Close()
|
||||
|
||||
handler, err := newRouterV2Handler(i, pkgName, rv2Config(map[string]string{
|
||||
"rv2-low": empty.URL, "rv2-hi": good.URL, "rv2-good": good.URL, "rv2-flaky": empty.URL,
|
||||
"rv2-fast": good.URL, rv2HoldProvider: hold.srv.URL,
|
||||
}))
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if err := exerciseRouterSaturation(handler, hold); err != nil {
|
||||
return err
|
||||
}
|
||||
return exerciseRouterLearning(handler)
|
||||
}
|
||||
|
||||
// exerciseRouterSaturation parks one request on rv2-hold's only slot, so tier t1 of rv2-sat is saturated:
|
||||
// a score-routed request starts one tier down, and returns to t1 once the slot frees.
|
||||
func exerciseRouterSaturation(handler http.Handler, hold *rv2Hold) error {
|
||||
rec := rv2Post(handler, rv2Sat, rv2Ask)
|
||||
if rec.Code != http.StatusOK || rec.Header().Get("X-Llmgw-Router-Tier") != "t1" || rec.Header().Get("X-Llmgw-Router-Downgraded") != "" {
|
||||
return fmt.Errorf("router %q unsaturated: status=%d tier=%q downgraded=%q, want 200 t1 and no downgrade header", rv2Sat, rec.Code, rec.Header().Get("X-Llmgw-Router-Tier"), rec.Header().Get("X-Llmgw-Router-Downgraded"))
|
||||
}
|
||||
|
||||
hold.block.Store(true)
|
||||
done := make(chan struct{})
|
||||
go func() {
|
||||
defer close(done)
|
||||
rv2Post(handler, rv2HoldProvider+"/m", "hold")
|
||||
}()
|
||||
select {
|
||||
case <-hold.arrived:
|
||||
case <-time.After(rv2HoldArrival):
|
||||
close(hold.release)
|
||||
return fmt.Errorf("router %q: the parked request never reached the %s upstream", rv2Sat, rv2HoldProvider)
|
||||
}
|
||||
|
||||
rec = rv2Post(handler, rv2Sat, rv2Ask)
|
||||
downgraded := rec.Code == http.StatusOK && rec.Header().Get("X-Llmgw-Router-Tier") == "t0" && rec.Header().Get("X-Llmgw-Router-Downgraded") == "t1"
|
||||
body := rv2Metrics(handler)
|
||||
close(hold.release)
|
||||
<-done
|
||||
hold.block.Store(false)
|
||||
if !downgraded {
|
||||
return fmt.Errorf("router %q saturated: status=%d tier=%q downgraded=%q, want 200 t0 downgraded from t1", rv2Sat, rec.Code, rec.Header().Get("X-Llmgw-Router-Tier"), rec.Header().Get("X-Llmgw-Router-Downgraded"))
|
||||
}
|
||||
want := `llmgateway_router_requests_total{router="` + rv2Sat + `",tier="t0",reason="saturated"} `
|
||||
if n, ok := rv2Sample(body, want); !ok || n != 1 {
|
||||
return fmt.Errorf("GET /metrics: %q = %d (found %v), want 1", want, n, ok)
|
||||
}
|
||||
|
||||
rec = rv2Post(handler, rv2Sat, rv2Ask)
|
||||
if rec.Header().Get("X-Llmgw-Router-Tier") != "t1" || rec.Header().Get("X-Llmgw-Router-Downgraded") != "" {
|
||||
return fmt.Errorf("router %q after the slot freed: tier=%q downgraded=%q, want t1 and no downgrade header", rv2Sat, rec.Header().Get("X-Llmgw-Router-Tier"), rec.Header().Get("X-Llmgw-Router-Downgraded"))
|
||||
}
|
||||
fmt.Println("yaegi-check: saturated tier t1 downgraded a score-routed request to t0 with the downgrade header and counter, and routed back to t1 once the slot freed under the interpreter")
|
||||
return nil
|
||||
}
|
||||
|
||||
// exerciseRouterLearning seeds calibration counters (tier t0 answers empty, which counts as bad) and bandit
|
||||
// arms (one good and one empty-answer candidate) with real traffic, waits for the learner's tick, and checks
|
||||
// that the calibrated threshold now sends the ask to t1 and that adaptive selection always leads with the
|
||||
// good candidate.
|
||||
func exerciseRouterLearning(handler http.Handler) error {
|
||||
for n := 0; n < rv2Seeds; n++ {
|
||||
if rec := rv2Post(handler, rv2Calib, rv2Ask); rec.Code != http.StatusOK || rec.Header().Get("X-Llmgw-Router-Tier") != "t0" {
|
||||
return fmt.Errorf("router %q seed %d: status=%d tier=%q, want 200 t0", rv2Calib, n, rec.Code, rec.Header().Get("X-Llmgw-Router-Tier"))
|
||||
}
|
||||
if rec := rv2Post(handler, rv2Adapt, "hi"); rec.Code != http.StatusOK {
|
||||
return fmt.Errorf("router %q seed %d: status=%d body=%s", rv2Adapt, n, rec.Code, rec.Body.String())
|
||||
}
|
||||
}
|
||||
|
||||
gauge := `llmgateway_router_calibration_delta{router="` + rv2Calib + `",tier="t1",mode="live"} `
|
||||
deadline := time.Now().Add(rv2LearnWait)
|
||||
var delta int
|
||||
var ok bool
|
||||
for time.Now().Before(deadline) {
|
||||
if delta, ok = rv2Sample(rv2Metrics(handler), gauge); ok && delta != 0 {
|
||||
break
|
||||
}
|
||||
time.Sleep(rv2PollEvery)
|
||||
}
|
||||
if delta != rv2CalibDelta {
|
||||
return fmt.Errorf("GET /metrics: %q = %d (found %v) after %s, want %d from %d bad answers", gauge, delta, ok, rv2LearnWait, rv2CalibDelta, rv2Seeds)
|
||||
}
|
||||
if rec := rv2Post(handler, rv2Calib, rv2Ask); rec.Header().Get("X-Llmgw-Router-Tier") != "t1" {
|
||||
return fmt.Errorf("router %q after calibration: tier=%q, want t1 (threshold 200 lowered by %d to 100, ask scores 151)", rv2Calib, rec.Header().Get("X-Llmgw-Router-Tier"), rv2CalibDelta)
|
||||
}
|
||||
|
||||
for n := 0; n < rv2AdaptChecks; n++ {
|
||||
rec := rv2Post(handler, rv2Adapt, "hi")
|
||||
if got := rec.Header().Get("X-Llmgw-Routed-Model"); rec.Code != http.StatusOK || got != "rv2-good/m" {
|
||||
return fmt.Errorf("router %q adaptive check %d: status=%d routed=%q, want 200 rv2-good/m first every time", rv2Adapt, n, rec.Code, got)
|
||||
}
|
||||
}
|
||||
fmt.Printf("yaegi-check: live calibration lowered the t1 threshold by %d after %d bad answers and moved the ask to t1; adaptive selection led with the good candidate %d of %d times under the interpreter\n", rv2CalibDelta, rv2Seeds, rv2AdaptChecks, rv2AdaptChecks)
|
||||
return nil
|
||||
}
|
||||
Reference in New Issue
Block a user