Commit Graph
19 Commits
Author SHA1 Message Date
yetone 24a68018e8 gateway: a held body's member is not checked again byte by byte when it is decoded alone (#5281)
heldLongOf remembers that a held request body is valid, and where its
top-level members are, by the body's data pointer, so only a whole body
matches it. A Responses request's input (a chat's messages) is then
decoded alone by each of its readers. The first decode of each checked
all of it again: inspectPrompt's goroutine and factsOf (the folder's
reader) do it at the same time, both before the hash memo knows the
slice. For TestCodexGeneratedImagesPastOldLimit's 516 MB turn that was
two more full jsonCheck scans before routing. Under -race each byte of
those scans calls into the race runtime, so they were a large part of
the 34s that got the turn a 504 on main CI.

heldMember says whether a slice is exactly the value of a top-level
member of a held body found valid (binary search over its member spans).
A part of a valid value split at its members is valid itself, so
jsonValid and longBody skip the byte-by-byte check for it. A slice that
only lies inside a member, or is cut short, is checked as before.

Run on mote:
- new TestDecodeJSONHeldMemberNotCheckedAgain: decodes a held body, then
  its input three times as a string and as items plus jsonValid(input).
  It expects the body checked once and the input never, and a cut input
  checked once and refused. Red with heldMember turned off by hand
  ("checked 1 times and its input 1, want 1 and 0"), green on the fix.
- TestCodexGeneratedImagesPastOldLimit's post timed under -race on mote,
  load 42 to 80, old and new interleaved: old 20.9/18.8/17.4s, new
  (with e710160df) 16.7/13.9/14.3s. Without -race: old 3.20/3.27/3.31s,
  new 3.05/3.13/3.14s.
- go test -race -run 'TestCodexGeneratedImagesPastOldLimit|TestRequestBody|
  TestDecodeJSON|TestJSONValid|Held|TestReadSized|LargeBody|OldLimit'
  ./internal/gateway: ok 114.9s.
- go vet ./internal/gateway on darwin, GOOS=linux and GOOS=windows: ok.
  gofmt -l: clean.

What is left of the time under -race is mostly three full parses of the
turn (stoppedToolLoop, factsOf, promptOf). Each is race-instrumented per
byte. Those are not changed here. Found by wall-clock sampling of
goroutine stacks in the test; a Go CPU profile on darwin shows them only
as runtime._ExternalCode.

