Files
CLIProxyAPI/internal/runtime/executor/helps/payload_query_eval_test.go
sususu98 40beca02c8 perf(payload,handlers): eliminate large base64 allocation amplification
Avoid full-payload copies when evaluating payload rules and reading HTTP
request bodies, cutting heap allocation amplification on multi-megabyte
base64 requests by >80% with zero behavioral changes:

- Evaluate single-item payload query predicates directly on ojson.Result
  without copying item.Raw into a temporary "[...]" buffer (with exact
  fallback for edge/malformed syntax).
- Resolve clean array "@reverse.<N>" paths via zero-copy ForEach traversal
  instead of ojson.modReverse full-array cloning.
- Fast-path scalar, empty-container ([] / {}), and type-mismatch checks in
  payloadResultEquals to skip moego/json.Unmarshal on large arrays, and use
  bytes.TrimSpace in normalizedPayloadJSON.
- Cache compiled moego/regexp patterns in payload.replace with a bounded map.
- Release originalRequest in ClaudeInputTokenState once disabled or handled,
  and only retain replayRequestPayload in Antigravity stream when replayScope
  is valid.
- Preallocate raw request body buffers from Content-Length (capped at 4 MiB)
  in ReadRawRequestBody to avoid io.ReadAll slice-doubling copies.
2026-11-29 12:22:41 +08:00

370 lines
10 KiB
Go

