Repository navigation
perf: Decode Anthropic Messages requests in one pass - #1971
Conversation
…ub (rossoctl#1965) Assisted-By: Claude (Anthropic AI) <noreply@anthropic.com> Signed-off-by: Hai Huang <huang195@gmail.com>
…t details The estimate for T2-T6 is more than 2,000 counted lines. P2 now has the reply decoder (T3). P3 has the encoder, the goldens, the resend tests and the docs, with parent P2. The encoder must not merge before the reply decoder, because translate.Target selects a protocol that has only a request encoder. The reply goldens use goldenName. The listener test builds its own request, because postCodex sets no query and no Authorization header. Assisted-By: Claude (Anthropic AI) <noreply@anthropic.com> Signed-off-by: Hai Huang <huang195@gmail.com>
DecodeRequest now reads the body with one json.Decoder (rule S16). Each member goes straight to its Go field. The old decoder parsed each level into a map of json.RawMessage, so it scanned the same bytes again at each level. A block whose type is not its first member is read as raw JSON one time to find its type, and then read again. Every known client writes type first, so this path is rare. The pivot output and the error type do not change. No golden file changes. BenchmarkAnthropicDecodeRequest (a 2 MB Claude Code body, 400 turns), on an Apple M4 Max: before: about 92,000,000 ns/op after: about 9,400,000 ns/op (budget: 15,000,000) BenchmarkRequestAnthropicToChat (the full conversion, no budget): before: about 94,000,000 ns/op after: about 11,000,000 ns/op Assisted-By: Claude (Anthropic AI) <noreply@anthropic.com> Signed-off-by: Hai Huang <huang195@gmail.com>
When type is not the first member, the first pass read the block into a struct. Struct decoding matches "Type" and "TYPE" too, so the decoder accepted a block with no "type" member, and it could read members for one kind and then set another kind. The first pass now reads a map and takes "type" exactly. The walk now refuses a second type that differs from the first. Assisted-By: Claude (Anthropic AI) <noreply@anthropic.com> Signed-off-by: Hai Huang <huang195@gmail.com>
|
Warning Review limit reachedYou've used all free OSS reviews for now. Wait for the free limit to reset to keep reviewing this public repository. Next included review available in 18 minutes. View limit details
Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out. |
clawgenti
left a comment
There was a problem hiding this comment.
Summary
The one-pass walker is a real improvement, and its behavior matches the old decoder closely. One claim in the PR does not hold, though: that "all known clients write type first". The two official Anthropic SDKs write type last, and for those bodies the slow path removes most of the speedup and misses the S16 budget. Details and a cheap fix are inline. The rest is nits.
What I checked
-
go test ./translate/...passes on head. -
Differential test, old vs new decoder. I copied the base
request.gointo a scratch package and comparedDecodeRequeston head against it. Each pair had to agree on accept/reject, and accepted bodies had to givereflect.DeepEqualpivots. Inputs:- about 65 hand-written bodies: string vs list content,
tool_use/tool_result(nested, string content, null content), image/documentsource(null, extra members,<&>escaping),thinking/redacted_thinking, server tools, unknown members, nulls, case-variant keys, bad types, trailing data, invalid UTF-8; - the bench body, plus a variant of it with
typemoved last in every object; - about 2M fuzz executions seeded from all of the above.
Bodies with duplicate keys were skipped, since you already list that divergence. No other divergence.
- about 65 hand-written bodies: string vs list content,
-
Benchmarks (this sandbox runs about 2.9x slower than your M4 Max):
| Body | ns/op |
|---|---|
| base decoder | ~220,000,000 |
head, bench body (type first) |
~27,000,000 |
head, same body with type last |
~97,000,000 |
head + the scanner sketched inline, type last |
~29,000,000 |
Author: huang195 (MEMBER — maintainer)
Areas reviewed: Go (decoder, tests, benchmark), Docs (plan)
Agent/IDE config (.claude/.vscode): none
Commits: 4 commits, all signed-off: yes
CI status: passing (Go CI (authbridge agentop) still pending, which is unrelated)
| var kind string | ||
| if err := errors.Join(take(m, "type", &kind), takeRaw(m, "cache_control", &b.CacheControl)); err != nil { | ||
| src := w | ||
| if !w.typeFirst() { |
There was a problem hiding this comment.
must-fix: the slow path is the common case for both official SDKs, so the S16 budget only holds for type-first bodies.
The PR body and the comment on typeFirst say every known client writes type first. I checked both official SDKs by capturing the exact bytes they send:
- anthropic-sdk-go (latest): every block param struct declares
Typelast, so every block comes out type-last:
{"text":"hi","type":"text"},{"id":"t1","input":{"a":1},"name":"n","type":"tool_use"},{"tool_use_id":"t1","is_error":false,"content":[{"text":"res","type":"text"}],"type":"tool_result"} - anthropic Python SDK (2.10.0), using the standard tool loop from the docs (
messages.append({"role": "assistant", "content": response.content})): the pydantic models serialize their fields in alphabetical order:
{"signature":"s","thinking":"t","type":"thinking"},{"text":"hi","type":"text"},{"id":"i","input":{"a":1},"name":"n","type":"tool_use"}
So for any Go or Python agent, every assistant block goes through this path. The path does Decode(&raw), then json.Unmarshal into a map (two more scans), then walks again. It nests, too: a type-last tool_result re-walks its content, and each inner block pays the same cost again.
I moved type last in every object of claudeCodeBody(). On head that body takes ~97 ms/op against ~27 ms/op for the type-first original (base: ~220 ms). Scaled to your M4 numbers, that is about 34 ms, over twice the 15 ms budget. This is not a regression from base, but the PR claims a one-pass decoder within budget, and that does not hold for these clients.
Possible fix (prototyped): don't decode the block a second time. Find the depth-1 "type" member with a byte scan over w.body[w.dec.InputOffset():]: track depth and skip strings and their escapes, with no decoding. Unmarshal only that small string value, then walk the block once on w itself. Keep the current raw/map path only as a fallback for when the scan finds no literal "type" key (for example an escaped key name). My rough version brought the type-last body down to ~29 ms, against ~26 ms for type-first. TestDecodeRequest_TypeNotFirst and TestDecodeRequest_TypeExactName still passed, and the old-vs-new differential fuzz (60 s, about 1.7M executions) found no divergence. Please also fix the comment on typeFirst and the claim in the commit message and PR body.
|
|
||
| // BenchmarkAnthropicDecodeRequest measures the decoder that rule S16 gives | ||
| // a budget of 15 ms. | ||
| func BenchmarkAnthropicDecodeRequest(b *testing.B) { |
There was a problem hiding this comment.
suggestion: please add a type-last variant of this body (for example, type moved last in each block, as the Go SDK writes it) as a second benchmark with the same 15 ms budget. Then the slow path is measured and cannot regress quietly. A small helper that rewrites claudeCodeBody() with ordered keys is enough.
| return w.rest(&rest, key) | ||
| }) | ||
| if err != nil { | ||
| return fmt.Errorf("output_config.%w", err) |
There was a problem hiding this comment.
nit: the .%w join made sense when the inner error was always effort: .... Now object can return must be a JSON object, and the message becomes output_config.must be a JSON object. The same happens with source.%w below. fmt.Errorf("output_config: %w", err) reads correctly in both cases. You already noted this one, and the client agent sees this text.
…ead once Fixes review: the slow path for a block with type not first decoded the block two more times, and the official Go and Python SDKs write type last Files: - core/translate/anthropic/request.go - core/translate/anthropic/request_test.go - core/translate/bench_test.go Assisted-By: Claude (Anthropic AI) <noreply@anthropic.com> Signed-off-by: Hai Huang <huang195@gmail.com>
clawgenti
left a comment
There was a problem hiding this comment.
Summary
The byte scan fixes the problem from my last review: a type-last body now costs about the same as a type-first one, and I found no change in the decoded output. One new problem is left. The old decoder got a nesting limit from encoding/json, and the walker has none. A deeply nested tool_result body can now crash the whole process with a stack overflow, while the old decoder refused it in under 1 ms. Details and a small fix are inline.
What I checked
go test ./translate/...passes on head.- Benchmarks (this sandbox is about 2.6x slower than your M4 Max):
BenchmarkAnthropicDecodeRequestabout 24 ms/op,BenchmarkAnthropicDecodeRequestTypeLastabout 28 ms/op (it was about 97 ms/op at d0061be),BenchmarkRequestAnthropicToChatabout 38 ms/op. The type-last path now works as the PR says. - Differential test, base vs head. I copied the base
request.gointo a scratch package and compared both decoders: the same accept/reject result, andreflect.DeepEqualpivots when both accept. Inputs: about 100 hand-written bodies, focused on the scan (whitespace and tabs around:and,, escaped quotes and backslashes beforetype,{[,]}in strings,typeas a value, nestedtypeininputandcache_control,typethat is null, a number, an object, a list or"", non-object blocks, nested type-lasttool_results, invalid UTF-8), plus the string vs listcontentandsystem, null members,tool_choice,thinking,output_config,metadata,streamand unknown or case-variant members. Each body also ran with sorted members (type last) and with extra whitespace around every token. Then about 5.2M fuzz executions seeded from these. Bodies with duplicate member names were skipped, because you already list that change. No divergence. - The
output_config.%w/source.%wwording from the last round is still open. You list it in the PR body, so I do not repeat it inline.
Author: huang195 (MEMBER — maintainer)
Areas reviewed: Go (decoder, tests, benchmarks), Docs (plan)
Agent/IDE config (.claude/.vscode): none
Commits: 5 commits, all signed-off: yes
CI status: passing
| } | ||
| out := []pivot.Block{} | ||
| for i := 0; w.dec.More(); i++ { | ||
| b, err := w.block() |
There was a problem hiding this comment.
must-fix: the walker has no nesting limit, so a deep tool_result body overflows the stack and kills the process.
content -> block -> blockMember -> content recurses once for each nested tool_result, and json.Decoder.Token does not check depth. The base decoder called json.Unmarshal on the whole body first, and encoding/json refuses nesting deeper than 10,000 (exceeded max depth). That limit is gone now.
I built bodies of the form {"model":"m","messages":[{"role":"user","content":[{"type":"tool_result","content":[{"type":"tool_result","content":[ ... ]}]}]}]}:
| Nesting | Body | Head | Base |
|---|---|---|---|
| 600,000, type first | 20 MB | accepted, 5.5 s | 400 in < 1 ms |
| 950,000, type first | 33,250,000 bytes | fatal error: stack overflow (Go's default 1 GB limit) |
400 in < 1 ms |
| 50,000, type last | 1.7 MB | accepted, 47.6 s | 400 in < 1 ms |
The forward proxy accepts request bodies up to 32 MiB (maxRequestBodySize, 33,554,432 bytes), and a /v1/messages request that the router sends to a server without anthropic-messages is translated, so the second body reaches DecodeRequest. A Go stack overflow is a fatal error, not a panic, so recover cannot catch it. One request from any client of the proxy stops all its traffic. The third row is a second effect of the same missing limit: with type last, scanType reads each nested block's whole subtree, so the cost grows with depth times size.
Possible fix: add a depth counter to the walker and refuse content nested past a small limit. Real requests nest content at most two levels (a tool_result holds text or image blocks, not other tool_results). For example:
const maxContentDepth = 32
func (w *walker) content() ([]pivot.Block, error) {
if w.depth++; w.depth > maxContentDepth {
return nil, errors.New("content is nested too deeply")
}
defer func() { w.depth-- }()
...The fallback path makes a new walker with newWalker(raw), so pass the depth on to it too. A test with a few hundred nested tool_results (both type first and type last) that expects a 400 would pin this down.
Fixes review: the walker had no nesting limit, so a deep tool_result body overflowed the stack and stopped the process Files: - core/translate/anthropic/request.go - core/translate/anthropic/request_test.go Assisted-By: Claude (Anthropic AI) <noreply@anthropic.com> Signed-off-by: Hai Huang <huang195@gmail.com>
clawgenti
left a comment
There was a problem hiding this comment.
Summary
The depth limit fixes the stack overflow from my last review, and the type-last fix from the round before still holds. I found no must-fix issue. Head and base give the same result on every body I tried, except the changes the PR body already lists. Two suggestions are inline. Neither one blocks the merge.
What I checked
go test ./translate/...andgo test -race ./translate/anthropic/pass on head.go vetandgofmtare clean.- Crash fix. Bodies with 100,000 and 1,000,000 nested
tool_results (5 MB and 53 MB) now get a 400 and do not crash. The boundary is where the PR says: 31 nestedtool_results are accepted (32 content levels), and 32 are refused. The depth carries over into the fallback walker (src.depth = w.depth). I checked this with escapedtypenames at each level. - Differential test, base vs head. I put the base
request.goin a scratch package. Both decoders had to give the same accept/reject result, andreflect.DeepEqualpivots when both accept.- 1.5M generated bodies, with off-spec types for every typed member:
contentandsystemas a string, list, object, number or null;inputandinput_schemaas a string or list;sourceas a string or null;typeas null, a number,""or missing;Type/TYPEkeys; unknown members and block kinds;<&>in raw members; extra whitespace. Each body also ran with its members sorted and reverse-sorted. About 270k of them were accepted by base. No divergence. - 89 hand-written probes, 32 of them nested
tool_resultbodies from 1 to 9,990 levels deep, with type first, type last and escaped type: a 5,000-levelinput, a 9,000-level unknown member andinput_schema, a 10,001-level member, a 1 MiB key, a BOM, invalid UTF-8,,,/ leading or trailing commas or a missing:around a scannedtype, a truncated block,\"type\"inside values and names, two objects in one body. The only divergence is the depth limit. - 5.5M fuzz executions seeded from the generator, with duplicate member names skipped. No divergence.
- 1.5M generated bodies, with off-spec types for every typed member:
- Benchmarks (this sandbox is about 2.6x slower than your M4 Max):
BenchmarkAnthropicDecodeRequestabout 26 ms/op,BenchmarkAnthropicDecodeRequestTypeLastabout 28 ms/op,BenchmarkRequestAnthropicToChatabout 37 ms/op. This matches the numbers in the PR body.
Author: huang195 (MEMBER — maintainer)
Areas reviewed: Go (decoder, tests, benchmarks), Docs (plan)
Agent/IDE config (.claude/.vscode): none
Commits: 6 commits, all signed-off: yes
CI status: passing (Go CI (core peerproc, macOS) still pending)
| // maxContentDepth is the deepest content that the walk reads. The walk | ||
| // recurses once per level, so the limit keeps one deep body from | ||
| // overflowing the stack. | ||
| const maxContentDepth = 32 |
There was a problem hiding this comment.
suggestion: a smaller limit would also make the deep type-last case cheaper. You list this in the PR body.
With type last, scanType reads the whole subtree of a block at each level before the walk refuses level 33. So a deep body is read about 33 times. I measured this at the 32 MiB request cap (maxRequestBodySize), with type-last nested tool_results: about 1.05 s of CPU before the 400 here (so about 400 ms on an M4). Base refuses the same body in under 1 ms. With type first, head also refuses in under 1 ms.
The walk nests at most 2 levels for a valid request: message content, then tool_result content. Anthropic accepts no tool_result inside a tool_result, and the other kinds (search_result, and so on) go to Extra as raw JSON, so the walk does not go into them. With a limit of 4 or 8 there is still room, and the worst case is 4 to 8 times smaller. TestDecodeRequest_DeepContent could then pin the boundary: limit-1 nested tool_results are accepted, and limit are refused.
| return err | ||
| }) | ||
| case "tool_choice": | ||
| return w.value(key, &choice) |
There was a problem hiding this comment.
suggestion: the duplicate-member list in the PR body is not complete. A later null now leaves the earlier value for every member that value or raw reads. In base, the later null cleared it. Probes, with base -> head:
"stream":true,"stream":null:Streamfalse -> true"role":"user","role":null:Role"" ->user"text":"a","text":null:Text"" ->a"input":{"x":1},"input":null,cache_control(in a block or a tool) andinput_schemawork the same way: nil -> the first value"source":{...},"source":null: the source fields stay set"output_config":{"effort":"high"},"output_config":null:Effort"" ->high
I do not ask you to bring back the base behavior. Head now does what encoding/json does when it decodes into a struct, and parse/inference/anthropic.go decodes the same body that way. So for stream and text, head now agrees with what the plugins see, and base did not. (tool_choice and thinking still differ, because the parser keeps the last raw value for them.) But no test covers any of this. Please write the rule in the PR body, and add a small table test with these cases, so that a later change to the walker cannot change it without anyone noticing.
What changed
anthropic.Protocol{}.DecodeRequestnow reads the body with onejson.Decoder(rule S16 of #1965). Each member goes directly to its Go field. The old decoder parsed each level into a map ofjson.RawMessage. Thus it scanned the same bytes again at each level.core/translate/anthropic/request.go: the one-pass decoder. The signature, the error type (*pivot.RequestError, 400,invalid_request_error) and the message prefix do not change. The pivot output does not change, and no golden file changes.typemember of a block before the walk, so a block withtypelast is also read one time. The official Go and Python SDKs writetypelast. Only when the scan gives no type (for example an escaped member name, or a value that is not a string) does the decoder read the block one time to findtype(by the exact member name only), and then read it again.core/translate/anthropic/request_test.go: new testsTestDecodeRequest_KeepsRawBytesandTestDecodeRequest_Errors(from the plan), andTestDecodeRequest_TypeNotFirst,TestDecodeRequest_TypeExactName,TestDecodeRequest_TypeLastOnePass,TestDecodeRequest_TypeScanandTestDecodeRequest_DeepContent(not in the plan, they cover blocks withtypenot first, and deep content).core/translate/bench_test.go:BenchmarkAnthropicDecodeRequest(budget: 15,000,000 ns/op)BenchmarkAnthropicDecodeRequestTypeLast(the same body with sorted member names, budget: 15,000,000 ns/op) andBenchmarkRequestAnthropicToChat(no budget), on a 2 MB Claude-Code-shaped body with 400 turns.New behavior
A block with two different
typemembers (for example{"type":"text","type":"image"}) now gets a 400. The old decoder accepted it and used the last value. Real clients do not send this.Content nested more than 32 levels deep (for example
tool_resultblocks intool_resultblocks) now gets a 400. The old decoder accepted it up to theencoding/jsonlimit of 10,000 levels. Without a limit, a deep body overflowed the stack and stopped the process.How it was tested
cd core && GOWORK=off go test ./translate/... ./listener/forwardproxy/ ./plugins/inferencerouter/...: PASS.TestDecodeRequest_Fieldsdid not change and passes.BenchmarkAnthropicDecodeRequestBenchmarkAnthropicDecodeRequestTypeLast(before = PR head before the byte scan)BenchmarkRequestAnthropicToChat(full conversion)The full conversion is also below 15 ms.
Size
docs/superpowers/plans/2026-11-18-anthropic-server-1965.md).Review findings that were not fixed
[minor] Duplicate members now merge. The old decoder took the last one. The old decoder read each object into a map, so a duplicate key kept only the last value. The new walker reads every occurrence, and
dec.Decodeinto an existing struct pointer keeps the old fields. Probe results (base -> HEAD):tool_choiceobjects keepNamefrom the first one.thinkingobjects keepbudget_tokensfrom the first one.output_config{"effort":"high"}then{"x":1}keeps Efforthighand also getsanthropic.output_config. The old decoder gave Effort"".output_config{"x":1}then{"effort":"high"}keepsanthropic.output_config{"x":1}in Extra.sourceobjects keepsSourceTypefrom the first one and the other fields from the last one.messages,tools,system,modelandcontentstill use the last value, so the decoder does not follow one rule. Possible fix: setchoiceandthinkingto nil before the decode. Clearreq.Effortand theanthropic.output_configExtra key at the start ofoutputConfig. Clear the four source fields and theanthropic.sourceExtra key at the start ofsource. Add these cases to a test. Real clients do not send duplicate keys, so the risk is low. But the plan says that the pivot output must be exact, and no test covers this.[minor] Some error messages have different words. The 400 type and the prefix are the same, but the text after the prefix changed. Example: the old
messages[0].content: [0]: ...is nowmessages[0]: content: [0]: .... A wrongoutput_configtype now givesoutput_config.must be a JSON object. Theraw()errors forcache_control,inputandinput_schemado not name the member. The agent sees this text. No test checks the message text.[minor] A block with two different
typevalues now gets a 400 (see "New behavior" above). Base accepted it with the last value, and Anthropic's own JSON parsing also uses the last value. The decode probe found no other change: 86 bodies cover every typed field, and base and HEAD accept or refuse each one in the same way.Review findings from the second round that were not fixed
kind != ""to mean "the type is known". So{"text":"x","type":"","type":"text"}is accepted as a text block withtextin Extra. Base refused it. Possible fix: aseenflag. Real clients do not send this.TestDecodeRequest_TypeScandoes not pin the escape handling instringEnd: a mutation that removes the backslash case still passes.typefirst. That is false. Commit 4fcb1a1 corrects the code.blockcomment names only one case where the fallback runs. ThescanTypecomment names all of them.output_config.%wandsource.%wgiveoutput_config.must be a JSON object(already listed above).Review findings from the third round that were not fixed
scanTypereads the subtree of each block at each level. The cost has a limit. Possible fix: refuse beforescanTypewhenw.depthis at the limit.TestDecodeRequest_DeepContentdoes not pin the value 32: it uses 300 levels. Possible fix: 31 nestedtool_resultblocks are accepted, and 32 are refused.TestDecodeRequest_DeepContentdoes not name the escaped-type case.contentreturns before itsdefer, sow.depthdoes not decrease. The error stops the decode, so this has no effect now.For a human after review
These steps need a real Anthropic API key and a live Codex session. They need P2 and P3 (all of T2-T6) merged or checked out and installed. Do not run them in this workflow.
api: {anthropic-messages: /v1/messages}forhttps://api.anthropic.com, and route Codex to it (agentop server use <name> --agent codex).cache_read_input_tokensis above 0 from turn 2 (S12). If it stays at 0, report it in the PR.Part of #1965
Assisted-By: Claude (Anthropic AI) noreply@anthropic.com