Files
magpie/internal/gateway/image_input.go
T
yetone 68133754a3 gateway: a request's body is read in place, not copied by every reader (yg6888 on X: ~1 GB)
yg6888 on X: "magpie 占用内存有点高 随时1个g", with a group of 29
accounts and three agents sending at once.

Cause: each reader of a request decodes its turns into json.RawMessage
values (the images walk, the conversation id, the prompt, the edits, the
chat parse), and decodeJSON copied each value it filled, as
encoding/json does. A 1.5 MB conversation allocated ~42.8 MB on its way
through a group. Three agents at once kept the heap in the hundreds of
MB, and the GC ran behind it.

Fix:
- readRequestBody holds the body (holdBody) until the request's context
  ends. A RawMessage decodeJSON fills from inside a held body shares the
  body's bytes, capped so an append can't write into it. The body must
  be at most 16x the value (heldShareMost), so a small value kept past
  its request (a cache entry, a signature) never pins a whole body.
  Anything not held is still copied: a stream's buffer, a scanner line,
  a body built and changed in place. The list is bounded at 64 bodies
  (heldBodiesMost) and each leaves it through context.AfterFunc.
- The ratio leaves a long conversation's many small turns copied, so
  the two readers that run on every request take them in place:
  - conversationID takes the turns with elementsOf, slices of the
    body.
  - walkImages, which runs several times a request, first scans the
    turns without decoding (anyImageBlock/anyImageIn) and returns at
    once when there is no image. Keys and kinds are compared with
    jsonStringIs, so an escaped "type", a duplicate key, a tool
    result, a Responses function_call_output and Gemini's inlineData,
    fileData and functionResponse still count.

Numbers: sandbox gateway, fresh process each run, 150 requests of a
1.5 MB conversation, 3 at once through a group, machine load ~250:

                    peak RSS  HeapSys  GCs  allocated   bytes.Clone
  before            273 MB    222 MB   117  6416 MB     3635 MB
  held bodies       233 MB    186 MB    74  3379 MB     1480 MB
  + id/image scan   223 MB    174 MB    64  2853 MB      927 MB

That is ~42.8 MB allocated per request before and ~19 MB after. What is
still copied comes from the translators (stringOrText, editMessages,
parseChat, responsesContent), unquoteJSON (~670 MB), io.ReadAll
(~480 MB) and rewriteModel (~225 MB). None of these is changed here.

Tests:
- TestRequestBodyRawValuesShareIt, TestDecodeJSONCopiesWhatIsNotHeld and
  TestHeldBodiesBounded (fastjson_held_test.go).
- TestImageWalkReadsTextOnlyTurnsInPlace: a 938 KB text-only
  conversation allocates under len/8 per walk plus id, and eight image
  shapes are still found.

Broken by hand, each red:
- no share cap
- no ratio
- no bound
- no release
- pre-scan removed (8,780,204 B per iteration)
- tool_result skipped (case not found)
- id decoding each turn (1,044,859 B over the 117,265 limit)
- kind compared as raw bytes (the escaped case is not found)

No subsystem page covers decodeJSON.