package helps
import (
"fmt"
"net/http"
"reflect"
"strings"
"testing"
"github.com/MoeForge/moego/json"
"github.com/MoeForge/moego/ojson"
"github.com/router-for-me/CLIProxyAPI/v8/internal/config"
sdktranslator "github.com/router-for-me/CLIProxyAPI/v8/sdk/translator"
)
type customJSONMarshalerTestValue struct {
raw string
}
func (c customJSONMarshalerTestValue) MarshalJSON() ([]byte, error) {
return []byte(c.raw), nil
}
func TestPayloadQueryTermMatchesDifferentialAgainstOjson(t *testing.T) {
items := []string{
`{"role":"user","n":1,"f":1.5,"zero":0,"flag":true,"off":false,"nil":null,"strTrue":"true","strFalse":"false","text":"a\"b\nc","parts":[{"text":"hello world"}]}`,
`{"role":"model","n":10,"flag":false,"text":"plain\\slash","parts":[{"text":"other"}]}`,
`{"role":"system","n":-5,"empty":"","parts":[]}`,
`{}`,
`[]`,
`[1,2]`,
`"hello"`,
`42`,
`0`,
`true`,
`false`,
`null`,
}
terms := []string{
`role=="user"`,
`role="user"`,
`role!="user"`,
`role=="model"`,
`role%"*us*"`,
`role!%"*mod*"`,
`role%"u?er"`,
`role%"user"`,
`role<"user"`,
`role<="user"`,
`role>"model"`,
`role>="user"`,
`n==1`,
`n!=1`,
`n<2`,
`n<=1`,
`n>0`,
`n>=10`,
`f==1.5`,
`zero==~false`,
`n==~true`,
`flag==true`,
`flag!=true`,
`flag==false`,
`flag>false`,
`flag>=false`,
`off==false`,
`off!=false`,
`off<true`,
`off<=true`,
`strTrue==~true`,
`strFalse==~false`,
`nil==~null`,
`nil==~false`,
`nil==~*`,
`missing==~null`,
`missing==~false`,
`missing==~true`,
`missing==~*`,
`role!=~null`,
`missing!=~*`,
`flag!=~true`,
`#==2`,
`0==1`,
`text%"a\\?b"`,
`role`,
`missing`,
`parts.#(text%"*hello*").text=="hello world"`,
`parts.#(text=="hello world")`,
`parts.#(text=="absent")`,
`text=="a\"b\nc"`,
`text=="plain\\slash"`,
`=="hello"`,
`=="other"`,
`==42`,
`>10`,
`==true`,
`==false`,
`==~null`,
`==~false`,
`==~true`,
`==~*`,
`role!user`,
`role=="unclosed`,
`role=="user")extra`,
`((role=="user")`,
`role\`,
`role=="user"\`,
`role\\`,
``,
}
for _, rawItem := range items {
item := ojson.Parse(rawItem)
for _, term := range terms {
got := payloadQueryTermMatches(item, term)
want := payloadQueryTermMatchesFallback(item, term)
if got != want {
t.Fatalf("item=%s term=%q: got=%v, want=%v", rawItem, term, got, want)
}
}
}
}
func TestPayloadGetPathReverseDifferentialAgainstOjson(t *testing.T) {
docs := []string{
`{"contents":[]}`,
`{"contents":[{"role":"user","parts":[{"text":"only"}]}]}`,
`{"contents":[{"role":"user","parts":[{"text":"a"},{"text":"b"}]},{"role":"model","parts":[{"text":"c"}]}]}`,
`{"contents":{"0":{"role":"zero"},"a":{"role":"alpha"}}}`,
`{"contents":"scalar"}`,
`{"other":1}`,
`[{"role":"first"},{"role":"last"}]`,
}
paths := []string{
`contents.@reverse.0.role`,
`contents.@reverse.1.role`,
`contents.@reverse.2.role`,
`contents.@reverse.0`,
`contents.@reverse.0.parts.@reverse.0.text`,
`contents.@reverse.0.parts.@reverse.1.text`,
`contents.@reverse.0.parts.@reverse.5.text`,
`contents|@reverse.0.role`,
`contents.#.parts.@reverse.0.text`,
`contents.*.parts.@reverse.0.text`,
`contents.@reverse.00.role`,
`contents.@reverse.0.`,
`contents.@reverse..role`,
`contents.@reverse.0.parts.#.text`,
`@reverse.0.role`,
`@reverse.1.role`,
}
for _, rawDoc := range docs {
doc := ojson.NewDocString(rawDoc)
rawBytes := []byte(rawDoc)
for _, path := range paths {
wantDoc := doc.Get(path)
gotDoc := payloadGetPathDoc(doc, path)
if gotDoc.Exists() != wantDoc.Exists() || gotDoc.Type != wantDoc.Type || gotDoc.Raw != wantDoc.Raw || gotDoc.Str != wantDoc.Str {
t.Fatalf("doc=%s path=%q (Doc): got=(exists=%v type=%v raw=%q str=%q), want=(exists=%v type=%v raw=%q str=%q)",
rawDoc, path, gotDoc.Exists(), gotDoc.Type, gotDoc.Raw, gotDoc.Str, wantDoc.Exists(), wantDoc.Type, wantDoc.Raw, wantDoc.Str)
}
wantBytes := ojson.GetBytesNoCopy(rawBytes, path)
gotBytes := payloadGetPathBytes(rawBytes, path)
if gotBytes.Exists() != wantBytes.Exists() || gotBytes.Type != wantBytes.Type || gotBytes.Raw != wantBytes.Raw || gotBytes.Str != wantBytes.Str {
t.Fatalf("doc=%s path=%q (Bytes): got=(exists=%v type=%v raw=%q str=%q), want=(exists=%v type=%v raw=%q str=%q)",
rawDoc, path, gotBytes.Exists(), gotBytes.Type, gotBytes.Raw, gotBytes.Str, wantBytes.Exists(), wantBytes.Type, wantBytes.Raw, wantBytes.Str)
}
}
}
}
func payloadResultEqualsReference(result ojson.Result, value any) bool {
actual, ok := normalizedPayloadResult(result)
if !ok {
return false
}
expected, ok := normalizedPayloadValue(value)
if !ok {
return false
}
return reflect.DeepEqual(actual, expected)
}
func TestPayloadResultEqualsDifferentialAgainstReference(t *testing.T) {
jsonValues := []string{
`null`,
`true`,
`false`,
`""`,
`"model"`,
`"a\"b\nc"`,
`0`,
`42`,
`3.14`,
`[]`,
`[ ]`,
`[1]`,
`[{"role":"user"}]`,
`{}`,
`{ }`,
`{"a":1}`,
`nul`,
"\"line1\nline2\"",
"\"\xff\"",
}
var nilSlice []any
var nilMap map[string]any
var nilIntPtr *int
values := []any{
nil,
true,
false,
"",
"model",
"a\"b\nc",
0,
42,
int64(42),
3.14,
[]any{},
nilSlice,
[]any{1},
map[string]any{},
nilMap,
map[string]any{"a": 1},
[]byte{},
[]byte("hi"),
map[int]any{},
customJSONMarshalerTestValue{raw: `[]`},
customJSONMarshalerTestValue{raw: `"model"`},
nilIntPtr,
"\xff",
"\ufffd",
}
for _, rawJSON := range jsonValues {
res := ojson.Parse(rawJSON)
for _, val := range values {
got := payloadResultEquals(res, val)
want := payloadResultEqualsReference(res, val)
if got != want {
t.Fatalf("json=%s value=%#v (%T): got=%v, want=%v", rawJSON, val, val, got, want)
}
}
}
missing := ojson.Get("{}", "absent")
for _, val := range values {
if got := payloadResultEquals(missing, val); got {
t.Fatalf("missing result matched %#v (%T)", val, val)
}
}
_ = json.Valid([]byte(`{}`))
}
func TestPayloadLargeBase64ZeroCopyAllocations(t *testing.T) {
largeB64 := strings.Repeat("A", 1500*1024)
payloadStr := `{"contents":[{"role":"model","parts":[{"text":"caption"},{"inlineData":{"mimeType":"image/png","data":"` + largeB64 + `"}}]},{"role":"user","parts":[{"text":"follow up"}]}],"generationConfig":{"temperature":0.7}}`
doc := ojson.NewDocString(payloadStr)
t.Run("payloadQueryTermMatches zero alloc on large item", func(t *testing.T) {
firstItem := doc.Get("contents.0")
if len(firstItem.Raw) < 1500*1024 {
t.Fatalf("expected large item, got %d bytes", len(firstItem.Raw))
}
allocs := testing.AllocsPerRun(20, func() {
if payloadQueryTermMatches(firstItem, `role=="user"`) {
t.Fatal("unexpected match for user")
}
if !payloadQueryTermMatches(firstItem, `role=="model"`) {
t.Fatal("expected match for model")
}
})
if allocs > 0 {
t.Fatalf("payloadQueryTermMatches allocated %v times on large item, want 0", allocs)
}
})
t.Run("payloadGetPathDoc @reverse.0 zero alloc on large array", func(t *testing.T) {
allocs := testing.AllocsPerRun(20, func() {
res := payloadGetPathDoc(doc, "contents.@reverse.0.role")
if res.Str != "user" {
t.Fatalf("got role %q, want user", res.Str)
}
})
if allocs > 0 {
t.Fatalf("payloadGetPathDoc(@reverse.0) allocated %v times on large array, want 0", allocs)
}
})
t.Run("payloadResultEquals empty array check zero alloc on large array", func(t *testing.T) {
contents := doc.Get("contents")
var emptySlice any = []any{}
allocs := testing.AllocsPerRun(20, func() {
if payloadResultEquals(contents, emptySlice) {
t.Fatal("non-empty contents matched empty slice")
}
})
if allocs > 0 {
t.Fatalf("payloadResultEquals([]any{}) allocated %v times on large array, want 0", allocs)
}
})
t.Run("ApplyPayloadConfigWithRequestDoc does not scale with base64 size", func(t *testing.T) {
cfg := &config.Config{
Payload: config.PayloadConfig{
Default: []config.PayloadRule{{
Models: []config.PayloadModelRule{{
Name: "gemini-*",
Protocol: "gemini",
Match: []map[string]any{{"contents.@reverse.0.role": "model"}},
}},
Params: map[string]any{"generationConfig.topP": 0.95},
}},
OverrideRaw: []config.PayloadRule{{
Models: []config.PayloadModelRule{{
Name: "gemini-*",
Protocol: "gemini",
Match: []map[string]any{{"contents": []any{}}},
}},
Params: map[string]any{"contents": `[{"role":"user","parts":[{"text":"ping"}]}]`},
}},
},
}
for i := 0; i < 8; i++ {
cfg.Payload.Replace = append(cfg.Payload.Replace, config.PayloadReplaceRule{
Models: []config.PayloadModelRule{{Name: "gemini-*", Protocol: "gemini"}},
Target: config.PayloadReplaceTarget{Paths: []string{`contents.#(role=="user"||role=="model")#.parts.#.text`}},
Replacements: []config.PayloadReplacement{
{fmt.Sprintf("absent_token_%d", i): "replaced"},
},
})
}
ApplyPayloadConfigWithRequestDoc(cfg, "gemini-2.5-pro", "gemini", "gemini", "", doc, nil, "gemini-2.5-pro", "", http.Header{})
res := testing.Benchmark(func(b *testing.B) {
b.ReportAllocs()
for i := 0; i < b.N; i++ {
ApplyPayloadConfigWithRequestDoc(cfg, "gemini-2.5-pro", "gemini", "gemini", "", doc, nil, "gemini-2.5-pro", "", http.Header{})
}
})
if res.AllocedBytesPerOp() > 32*1024 {
t.Fatalf("ApplyPayloadConfigWithRequestDoc allocated %d B/op on 1.5 MiB base64 payload, want <= 32768 B/op", res.AllocedBytesPerOp())
}
})
}
func TestClaudeInputTokenStateReleasesOriginalRequest(t *testing.T) {
large := []byte(`{"messages":[{"role":"user","content":"hello"}]}`)
disabled := NewClaudeInputTokenState(sdktranslator.FormatGemini, sdktranslator.FormatGemini, sdktranslator.FormatGemini, large)
if disabled.originalRequest != nil {
t.Fatal("disabled ClaudeInputTokenState retained originalRequest")
}
enabled := NewClaudeInputTokenState(sdktranslator.FormatClaude, sdktranslator.FormatGemini, sdktranslator.FormatClaude, large)
if enabled.originalRequest == nil {
t.Fatal("enabled ClaudeInputTokenState should retain originalRequest until message_start")
}
msgStart := []byte("event: message_start\ndata: {\"type\":\"message_start\",\"message\":{\"usage\":{\"input_tokens\":123}}}\n\n")
_ = enabled.FinalizeTranslatedUsage(t.Context(), sdktranslator.FormatClaude, [][]byte{msgStart}, nil)
if !enabled.handled {
t.Fatal("expected message_start to mark state handled")
}
if enabled.originalRequest != nil {
t.Fatal("handled ClaudeInputTokenState still retained originalRequest")
}
}