Commit Graph
5 Commits
Author SHA1 Message Date
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 a9304efe01 gateway: an image's decode is counted wherever its header sits
3eee19b08 batches a request's images by what each holds once decoded,
read from its header. fitHolds read only the first 4 KB of base64 for
the header, so a JPEG whose frame header sits behind a large EXIF
segment (a phone photo's often does, up to 64 KB) counted as holding
nothing, and was made beside three others each holding up to
codexImageMaxBytes. fitHolds now reads the header from the base64 as a
stream, as far as the format needs, and counts the bytes the image came
in too, as codexImageRefit does.

Run:
- go test -run TestCodex -count=1 ./internal/gateway/: ok.
- TestCodexAHeaderBehindExifIsCounted on 3eee19b08's codex_images.go:
  red, "a JPEG with its header behind 63 KB of EXIF holds 0 MB, want
  29 MB"; green with this change.
2026-10-20 23:14:02 +08:00
zzjcool 3eee19b08b gateway: a codex image's header can't make its decode hold what it declares
A Codex turn's inline image is decoded, resized and written again before
it goes to ChatGPT (codexImagesFit). What a decode may hold was judged in
pixels: codexImageMaxPixels, 80<<20. A pixel is not a byte, and a
compressed image declares its size before it carries any pixels, so a
header of a few dozen bytes commanded the allocation: 110 bytes declaring
8000x8000 at 16 bits a channel held 488 MB, and four of them in one
request held 1710 MB (fitWorkers makes 4 at once, with no budget for what
they hold between them). The decode then fails and the image goes as it
came, so the bytes were spent for nothing. With a few agents sending such
a turn at once the process is one the system kills.

The bytes a decode will hold are now what is judged, from the header
alone, before anything is decoded (imageHolds: the pixel count times the
bytes its format's image allocates a pixel — 4 for anything with colour or
alpha, 1, 2 or 8 as image/png's readImagePass allocates them, in int64 so
that 70000x70000 can't wrap). codexImageMaxBytes keeps that at 320 MB,
which is what 80<<20 pixels was taken as, so every screenshot Codex sends
is fitted as before: 3456x2234 holds 29 MB, 4032x3024 46 MB, 6000x4000
91 MB. What one request makes at once is batched against fitBudget
(512 MB), so a request of 100 screenshots holds what 4 do and not what 100
do.

Verified at this head, with `-tags nogui`:

- New tests fail without the change. With codexImageRefit's two gates and
  the batching put back to the old behaviour (helpers kept, so nothing
  fails to compile):
  TestCodexAHeaderAloneCantHoldPastTheBudget — "8000x8000 at 16 bits a
  channel: 110 bytes of upload held 488 MB, past the 320 MB a decode may
  hold"; TestCodexFourHeadersInOneRequestCantHoldTheHeap — "1299 bytes of
  upload, sent as 4 images in one request, held 1710 MB, past 128 MB".
  Both pass with the change.
- The first version of the header test asserted only that the image went
  as it came, and it passed on the old code, because the old decode also
  failed — after spending the bytes. The tests measure what the decode
  allocates (runtime.MemStats TotalAlloc either side) instead.
- TestCodexFittingHoldsTheBudget covers the batching's edges, including an
  image that holds more than the budget by itself (made alone, turned away
  by codexImageRefit).
- TestCodexRealScreenshotsFitBytesTheyHold and
  TestCodexFittingLeavesATurnThatFitsAsItWas: a real screenshot is neither
  turned away nor made differently.
- go test -race -tags nogui -run TestCodex ./internal/gateway: pass
  (228s). go test -tags nogui -run TestCodex ./internal/gateway: pass.
- gofmt clean; go vet -tags nogui ./internal/gateway, GOOS=linux go vet
  -tags nogui, GOOS=windows go vet: clean. go build -tags nogui,
  GOOS=windows go build: pass.
- Full go test -tags nogui ./...: fails in internal/agent (aside, cursor,
  copilot, qoder, omp, zed), internal/cli (TestKeyNote) and
  internal/gateway (TestClaudeClientCacheAbsentUnchanged). Each was
  reproduced on origin/main dee5c9d7 with this change stashed, so none is
  this change's; they read the PATH for pnpm, cursor-agent and copilot,
  and two runs of the agent package failed different sets.

Found by an AI scan of the image paths, not by a report.

Not changed here: the same judgement is missing on other paths this scan
touched (draw.go's image requests, and holdWriter.wantWhole skipping
holdMost), which want issues of their own.
2026-10-20 23:11:32 +08:00
yetone 11173c8a20 gateway: a long Computer Use turn fits each screenshot once, not every turn (fflake33 on Discord)
fflake33 (magpie 0.1.1279, macOS) sent Codex Computer Use turns of
570K-680K tokens with hundreds of screenshots through the Responses
route to codex/gpt-6.1-sol: 26.5s and 52.7s of the 41.7s and 71s to the
first token were magpie's own work, sampled in image resize, JPEG
decode/encode and JSON.

The causes, from a pprof CPU and alloc profile of a synthetic turn (160
distinct 2940x1912 JPEG screenshots, 112 MB body):
- codexImagesFit's cache of fitted images was a map cleared at 64
  entries, so past 64 screenshots every image of every turn was decoded,
  resized and JPEG-encoded again: ~19s CPU a turn (triangleResize 42 GB
  allocated over 3 turns).
- It looked each part up by path from the top of the body
  (gjson "input.%d.content.%d"), reading the 112 MB body again for every
  image: ~9s CPU a turn.

What changed:
- codexImagesFit walks the body once (ForEach over items and parts, at
  their offsets) and splices only the changed image strings; the rest of
  the body goes byte for byte as before.
- The cache (fitted) is an LRU keyed by sha256 of the limits and data
  URL, bounded at 256 MB of fitted bytes and 8192 entries, letting go of
  what goes unsent for an hour. It holds the encoded bytes, not the
  base64. A request looks all its images up before keeping any it made,
  so a conversation larger than the budget still finds what was kept
  since its last turn.
- Images not kept are made side by side, at most min(4, GOMAXPROCS) at
  once (each holds ~100 MB for a Retina screenshot); the same image twice
  in one request is made once.
- Sibling: the describer's cache (vision.go sights) was FIFO at 256, so a
  text-only model sent 300 screenshots described every one again each
  turn. It is now LRU at 2048 (a description is a few KB).

Numbers, codex_images_timing_test.go (MAGPIE_TURN_TIMING=1), magpie's
time before the fake upstream had the request, 160-163 screenshots, run
back to back at load ~15-60 on this M-series mac:
- before (de671719a): turns 1-4 31.4s, 30.6s, 31.7s, 35.2s; CPU
  27.5-28.4s per turn (pprof labels per turn)
- after: turn 1 7.5s (18.4s CPU, 160 images made in parallel), turns 2-4
  2.7s, 2.6s, 5.2s; CPU 2.4-2.6s per turn
The ~2.4s left per 112 MB turn is whole-body JSON passes (decodeJSON with
jsonValid and RawMessage clones, parseResponses, codexBody's re-marshal,
~0.4-0.8s each); not changed here, as each needs its byte-for-byte output
re-proven.

echo_ts (Codex through magpie on Copilot ~10x slower, no images): the
same timing test on a Copilot account with no images measured magpie's
local work at ~3ms (33 KB), ~13ms (215 KB) and ~56ms (989 KB) per turn
on the old code at low load, the same on the new. That is not a 10x, so
its cause is elsewhere and is not fixed here.

Tests, each broken by hand and seen red:
- TestCodexScreenshotsAreNotFittedAgainEachTurn: 100 then 101 distinct
  screenshots; the second turn makes only its new one, and sends the
  others as the same bytes. Clear-at-64 restored: "made 65 images again".
- TestCodexFittedImagesPastTheBudget: 30 images over a budget of 10;
  turns 2 and 3 make 20 each, held bytes within budget. Keeping each
  image as it is made: 30 of 30 each turn; budget unchecked: held past it.
- TestCodexFittedImagesLetGoWhenIdle.
- TestManyImagesDescribedOnce: 300 images twice to a text-only model are
  described 300 times. sightsKept 256 restored: 576.

Run: gofmt -l (clean); go vet ./... on darwin, GOOS=linux and
GOOS=windows -tags nogui; go test -race on the gateway's TestCodex*,
TestManyImagesDescribedOnce and TestTextOnlyModel* (ok); full
`set -o pipefail; go test -timeout 45m ./...` at ab88ffd55 (this
change on origin/main 2026-10-18 21:4x): every package ok except
internal/agent, which hit the 45m package timeout under load ~200
(running TestT3CodeKeepsTheUsersSettings at 0s, the known #2544/#2723);
alone with -timeout 90m it is ok (4385s, load ~250-350). gateway ok in
2600s, provider ok in 438s.

Not tried: a real Computer Use session against ChatGPT; Windows or
Linux runs of the timing test.
2026-10-19 00:26:39 +08:00
yetone 6679e963fd gateway: a screenshot sent to a ChatGPT account goes at the size Codex's own client sends it (ylorn on Discord)
ylorn's ChatGPT account dropped turns a PNG screenshot took past about
1 MiB (the commit before this tells that as too large). ylorn uses Pi's
openai-codex through magpie, not Codex, and Codex's own client never
sends a screenshot that size: it scales every inline image down first.
Read in openai/codex at cc7ba336 (codex-rs/core/src/image_preparation.rs
resize_image, codex-rs/utils/image/src/lib.rs):
- detail none, auto or high: at most 2048 px a side and 2500 patches of
  32 px (HIGH_DETAIL); "original": 6000 px and 10000 patches; "low" it
  refuses itself (DetailBased mode, the default; UnifiedBudget is a
  feature flag)
- prompt_image_output_dimensions_for_limits: as it is if it fits,
  scaled to the longest side, then by area with the patch grid rounded
  down
- resized with FilterType::Triangle; PNG written as PNG, JPEG as JPEG at
  quality 85, WebP lossless, GIF as PNG; an image that fits keeps its
  bytes; no byte cap other than a 1 GiB guard
- Codex zstd-compresses request bodies to ChatGPT by default
  (enable_request_compression); magpie already reads those and sends
  upstream plain, which this doesn't change.

codexImagesFit (codex_images.go) does the same in forwardOnce, for a
ChatGPT (codex) account's Responses requests only: every data-URL
input_image in a message's content or a tool output's output larger
than Codex's limits for its detail is scaled to Codex's size with a
separable triangle filter widened by the scale (as the image crate's)
and written in its own format (JPEG q85, PNG, GIF as PNG). Only the
image_url string's bytes are replaced, so the rest of the request is
the same bytes for the prompt cache, and the last 64 results are kept
so a conversation's screenshot isn't resized on every turn. An image
that fits, "low" detail, a remote URL, an image past 80 Mpx, and WebP
(which Go's standard library doesn't decode) go as they came. Other
vendors, API keys and Chat requests are untouched. Codex's own requests
come already sized, so this changes nothing for them.

Tests (codex_images_test.go):
- TestCodexImageSizeAsCodex: Codex's own test cases (2048x2048 →
  1600x1600, 2050x2 → 2048x2, original 6401x100 → 6000x94, 4096x2048
  kept, 64x32 kept) and a 3456x2234 screenshot → 1979x1280 (checked
  against Codex's formula in f64).
- TestCodexScreenshotSizedAsCodex: still PNG, 1979x1280, its black and
  white halves and red band where they were, the rest of the body
  byte-identical.
- TestCodexImagesSizedInEveryPlace: JPEG stays JPEG, a tool output's
  image is sized, "original" gets the larger budget.
- TestCodexImagesThatFitGoAsTheyCame, TestCodexImagesOnlyForChatGPT.
- TestCodexAccountGetsScreenshotAtCodexSize: an agent's /v1/responses
  turn of 2.2 MB reaches the fake ChatGPT backend as 657 KB at
  1979x1280. Red with the call taken out of forwardOnce; the legibility
  checks go red with the filter's centre moved.

Run: go test -tags nogui ./internal/gateway, gofmt -l, go vet -tags
nogui with GOOS=darwin, linux and windows on ./internal/gateway. Not
tried: ylorn's account and network, a real agent's screenshot through
a real ChatGPT account after this change, WebP.
2026-10-11 14:32:57 +08:00