Run record, the three commits on origin/main d9c6a60d8 (machine load
~270-480, with other sessions' GUI suites running):
- gofmt -l: clean. go vet ./... on darwin, GOOS=windows and
  GOOS=linux -tags nogui: exit 0.
- go test ./... -count=1 -timeout 45m (sandbox HOME, 11:02-11:34): 64
  ok, 1 FAIL: internal/gui TestCoreScriptBudget, app.js 155 bytes over
  from the first ledNum. ledNum was made smaller (1,268,907 of
  1,269,000 bytes), then internal/gui -count=1 alone: ok (329 s).
- Before the rebase (723f40778 on 9588501c0): internal/gateway ok
  (2064 s), internal/agent ok at -timeout 120m (it timed out at 45m
  at load ~700, #2869), internal/gui red only in
  TestSetAnswersWhileDevinAndProvidersHang (#1375).
- GUI suite, all 140 files, Chromium and WebKit, every language, at
  load 400-840 on 723f40778. Every red was run alone against
  9588501c0, and none comes from this change: routing-bodies
  (#2559/#2658), routing-keys-fold and routing-model-rest (#2658),
  routing-mode-goes WebKit (#2151, head 2/20 vs base 3/20),
  routing-request-metrics (#2571), routing-wb-restricted (#1905),
  usage-agents-hide (#2276/#2399), usage-fold (#2399), usage-checkin
  WebKit Qoder (#2549), usage-refresh (#2184). 5 s first waits under
  load were added to #2900. The usage-ledger route-callback race at
  page close was filed as #3001.
- After the rebase, each alone in both engines: routing-busy-frames,
  routing-intent-entry, routing-key-windows, routing-pause and
  usage-ledger were green.
- After the smaller ledNum, each alone, both engines, all languages:
  routing-busy-frames 6/0 (one later run lost Chromium's launch at
  180 s twice; Chromium alone right after: 3/3), usage-ledger
  Chromium 16/16 and WebKit 17/0. usage-ledger-leave and
  routing-request-metrics were red in browser launch and 5 s waits on
  this head and on d9c6a60d8 alike (#2900, #2571). Added to #2900:
  a WebKit zh usage-ledger run hung after a 5 s timeout.
2026-10-20 13:26:05 +08:00

318 lines
9.5 KiB
Go

package gateway
import (
"encoding/json"
"errors"
"strings"
"github.com/yetone/magpie/internal/provider"
)
const imageOmitted = "[Image omitted: this model accepts text only.]"
// errCurrentImage stops a walk at an image the latest turn gives the model.
var errCurrentImage = errors.New("an image in the latest turn")
// textOnlyBody rejects a user image in the latest turn and omits tool images
// and images in older turns. It edits the wire JSON so passthrough keeps fields
// the IR does not represent (such as provider-specific request options).
func textOnlyBody(proto provider.Protocol, body []byte) ([]byte, bool) {
out, err := walkImages(proto, body, func(im imageAt) (json.RawMessage, error) {
if im.Current() {
return nil, errCurrentImage
}
return textBlock(proto, imageOmitted), nil
})
if err != nil {
return body, true
}
return out, false
}
// hasImage is whether the body has an image in any turn.
func hasImage(proto provider.Protocol, body []byte) bool {
found := errors.New("found")
_, err := walkImages(proto, body, func(imageAt) (json.RawMessage, error) { return nil, found })
return err == found
}
// hasUnportableCurrentImage reports a current Responses image with no URL to
// carry to another protocol. A file_id belongs to the Responses provider that
// stored it; translating it as a URL or dropping it would mislead the model.
func hasUnportableCurrentImage(body []byte) bool {
missing := errors.New("current image has no portable source")
_, err := walkImages(provider.Responses, body, func(im imageAt) (json.RawMessage, error) {
if im.Current() && im.Src == "" {
return nil, missing
}
return nil, nil
})
return err == missing
}
// imageAt is an image in a request, where it is.
type imageAt struct {
// Src is the image as a URL, a data: URL for one sent inline; empty for
// one only its vendor can open (a Responses file_id, a Gemini file).
Src string
// Last is set on one in the latest turn, Tool on one a tool gave back.
Last, Tool bool
}
// Current is whether the image is one the user gives the model now, which
// the model is asked about.
func (im imageAt) Current() bool { return im.Last && !im.Tool }
// walkImages gives every image in the body's turns to swap, and puts the
// block it returns in the image's place (nil keeps it). An error from swap
// ends the walk. The body is returned as it was when nothing was swapped.
func walkImages(proto provider.Protocol, body []byte, swap func(imageAt) (json.RawMessage, error)) ([]byte, error) {
var request map[string]json.RawMessage
if decodeJSON(body, &request) != nil {
return body, nil
}
turnsKey, contentKey := "messages", "content"
switch proto {
case provider.Responses:
turnsKey = "input"
case provider.Gemini:
turnsKey, contentKey = "contents", "parts"
}
if raw := request[turnsKey]; len(raw) > 0 && raw[0] == '[' && !anyImageBlock(proto, raw, contentKey) {
// Most requests have no image, and this walk runs several times
// on each: decoding every turn and block cost ~2.6 MB for each
// 1.5 MB conversation (yg6888 on X).
return body, nil
}
var turns []json.RawMessage
if decodeJSON(request[turnsKey], &turns) != nil {
return body, nil
}
changed := false
for i, raw := range turns {
var turn map[string]json.RawMessage
if decodeJSON(raw, &turn) != nil {
continue
}
key := contentKey
tool := false
var kind string
if proto == provider.Responses {
decodeJSON(turn["type"], &kind)
if kind == "function_call_output" {
key, tool = "output", true
}
}
if proto == provider.Chat {
decodeJSON(turn["role"], &kind)
tool = kind == "tool"
}
content, swapped, err := swapImageBlocks(proto, turn[key], i == len(turns)-1, tool, swap)
if err != nil {
return body, err
}
if !swapped {
continue
}
turn[key] = content
turns[i], _ = json.Marshal(turn)
changed = true
}
if !changed {
return body, nil
}
request[turnsKey], _ = json.Marshal(turns)
return json.Marshal(request)
}
// anyImageBlock is whether turns, a valid JSON array, may hold a block
// walkImages gives to swap, read in place without decoding: a turn's
// contentKey (or a Responses function_call_output's output) that is a list
// with a block among it of an image's type, an Anthropic tool_result, or
// a Gemini part with inlineData, fileData or a functionResponse. It errs
// toward yes, as for a key spelled twice.
func anyImageBlock(proto provider.Protocol, turns []byte, contentKey string) bool {
found := false
eachElement(turns, func(turn []byte) bool {
if turn[0] != '{' {
return true
}
eachMember(turn, func(key, val []byte) bool {
if val[0] == '[' && (jsonStringIs(key, contentKey) || (proto == provider.Responses && jsonStringIs(key, "output"))) {
found = anyImageIn(proto, val)
}
return !found
})
return !found
})
return found
}
// anyImageIn is whether blocks, a valid JSON array, has a block
// swapImageBlocks would look into (anyImageBlock).
func anyImageIn(proto provider.Protocol, blocks []byte) bool {
kind := "image" // Anthropic's
switch proto {
case provider.Chat:
kind = "image_url"
case provider.Responses:
kind = "input_image"
}
found := false
eachElement(blocks, func(block []byte) bool {
if block[0] != '{' {
return true
}
eachMember(block, func(key, val []byte) bool {
switch {
case proto == provider.Gemini:
found = jsonStringIs(key, "inlineData") || jsonStringIs(key, "fileData") || jsonStringIs(key, "functionResponse")
case jsonStringIs(key, "type"):
found = jsonStringIs(val, kind) || (proto == provider.Anthropic && jsonStringIs(val, "tool_result"))
}
return !found
})
return !found
})
return found
}
// swapImageBlocks swaps the images among a turn's blocks, and those in an
// Anthropic tool_result's, which are a tool's.
func swapImageBlocks(proto provider.Protocol, raw json.RawMessage, last, tool bool, swap func(imageAt) (json.RawMessage, error)) (json.RawMessage, bool, error) {
var blocks []json.RawMessage
if decodeJSON(raw, &blocks) != nil {
return raw, false, nil
}
swapped := false
for i, rawBlock := range blocks {
var block map[string]json.RawMessage
if decodeJSON(rawBlock, &block) != nil {
continue
}
var kind string
decodeJSON(block["type"], &kind)
src, isImage := imageSrc(proto, kind, block)
if isImage {
out, err := swap(imageAt{Src: src, Last: last, Tool: tool})
if err != nil {
return raw, false, err
}
if out != nil {
blocks[i] = out
swapped = true
}
continue
}
// Gemini's function response holds a tool's images in its own parts
if proto == provider.Gemini && len(block["functionResponse"]) > 0 {
var fr map[string]json.RawMessage
if decodeJSON(block["functionResponse"], &fr) == nil && len(fr["parts"]) > 0 {
content, nested, err := swapImageBlocks(proto, fr["parts"], last, true, swap)
if err != nil {
return raw, false, err
}
if nested {
fr["parts"] = content
block["functionResponse"], _ = json.Marshal(fr)
blocks[i], _ = json.Marshal(block)
swapped = true
}
}
}
if proto == provider.Anthropic && kind == "tool_result" {
content, nested, err := swapImageBlocks(proto, block["content"], last, true, swap)
if err != nil {
return raw, false, err
}
if nested {
block["content"] = content
blocks[i], _ = json.Marshal(block)
swapped = true
}
}
}
if !swapped {
return raw, false, nil
}
out, _ := json.Marshal(blocks)
return out, true, nil
}
// imageSrc is whether a block is an image, and the image as a URL when it
// can be read from the block.
func imageSrc(proto provider.Protocol, kind string, block map[string]json.RawMessage) (string, bool) {
switch proto {
case provider.Chat:
if kind != "image_url" {
return "", false
}
var url string
if decodeJSON(block["image_url"], &url) != nil {
var obj struct {
URL string `json:"url"`
}
decodeJSON(block["image_url"], &obj)
url = obj.URL
}
return url, true
case provider.Responses:
if kind != "input_image" {
return "", false
}
var url string
decodeJSON(block["image_url"], &url)
return url, true
case provider.Anthropic:
if kind != "image" {
return "", false
}
var src struct {
Type string `json:"type"`
MediaType string `json:"media_type"`
Data string `json:"data"`
URL string `json:"url"`
}
decodeJSON(block["source"], &src)
switch {
case src.Type == "base64" && src.Data != "":
return "data:" + src.MediaType + ";base64," + src.Data, true
case src.Type == "url":
return src.URL, true
}
return "", true
case provider.Gemini:
var data struct {
MimeType string `json:"mimeType"`
Data string `json:"data"`
}
decodeJSON(block["inlineData"], &data)
if strings.HasPrefix(data.MimeType, "image/") {
return "data:" + data.MimeType + ";base64," + data.Data, true
}
if len(block["fileData"]) > 0 {
var file struct {
MimeType string `json:"mimeType"`
}
if decodeJSON(block["fileData"], &file) != nil || file.MimeType == "" || strings.HasPrefix(file.MimeType, "image/") {
return "", true // unknown file types may be images; fail closed
}
}
}
return "", false
}
// textBlock is a text block of the protocol's.
func textBlock(proto provider.Protocol, text string) json.RawMessage {
var b []byte
switch proto {
case provider.Responses:
b, _ = json.Marshal(map[string]string{"type": "input_text", "text": text})
case provider.Gemini:
b, _ = json.Marshal(map[string]string{"text": text})
default:
b, _ = json.Marshal(map[string]string{"type": "text", "text": text})
}
return b
}