Not tried: a real Codex client sending a 516 MB turn.
2026-11-05 03:37:36 +08:00
yetone ccb75030aa gateway: a held request body is known by where it is, not summed again (#4371)
Each of the dozen decodes, topMember reads and validity checks a request
body goes through summed all its bytes with maphash to find what
validMemo knew of it: about 5% of the gateway's CPU on long Codex
requests (#4371). A body being served (holdBody) is not written while
held, so longBody and jsonValid now know it by its address and length,
check and split it once, and keep that in heldBodies.long until it is
released, as factsOf keeps its facts. Any other long body is summed as
before.

Run on mote at this tree:
- gofmt, go vet (darwin, GOOS=windows, GOOS=linux): ok
- TestHeldBodyIsNotSummed, TestHeldBodyNotJSON, TestDecodeJSON*,
  TestRequestBodyRawValuesShareIt, TestTopMember*, TestWithoutTopMember*:
  ok 3 of 3 alone, ok under -race
- go test -timeout 45m ./internal/gateway: ok (609s)
- Broken by hand: held lookup skipped -> "a held 84077-byte body was
  summed 18 times"; release left the finds kept -> "a released body's
  finds were kept".
- BenchmarkHeldBodyDecodes (1.8MB Responses body held, 12 decodes plus 12
  topMember reads an op): 3.31ms/op before, 7.9us/op after, allocations
  the same (24/op).

Real use: sandbox HOME copied from the owner's, real DeepSeek account,
deepseek-flash, four turns of a 115-123KB history through
/v1/chat/completions with masking on: every reply HTTP 200 (three "ok",
one empty at finish_reason length, the model's reasoning using
max_tokens, as on the old binary).

Not run: the full ./... suite; a real Codex account; Windows and Linux
runs of the tests.

Picked onto 9162277b9 (3 commits, none in internal/gateway/fastjson.go); not run again there.
2026-11-01 09:59:21 +08:00
yetone ccc791231f gateway: a long turn sent to a Chat upstream is copied once, not five times
A 3.2 MB Codex /v1/responses request served by a Chat provider allocated
about 70 MB in the gateway, and that garbage, at GOGC 100 over the app's
live heap, set the peak footprint. Four copies went:

- unquoteJSON built an escaped string (any text with a newline) in a
  buffer and then copied it into a string; the buffer is the string now
  (unsafe.String, nothing writes to it again), with a copy only when
  \u escapes left more than a quarter of it unused.
- turnIn joined every user text of the conversation (userSaid) only to
  see whether any was there; saysAnything stops at the first.
- buildChat's user message grew a strings.Builder part by part across
  a merged turn; joinTexts sizes it once and takes a lone part as it is.
- marshalItems ran json.Marshal, whose buffer doubles and is then
  copied out, over one message that holds the whole turn. marshalSized
  sizes the maps, lists, strings, bools and ints a body is made of
  first and writes them into one slice of that size, as encoding/json
  writes them (HTML escaped, � for bad UTF-8, U+2028/2029); any
  other value is json.Marshal's own. A []any item, reached by its
  address, is a *any, which went to json.Marshal twice (to size, then
  to write) until it was dereferenced; TestMarshalBodyAllocatesTwoBodies
  caught that at 154 MiB for a 47 MiB body, now 52.

Run on mote (M5 Pro), at this tree:
- TestLongTurnCopiedFewTimes, a 2.0 MB 300-turn Responses body with
  CJK and newlines: read 6.72 MB -> 4.76 MB (3.4x -> 2.4x), turnIn
  1.93 MB -> 10 KB, buildChat 27.3 MB -> 6.06 MB (13.7x -> 3.0x).
  Broken by hand one at a time in the mote copy, each red on its own
  bound: unquote back to string(b) 3.4x; userSaid back in turnIn
  1.9 MB; the Builder back 7.4x; json.Marshal back 6.2x.
- TestMarshalSizedIsJSONMarshal: byte for byte against json.Marshal
  over all 256 bytes, bad UTF-8, a lone surrogate, U+2028/2029, HTML
  characters, keys needing escapes, nil maps and lists, floats,
  RawMessage, pointers, and a func json.Marshal refuses.
- go test -count=1 -timeout 45m ./internal/gateway/: ok (582.9s).
- go vet ./internal/gateway/ for darwin, linux and windows; gofmt clean.
- Gateway bench (120 requests of a 3.2 MB Responses body, 4 at a time,
  through a fake Chat provider, 200 MB ballast held live), 3 runs each,
  old/new: TotalAlloc 8368-8403 MB -> 5889-5891 MB (-30%), GCs 26-27
  -> 18-19, phys_footprint_peak 795/806/807 MB -> 763/762/749 MB,
  CPU 7.89-7.92 s -> 8.01-8.17 s (the size pass costs about what the
  copies saved).

Real use: this build (go build -tags nogui) in a sandbox HOME with the
owner's DeepSeek key only, magpie serve on 127.0.0.1:3581. A 180 KB
/v1/responses request (a long CJK turn with <tag> & "quotes" \ tabs,
a function_call and its output holding U+2028, then a question) to
deepseek/deepseek-flash, served through buildChat: answered with both
code words as sent (<ZEBRA&42>, MANGO), non-streamed and streamed.

Not tried: an Anthropic-in, Chat-out request, and the live app's own
peak (the bench stands in for it).
2026-10-31 21:39:37 +08:00
yetone ddf31ca305 gateway: a large translated body is written into itself, its items not kept beside it (#4004)
marshalBody marshalled every item of a translated request's list (the
messages, the input items) and kept the bytes, so it could size the body
exactly before copying them in: at the body's peak the written items
were a whole copy of the conversation beside the body. Past bodyKept
(4 MiB) of kept items, an item is now only measured, encoded through a
json.Encoder into a writer that only counts, and
once the body is made it is encoded again straight into it, then let go
when its list is spent. A body under 4 MiB is written as before, with no
second encoding; a larger one pays its encoding once more (on mote the
47 MiB case of TestMarshalBodyAllocatesTwoBodies went 0.09 -> 0.11 s
for both marshals together). The bytes are json.Marshal's either way.

Measured on mote, scratch harness (not committed): a 45 MiB Codex
conversation sent Responses -> Chat through the gateway, GOGC=10,
HeapInuse sampled every 2 ms, 3 runs each, base heap 54 MiB:
  425a61322 (before 8eb7f5565):  peak 302, 301, 301 MiB
  8eb7f5565 (spent list):        peak 278, 271, 273 MiB
  this change:                 peak 264, 263, 263 MiB
marshalBody of the 47 MiB test body allocates 52 MiB, was 98 MiB.

Tests: TestMarshalBodyAllocatesTwoBodies now holds marshalBody to 1.5x
the body (was 2.5x); red on the old code, which allocated 98 MiB for
47. TestMarshalBodyIsJSONMarshal runs every body, and every value
json.Marshal refuses, with everything kept, with every item measured
(bodyKept 0) and with the first kept and the rest measured (1).

Run at the pushed head (mote): GOOS=linux/windows/darwin go vet -tags
nogui ./internal/gateway/: ok. go test -count=1 -timeout 45m
./internal/gateway/: ok (465.1s)

Not tried: a real upstream; the bytes sent are unchanged.
2026-10-29 02:26:33 +08:00
yetone 8eb7f5565b gateway: a translated body lets its built conversation go as it fills (#4004)
marshalBody wrote a translated request's list (Chat's and Anthropic's
messages, Responses' input) an item at a time, but the list itself, the
conversation the builder made, strings joined from the request's parts
among it, stayed held in the body's map until the whole body was
written: at the body's peak it sat beside the written items and the
body. The builder names that list as spent, and each item is set to its
zero value once written. Every caller's map is its own and dropped after
the call (buildChat, buildAnthropic, buildResponses); buildGemini spends
nothing. Keys are checked before anything is spent, so the json.Marshal
fallback for an odd key still sees the whole map.

Measured on mote, TestZZPeak4004-style scratch harness (not committed):
a 45 MiB Codex conversation sent Responses -> Chat through the gateway,
GOGC=10, HeapInuse sampled every 2 ms, 3 runs each:
  base 425a61322: peak 302, 301, 301 MiB (base heap 54 MiB)
  this change:    peak 278, 271, 273 MiB
Live at send is the same, 149 MiB above base (the request, its parse,
the body), as the conversation was garbage by then either way.

Tests: TestMarshalBodyLetsSpentGo (new) writes a list of probes, each
looking whether the item before it was let go, and that a list not
named spent is unchanged. Broken by hand (spend never zeroing): red,
"items [0 1 2 3] were still held when the next was written".
TestMarshalBodyIsJSONMarshal passes with the messages spent.

Run on mote at 425a61322 + this change: GOOS=linux/windows/darwin go
vet -tags nogui ./internal/gateway/: ok; go test -count=1 -timeout 45m
./internal/gateway/: ok (537.8s). Rebased onto f6e7214af, whose only
gateway change is a host in buildChat's inlineThink; at the pushed head:
the three vets again ok, and go test -run 'TestMarshalBody|MiniMax|
Minimax|TestChat|TestResponses|TestAnthropic|Translat' ./internal/gateway/:
ok (31.8s).

Not tried: a real upstream; the bytes sent are the same, which
TestMarshalBodyIsJSONMarshal holds to json.Marshal's.
2026-10-29 02:17:47 +08:00
yetone 56d26f0bba gateway: a conversation's list is looked at where it sits in the body, not copied (#4004)
gjson.GetBytes copies the value it finds. For "input" or "messages"
that is the conversation, so tailOf, the effort, deferred-tools and
refs-only checks, Cline's images, Codex's images, the compaction
lookups and the title digest each copied a 44 MiB Codex turn once
per request to look at it. getIn reads it in place (gjson.Get over
the body's bytes). None of the nine sites changes the body while a
result is held, and none keeps a string past the request: Codex's
image jobs read url.Str and write a new buffer, the compaction encs
are lookups, the title keeps a digest.

Together with the masked-record copy, a 44 MiB Responses turn sent
on as Chat allocates ~89 MB less (1,068 to 1,005 MB over the turn)
and runs fewer GCs. Peak live heap is unchanged (282 MB at GOGC=10
with gctrace, before and after): the body, the parsed request and
the outgoing Chat body are what is held at the peak. This is less
allocation and GC CPU, not a lower RSS peak.

TestTailOfReadsInPlace: a 4 MiB conversation's last 64 items come back
right, allocating under the tail plus a quarter of the body. Red with
GetBytes put back (5,480,048 bytes for a 1.3 MB tail of a 4.1 MB body).

Run (mote-run at aa8ded04e, both commits, on 56602426d):
- gofmt -l clean; go vet ./internal/gateway ./internal/maskrec for
  linux, windows and darwin: ok.
- go test -count=1 -timeout 45m ./internal/gateway ./internal/maskrec:
  ok (gateway 533s).
- The new test red with the old code put back (above), green with it.
- The allocation and peak numbers: a scratch test of one 44 MiB
  Responses turn sent on as Chat (not committed), GOGC=10 gctrace for
  the peak.
- Rebased onto 27bf14790 (lan.go changed in the gateway): the same vet
  and go test -timeout 45m ./internal/gateway ./internal/maskrec again
  at this head: ok (gateway 549s).

Reported-by: jihuayu
2026-10-28 20:11:57 +08:00
yetone 0b99b8fbe5 gateway: a translated body is written a message at a time (#4004)
jihuayu's heap profile (#4004, v0.1.1707 on a 2 GiB server) had
json.Marshal and its bytes.growSlice under buildChat as the largest
holders, about 128 MiB together, on 45 MiB Codex requests. json.Marshal
writes the whole body into one buffer that doubles as it fills and then
copies it out, so each grown-out buffer is garbage until the next GC.

marshalBody writes the same bytes: the keys sorted, every value through
json.Marshal, but a list (messages, input items, contents) one item at a
time, into one buffer sized to what they come to. buildChat,
buildResponses, anthropicBody and buildGemini use it. Anything
json.Marshal refuses gets json.Marshal's own answer. A slice's items are
marshalled by address, as json.Marshal reaches them, so a MarshalJSON on
the pointer is still called.

Run on mote at this head:
- TestMarshalBodyIsJSONMarshal: byte-equal to json.Marshal for lists of
  maps and of typed maps, one-item, empty and nil lists, nil, []byte,
  json.RawMessage and lists of it, pointer and value Marshalers, HTML
  characters, U+2028/2029, control characters, escaped keys; NaN, Inf
  and a chan are refused as json.Marshal refuses them.
- TestMarshalBodyAllocatesTwoBodies: a 47 MiB, 170-message body.
  json.Marshal allocated 205 MiB, marshalBody 98 MiB. The bar is 2.5x the
  body (117 MiB), which json.Marshal's 205 fails.
- go vet ./internal/gateway for darwin, linux and windows: ok.
- go test ./internal/gateway -timeout 45m: ok (543s), and again after
  the rebase onto origin/main, at this head: ok (529s).

Real account, on this Mac in a sandbox HOME with only the DeepSeek
provider copied: a streamed Codex-style /v1/responses request with a
function call and a ~100 KB tool output (translated, 36,343 tokens in)
answered about the tool's output and completed. /v1/messages and
/v1/chat/completions also answered 200.

Not tried: a 45 MiB request against a real vendor; the plugin RPC copy
and toolOutput's unquote, which the same profile lists, are separate
changes.
2026-10-28 17:50:17 +08:00
yetone 254461829b gateway: a Codex Lite request is no longer decoded whole, nor parsed twice for its facts
XiaoYin_OK on X: after a long run the app's memory climbs toward 2 GB.
The owner's own app (26h up) showed RSS 550 MB, HeapInuse 317 MB but
HeapSys 992 MB: the heap peaks while requests are in flight. Its profile
had 209 GB allocated, ~94 GB of it under codexBackend/serve, of which:
- parseResponses 24.7 GB, liftAdditionalTools 14.9 GB of it;
- factsOf 24.6 GB, reached from turnOf (13.6 GB) and dirOf (11.0 GB),
  the same conversation parsed twice per request.

Three causes, each fixed where it is:
1. liftAdditionalTools decoded the whole Lite request into maps to move
   its additional_tools item, and wrote it all again: ~7.6x the body.
   Now only that item and the tools are decoded; every other item and
   member goes byte for byte as it came, written once into one buffer.
2. affine counted the turn in the masked body while dirOf read the plain
   one, two different slices, so factsOf's memo could never serve both.
   affine now counts it in the body as the agent wrote it.
3. That body is rarely the one readRequestBody held (requestModel,
   spawnAgentModels and the lift each write a new one), so factsOf's
   memo missed for it anyway. serve now holds it (holdBody), and holdBody
   lists a body once when it is held twice.

Tests (internal/gateway/lite_lift_test.go), each red on the old code:
- TestLiteLiftMovesOnlyTheTools: same result as the old whole decode
  (liftWhole, kept in the test) on testdata/context/codex.json, the
  merged-namespace case, a 2,000-word conversation and the no-op shapes;
  an item with its keys unsorted, \u escapes and 2.50 goes as written.
  Old: the kept item came back re-sorted and re-escaped.
- TestLiteLiftAllocatesAboutTheBody: under 2x a 1.35 MB body.
  Old: 14,126,976 B (10.4x).
- TestMaskedRequestParsedOnceForItsFacts: a served masked Lite request
  is parsed once for its turn and folder (factsParsed hook in readFacts).
  Old: 2. With only change 2 it was still 2 (cause 3).

Measured (darwin/arm64, a 4,012,240 B Lite body):
- liftAdditionalTools: 30.46 MB/op, 98,560 allocs -> 5.17 MB/op, 6,609.
- readFacts of it: 54.0 MB/op -> 26.7 MB/op.
- Served through New().Handler() with masking on, 8 concurrent x 5
  rounds of a 4,010,268 B body, two runs each:
  allocated per request 215.6 / 220.7 MB -> 116.2 / 116.2 MB;
  peak HeapInuse 993 / 802 MB -> 612 / 561 MB;
  HeapSys 1001 / 892 MB -> 699 / 674 MB.
- The live app's WebKit processes were ~8-9 MB RSS each, so the webview
  is not where the memory went on macOS; the live pid sat at 476-596 MB
  RSS over a 15-minute sample.

Run at this head: gofmt -l clean; go vet ./...; GOOS=linux go vet -tags
nogui ./...; GOOS=windows go vet ./...; go build (gui and nogui);
go test -tags nogui -timeout 45m ./... in a sandbox HOME at d2e0ea393
plus this change: every package ok (internal/gateway 619s) except two
guard reds already on main and untouched here: internal/proc's
TestNoCommandBypassesProc (#3567) and internal/agent's
TestFolderVarsAreListed (TZ in grouprule.go, filed as #3600). After the
rebase onto 642d430ec (one gateway test file added upstream),
internal/gateway was run again: ok (425s), with gofmt and the three vets of it clean.
Not tried: a 26h run of the new build against real Codex traffic, and
Windows (#3383's 4.2 GB report) beyond go vet.
2026-10-25 20:02:12 +08:00
yetoneandEdward4226 46c4188327 gateway: Codex's access_programs goes to OpenAI alone, so OpenCode Go's DeepSeek and GLM answer (#3172)
csic21, HONGs23 and TimWongUp (#3172): a Codex subagent inherits
access_programs {"cyber":"standard"}, magpie relayed it to OpenCode Go,
and Go answered DeepSeek and GLM with 503 "Upstream request failed:
Endpoint is unavailable."; without the field, or with null, 200. Go's
Haiku took it.

Scope: Codex itself sends the field only with a ChatGPT sign-in, or an
API key on its provider named "openai" (codex-rs core/src/
cyber_access_program.rs, for_auth and for_provider; read at openai/codex
970111f6c). It comes to magpie because Codex thinks magpie is OpenAI,
the same reason forVendor takes OpenAI-only parts out (#292). So the
class is "only the upstreams Codex would send it to", not an OpenCode Go
rule: no other vendor has a Cyber program to read, and Go is the one
seen to refuse it. keepsAccessPrograms keeps it for a ChatGPT (Codex)
account, a host ending in openai.com, another magpie (IsRemoteMagpie,
whose own upstream decides) and a codexAsSent relay when Codex sent the
request. Every other Responses upstream, relayed or built (from Chat
too), plugins included, goes without it. A relay that fronts ChatGPT
loses it unless set codex=as-sent, as Codex with a custom provider
would send it none.

- forwardOnce takes it out before the user's extraBody is merged, so an
  access_programs the user wrote there still goes (Edward4226's branch
  did it after, which would override the user's own value).
- withoutTopMember (from Edward4226's branch, using longBody's spans on
  a long body) removes the member, every one of that name, the rest byte
  for byte; a body that isn't a valid object goes as it came. A
  bytes.Contains check first, so a body without it costs nothing.
- Chat and Messages builds never carried it (now tested).
- Docs: gateway-routing.md, providers-accounts.md, ir.go comment.

Run:
- TestAccessProgramsGoToOpenAIAlone (new; fakes by the gateway client's
  RoundTrip, no network): Go DeepSeek/GLM from Codex and from curl, null,
  Chat built as Responses, Zen, a relay, codexAsSent with and without
  Codex's headers, the user's extraBody, OpenAI (daybreak_blue, null,
  from Chat), another magpie, a Chat and a Messages upstream.
  TestWithoutTopMember (new). TestCodexAccessProgramsReachBackend,
  TestAccessProgramsNullKept, TestCodexAccountTakesExtraBody pass.
- Broken by hand, each red: no strip (9 cases: Go, Zen, relay, extraBody);
  IsRemoteMagpie out; openai.com out (3 OpenAI cases); codexAsSent out;
  codexAsSent without fromCodex; Codex account out
  (TestCodexAccessProgramsReachBackend red); strip moved after extraBody
  (the user's value lost).
- gofmt -l clean; go vet -tags nogui ./... for darwin, linux, windows.
- HOME=<scratch> go test -tags nogui -timeout 45m ./internal/gateway/:
  ok (414s), at 42976f9a0 plus this change.

Not tried: a real OpenCode Go account on this head (the reporters' and
Edward4226's real A/B runs show the field alone turns 503 into 200);
OpenCode Zen's DeepSeek with the field (now sent without it either way);
a real Codex collab_spawn end to end.

Co-authored-by: Edward4226 <Edward4226@users.noreply.github.com>
2026-10-25 11:55:16 +08:00
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 d7ad3f2a3e gateway: input scanners read a request's items in place, not copied (#3383)
Seven readers of a Responses request's input (the seal stripper and
withoutKinds in affinity, hasSealedAgentMessage, joinToolRuns,
orphanedToolOutputs, pairToolItems, withReasoningText) and the prompt
builder decoded `input` into a []json.RawMessage. fillJSONIn clones each
RawMessage under a sixteenth of the held body, so every item of a long
Codex history was copied once per reader, per request. None of them
keeps an item past its return (they marshal new output or assign into
the slice), so inputList hands them elementsOf's capped subslices of the
raw input instead. hasSealedAgentMessage reads an item's content the
same way.

Run at 83234fe92 + this change:
- BenchmarkZZCodexStream (a 680 KB Codex request through the gateway,
  a probe not committed), -benchtime 30x -count 3:
  before 20,077,746 B/op 76,687 allocs/op;
  after  16,417,942 / 16,430,955 / 16,469,180 B/op, ~72,780 allocs/op
  (-18% bytes).
- Real account, sandbox HOME with only the DeepSeek provider, through a
  recording proxy to api.deepseek.com: 5 Codex-UA /v1/responses requests
  each with a user message, reasoning, function_call,
  function_call_output and assistant message in the history, on the old
  and new binary. All 10 answered "ok"; the 5 bodies sent upstream are
  byte-identical between old and new.
- gofmt -l clean; GOOS=linux and windows go vet -tags nogui
  ./internal/gateway ok.
- go test -timeout 45m ./internal/gateway/: ok (667s).

Rebased onto 1537817e0: build, both vets and go test -run
'Responses|Affin|Seal|Prompt|Tool|Codex|Reasoning|Orphan|DecodeJSON'
./internal/gateway/ ok (64s).

Not tried: the full ./... suite at this head (it runs after the push).
2026-10-24 21:38:12 +08:00
yetone 82fb0702fc gateway: a test run fails when any route writes a held request body in place
A held body is shared, not copied: decodeJSON's strings point into it,
and factsOf reads it once for every later reader. Writing it in place
would change what those readers see. Nothing guarded that.

In the gateway's tests only, checkHeldBody records a held body's hash
when it is listed and compares it at its release. TestMain fails the
run, naming the body, when one changed (heldWrittenAfter). Production
code pays one nil check per hold.

No change in allocations (BenchmarkLargeRequest anthropic 45.58 MB/op
before and after; the hook is nil outside tests).

TestHeldBodyWrittenIsCaught writes one byte of a held body and expects
the guard to catch it, and a body left alone not to be reported.
Broken by hand (the comparison replaced with `_ = unchanged`): red, "a
held body written in place was not caught at its release". The whole
gateway package passes with the guard on, so no route writes a held
body today.

Run (darwin arm64, go1.26.8, sandbox HOME, load 40 to 90 from other
sessions' suites):
- go test ./... -count=1 -timeout 45m on the series' final tree at
  ba319a758: exit 0, all 68 packages ok (gateway 1498s, agent 1633s).
- After the rebase onto b855cfee9 (two redact commits): go test
  ./internal/redact ./internal/gateway -count=1 -timeout 45m, both ok
  (gateway 917s).
- go test -race -count=3 on the Held, ReadersOfAHeldBody, RecentRing,
  RequestBody, CaptureRequest, folder, WorkPlace, WorkDir and Turn
  tests: ok, after
  TestReadersOfAHeldBodyParseItOnce's byte bound was skipped under
  -race (the third commit says why); that test and
  TestHeldFactsGoWithTheirBody then passed -count=30 with and without
  -race.
- Each commit alone: go vet ./internal/gateway and gofmt -l clean.
- Final tree: gofmt -l clean; go vet ./... for darwin, GOOS=windows and
  GOOS=linux -tags nogui, all exit 0.
Not tried: a second 60-minute soak after the series (the one before is
the "before" here; the "after" numbers are the benchmark's), the GUI
suite (nothing in it changed), Windows and Linux test runs (vet only).

After rebasing the series onto 1bd99194e: gofmt -l internal clean; go vet ./internal/gateway for darwin, GOOS=windows, GOOS=linux -tags nogui ok; go test ./internal/gateway ./internal/sessions ./internal/provider -count=1 -timeout 45m: gateway ok (686s), sessions ok (125s), provider red once on TestClaudeAccountServesModelsListedSinceItsFetch, which nothing here touches and which passes alone -count=5 and with -run Claude (filed #3174). Then rebased onto d3db461bb (redact and GUI warm-up only).
2026-10-21 19:17:10 +08:00
yetone 41147956d2 gateway: a conversation's turn count and folder come from one parse of it, not one each (yg6888 on X: ~1 GB)
turnOf (affinity), dirOf (the trace's folder) and tellWorkPlace (a
plugin's work-place headers) each parsed the whole conversation for a
number and a folder. A parse decodes every message and tool output into
strings of its own, so a long conversation was decoded twice over on
every request for them. In the 60-min soak before (dee5c9d75, 4746
requests), parse was 26.4 GB of 106.7 GB allocated: turnOf 11.5 GB and
dirOf 11.4 GB.

factsOf parses once for the turn count, the folder, and whether the
text says it is a git repository (bodyFacts). For a body being served
(holdBody), it keeps those facts, a few words, while the body is held.
The pause-by-folder check reads the same facts.

It keeps the facts, not the parse. A first version kept the *Request
weakly. In the served benchmark the weak pointer was already collected
between turnOf and dirOf on 1 read in 6, and under real load the
collector runs more often. Keeping the parse strongly would keep a copy
of the conversation for the whole request. The facts are kept only
while their body is listed whole; the entry goes when the body is
released, so a body's memory given to another never reads as this one.
A body not held, or read in another protocol, is parsed for its own.

BenchmarkLargeRequest, ~2 MB conversation, B/op before → after:
  anthropic        53.81 → 45.84 MB
  anthropic-group  65.26 → 57.30 MB
  chat             43.27 → 36.61 MB
  responses        53.81 → 46.04 MB
6.7 to 8.0 MB less per request, about 3.5× the body.

Tests (parse_memo_test.go):
- TestReadersOfAHeldBodyParseItOnce: what the three readers say equals
  a parse of their own. Together they allocate at most 1.5× one parse,
  and readers after the first allocate almost nothing. A Chat read of
  the same bytes is its own, and a copy not held is parsed again.
- TestHeldFactsGoWithTheirBody: the entry goes when the request ends,
  a released body is not listed again, and a prefix of a held body is
  not the body.
Broken by hand:
- factsOf always parsing: red, "turnOf, dirOf and tellWorkPlace
  allocate 446064 bytes on a held body, a parse 135096", and "a held
  body's facts were not kept".
- The delete at release removed: red, "a body's facts are still listed
  after its request ended".
TestPauseByFolder, TestRuleByFolder, the WorkDir and WorkPlace tests and
the affinity and turn tests pass, with -race too.
Under -race the readers' byte bound is skipped (raceOn, as
request_zstd_pool_test does): sync.Pool drops a quarter of what is put
in it there, and workDirIn's regexps take their ~37 KB matchers from
one. Five tries read 1.3x to 2.1x a parse, while the parse stayed at
135304 bytes; -race -count=3 went red at 1.57x before the skip.

Run (darwin arm64, go1.26.8, sandbox HOME, load 40 to 90 from other
sessions' suites):
- go test ./... -count=1 -timeout 45m on the series' final tree at
  ba319a758: exit 0, all 68 packages ok (gateway 1498s, agent 1633s).
- After the rebase onto b855cfee9 (two redact commits): go test
  ./internal/redact ./internal/gateway -count=1 -timeout 45m, both ok
  (gateway 917s).
- go test -race -count=3 on the Held, ReadersOfAHeldBody, RecentRing,
  RequestBody, CaptureRequest, folder, WorkPlace, WorkDir and Turn
  tests: ok, after
  TestReadersOfAHeldBodyParseItOnce's byte bound was skipped under
  -race (the third commit says why); that test and
  TestHeldFactsGoWithTheirBody then passed -count=30 with and without
  -race.
- Each commit alone: go vet ./internal/gateway and gofmt -l clean.
- Final tree: gofmt -l clean; go vet ./... for darwin, GOOS=windows and
  GOOS=linux -tags nogui, all exit 0.
Not tried: a second 60-minute soak after the series (the one before is
the "before" here; the "after" numbers are the benchmark's), the GUI
suite (nothing in it changed), Windows and Linux test runs (vet only).
2026-10-21 19:17:09 +08:00
yetone 58cfca2f77 gateway: a Codex turn's rewrites look at its items in place and decode it only when one has something to change (#1532, #2354)
A long Codex session grew slower each turn through magpie because every
request went through up to eight rewrites (callItemIDs, plainItemIDs,
boundCallIDs, codexInputAs, forVendor, withoutBareReasoning,
withoutReasoningText, withModel), and each one json.Unmarshal'ed the
whole conversation into maps, even though on most turns none of them had
anything to change. When one did change something, encoding/json
re-scanned every raw item one byte per call to write the body back. In
the live heap, withModel's json.Marshal held 28.8 MB, and checkValid and
stateInString were ~25% of CPU.

- Before decoding anything, each rewrite now asks whether any input item
  is one it changes (anyInputItem, over longBody's remembered split). It
  reads the item's members where they lie, matching keys as the old
  decode did: exact and last-wins for map reads, EqualFold for struct
  reads (reasoningOf). An escaped key, or a null in a field, falls back
  to decodeJSON. The change path is still the old code.
- forVendor and withModel split the body with rawObject/rawArray. When a
  rewrite writes the body back, marshalRaw is used (marshalPlain without
  HTML escaping, marshalJSON with it). It copies each raw value with its
  strings whole, into one buffer sized up front, and its bytes are
  encoding/json's own. Where encoding/json would refuse a value, the call
  falls back to encoding/json and gets its error.
- withModel now passes a body of null through unchanged. It used to panic
  writing into a nil map.

Measured with a sandbox gateway and a fake upstream. The bodies were
shaped from local Codex rollouts and never leave the machine. The machine
was at load ~160-180, so wall times are noisy; the CPU profiles are the
steadier number.
  5 MB body, CPU per mode (17 requests, pprof):
    relay    4.36s -> 1.38s  (~256 -> ~81 ms a request)
    accounts 10.29s -> 3.78s (~605 -> ~222 ms)
    magpie   7.00s -> 3.40s  (~412 -> ~200 ms)
  wall time to upstream, medians before -> after:
    relay    100k 8.1 -> 7.2ms, 1m 66.7 -> 47.9ms, 5m 1069 -> 280-661ms
    accounts 100k 32.3 -> 17.3ms, 1m 1016 -> 373ms, 5m 4852 -> 2118-2567ms
    magpie   100k 13.3 -> 10.1ms, 1m 345 -> 139ms, 5m 2713 -> 960-1805ms
  The remaining cost at 5 MB is parse/promptOf/codexBody decoding the
  body for their own needs (decodeJSON, longBody), not these rewrites.
  SSE: the relay flushes each read and the masking writer passes Flush
  on; TTFB stayed within ~1-10ms of to-upstream before and after.

Tests:
- TestCodexRewritesAsBefore compares each rewrite's output byte for byte
  against its old code, which is kept in the test. It covers marked items
  (bad ids, magpie compactions, triggers, reasoning with text or nothing
  sealed, configuration_update, Codex metadata), duplicate and escaped
  keys, non-object items, an input that is null or an object, and 300
  random mixes.
- FuzzCodexRewritesAsBefore ran 150s: 22,796 execs, PASS.
- TestMarshalRawIsEncodingJSON and FuzzMarshalRaw (90s, 46,537 execs,
  PASS) check marshalRaw against encoding/json, with and without HTML
  escaping.
- Broken by hand to see the new tests fail:
  - With anyInputItem always true, TestCodexRewritesLeaveTurnUndecoded
    went red: "callItemIDs: 11086 allocations for a turn it leaves as it
    came (243 KB)", and every rewrite, forVendor 9172.
  - With marshalPlain's marshalRaw path off, TestMarshalRawAllocatesOnce
    went red: "marshalPlain of 420 items: 4 allocations".
- gofmt -l and go vet -tags nogui ./internal/gateway are clean.
- GOOS=linux and GOOS=windows go vet -tags nogui ./... are clean.
- go test -tags nogui ./internal/gateway -count=1 -timeout 45m:
  ok  github.com/yetone/magpie/internal/gateway 2579.125s
2026-10-20 20:23:52 +08:00
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
yetone ec6fba4720 gateway: a long body's top level is split at its members once, not by each decode of it
decodeJSON remembered that a body of 32KB or more was valid (validMemo),
but each decode of it still walked every byte of the conversation to
find its members: a request's readers (the model and stream flag, the
metadata, max tokens, the messages, the tools...) decode the same body a
dozen times, each into a few members. Where the top level's members are
is now remembered with the body's validity (longBody), and fillJSON
fills a struct or map at the top from those spans; a member the type
doesn't want is passed over without a walk. A body under 32KB, or one
not an object, is decoded as before.

Test: TestDecodeJSONSplitsALongBodyOnce: 20 decodes of one long body
into five types (a struct, a slice inside one, a pointer, a map of
RawMessage, a nested struct) split it once, and each gets what
encoding/json gives. Broken by hand (members never remembered): red,
"split 21 times over 20 decodes, want 1".

BenchmarkDecodeReaders (one 200KB body decoded into three small
structs, as a request's readers do; -test.cpu 1, user+sys CPU of the
whole binary, 3000 iterations minus a 30-iteration run, two rounds;
load average ~450, so CPU time, not wall ns/op):
  before  1.26 / 1.25 s (0.09-0.11 s at 30)  ~383 us per request's three decodes
  after   0.26 / 0.26 s (0.07-0.11 s at 30)  ~57 us
Allocations are unchanged (25 allocs, ~358B per iteration).
BenchmarkGroupOverhead's 200KB request moved within its noise
(12x20 p0/m1 22.16 -> 19.30/21.45 cpu-ms/op; 30x60 g4 43.22/48.49 ->
43.86/45.24).

Run: go test ./internal/gateway -run 'JSON|Json|Decode|Fill|Memo'
-count 1: ok (23.5s).
2026-10-19 15:19:31 +08:00
yetone 938c31424e gateway: a long request body is checked for valid JSON once, not by every decodeJSON
decodeJSON runs jsonValid over its whole input before filling the value,
and a request's body goes through it a dozen times on its way: modelOf,
parseAnthropicRequest, swapImageBlocks, blocksOf, the prompt builder,
conversationID, requestEffort, bodyEffort, streamOf, walkImages... On a
2 MB Anthropic request the repeated checks were ~18% of the CPU of
serving it (pprof).

jsonValid now remembers the last 8 bodies of 32 KB or more that it found
valid, by length and a maphash under a seed of the process's own. Only
valid results are kept, so an invalid body is checked (and refused) every
time. A false hit needs a 64-bit collision under a seed no caller can
see; even then fillJSON still parses the body.

Guard: TestDecodeJSONChecksALongBodyOnce counts the byte-by-byte checks
of one 84 KB body over six decodes. With the lookup turned off by hand:
"a 84087-byte body was checked 6 times over six decodes, want 1".
TestDecodeJSONMemoKeepsRefusing: a body changed by one byte at the same
length, and a truncated one, are still refused after the valid one was
remembered.

Numbers (BenchmarkZZHot, a fake upstream with no network, 2 MB request,
count 3, CPU from rusage since the box sits at load ~350):
  big-nostream     before 113.4 / 140.1 / 117.1 cpu-ms/op
                   after  107.6 /  98.7 /  99.2 cpu-ms/op
  big-stream-pass  before 134.6 / 151.0 / 161.6 cpu-ms/op
                   after  124.1 / 131.0 / 144.5 cpu-ms/op
B/op and allocs/op are unchanged (65.9 MB, 181k; 81.9 MB, 310k), as
expected: the check allocates nothing.

Run (on ccb2eea15 with this commit and the previous one, the collector
fix, both in the tree, sandbox HOME, load ~350):
- go test -tags nogui ./... -timeout 45m -count=1: 62 packages ok,
  internal/gateway ok (2694s). Two reds, both in untouched packages and
  both filed:
  - internal/gui TestSetAnswersWhileDevinAndProvidersHang: set slow/slow-1
    took 10.67s against its 10s bound (#1375). Rerun alone with -count=3,
    it passed at 4.7s, 2.8s and 7.1s.
  - internal/agent ran past 45m, with TestWSLMoreAgentsPick running at the
    deadline (#2544).
- gofmt -l internal/: clean.
- go vet ./internal/gateway passed.
- GOOS=linux and GOOS=windows go vet -tags nogui ./... passed.
- go build passed.
- The memo guard is red with the lookup turned off by hand (above).
2026-10-19 03:11:12 +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