Commit Graph
3 Commits
Author SHA1 Message Date
yetone 1859da57bd gateway: readers of a rewritten request see its input in place (#3383)
Only the body a request arrived with is held (holdBody), so decodeJSON
shares a raw value with it and copies one from any other body. Once a
route rewrites a Codex request (its model, its fields), the new body is
held by nobody, and each reader that only looks at it copied the whole
input to do so: conversationID, hasSealedAgentMessage,
orphanedToolOutputs, joinToolRuns, pairToolItems, withReasoningText,
and affinity's seal and kind strippers. Each such copy was ~0.4 to
0.5 MB on a 680 KB request.

decodeJSONView is decodeJSON whose raw values always share the bytes
they came from, capped, for a reader that keeps nothing it decodes and
writes none of it. Those readers use it. Each one only reads, or builds
a new body with json.Marshal or marshalPlain (which copy), or returns
the body it was given. promptBuilder keeps raw parts past its return,
and parseResponses keeps its result, so both stay on decodeJSON.

Measured on the 680 KB Codex request benchmark (30x, 3 runs):
16.37 MB/op, 54,703 allocs/op -> 14.96 MB/op, 54,222 allocs/op (-8.6%).

What was run:
- TestDecodeJSONViewShares: q["input"], q["tools"] and an item's
  content from decodeJSONView point into the body and are capped, and
  decodeJSON still copies from a body that isn't held. With `share ||`
  taken out of fillJSONIn it is red ("tools []: not body's own bytes,
  capped"); restored, green.
- fjCompare checks decodeJSONView against json.Unmarshal on every seed
  as it does decodeJSON.
- Real DeepSeek A/B through a recording proxy in a sandbox HOME, Codex
  UA, 5 requests with a tool-call history: 2d21034d8 and this commit
  each answered "ok" 5 of 5, and the 5 upstream bodies are byte for
  byte the same.
- go vet (darwin; linux and windows with -tags nogui), gofmt -l clean.
- go test -timeout 45m ./internal/gateway/: ok (492s) at beef295be

Not tried: the full ./... suite at this head (queued behind others).
2026-10-24 21:59:05 +08:00
yetone 2d21034d81 gateway: a decoded struct's keys are read without a string made for each (#3383)
fillJSONIn made a string of every member key of every object it decoded
into a struct (unquoteJSON), then a []byte of that string to look the
field up, and a []bool for each struct to see a key twice. A Codex
request's history is thousands of small objects, so these were a
quarter of its allocations. keyName gives a plain ASCII key's bytes
between its quotes and leaves any other key to unquoteJSON as before,
and the fields seen are bits of a uint64 unless a struct has more than
64 of them.

Run at 83234fe92 + the previous change + this one:
- BenchmarkZZCodexStream (680 KB Codex request, probe not committed),
  -benchtime 30x -count 3: before ~72,780 allocs/op, 16.42 MB/op;
  after 54,698 / 54,692 / 54,696 allocs/op (-25%), 16.33 MB/op.
- TestDecodeJSONIsUnmarshal gains a non-ASCII key, a fullwidth key and
  keys with control bytes; TestDecodeJSONKeyTwice checks fillJSON refuses
  a key twice in a 3-field struct and a 70-field one. Broken by hand:
  keyName not looking for escapes turns TestDecodeJSONIsUnmarshal and
  FuzzDecodeJSON red; dropping the twice check in either the bits or the
  slice path turns TestDecodeJSONKeyTwice red.
- go test -fuzz FuzzDecodeJSON -fuzztime 60s: ~966k execs, no failure.

At c0b3aadfe (on d7ad3f2a3):
- Real account, sandbox HOME with only DeepSeek, through a recording
  proxy to api.deepseek.com: 5 Codex-UA /v1/responses requests with a
  tool-call history on d7ad3f2a3 and on this; all 10 answered "ok", and
  the 5 bodies sent upstream are byte-identical.
- gofmt clean; GOOS=linux and windows go vet -tags nogui ok.
- go test -timeout 45m ./internal/gateway/: ok (449s) at c0b3aadfe
2026-10-24 21:49:50 +08:00
yetone 5feadabef6 gateway: a long conversation's request costs about a third of the CPU it did, with the same bytes sent on (#1532, #1654)
The gateway reads one request's body a dozen times or more on its way:
modelOf, streamOf, conversationID, requestEffort, bodyEffort,
walkImages and swapImageBlocks (more than once through a group), turnOf's
parse, promptOf, chatToolNames, thinkingOffUnlessAsked, decodeRequest,
and for Responses pairToolItems, orphanedToolOutputs,
hasSealedAgentMessage and askedTier. Each read took a field or two with
json.Unmarshal, which checks the whole input and then steps through every
byte of every string one call at a time, so each read cost as much as
decoding the whole conversation: 74-77% of a request's CPU in pprof, most
of it checkValid and stateInString.

decodeJSON (fastjson.go) is json.Unmarshal for these reads. It checks the
body once with its own validator (json.Valid's grammar and 10000 depth,
8 string bytes at a time), splits objects and arrays at their members
without decoding them, and decodes only what dst has a place for:
strings, booleans, json.RawMessage (copied, as encoding/json does),
structs, pointers, slices and string-keyed maps by their parts, and
everything else (numbers, interfaces, types that decode themselves) by
encoding/json itself. Whatever it doesn't take on exactly as
json.Unmarshal would goes to json.Unmarshal with dst zeroed: invalid
input, a dst already holding something, an embedded field, a ",string"
option, two fields of one name, a key given twice, a value of the wrong
type. A list or object where dst takes a string (a "string or parts"
read) is answered by json.Unmarshal of its opening and close, which gives
the same error at the same offset without reading the rest. The request
paths' json.Unmarshal calls in gateway.go, decide.go, affinity.go,
image_input.go, textcalls.go, anthropic.go, ir.go, prompt.go, chat.go,
chattidy.go and responses.go, and hasSealedAgentMessage and askedTier,
now call it. Nothing that writes a body changed.

Numbers, M4 Pro under load 10-20 from other sessions, BenchmarkLargeRequest
(new: a 2 MB agent conversation with 30 tools, tool calls and results,
through a fake vendor), 20 requests each:

                    CPU in the request's handler    time per request
                    (pprof, per request)            (ns/op)
  anthropic         154ms -> 45ms                   208-212ms -> 52ms
  anthropic, group  178ms -> 51ms                   249-262ms -> 65-67ms
  chat              122ms -> 35ms                   167-254ms -> 50-54ms
  responses         215ms -> 56ms                   294-452ms -> 70ms

TestLargeRequestEndpoints (64 MB padded bodies): 16.8-17.6s -> 2.9-4.8s
(skipping runs of spaces 8 bytes at a time took its last ~5s).

Tests:
- TestUpstreamBodiesUnchanged sends 18 requests (Anthropic, Chat and
  Responses; direct, through a group, translated to each other protocol,
  with images, thinking, escapes, odd spacing, a repeated key, and four
  2 MB conversations) and compares what the vendor gets with
  testdata/upstream_bodies, recorded on the code before this change
  (all 18 identical; three runs agreed). Breaking decodeJSON's \n
  unescape by hand turns the three translated cases holding one red.
- TestDecodeJSONIsUnmarshal / FuzzDecodeJSON compare decodeJSON with
  json.Unmarshal (dst DeepEqual, error nil-ness) for 19 types shaped like
  the gateway's, and jsonValid with json.Valid, over seeds, every cut
  and a changed byte at every place of each seed, and 2.5 minutes of
  fuzzing (~1.75M inputs). Breaking the validator's control-byte check
  by hand turns it red.
- go test -tags nogui -timeout 40m ./... on this commit rebased onto
  origin/main 498b77fbc, with #1667's fix below it: all 48 packages ok
  (gateway 394s).
gofmt -l clean; GOOS=linux and GOOS=windows go vet -tags nogui
./internal/gateway clean.

Not tried: real vendor traffic; Windows and Linux runs (vet only).
2026-10-12 03:28:16 +08:00