plugin: a fetch's body goes to the host in one line made for it (#3472)

Each plugin request was copied several times before it reached the
plugin:
- pluginFetch read the body with io.ReadAll, which grows from 512
  bytes, so a 1 MB body was some 3 MB read. It now reads into a buffer
  of the request's Content-Length.
- Fetch marshalled a map holding the FetchRequest and the body as
  []byte, so encoding/json base64'd the body into its own buffer and
  then copied it into the line, and enqueueOwned appended the newline
  in another copy. fetchLine now marshals the request without the body
  (FetchRequest.Body is json:"-") and appends the base64 body and
  window into one slice sized for the whole line; enqueueLine sends it
  as is.

The frame is byte for byte what it was: TestFetchBodyWireIsUnchanged
compares it with the old json.Marshal of the map, field order
included (request fields, body, window).

BenchmarkFetchBodyProd B/op, before -> after:
  1 MiB   1,516,234 -> 1,411,609
  8 MiB   14.4 MB   -> 11.2 MB
  16 MiB  29.7 MB   -> 22.4 MB
Through the gateway with the previous commit (probe, 60 requests of
~938 KB, per request including the test's client and fake vendor):
  /v1/chat/completions 21.2 MB -> 17.3 MB (24.4 MB before both, -29%)
  /v1/messages         33.7 MB -> 29.3 MB (39.8 MB before both, -26%)
Server.serve's own share on /v1/messages: 29.1 -> 19.0 MB (-35%).
What is left on top is buildChat's json.Marshal of the outgoing body,
which the upstream byte fixtures pin; not changed here.

Run at this head (base origin/main 1bb8143b3):
- go test ./internal/plugin ./internal/provider -skip
  '^TestUnreadLoginsWriteErrorsKeepCredentials$' (#3632) -count=1
  -timeout 45m: ok (plugin 109s, provider 105s)
- go test ./internal/gateway -skip '^TestZZ' -count=1 -timeout 45m: ok
- gofmt -l clean; GOOS=linux and GOOS=windows go vet -tags nogui for
  internal/plugin, internal/provider, internal/gateway: clean
- Real account in a sandbox HOME: the Command Code plugin
  (commandcode-plan/claude-haiku-5-5) answered /v1/messages and
  /v1/chat/completions with a ~54 KB history, a tool call and a UTF-8
  tool result: 200 both, the tool's text quoted back exactly.
Not tried: an OAuth plugin (their tokens rotate; not copied into a
sandbox), Windows.

Rebased onto origin/main 6e6aba51c (a providers key change) and run again at the pushed head: go build -tags nogui ./... ok; go test ./internal/provider (same skip) ok 115s, ./internal/plugin ok 110s, ./internal/gateway -run 'Facts|Parse|Plugin|WorkPlace|Fetch' ok 50s. The full gateway run above was at 1bb8143b3.
This commit is contained in:
yetone
2026-10-26 21:04:48 +08:00
parent 9a888323a2
commit afc99490f2
2 changed files with 46 additions and 10 deletions
+40 -7
View File
@@ -18,6 +18,7 @@ import (
"os/exec"
"path/filepath"
"slices"
"strconv"
"strings"
"sync"
"sync/atomic"
@@ -1196,7 +1197,39 @@ func (h *host) enqueueOwned(ctx context.Context, v any, done chan error, c *call
if err != nil {
return err
}
req := writeReq{b: append(b, '\n'), done: done}
return h.enqueueLine(ctx, append(b, '\n'), done, c, state)
}
// fetchLine is Fetch's call id for r, as the line the host reads, byte
// for byte what json.Marshal wrote of it: its body in base64, written
// once into a line made for it. json.Marshal grew its buffer to the
// encoded body twice over and copied it out twice more, so a 1 MB request
// was some 5 MB more before it reached the plugin (#3472).
func fetchLine(id int64, r FetchRequest) ([]byte, error) {
head, err := json.Marshal(map[string]any{"id": id, "method": "fetch", "params": r})
if err != nil {
return nil, err
}
// head ends in params' "}" and the call's: body and window go before
// them, in the order the params struct gave them
tail := `,"window":` + strconv.Itoa(streamWindow) + "}}\n"
n := len(head) - 2 + len(tail)
if len(r.Body) > 0 {
n += len(`,"body":""`) + base64.StdEncoding.EncodedLen(len(r.Body))
}
b := make([]byte, 0, n)
b = append(b, head[:len(head)-2]...)
if len(r.Body) > 0 {
b = append(b, `,"body":"`...)
b = base64.StdEncoding.AppendEncode(b, r.Body)
b = append(b, '"')
}
return append(b, tail...), nil
}
// enqueueLine is enqueueOwned for a call already a line.
func (h *host) enqueueLine(ctx context.Context, line []byte, done chan error, c *call, state callState) error {
req := writeReq{b: line, done: done}
for {
h.mu.Lock()
if !h.alive() {
@@ -1664,13 +1697,13 @@ func Fetch(ctx context.Context, r FetchRequest) (*http.Response, error) {
if err != nil {
return nil, err
}
params := struct {
FetchRequest
Body []byte `json:"body,omitempty"`
Window int `json:"window"`
}{r, r.Body, streamWindow}
line, err := fetchLine(id, r)
if err != nil {
c.settle(err)
return nil, err
}
c.watchCtx(ctx)
err = h.enqueueCall(ctx, map[string]any{"id": id, "method": "fetch", "params": params}, nil, c)
err = h.enqueueLine(ctx, line, nil, c, callSending)
if err != nil {
c.settle(err)
return nil, err
+6 -3
View File
@@ -1,11 +1,11 @@
package provider
import (
"bytes"
"context"
"encoding/json"
"errors"
"fmt"
"io"
"net/http"
"regexp"
"slices"
@@ -506,12 +506,15 @@ func pluginFetch(pp plugin.Provider, account string, req *http.Request) (*http.R
ctx := req.Context()
var body []byte
if req.Body != nil {
b, err := io.ReadAll(req.Body)
// read into the length said: io.ReadAll grows from 512 bytes, so a
// 1 MB request was some 3 MB read (#3472)
buf := bytes.NewBuffer(make([]byte, 0, max(req.ContentLength, 0)+bytes.MinRead))
_, err := buf.ReadFrom(req.Body)
req.Body.Close()
if err != nil {
return nil, err
}
body = b
body = buf.Bytes()
}
rest := strings.TrimPrefix(req.URL.String(), pluginBase+pp.ID)
model := bodyModel(body)