Commit Graph
4 Commits
Author SHA1 Message Date
yetone c9d253e4a2 gateway: an agent's compaction is recorded as Compaction, not a plain turn
shangyuan0818 (Discord, v0.1.3354): Claude Code's compactions don't show
in Usage → Requests. Through the gateway they were recorded and counted,
but as ordinary turns (Kind ""), so nothing read as a compaction: the
Compaction purpose listed none, the OTel export skipped them as turns
the transcript has (Claude Code's compaction is skipTranscript, so it
has none), and the reply ended the agent's turn.

The main handler now marks a call compacting() recognises (Claude
Code's summary ask, OpenCode's and the other agents' prompts) as
KindCompact, on every route it serves (messages, chat, responses,
gemini), unless a header already set its kind. The check reads the
facts parse the request already makes (bodyFacts.compact). Codex's
backend route already took the kind from its header; it now uses the
same constant.

Not fixable here: Claude Code used directly (not through magpie) never
writes a compaction's usage to its transcript (only compact_boundary
with token counts before and after), so magpie can't count those.

Run (mote, at this change on 3cabaab54):
- go test -timeout 45m -count=1 ./internal/gateway ./internal/usage ./internal/otlp: ok
- go vet ./internal/gateway, GOOS=linux and GOOS=windows: ok
- gofmt -l internal/: clean
Rebased onto 25eec8f6c (4 commits, 65 lines in internal/gateway, an
images-API change); at the pushed head: go vet ./internal/gateway and
go test ./internal/gateway -run 'Compact' (every compaction test): ok.
Broken by hand: TestCompactionRecordedAsCompaction on the old code is
red in 4 of 5 cases (claude code fork, claude code plain, chat,
responses: recorded as kind "", want "compact"); the plain turn stays "".
Not tried: a real Claude Code /compact through a sandbox gateway, and
Claude Desktop (assumed to be the same, since it runs Claude Code).
2026-11-09 11:37:06 +08:00
yetone d088030315 gateway: a long Codex request's facts, tier and metadata skip the walks over its conversation (#3394)
A Codex Responses request carries the whole conversation, and the gateway
walked it several times per request for what it reads at the top level:

- requestSessionMetadata searched the body for "client_metadata", which
  Codex sends last, before asking topMember. A long body now asks the
  memoized split straight away.
- bodyTier asked gjson for speed and service_tier, walking the body each
  time; a long body now asks topMember too (topValue).
- userWords ran its reminder and "## My request" regexes on every text;
  each now runs only when its marker is present.
- readFacts (turn count, work folder) ran the full parse. It now parses
  in facts mode (readResponses): views over the raw bytes, no parts for
  assistant replies, and tool outputs as bare ToolResult parts, which is
  all turnIn and workPlace read.

Bench (a fake ChatGPT backend, ~2MB Codex body, client_metadata last),
per request: 31.7ms, 24.2MB, 71.2k allocs on origin/main; 19.2-21.4ms,
17.2MB, 59.6k allocs with these and the provider commit after it.

Real account: a sandbox HOME with only the deepseek provider, 310KB
Responses bodies to deepseek/deepseek-flash through `magpie serve`:
base 15ms process CPU per request (19/20 ok), new 13ms (20/20, then
8/8 again).

TestResponsesFactsAsTheWholeParse compares readFacts with the full
parse's turnIn and workPlace over constructed bodies and five real Codex
fixtures. Broken by hand twice (user parts skipped; ToolResult turned
into Text): red both times. tier_record_test adds four long-body cases
(tier after the conversation, a nested one ignored, Anthropic speed
fast, a Chat numeric tier).

Run at this head (720e491d2 + these two commits): gofmt clean, go build,
GOOS=linux and GOOS=windows go vet -tags nogui on gateway and provider;
go test -run 'Facts|Tier|Session|Responses|Metadata|UserWords|Prompt|Memo'
./internal/gateway ok. The full gateway and provider packages are
running and are reported on #3394.
2026-10-26 16:13:27 +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
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