mirror of
https://github.com/Wei-Shaw/sub2api
synced 2026-12-06 01:12:31 +00:00
fix(gateway): reduce large request allocation and retention
This commit is contained in:
1 parent
81ce8356d9
commit
85cf114332
8 files changed
+244
-14
No files matched your search
@@ -21,6 +21,7 @@ import (
|
||||
"net/http"
|
||||
"strconv"
|
||||
"strings"
|
||||
"unsafe"
|
||||
|
||||
"github.com/Wei-Shaw/sub2api/internal/pkg/httputil"
|
||||
"github.com/tidwall/gjson"
|
||||
@@ -47,8 +48,10 @@ func FromBodyCandidates(routePath, contentType string, body []byte) []string {
|
||||
if doc := TrimUTF8BOM(body); LooksLikeJSON(doc) {
|
||||
// 按内容识别 JSON,不看 Content-Type:JSON handler 不校验请求头,且宽容
|
||||
// 读取会剥掉 BOM,两者都不能成为绕过准入的手段。gjson 只读首个顶层值。
|
||||
topLevel = jsonModelCandidates(doc)
|
||||
session = jsonSessionModelCandidates(doc)
|
||||
// 同步解析时复用请求字节,返回的模型名独立拥有字符串。
|
||||
root := gjson.Parse(unsafe.String(unsafe.SliceData(doc), len(doc)))
|
||||
topLevel = jsonModelCandidates(root)
|
||||
session = jsonSessionModelCandidates(root)
|
||||
}
|
||||
if isMultipartContentType(contentType) {
|
||||
// multipart handler 跳过首个 boundary 之前的前导内容(可以是任意 JSON),
|
||||
@@ -124,12 +127,12 @@ func jsonModelWithPaths(body []byte, paths []string) (string, string) {
|
||||
|
||||
// jsonModelCandidates 返回顶层所有键名大小写不敏感等于 "model" 的字符串值,
|
||||
// 按出现顺序保留重复(覆盖 gjson 首 matches 与 encoding/json 末值绑定两类解析器)。
|
||||
func jsonModelCandidates(body []byte) []string {
|
||||
func jsonModelCandidates(root gjson.Result) []string {
|
||||
var out []string
|
||||
gjson.ParseBytes(body).ForEach(func(key, value gjson.Result) bool {
|
||||
root.ForEach(func(key, value gjson.Result) bool {
|
||||
if value.Type == gjson.String && strings.EqualFold(key.String(), "model") {
|
||||
if trimmed := strings.TrimSpace(value.String()); trimmed != "" {
|
||||
out = append(out, trimmed)
|
||||
out = append(out, strings.Clone(trimmed))
|
||||
}
|
||||
}
|
||||
return true
|
||||
@@ -139,16 +142,16 @@ func jsonModelCandidates(body []byte) []string {
|
||||
|
||||
// jsonSessionModelCandidates 返回每个顶层 "session"(大小写不敏感)对象内
|
||||
// 所有键名大小写不敏感等于 "model" 的字符串值。
|
||||
func jsonSessionModelCandidates(body []byte) []string {
|
||||
func jsonSessionModelCandidates(root gjson.Result) []string {
|
||||
var out []string
|
||||
gjson.ParseBytes(body).ForEach(func(key, value gjson.Result) bool {
|
||||
root.ForEach(func(key, value gjson.Result) bool {
|
||||
if !strings.EqualFold(key.String(), "session") {
|
||||
return true
|
||||
}
|
||||
value.ForEach(func(sessionKey, sessionValue gjson.Result) bool {
|
||||
if sessionValue.Type == gjson.String && strings.EqualFold(sessionKey.String(), "model") {
|
||||
if trimmed := strings.TrimSpace(sessionValue.String()); trimmed != "" {
|
||||
out = append(out, trimmed)
|
||||
out = append(out, strings.Clone(trimmed))
|
||||
}
|
||||
}
|
||||
return true
|
||||
@@ -162,7 +165,7 @@ func jsonSessionModelCandidates(body []byte) []string {
|
||||
func sessionModelCandidates(rawSessions []string) []string {
|
||||
var out []string
|
||||
for _, raw := range rawSessions {
|
||||
out = append(out, jsonModelCandidates([]byte(raw))...)
|
||||
out = append(out, jsonModelCandidates(gjson.Parse(raw))...)
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
@@ -5,12 +5,35 @@ import (
|
||||
"mime/multipart"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"runtime"
|
||||
"strconv"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/Wei-Shaw/sub2api/internal/pkg/httputil"
|
||||
)
|
||||
|
||||
func TestFromBodyCandidatesRetainsOnlyModelValues(t *testing.T) {
|
||||
runtime.GC()
|
||||
var before runtime.MemStats
|
||||
runtime.ReadMemStats(&before)
|
||||
models := func() []string {
|
||||
body := []byte(`{"model":"public-model","session":{"model":"live-model"},"input":"` + strings.Repeat("x", 16<<20) + `"}`)
|
||||
return FromBodyCandidates("", "application/json", body)
|
||||
}()
|
||||
runtime.GC()
|
||||
var after runtime.MemStats
|
||||
runtime.ReadMemStats(&after)
|
||||
retained := int64(after.HeapAlloc) - int64(before.HeapAlloc)
|
||||
if len(models) != 1 || models[0] != "public-model" {
|
||||
t.Fatalf("model candidates = %q", models)
|
||||
}
|
||||
if retained > 2<<20 {
|
||||
t.Fatalf("model candidates retain %d bytes of the large request", retained)
|
||||
}
|
||||
runtime.KeepAlive(models)
|
||||
}
|
||||
|
||||
func TestFromBodyJSONModel(t *testing.T) {
|
||||
if got := FromBody("application/json", []byte(`{"model":"gpt-5.4"}`)); got != "gpt-5.4" {
|
||||
t.Fatalf("got %q", got)
|
||||
|
||||
@@ -62,7 +62,16 @@ func requireSameCompactionNormalization(t *testing.T, body []byte) {
|
||||
want, wantChanged, wantErr := referenceNormalizeCompactionTriggerInputOrder(body)
|
||||
require.Equal(t, wantErr != nil, err != nil, "error mismatch for %s", body)
|
||||
require.Equal(t, wantChanged, changed, "changed mismatch for %s", body)
|
||||
require.Equal(t, string(want), string(got), "body mismatch for %s", body)
|
||||
if err != nil || !changed {
|
||||
require.Equal(t, want, got, "body mismatch for %s", body)
|
||||
return
|
||||
}
|
||||
// Reordering preserves raw JSON, including object key order and escaping.
|
||||
// Compare decoded values with UseNumber to keep the exact number semantics.
|
||||
var gotPayload, wantPayload map[string]any
|
||||
require.NoError(t, decodeOpenAIJSONUseNumber(got, &gotPayload))
|
||||
require.NoError(t, decodeOpenAIJSONUseNumber(want, &wantPayload))
|
||||
require.Equal(t, wantPayload, gotPayload, "body mismatch for %s", body)
|
||||
}
|
||||
|
||||
func TestCompactionTriggerOrderFastPathMatchesDecode(t *testing.T) {
|
||||
|
||||
@@ -2,9 +2,12 @@ package service
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
"strings"
|
||||
"unicode/utf8"
|
||||
|
||||
"github.com/Wei-Shaw/sub2api/internal/pkg/requestmodel"
|
||||
"github.com/gin-gonic/gin"
|
||||
"github.com/tidwall/gjson"
|
||||
)
|
||||
@@ -32,6 +35,49 @@ func NormalizeCompactionTriggerInputOrder(body []byte) ([]byte, bool, error) {
|
||||
if !compactionTriggerNeedsDecode(body) {
|
||||
return body, false, nil
|
||||
}
|
||||
// 直接读取历史项的类型,让普通长会话和图片请求复用原始字节。
|
||||
// 重复键与异常输入沿用完整解码的既有语义。
|
||||
root := parseRawJSONView(body)
|
||||
if !json.Valid(body) || !utf8.Valid(body) || !root.IsObject() || hasDuplicateJSONObjectKeys(root) {
|
||||
return normalizeCompactionTriggerInputOrderDecoded(body)
|
||||
}
|
||||
input := root.Get("input")
|
||||
if !input.IsArray() {
|
||||
return body, false, nil
|
||||
}
|
||||
items := make([]string, 0)
|
||||
triggerCount := 0
|
||||
lastIsTrigger := false
|
||||
duplicateKeys := false
|
||||
input.ForEach(func(_, item gjson.Result) bool {
|
||||
if item.IsObject() && hasDuplicateJSONObjectKeys(item) {
|
||||
duplicateKeys = true
|
||||
return false
|
||||
}
|
||||
typ := item.Get("type")
|
||||
lastIsTrigger = item.IsObject() && typ.Type == gjson.String && typ.Str == "compaction_trigger"
|
||||
if lastIsTrigger {
|
||||
triggerCount++
|
||||
} else {
|
||||
items = append(items, item.Raw)
|
||||
}
|
||||
return true
|
||||
})
|
||||
if duplicateKeys {
|
||||
return normalizeCompactionTriggerInputOrderDecoded(body)
|
||||
}
|
||||
if triggerCount == 0 || (triggerCount == 1 && lastIsTrigger) {
|
||||
return body, false, nil
|
||||
}
|
||||
// 重排前核对所有嵌套对象,使输出继续采用完整解码的末值语义。
|
||||
if _, conflict := requestmodel.ConflictingField("application/json", body); conflict {
|
||||
return normalizeCompactionTriggerInputOrderDecoded(body)
|
||||
}
|
||||
items = append(items, `{"type":"compaction_trigger"}`)
|
||||
return replaceOpenAIRawInput(body, input, items), true, nil
|
||||
}
|
||||
|
||||
func normalizeCompactionTriggerInputOrderDecoded(body []byte) ([]byte, bool, error) {
|
||||
var payload map[string]any
|
||||
if err := decodeOpenAIJSONUseNumber(body, &payload); err != nil {
|
||||
return body, false, err
|
||||
|
||||
@@ -0,0 +1,98 @@
|
||||
package service
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"fmt"
|
||||
"runtime"
|
||||
"testing"
|
||||
|
||||
"github.com/stretchr/testify/require"
|
||||
"github.com/tidwall/gjson"
|
||||
)
|
||||
|
||||
func compactionMemoryRequestBody(imageBytes int, final bool) []byte {
|
||||
body := largeNativeResponsesBody(imageBytes)
|
||||
if final {
|
||||
return bytes.Replace(body, []byte(`]}]}`), []byte(`]},{"type":"compaction_trigger"}]}`), 1)
|
||||
}
|
||||
return bytes.Replace(body, []byte(`"input":[`), []byte(`"input":[{"type":"compaction_trigger"},`), 1)
|
||||
}
|
||||
|
||||
func TestCompactionNormalizationLargeTriggerRequestAllocations(t *testing.T) {
|
||||
for _, final := range []bool{true, false} {
|
||||
t.Run(fmt.Sprintf("already_final=%v", final), func(t *testing.T) {
|
||||
body := compactionMemoryRequestBody(2<<20, final)
|
||||
runtime.GC()
|
||||
var before, after runtime.MemStats
|
||||
runtime.ReadMemStats(&before)
|
||||
out, changed, err := NormalizeCompactionTriggerInputOrder(body)
|
||||
runtime.ReadMemStats(&after)
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, !final, changed)
|
||||
budget := uint64(3 * len(body))
|
||||
if final {
|
||||
budget = 1 << 20
|
||||
require.Same(t, &body[0], &out[0])
|
||||
}
|
||||
require.Less(t, after.TotalAlloc-before.TotalAlloc, budget, "压缩标记整理的分配随请求体积增长")
|
||||
runtime.KeepAlive(out)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func BenchmarkCompactionTriggerLargeRequest(b *testing.B) {
|
||||
for _, size := range []int{16 << 20, 112 << 20} {
|
||||
for _, final := range []bool{true, false} {
|
||||
b.Run(fmt.Sprintf("%dMiB_final=%v", size>>20, final), func(b *testing.B) {
|
||||
body := compactionMemoryRequestBody(size, final)
|
||||
b.ReportAllocs()
|
||||
b.SetBytes(int64(len(body)))
|
||||
b.ResetTimer()
|
||||
for i := 0; i < b.N; i++ {
|
||||
out, changed, err := NormalizeCompactionTriggerInputOrder(body)
|
||||
if err != nil || changed == final {
|
||||
b.Fatalf("压缩标记整理结果:changed=%v err=%v", changed, err)
|
||||
}
|
||||
runtime.KeepAlive(out)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestCompactionNormalizationPreservesNestedDuplicateKeyValues(t *testing.T) {
|
||||
for _, fixture := range []struct {
|
||||
body string
|
||||
path string
|
||||
want string
|
||||
changed bool
|
||||
}{
|
||||
{
|
||||
body: `{"reasoning":{"effort":"low","effort":"high"},"input":[{"type":"compaction_trigger"},{"role":"user","content":"hello"}]}`,
|
||||
path: "reasoning.effort",
|
||||
want: "high",
|
||||
changed: true,
|
||||
},
|
||||
{
|
||||
body: `{"input":[{"type":"compaction_trigger"},{"role":"user","content":[{"type":"input_text","text":"first","text":"latest"}]}]}`,
|
||||
path: "input.0.content.0.text",
|
||||
want: "latest",
|
||||
changed: true,
|
||||
},
|
||||
{
|
||||
body: `{"reasoning":{"effort":"low","effort":"high"},"input":[{"role":"user","content":"hello"},{"type":"compaction_trigger"}]}`,
|
||||
path: "reasoning.effort",
|
||||
want: "low",
|
||||
},
|
||||
} {
|
||||
t.Run(fmt.Sprintf("%s_changed=%v", fixture.path, fixture.changed), func(t *testing.T) {
|
||||
out, changed, err := NormalizeCompactionTriggerInputOrder([]byte(fixture.body))
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, fixture.changed, changed)
|
||||
require.Equal(t, fixture.want, gjson.GetBytes(out, fixture.path).String())
|
||||
if fixture.path == "reasoning.effort" {
|
||||
require.Equal(t, fixture.want, newOpenAIRequestView(out).ReasoningEffort)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -61,14 +61,14 @@ func NormalizeOpenCodeUserAgentVersion(version string) string {
|
||||
return version
|
||||
}
|
||||
|
||||
// rememberOpenCodeInboundBody keeps the client request body so protocol
|
||||
// conversion (Responses↔Anthropic↔Chat Completions) can still recover
|
||||
// prompt_cache_key / metadata.user_id after those fields are dropped.
|
||||
// 协议转换前保存会话提示,使转换后的请求仍能使用原始会话身份。
|
||||
// 提示只包含已校验的会话标识,请求中的文本和图片随原请求释放。
|
||||
func rememberOpenCodeInboundBody(c *gin.Context, body []byte) {
|
||||
if c == nil || len(body) == 0 {
|
||||
return
|
||||
}
|
||||
c.Set(openCodeInboundBodyContextKey, body)
|
||||
sessionID := sanitizeSessionID(openCodeSessionIDFromPayload(body))
|
||||
c.Set(openCodeInboundBodyContextKey, openCodeSessionHintBody(sessionID))
|
||||
}
|
||||
|
||||
func openCodeInboundBodies(c *gin.Context) [][]byte {
|
||||
|
||||
@@ -219,6 +219,31 @@ func TestApplyOpenCodeSessionHeaderUsesRememberedInboundBodyAfterConversion(t *t
|
||||
require.Equal(t, "inbound-messages-session", headers2.Get(openCodeSessionHeader))
|
||||
}
|
||||
|
||||
func TestRememberOpenCodeInboundBodyRetainsOnlySessionHint(t *testing.T) {
|
||||
account := &Account{Platform: PlatformOpenCodeGo, Type: AccountTypeAPIKey}
|
||||
c := newOpenCodeSessionTestContext(t, "")
|
||||
body := []byte(`{"model":"gpt-5","prompt_cache_key":"conversation-42","input":"` + strings.Repeat("x", 2<<20) + `"}`)
|
||||
rememberOpenCodeInboundBody(c, body)
|
||||
|
||||
remembered := openCodeInboundBodies(c)
|
||||
require.Len(t, remembered, 1)
|
||||
require.Less(t, len(remembered[0]), 256, "conversation correlation only retains the session hint")
|
||||
headers := make(http.Header)
|
||||
applyOpenCodeSessionHeader(c, account, "https://opencode.ai/zen/go/v1/messages", headers, []byte(`{"messages":[]}`))
|
||||
require.Equal(t, "conversation-42", headers.Get(openCodeSessionHeader))
|
||||
}
|
||||
|
||||
func TestRememberOpenCodeInboundBodyPreservesSessionFallback(t *testing.T) {
|
||||
account := &Account{Platform: PlatformOpenCodeGo, Type: AccountTypeAPIKey}
|
||||
c := newOpenCodeSessionTestContext(t, "")
|
||||
rememberOpenCodeInboundBody(c, []byte(`{"prompt_cache_key":"previous-session"}`))
|
||||
rememberOpenCodeInboundBody(c, []byte(`{"prompt_cache_key":"a\nb","metadata":{"user_id":"metadata-session"}}`))
|
||||
|
||||
headers := make(http.Header)
|
||||
applyOpenCodeSessionHeader(c, account, "https://opencode.ai/zen/go/v1/messages", headers, []byte(`{"metadata":{"user_id":"converted-session"}}`))
|
||||
require.Equal(t, "converted-session", headers.Get(openCodeSessionHeader))
|
||||
}
|
||||
|
||||
func TestOpenCodeSessionIDFromPayloadIgnoresEmptyBody(t *testing.T) {
|
||||
require.Empty(t, openCodeSessionIDFromPayload(nil))
|
||||
require.Empty(t, openCodeSessionIDFromPayload([]byte(`{"model":"gpt-5"}`)))
|
||||
|
||||
@@ -0,0 +1,26 @@
|
||||
# 减少长会话请求的复制与持有
|
||||
|
||||
- 模型候选同步读取请求字节,返回独立持有的模型名。继续收集 JSON 和 multipart 两种解析路径的候选。
|
||||
- 压缩标记沿用上游提前返回检查。需要重排时保留其他字段的顺序和转义,只重建一次请求。存在重复字段或特殊输入时沿用完整解码的取值规则。
|
||||
- OpenCode 协议转换保存经过校验的会话标识,沿用会话来源优先级。
|
||||
|
||||
上游已实现 OAuth 元数据一次合成、请求视图短字段独立持有,以及审计队列按需分配。本次以最新 `main` 的实现为基础。
|
||||
|
||||
## 压缩标记重排的内存分配
|
||||
|
||||
以 `81ce8356d` 为基线。在 Apple M1 Pro 和 Go 1.27.4 上用相同的合成请求各运行 3 次,每次处理 1 个请求。表中为单次调用的累计分配中位数。
|
||||
|
||||
| 图片字段大小 | 上游基线 | 本次调整 |
|
||||
| --- | ---: | ---: |
|
||||
| 16 MiB | 117,475,888 B | 16,787,224 B |
|
||||
| 112 MiB | 620,792,368 B | 117,450,520 B |
|
||||
|
||||
## 验证
|
||||
|
||||
使用合成图片和工具输出构造长会话,分别验证标记移动、已在末尾的快速返回,以及嵌套重复字段。模型候选与 OpenCode 回归分别覆盖大请求释放和会话标识优先级。
|
||||
|
||||
```sh
|
||||
cd backend
|
||||
GOMAXPROCS=2 go test -p 2 -tags=unit ./internal/pkg/requestmodel ./internal/service ./internal/handler -run 'Test.*(Compaction|OAuthInput|OpenCode|OpenAIRequestView)|^TestFromBody|^TestConflictingField' -count=1
|
||||
GOMAXPROCS=2 go test -p 1 ./internal/service -run '^$' -bench '^BenchmarkCompactionTriggerLargeRequest' -benchtime=1x -benchmem
|
||||
```
|
||||
Reference in new issue
Block a user