Skip to content

perf(decode): decode each value once with generated fast decoders - #156

Merged
ThomasK33 merged 53 commits into
mainfrom
perf/fast-decoders
Nov 21, 2026
Merged

ThomasK33 merged 53 commits into
mainfrom
perf/fast-decoders

Conversation

@ThomasK33

@ThomasK33 ThomasK33 commented Nov 20, 2026 •

Copy link
Copy Markdown
Member

Why

Part of #125 (Decoding item 3). After #155, every generated UnmarshalJSON still called json.Unmarshal on its own input, so each nested value was validated and scanned again at every level of a message, and encoding/json.checkValid was the largest cost on the recorded traffic of #148. This PR reads each value once and keeps every decoded value and error as on main.

What changed

  • cmd/generate/internal/emit/fast.go writes decode_fast_gen.go: an unexported decodeFast(b []byte) bool for every generated type (355). It walks the object once with the scanner of perf(decode): read union members and hinted values without decoding them again #155, decodes leaves straight into their fields, and applies the same required-member, lenient-hint, default and shape rules as the exact decoder, with the runtime helpers in decode_fast.go.
  • Each generated UnmarshalJSON starts with tryFast: on a zero value and input without surrounding whitespace, the fast decoder runs; when it declines, the existing code (the exact decoder) runs unchanged. Contract: fast success implies the exact decoder returns nil with the identical value; a fast decoder never makes an error.
  • It declines a repeated key, an escaped or non-ASCII key in a struct, a key that matches a field only in another case, more than 16 unknown keys in one object, and any value that does not decode. On the corpus, 0 of 1543 messages that decode fall back.
  • validjson.go: validJSON, equal to json.Valid (fuzzed), 5.6 times faster on the corpus; used by decodeJSON and tryFast.
  • GOEXPERIMENT=jsonv2 turns the fast decoders off.

Tradeoffs

  • Two decoders per type to keep in step. The emitter writes both from the same plans, and the tests compare them on every corpus message, on reused values and in three fuzz targets, but drift on an input no test reaches would go unnoticed.
  • 14,166 generated lines. A decoded slice can have a different capacity than on main; values are equal.

Blast Radius

Every inbound decode and every json.Unmarshal into an SDK type. No API change.

Verification

  • BenchmarkInbound/corpus against main: CPU 81.9 ms to 22.8 ms (-72.1%, p=0.000, 10 runs), allocs 307.7k to 51.9k (-83.1%); against perf(decode): read union members and hinted values without decoding them again #155: -64.8%. Pipe pair +100% msgs/s, inbound +290%. Every corpus message decodes as on main. Runs.
  • Fast vs exact: corpus messages, reused values, seeds against all 355 types; fuzz 8.4M execs. FuzzValidJSON 35M execs.
  • make check, make test, go test -race ./...: pass. G2 failures.txt equal to main. rust-diff: RUST PASS. G3: 15 of 15.

Generated with xum • Model: anthropic:claude-opus-5-5 • Thinking: xhigh

The benchmarks read a corpus of real traffic the way a Connection reads
what its peer sends: the scenario fixtures of the Claude and Codex
adapters (pinned commits, Apache-2.0, converted to acpwire transcript
lines by internal/benchcorpus), the G3 journeys, and the G2 transcripts.

- BenchmarkInbound/corpus: every message once per op.
- BenchmarkInboundStream: the agent_message_chunk and tool_call_update
  bursts.
- BenchmarkConnectionPipe: session/update notifications through a
  Connection pair over io.Pipe, and through the client side alone.

scripts/bench (make bench BASE=<commit>) builds both sides with the same
benchmark file and corpus, checks that both decode every message to the
same outcome (TestInboundCorpus), alternates the runs and prints
benchstat. It is not part of make test.

---
_Generated with [`xum`](https://github.com/coder/xum) • Model: `anthropic:claude-opus-5-5` • Thinking: `xhigh`_
On a shared machine the wall time of a run grows while other processes
hold the CPU. The process's user and system time does not, so the
benchmarks also report cpu-ns/op (Unix only).

---
_Generated with [`xum`](https://github.com/coder/xum) • Model: `anthropic:claude-opus-5-5` • Thinking: `xhigh`_
The Rust SDK reads an integer of format uint64 as a u64, int32 as an i32,
and so on. These tests pin that range at both ends, with a recorded
Claude session (claude-g5-1.jsonl) and with the outcomes that the
rust-diff probe recorded for agent-client-protocol-schema 1.18.0.

On main 13 rows of TestIntegers_ReadTheRangeOfTheirFormat and
TestClientSideConnection_ReadsAUint64AboveMaxInt64 fail: a uint64 above
2^63-1 fails to decode or reads as absent, an ErrorCode outside int32
decodes, -0 decodes as 0, and a uint32 out of range in
StringPropertySchema or a uint16 out of range in a result decodes.

The ten control/integer-* rust-diff cases hold the same values.

Part of #141 (items 7 and 8)

---
_Generated with [`xum`](https://github.com/coder/xum) • Model: `anthropic:claude-opus-5-5` • Thinking: `xhigh`_
---
_Generated with [`xum`](https://github.com/coder/xum) • Model: `anthropic:claude-opus-5-5` • Thinking: `xhigh`_
---
_Generated with [`xum`](https://github.com/coder/xum) • Model: `anthropic:claude-opus-5-5` • Thinking: `xhigh`_
Since #120 an integer of format uint32 or uint64 was an int64, and one
of format int32 or uint16 an int, and #138 checked each format's range
in Validate and in the lenient shapes. An int64 cannot hold a uint64
above 2^63-1, so a usage_update or a token count that Rust reads failed
to decode, and the range lived in two places that each site had to
reach: responses, the Other variant of ErrorCode and an optional
integer that cannot be null had none.

integerType now gives each format the Go type of the Rust type that it
names (formatTypes): int32, int64, uint16, uint32, uint64, and int
without a format. encoding/json fails a value out of that range, as
serde_json does, at every site and in every direction, so Validate and
the shapes keep only a minimum or maximum that is narrower than the Go
type (ownRange). No schema from 1.18.0 through 1.33.0 has one, so the
generated Validate methods lose every range check, and the six lenient
decoders that checked a shape only for the range no longer do.

shape.go reads a uint64 above math.MaxInt64 as within a range that has
no upper bound. The examples and the verification harness clamp the
uint32 line and limit through uint64, and MIGRATION_v0.21.md lists each
field that changes type, with before and after code.

Part of #141 (items 7 and 8)

---
_Generated with [`xum`](https://github.com/coder/xum) • Model: `anthropic:claude-opus-5-5` • Thinking: `xhigh`_
An optional integer whose schema does not allow null is not a pointer,
so an absent member reads as 0. Its Go type holds the range of its
format, so a value out of it fails to decode, but checkPlan gives the
field no minimum or maximum check. No integer of schema 1.18.0 through
1.33.0 has this form, so a synthetic schema stands for one.

On the parent commit the four rows with a bound fail: level 11, offset
-6 and 6 pass Validate, and so does a value built with level 11.

Part of #141 (item 7)

---
_Generated with [`xum`](https://github.com/coder/xum) • Model: `anthropic:claude-opus-5-5` • Thinking: `xhigh`_
checkPlan skipped every optional member whose Go type is not a
pointer, because an absent one reads as its zero value. For a struct or
union that stays right: a zero value cannot say whether it was sent. An
integer can: 0 is the value an absent member reads as, so Validate now
checks the minimum and maximum of such an integer when it is not 0,
through a nonZero container of the eachHeld walker. An explicit 0
outside the bounds passes as absent, as encoding/json cannot tell the
two apart. The range of the integer's format needs no check since the
parent commit: its Go type holds it.

No schema from 1.18.0 through 1.33.0 has such an integer, so the
generated code does not change.

Part of #141 (item 7)

---
_Generated with [`xum`](https://github.com/coder/xum) • Model: `anthropic:claude-opus-5-5` • Thinking: `xhigh`_
- scripts/bench stops when the two sides decode a message differently,
  unless ALLOW_OUTCOME_DIFF=1, because they would not time the same work.
- It truncates base.txt and head.txt before the first run, so a reused
  BENCH_OUT does not mix samples of an earlier run.
- The G2 transcripts are optional for the corpus: the module the Go proxy
  serves leaves out .agents (a module of its own), and TestInboundCorpus
  must pass there. The corpus digest still tells the corpora apart.
- internal/benchcorpus writes a fixture only under a local file name.

---
_Generated with [`xum`](https://github.com/coder/xum) • Model: `anthropic:claude-opus-5-5` • Thinking: `xhigh`_
The generated decoders call encoding/json again on each nested value, so
the bytes of a deep message are scanned once per level. jsonscan.go reads
the members of an object and the items of an array, and skips a value,
without decoding it or allocating. It expects JSON that encoding/json
accepts and never panics or loops on other input.

TestJSONScan_Corpus and FuzzJSONScan compare it with json.Decoder.

---
_Generated with [`xum`](https://github.com/coder/xum) • Model: `anthropic:claude-opus-5-5` • Thinking: `xhigh`_
shapeID.accepts decoded every hinted value again into an any (maps,
slices, strings) and walked the result with fits. On the inbound
benchmark corpus that is 80823 allocations of BenchmarkInbound/corpus.

accepts now walks the raw JSON with the scanner in jsonscan.go: scan
checks the same rules as fits on the bytes and returns yes, no, or
unknown. The rules of a shape combine as the least verdict, anyOf as
the greatest, and not swaps yes and no. When scan cannot tell,
accepts decodes as before (acceptsDecoded, which the tests also use as
the reference). scan cannot tell for a string that a values rule
compares when it holds an escape or bytes that are not UTF-8, for an
object key that does, for an object with more than 16 members, and
past 1000 levels of value and shape. Of duplicate keys it checks only
the last, which encoding/json keeps.

Every one of the 3756 hinted values that the corpus decodes is a
value in its messages, and scan decides all of them without
allocating. shape_test.go checks scan and accepts against fits for
every value in every corpus message and every shape, for seeds on the
edges above, and in FuzzShapeScan.
Each generated union UnmarshalJSON decoded its input into a
map[string]json.RawMessage only to read the discriminator or the keys
that pick a variant, and then decoded the input again into the variant.
It now calls readUnionObject (union.go), which scans the object with the
memberIter of jsonscan.go: no map, no copied values, no validation pass.
get looks a key up with last-wins, tag reads a plain ASCII
discriminator without json.Unmarshal.

The scan does not validate. A variant decodes only valid JSON, so input
that is not JSON reaches the end of the decoder, where unionError returns
the syntax error that the map decode used to return first. An escaped
key or an object the scanner cannot read falls back to the map decode.
The dead []map decode of the array step is now emitted only for unions
with array variants matched by item keys.

stablecheck treats unionObject.get and tag as side-effect free, so that
a union that gains a discriminator still passes as an addition.
TestUnionObject_DecodesLikeAMap and FuzzUnionObject compare every union
against the map path (unionsByMap) on the corpus values, changed copies
of them, and fuzzed input: same variant, value, encoding, and error.
The generated dispatcher decoded each request's and notification's params
with json.Unmarshal, and SendRequest did the same for a response's result.
Every one of those types has an UnmarshalJSON method. For such a type
json.Unmarshal validates the input, scans the value again to find its end,
and only then calls UnmarshalJSON with the value without the whitespace
around it. It adds no context to that error at the top level.

decodeJSON (decode.go) does the same in one pass. It validates the input
with json.Valid, which uses a pooled scanner, trims the whitespace, and
calls UnmarshalJSON. Input that is not one JSON value (empty, trailing
data, a syntax error) goes to json.Unmarshal, which returns its exact
error and leaves the value as it is. So does a type without UnmarshalJSON.
Per call this saves the second scan and four allocations: the escaping
decodeState and the growth of its scanner's stack.

TestDecodeJSON_MatchesUnmarshal, TestDecodeJSON_Corpus and FuzzDecodeJSON
compare decodeJSON with json.Unmarshal on edge cases, on every corpus
params and result, and on fuzzed input. They check a struct with
UnmarshalJSON, unions, a plain struct and json.RawMessage, fresh and
already holding data, for the same error (deeply equal) and value.
Every generated UnmarshalJSON called json.Unmarshal on its own input, and
each nested type, union variant, and lenient field did it again on its
part, so a byte at depth d was validated and decoded about 4d times.

Each generated type now has an unexported decodeFast, emitted into
decode_fast_gen.go by cmd/generate/internal/emit/fast.go. It walks the
object's members once with the scanner of jsonscan.go, decodes each value
straight into its field with the helpers of decode_fast.go, and calls the
decodeFast of the types it holds. UnmarshalJSON runs it first (tryFast):
only on a zero value, for valid JSON without whitespace around it. When
decodeFast returns true, the exact decoder, which is unchanged, would
return nil with the identical value; on false it runs as before, so every
error comes from it. A fast decoder declines a repeated key, an escaped or
non-ASCII key, a key that matches a field only in another case, and any
value that does not decode.

Custom-decoded fields, required members, defaults and additionalProperties
follow decodeStmt and emitRequireMembers on the member spans that the walk
keeps. Unions select a variant with readUnionObject and the predicates of
emitUnion, and decode it with fastOrExact, whose answer is exact, so a
variant that fails passes the turn to the next as before. With
GOEXPERIMENT=jsonv2 the fast path is off.

Tests compare the fast path with the exact one (fastDecode off): every
corpus message, every corpus value decoded into a reused value, seeds
against all 355 types, and fuzz targets for messages, types and leaves.

---
_Generated with [`xum`](https://github.com/coder/xum) • Model: `anthropic:claude-opus-5-5` • Thinking: `xhigh`_
decodeJSON checked its input with json.Valid, whose scanner makes an
indirect call per byte. validJSON is a recursive-descent validator that
returns exactly what json.Valid returns: the same number grammar, string
escapes, control characters invalid, invalid UTF-8 valid, whitespace
rules and the 10000-level nesting limit. Strings are most of the bytes
of ACP traffic, so it finds the next quote, backslash or control
character eight bytes at a time with a zero-byte bit test.

Over every message of the inbound corpus validJSON takes 612 us per pass
and json.Valid 3458 us (median of 6, -cpu 1), with no allocations.
FuzzValidJSON compares the two on arbitrary bytes.

---
_Generated with [`xum`](https://github.com/coder/xum) • Model: `anthropic:claude-opus-5-5` • Thinking: `xhigh`_
tryFast checked its input with json.Valid before running a fast decoder.
validJSON returns the same answer (FuzzValidJSON) about 5.6 times faster.

---
_Generated with [`xum`](https://github.com/coder/xum) • Model: `anthropic:claude-opus-5-5` • Thinking: `xhigh`_
tryFast in decode_fast.go now calls validJSON, so the package that
TestWriteTypesJen_* builds from the generated code needs validjson.go
next to decode_fast.go.

---
_Generated with [`xum`](https://github.com/coder/xum) • Model: `anthropic:claude-opus-5-5` • Thinking: `xhigh`_
@ThomasK33

Copy link
Copy Markdown
Member Author

Evidence: this branch against main and against #155

scripts/bench from a checkout of this branch (41d1177; ce64625 after it changes only an emitter test): 10 runs per side, alternating, -cpu 1, Go 1.26.3, AMD EPYC 9454P, load average 9 to 20. Both runs printed "outcomes: every message decodes as on base" (1543 messages, 60 rejected on both sides).

Against main (50da019, the harness of #148)

                                  │  cpu-sec/op  │ cpu-sec/op   vs base                │
Inbound/corpus                       81.87m ± 7%   22.82m ± 6%  -72.12% (p=0.000 n=10)
InboundStream/agent_message_chunk   2788.6µ ± 3%   810.4µ ± 6%  -70.94% (p=0.000 n=10)
InboundStream/tool_call_update       5.783m ± 5%   1.656m ± 4%  -71.36% (p=0.000 n=10)
ConnectionPipe/pair                  69.32m ± 7%   34.71m ± 4%  -49.92% (p=0.000 n=10)
ConnectionPipe/inbound               46.07m ± 3%   11.80m ± 5%  -74.39% (p=0.000 n=10)
geomean                              21.13m        6.602m       -68.76%
                                  │  allocs/op   │  allocs/op   vs base                │
Inbound/corpus                      307.75k ± 0%   51.86k ± 0%  -83.15% (p=0.000 n=10)
InboundStream/agent_message_chunk   15.899k ± 0%   3.539k ± 0%  -77.74% (p=0.000 n=10)
InboundStream/tool_call_update      27.536k ± 0%   6.117k ± 0%  -77.79% (p=0.000 n=10)
ConnectionPipe/pair                 231.93k ± 0%   90.58k ± 0%  -60.95% (p=0.000 n=10)
ConnectionPipe/inbound              174.04k ± 0%   29.59k ± 0%  -83.00% (p=0.000 n=10)
geomean                              88.53k        19.76k       -77.69%
                                  │     B/op      │     B/op      vs base                │
Inbound/corpus                      21.017Mi ± 0%   3.813Mi ± 0%  -81.86% (p=0.000 n=10)
InboundStream/agent_message_chunk    838.9Ki ± 0%   202.7Ki ± 0%  -75.83% (p=0.000 n=10)
InboundStream/tool_call_update      1838.0Ki ± 0%   440.2Ki ± 0%  -76.05% (p=0.000 n=10)
ConnectionPipe/pair                 18.877Mi ± 0%   8.343Mi ± 0%  -55.81% (p=0.000 n=10)
ConnectionPipe/inbound              12.968Mi ± 0%   2.448Mi ± 0%  -81.12% (p=0.000 n=10)
geomean                              5.967Mi        1.460Mi       -75.54%
                       │    msgs/s    │   msgs/s     vs base                 │
ConnectionPipe/pair      13.51k ± 16%   26.98k ± 4%   +99.73% (p=0.000 n=10)
ConnectionPipe/inbound   20.32k ±  3%   79.35k ± 5%  +290.50% (p=0.000 n=10)
geomean                  16.57k         46.27k       +179.28%

Against #155 (f0d4b9c)

                                  │  cpu-sec/op   │  cpu-sec/op   vs base                │
Inbound/corpus                       64.17m ± 10%   22.61m ± 11%  -64.76% (p=0.000 n=10)
InboundStream/agent_message_chunk   1998.5µ ± 10%   817.4µ ±  6%  -59.10% (p=0.000 n=10)
InboundStream/tool_call_update       4.118m ±  4%   1.658m ± 11%  -59.75% (p=0.000 n=10)
ConnectionPipe/pair                  59.98m ± 26%   34.85m ±  6%  -41.90% (p=0.000 n=10)
ConnectionPipe/inbound               34.57m ±  5%   11.61m ±  7%  -66.42% (p=0.000 n=10)
geomean                              16.14m         6.587m        -59.19%
                                  │  allocs/op   │  allocs/op   vs base                │
Inbound/corpus                      172.65k ± 0%   51.86k ± 0%  -69.96% (p=0.000 n=10)
InboundStream/agent_message_chunk    8.920k ± 0%   3.539k ± 0%  -60.33% (p=0.000 n=10)
InboundStream/tool_call_update      15.481k ± 0%   6.117k ± 0%  -60.49% (p=0.000 n=10)
ConnectionPipe/pair                 150.22k ± 0%   90.58k ± 0%  -39.71% (p=0.000 n=10)
ConnectionPipe/inbound               91.49k ± 0%   29.59k ± 0%  -67.66% (p=0.000 n=10)
geomean                              50.48k        19.76k       -60.86%

Each change against the one before (hill-climb rows)

Row Change Corpus CPU before → after Allocs Verdict
H3 generated fast decoders (ea4bf7a) 66.34 → 29.75 ms (-55.2%, p=0.000) 172.7k → 51.9k (-70.0%) kept
H7 validJSON in decodeJSON and tryFast (6985233, 41d1177) 26.67 → 21.51 ms (-19.3%, p=0.000) unchanged kept
H8 decodeJSON runs the fast decoder itself, skipping the second validation 22.79 → 22.20 ms (-2.6%, p=0.353) +17 reverted: below noise once validation is cheap

Fallbacks: a test counts the corpus decodes that reach the exact path: 0 of the 1543 messages that decode; the 3 messages that fail decline and get their error from the exact decoder.

Limiter after this branch (CPU profile, 4 s, not a reported run): the scanner (skipString 18% flat, skipValue 21% cumulative), because each object level still skips the bytes of its members to find where they end, and the benchmark's own envelope decode (json.Unmarshal into the JSON-RPC message, checkValid + skip, about a third), which mirrors connection.go and this PR does not change. Strings are 26% of the remaining allocations.

Gates

head 41d11777f5f655a6302b039b9a2eb56b925371ab
regen: clean
make check rc=0
make test rc=2 at 41d1177 (emitter vet test lacked validjson.go; fixed in ce64625), rc=0 at ce64625
go test -race rc=0
G2 failures.txt: equal to main
rust-diff: RUST PASS (SUMMARY rust: 21 cases: 13 same, 8 both-reject, 0 differs, 0 go-only, 0 rust-only, 0 no-type)
G3 journeys: 15 pass, 0 fail (run <scratch>/gates/pr3/acp-verify/20261120-131529-lT8xPd)

Generated with xum • Model: anthropic:claude-opus-5-5 • Thinking: xhigh

@ThomasK33

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Nov 20, 2026 •

Copy link
Copy Markdown
Codex Review Summary: ✅ Completed

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-11-20T13:31:41.825628Z ce64625 Manual request
ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review" or "@codex security review".

Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. Keep them coming!

Reviewed commit: ce646257b5

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

A union drops an untitled alternative that is a string, a const, an
enum, a number, a boolean or an array, under anyOf and oneOf, so such a
value does not decode. Under oneOf, the constructor of a titled string
alternative, or of a $ref to a string type, builds a composite literal
that does not compile, and a oneOf of consts beside an open string
becomes a union instead of an open enum.

These tests generate one union per kind of alternative under both
keywords, plus the real unions ElicitationContentValue and
SessionConfigSelectOptions of schema 1.32.0 with and without titles,
and round-trip their G2 transcript values. They fail on main.

Part of #141 (item 4)

---
_Generated with [`xum`](https://github.com/coder/xum) • Model: `anthropic:claude-opus-5-5` • Thinking: `xhigh`_
@ThomasK33

Copy link
Copy Markdown
Member Author

Independent verification of ce64625: PASS+NOTES

The fast decoders are correct on every input I tried. Each fast decode equals the exact decoder and main, and no value aliases its input. The only note is a count in the PR description.

  • Mutation sweep at ce64625: 8,839,873 inputs and 0 differences from main, repeated keys included. Fast and exact agree on every input, including the 332,873 inputs with a repeated key.
  • Coverage fuzz: SessionNotification, SessionUpdate, RequestPermissionRequest and InitializeRequest ran 6 min, 2.64M execs, 0 failures. The longer runs on perf(decode): skip strings a word at a time and allocate slices once #158 cover this code too, because perf(decode): skip strings a word at a time and allocate slices once #158 changes only skipString and the slice helpers.
  • Fallback count: I reproduced 0 of 1,543. TestFastDecode_Corpus reports 0 declined among the messages that decode. The 3 messages that fail decline, and the exact decoder makes their error.
  • validJSON vs json.Valid (validjson.go is unchanged up to perf(decode): skip strings a word at a time and allocate slices once #158):
    • FuzzValidJSONDiff ran 6 min, 17.49M execs, 0 failures.
    • Exhaustive: every 1- and 2-byte input, and every 4-byte input over a 45-symbol alphabet, bare and inside quotes.
    • Nesting depth 9990-10010 in 6 shapes (arrays, objects, mixed, unclosed, spaced): equal at every depth. The exhaustive inputs include invalid UTF-8 (0x80, 0xFF, a lone 0xC3).
    • The same checks pass under GOEXPERIMENT=jsonv2.
  • Aliasing:
    • There is no unsafe anywhere. Every fast leaf copies: unquote returns a string, and fastRaw and keep append to nil.
    • Overwriting the input after each decode changed no value on any input.
    • connection.go reuses the bufio.Scanner line, but json.Unmarshal into anyMessage copies params and result into their own RawMessage first. The decoders never see the scanner's buffer.
  • GOEXPERIMENT=jsonv2: the fast decoders are off. A sweep of 5 hot types, head against main both under jsonv2, found 0 differences.
  • Gates at ce64625: generate leaves no diff. make check, make test and go test -race -count=1 ./... pass. G2 failures.txt and the corpus outcomes are identical to main's.

Note (description only): the PR body says decodeFast exists "for every generated type (324)". decode_fast_gen.go at ce64625 has 355, counted with grep -c '^func (.*) decodeFast(b \[\]byte) bool'.

Outside this stack, also on main: a hang in ElicitationContentValueStringArray.UnmarshalJSON

ElicitationContentValueStringArray.UnmarshalJSON loops forever on invalid JSON when called directly, on main and on every head:

var v acp.ElicitationContentValueStringArray
v.UnmarshalJSON([]byte(`["a" "b"]`)) // never returns

rejectNullItems runs before json.Unmarshal there. When dec.Decode hits a syntax error it does not advance, and dec.More() stays true. json.Unmarshal, decodeJSON and the connection validate first, so wire input cannot reach it. Only a direct caller, or a third-party decoder that does not validate, can. It is not a regression of this stack. It is the only type whose UnmarshalJSON calls rejectNullItems(b) before validating.

How the differential check works (same harness on #155-#158)
  • Reference: the root package of main 6c4769e, copied as module example.com/mainacp. Each PR head's root package is copied next to it with a scratch test file. Nothing is committed.
  • Types: all 357 exported data types that exist in both (every generated struct and union, Meta, RequestError).
  • Per input, four paths: json.Unmarshal with fast decoders on, the same with fastDecode=false, decodeJSON, and UnmarshalJSON called directly on the raw bytes (untrimmed, invalid JSON included). Compared: error type, text and Offset; a structural compare across the two packages (nil vs empty slice/map, float bits, unexported fields); re-marshaled JSON byte for byte; panics. Aliasing: after each decode the input buffer is overwritten with x and the value is checked again.
  • Repeated keys: inputs with a key repeated at any depth (compared unescaped) skip only the head-vs-main compare, because fix(decode)!: reject an object that repeats one of its properties #157 changes them on purpose. They keep fast-vs-exact, decodeJSON, panic checks, and a check that the head never accepts what main rejects.
  • Seeds (21,130): G2's instance builder for every def (required-only and full, plus G2's deep mutations), the rust-diff cases, 5,858 distinct sub-values of the 1,562 corpus lines, and nested values of every type re-marshaled.
  • Mutation sweep, per seed:
    • whole input: whitespace forms, BOM, leading and trailing whitespace, trailing garbage, truncation
    • every node replaced by 57 values: int32, int64 and uint64 bounds, -0, 1e2, 1.0, 1e400, null, lone surrogates, invalid UTF-8, escaped strings; nesting to depth 9998-10000
    • strings of 0-17, 31-33, 63-65, 200 and 5000 bytes with \", \\, \\\", 0xFF, é or \u0041 at every offset
    • every key removed, repeated (4 values, before and after), escaped (\u00XX), case-changed, or with ſ or the Kelvin sign substituted
    • 1, 15, 16, 17 or 20 unknown members; 32- and 33-byte keys
    • arrays emptied, given null items, or 63, 64, 65, 70 or 130 items long
  • Coverage fuzz: FuzzDiff(sel uint16, data []byte), with the same seeds and the same checks.
  • Negative controls: I injected two bugs, parseInt accepting 2^63 and the lenient shape check skipped. The sweep caught both within seconds.

Generated with xum • Model: anthropic:claude-opus-5-5 • Thinking: high

A recorded select option has "description": null, which the Go type
drops as an optional field, as on main. The G2 comparison counts such a
member as absent too (roundtrip/compare_test.go, normalize).

Part of #141 (item 4)

---
_Generated with [`xum`](https://github.com/coder/xum) • Model: `anthropic:claude-opus-5-5` • Thinking: `xhigh`_
Under oneOf, main fails to compile the constructors, which hid that the
untitled anyOf forms fail to decode. One run per keyword shows both.

Part of #141 (item 4)

---
_Generated with [`xum`](https://github.com/coder/xum) • Model: `anthropic:claude-opus-5-5` • Thinking: `xhigh`_
emitUnion let the title decide whether an alternative that is not a
$ref, an object or null gets a Go type: an untitled string, const,
enum, number, boolean or array was a phantom and was dropped, under
anyOf and oneOf, so such a value did not decode. The constructors of a
oneOf assumed every variant is a struct and built &T{} for a string
type, which did not compile. A oneOf of consts beside an open string
became a union, where the same anyOf is an open enum.

alternativeKind now decides the Go type of each alternative from its
shape, once, in unionAlternatives; the title only names it, and the
Variant%d names stay. Every reader takes that kind:

- emitUnion declares the type of a value alternative from valueType,
  which reads the type of an untyped const or enum from its values.
- The decoder checks the const or the enum members of a value
  alternative, not only a typed const.
- A constructor of a variant that is not a struct takes its value, or
  sets the one value of a const.
- isOpenStringEnum reads anyOf or oneOf.

The generated files at schema 1.32.0 do not change: every scalar
alternative there has a title and sits in an anyOf.

Part of #141 (item 4)

---
_Generated with [`xum`](https://github.com/coder/xum) • Model: `anthropic:claude-opus-5-5` • Thinking: `xhigh`_
A const or enum value of a union alternative that its Go type cannot
hold exactly (another JSON type, null, an array or object, a fraction
under integer, or a number of magnitude 2^53 or more) is dropped
today, so the decoder takes every value of the type or a rounded one.

---
_Generated with [`xum`](https://github.com/coder/xum) • Model: `anthropic:claude-opus-5-5` • Thinking: `high`_
A property with x-deserialize-default-on-error returns from
fieldCheckFor before its bounds are computed, so mustHoldDefault never
sees its default (Codex r4645610192). Expect the same panic for it.

---
_Generated with [`xum`](https://github.com/coder/xum) • Model: `anthropic:claude-opus-5-5` • Thinking: `high`_
fieldCheckFor returned for a lenient field before mustHoldDefault ran,
so a default outside its bounds or format still reached setDefault
(Codex r4645610192). Run the check first.

load reads a default as a float64, so a default of 2^53 or beyond may
be rounded, and planFor would write the rounded fallback (Codex
r4645610179). Stop with a message that says so instead of the range
error that the rounded value gives. Keeping the exact text would need
load to decode numbers as json.Number everywhere, for a form that no
schema has.

---
_Generated with [`xum`](https://github.com/coder/xum) • Model: `anthropic:claude-opus-5-5` • Thinking: `high`_
fieldCheckFor returns for a const property before mustHoldDefault runs
(Codex r4645713059). Expect the panic for it too.

---
_Generated with [`xum`](https://github.com/coder/xum) • Model: `anthropic:claude-opus-5-5` • Thinking: `high`_
fieldCheckFor returns early for a const property, so mustHoldDefault
missed a const integer's default (Codex r4645713059), as it had missed
a lenient one. planFor handles every default, before it writes the
fallback that setDefault decodes, so check the default there and drop
the call from fieldCheckFor.

---
_Generated with [`xum`](https://github.com/coder/xum) • Model: `anthropic:claude-opus-5-5` • Thinking: `high`_
{"const": "a", "allOf": [{"$ref": "#/$defs/Label"}]} is a $ref
alternative (variantRef), and its const is dropped: the union takes
every Label, and its oneOf constructor takes any Label. On main the
old scalarConstOf checked it.

---
_Generated with [`xum`](https://github.com/coder/xum) • Model: `anthropic:claude-opus-5-5` • Thinking: `high`_
variantRef reads {"const": "a", "allOf": [{"$ref": ...}]} as a $ref
alternative, and values returned none for it, so the union took every
value of the $ref type. unionAlternatives now records the values an
alternative names (named) and the schema of its Go type (value) for a
$ref alternative with its own const too, and values checks both kinds.

---
_Generated with [`xum`](https://github.com/coder/xum) • Model: `anthropic:claude-opus-5-5` • Thinking: `high`_
mustHoldDefault returns for a default that load did not read as a
float64, so "default": "5" or true on an integer passes generation and
setDefault leaves 0 (Codex r4645771578). Expect the panic for both.

---
_Generated with [`xum`](https://github.com/coder/xum) • Model: `anthropic:claude-opus-5-5` • Thinking: `high`_
mustHoldDefault skipped a default that load did not read as a float64,
so "default": "5" or true on an integer generated a fallback that
setDefault failed to decode, leaving 0 (Codex r4645771578). Panic on
it. planFor passes only a field that holds the integer itself or
through a pointer, because the default of an array or a map of
integers is not an integer; null never reaches it.

---
_Generated with [`xum`](https://github.com/coder/xum) • Model: `anthropic:claude-opus-5-5` • Thinking: `high`_
Arithmetic among changed fields compiles and can now wrap (Size - Used),
so the compiler does not report each use of a changed field. A code above
MaxInt32 in RequestError reads fine on a 64-bit platform; only Rust and a
32-bit SDK fail. The signed -0 list gains IntegerPropertySchema.maximum and
.default.

---
_Generated with [`xum`](https://github.com/coder/xum) • Model: `anthropic:claude-opus-5-5` • Thinking: `high`_
A const beside a $ref to {"enum": ["a", "b"]} stops generation, though
main generated it. A number const on a $ref to an integer enum, whose Go
type is a string type, generates code that go vet rejects.

---
_Generated with [`xum`](https://github.com/coder/xum) • Model: `anthropic:claude-opus-5-5` • Thinking: `high`_
The own const of a $ref alternative was checked against the JSON type of
the $defs entry. An entry with an enum is a Go string type whatever its
JSON type (jenTypeFor), so a string const on an untyped enum now builds,
and a number const on an integer enum fails generation instead of vet.
An entry with no JSON type gets its own panic message.

---
_Generated with [`xum`](https://github.com/coder/xum) • Model: `anthropic:claude-opus-5-5` • Thinking: `high`_
ErrorCodeOther(70000) stays 70000: it wraps only past int32, so the 4464
example names ProtocolVersion alone. The Rust SDK leaves a -0
IntegerPropertySchema.default unset, as with ResourceLink.size, rather than
rejecting it.

---
_Generated with [`xum`](https://github.com/coder/xum) • Model: `anthropic:claude-opus-5-5` • Thinking: `high`_
A uint32 minimum above its max, or a signed maximum below its min, now
records an out-of-type constant, and the check does not compile.

---
_Generated with [`xum`](https://github.com/coder/xum) • Model: `anthropic:claude-opus-5-5` • Thinking: `high`_
A minimum above the greatest value of a field's Go type, or a maximum below
its least, left an empty range whose check did not compile. ownRange now
panics with the bound and the type. Fixes Codex r4646051333.

---
_Generated with [`xum`](https://github.com/coder/xum) • Model: `anthropic:claude-opus-5-5` • Thinking: `high`_
…und panic

The guide's wrap example now uses an int variable, since the constant
conversion does not compile. The emit README lists the new ownRange panic.

---
_Generated with [`xum`](https://github.com/coder/xum) • Model: `anthropic:claude-opus-5-5` • Thinking: `high`_
The panic advised giving the type a JSON type, which does not fit a $ref to
a oneOf of consts, the form of every ACP enum. It now names the problem.

---
_Generated with [`xum`](https://github.com/coder/xum) • Model: `anthropic:claude-opus-5-5` • Thinking: `high`_
Merges af6272d (main 2a4cf5c with #153) into #159's head 7cbc478, so
that #159 lands on the tree main will have once #153 lands.

Resolutions:
- emit/types.go unionVariant: keep main's fieldType (#149) and #159's
  isStruct and value. emitUnion keeps fieldType: b.fieldType in the
  variant literal and #159's isStruct and one-value handling.
- emit/README.md: the edits touch different lines. Keep main's
  name-registration sentence and its alias bullet (#153), #159's
  open-enum, alternative-kind and constructor sentences, and main's
  Validate bullet.
- #153 x #159: a union alternative that refers to an alias (isRefAlias)
  now reads the entry that the alias names (aliasTarget). isStruct gives
  an alias of a struct the struct constructor that main generates, and
  an alias of a string a value constructor, where main built
  &LabelAlias{}, which does not compile. An own const on a $ref to an
  alias is checked against that entry's Go type instead of panicking.
  Test: PickAlias and PickRefAliasConst in
  TestWriteTypesJen_UnionKeepsEveryKindOfAlternative, red before the
  fix (panic, then a constructor that takes the value).

The generated files at schema 1.32.0 do not change.

---
_Generated with [`xum`](https://github.com/coder/xum) • Model: `anthropic:claude-opus-5-5` • Thinking: `high`_
Merges R159 (af6272d, main 2a4cf5c with #153, then #159) into #150's
head 76407db.

Resolutions:
- emit/types.go integerType: #150's formatType version. #159's
  wideInteger is gone with formatRange, and the math import stays for
  #159's values.
- #159 x #150, the union fit check: values checks an integer const or
  enum value against the Go type of its format with the new holdsInteger
  (ranges.go), instead of #159's int-or-int64 test on formatRange. An
  int64 or uint64 value above int32 is still taken, an int beyond int32
  still panics (it does not compile for GOARCH=386), and a value outside
  int32, uint16, uint32 or uint64 now panics, where a plain port of
  wideInteger generated code that does not compile. New rows in
  TestWriteTypesJen_PanicsOnAValueTheAlternativeCannotHold (uint16
  65536, uint32 -1, uint64 enum -1, uint32 $ref 4294967296) fail on that
  port and pass here; int32 2147483648 panics on both. PickFormatConsts
  takes each format's limit.
- MIGRATION_v0.21.md: #150's "Integer types and ranges" and "Connection
  constructors and limits" rows and sections, then main's "Log
  attributes" and "Null in a tool call update", in section order. The
  sentence that lists the Validate methods of the old range checks goes,
  as #150 removes those methods.
- README.md: #150's Integers bullet before main's Patch fields bullet.
- emit/README.md: #150's integer and Validate text merged word by word
  with main's #149 and #147 edits, and #159's panic list names
  holdsInteger.

types_gen.go is regenerated; its diff from R159 equals #150's own diff.

---
_Generated with [`xum`](https://github.com/coder/xum) • Model: `anthropic:claude-opus-5-5` • Thinking: `high`_
Merges R150 (main 2a4cf5c with #153, #159 and #150) into #152's head
6ca095a. #152's own change is 7bc1936..6ca095a, since its stack
merged #150 at 7bc1936.

Resolutions:
- emit/structs.go planFor: main's #149 made fieldType a method that
  adds a pointer for an indirect member, and planFor already holds that
  type in p.goType, so mustHoldDefault's check peels p.goType instead
  of the gone package-level fieldType(field).
- emit/ranges_test.go: keep #150's TestWriteTypesJen_PanicsOnABoundNoValueCanMeet
  (82a9443, newer than #152's base) and #152's optional-integer and
  default tests; both only add functions after the same test.
- emit/README.md: #152's Validate text merged word by word with main's
  #149 edits and #159's alternative-kind sentence.

The generated files at schema 1.32.0 do not change from R150.

---
_Generated with [`xum`](https://github.com/coder/xum) • Model: `anthropic:claude-opus-5-5` • Thinking: `high`_
Applies #148's own patch (6c4769e..50da019) onto land/pr152 (d092f3a),
which holds main 2a4cf5c plus #153, #159, #150 and #152.

Resolutions:
- inbound_bench_test.go: #153 made handleCancelRequest take the params of
  the $/cancel_request (the receive loop finds them with
  cancelRequestParams), so the harness passes msg.Params instead of &msg.

---
_Generated with [`xum`](https://github.com/coder/xum) • Model: `anthropic:claude-opus-5-5` • Thinking: `xhigh`_
Applies #155's own patch (50da019..f0d4b9c) onto the merge of #148
(land/pr148), and regenerates *_gen.go.

Resolutions:
- connection.go: #153 split SendRequest into sendRequest and
  sentRequest.wait; wait now returns the raw result, so the decodeJSON
  call moves to where SendRequest decodes it.
- proxy.go: proxyRequest decodes a result as SendRequest does, so it
  calls decodeJSON too; proxy_gen.go (regenerated) decodes params with
  decodeJSON through jUnmarshalValidate, as agent_gen.go does.
- shape.go: #150 lets an integer shape hold a uint64 above
  math.MaxInt64 (intRange.holds). scan checked ints with ParseInt alone
  and said fitNo where fits says yes (FuzzShapeScan seed#16 and
  TestWriteTypesJen_ValidateChecksIntegerRanges failed), so scan calls
  holds too.
- verify-notification-barrier and verify-session-cancel: both check.sh
  pass every config; fingerprints re-recorded for SendRequest and the
  regenerated agent_gen.go cases. The connection.go edit stays on its line
  (git diff -U0: -1007 +1007), so no SKILL.md line citation moves.

---
_Generated with [`xum`](https://github.com/coder/xum) • Model: `anthropic:claude-opus-5-5` • Thinking: `xhigh`_
Applies #156's own patch (f0d4b9c..ce64625) onto the merge of #155
(land/pr155), and regenerates *_gen.go. A fast decoder must decline or
read a value exactly as the exact decoder does, so fast.go follows each
rule that the exact decoders gained on main.

Resolutions:
- emit/types.go: #159 replaced isPhantomVariant's branches with
  alternativeKind: the empty fast decoder goes on nullAlt and emptyAlt,
  rawAliases gets extensionAlt, and valueAlt declares its fast decoder
  with the Go type of alt.value. #149 dropped the validated memo map.
- emit/fast.go, union alternatives (#159): scalarConst is gone; a value
  variant takes only its values (unionAlternative.values). takesValue
  builds that check for the exact decoder and for the fast one, which
  checks it in the ordered tries only, as the exact decoder does. Before,
  ErrorCode read 0 and -0 as ParseError.
- emit/fast.go, null as unset (#147): a patch field without a clear reads
  null as absent (absentIfNull, or a present check that leaves out
  null), as decodeStmt does. Before, the 20 fields read null as PatchNull.
- emit/types.go, aliases (#153): an alias of an alias of json.RawMessage
  is a raw alias too (aliasTarget), or its field would call a decodeFast
  that json.RawMessage lacks. An alias of a struct shares its methods.
- emit/fast.go, integer formats (#150): int32 reads with fastInt, and
  uint16, uint32 and uint64 with fastUint (decode_fast.go: fastUint,
  parseUint, which takes no sign, as strconv.ParseUint). They went to
  fastExact, which is exact but decodes with encoding/json.
- #149 members held through a pointer: declType reads p.goType, which
  holds the pointer, so fastPtr decodes them; no change.
- stablecheck: a decodeFast is not compared (fastDecoder). The fast
  decoder of Tags, once it gains additionalProperties, keeps an unnamed
  member where the stable one skips it; TestCompare_AllowsAdditions
  failed on that. What a caller sees changes only in the exact decoder.
- decode_fast_test.go: fastTypes lists the decoders of #153's
  UnstableProxySuccessorNotification and UnstableProxySuccessorRequest.
- New tests: decode_fast_semantics_test.go mutates seeds of the types
  that hold these fields (each member and item replaced by null, integer
  bounds and one past them, -0, 1e0, 1.5, the ErrorCode codes, or
  repeated) and compares both decoders; emit/fast_test.go compares them on
  a schema with recursive pointer members, aliases, scalar alternatives
  of each kind and every integer format, on amd64 and 386.

---
_Generated with [`xum`](https://github.com/coder/xum) • Model: `anthropic:claude-opus-5-5` • Thinking: `xhigh`_
@ThomasK33
ThomasK33 changed the base branch from perf/decode-scan to main November 21, 2026 09:55
@ThomasK33

Copy link
Copy Markdown
Member Author

Verifier verdict for integration land/pr156 (8de46c8): PASS+NOTES

I checked the merge of this PR's head (ce64625) onto land/pr155 (f51de42). Each claimed resolution checks out, and the fast and generic decoders agree on every input I tried. In 519M comparisons on R158, amd64 and 386, I found 0 differences.

Merge redo. git merge-tree gives conflicts in emit/types.go only. 8de46c8 differs from that merge in the following places, and in nothing else:

  • types.go:
    • The validated map is gone. rawAliases now also marks an alias of a raw alias, through aliasTarget.
    • emitFastEmpty and emitFastNamed now sit on fix(generate): keep union alternatives that are not objects #159's nullAlt, objectAlt and valueAlt switch, using alt.value.
    • The takesValue helper is shared by the exact decoder and the fast decoder.
  • fast.go:
    • scalarConst is replaced by values, which is checked only in ordered tries, as the exact decoder does.
    • The two nullAsAbsent branches are new: they check that the value is not null, and use absentIfNull for lenient patches.
    • leafHelpers now cover int32 and uint16, uint32 and uint64.
  • decode_fast.go:
    • fastInt also takes ~int32.
    • The new fastUint and parseUint check for overflow and reject a sign. parseInt now uses parseUint.
  • stablecheck skips decodeFast bodies, and its README says so.
  • fastTypes now lists the 2 UnstableProxySuccessor* types.
  • The generated files were regenerated, and the 2 new tests were added.

Diff of diffs: 7 of 17 files have the same per-file patch-id as this PR's own patch (f0d4b9c..ce64625). The other 10 are the files above.

Differential sweep at R158. I wrote the harness myself and did not reuse the PR's tests. It ran on 3,189 seeds:

  • schema instances generated from schema.unstable.json, for 262 defs
  • every object and array in testdata/bench
  • the typeSeeds and semanticSeeds

The seeds go into each of the 358 fastTypes. For every pair that the exact decoder accepts, the harness puts each of 152 values in place of every member and item. The values include these classes:

  • null with whitespace around it
  • the zero forms -0, 0e0, -0.0, 1e0, 10e-1 and 1.00
  • the bound of each format (int32, uint16, uint32, uint64, int64) and one past it, including 2^63 through 2^64 and their exponent forms
  • 1e400 and 5e-324
  • every ErrorCode const, plus -32700.0 and -3.27e4
  • invalid numbers
  • invalid UTF-8: \xff, a truncated sequence, an encoded surrogate, an overlong form, and above U+10FFFF
  • lone surrogate escapes, \u0000 and bad escapes
  • nesting 10,000 and 10,001 deep

It also makes these key mutations:

  • duplicate the member with the same value, null first, null last, or another value
  • add unknown members, repeated
  • remove a member
  • use a case-swapped key, a \u-escaped key, or one with the Kelvin sign or long s that encoding/json folds, as the only key and as a duplicate

For each input, the harness compares the value with reflect.DeepEqual, the error text, and json.Marshal of the result, together with its error. It compares json.Unmarshal with fast decoding on and off, and a copy of decodeJSON with fast decoding on. It also compares validJSON with json.Valid, and checks that whatever decodeFast accepts equals the exact result.

Arch Comparisons Fast decoder took Differences
amd64 (all 400 shards) 415,205,165 313,936,912 0
386 (every fourth shard) 103,705,438 78,384,791 0

A second probe (557,820 inputs) used keys with invalid UTF-8, lone surrogate escapes, NBSP and ZWSP suffixes, and an upper-case \u escape: 0 differences.

Do the fixes fail when reverted? I reverted 3 of them, regenerated and reran:

Revert Generated diff Repo tests My harness
A: the nullAsAbsent branches in fastDecodeStmt 20 lines in decode_fast_gen.go TestFastDecode_Semantics, TestFastDecode_ReadsNullAsUnset and TestFastDecode_Types fail 2,606 differences on the built-in seeds alone
B: try(v, true) set to false, which drops the const check of ordered tries 8 lines TestFastDecode_Types and TestFastDecode_Semantics fail (ErrorCode takes 0 or -0 as ParseError) 409 differences
C: the alias of a raw alias, back to classify(def) no diff on schema 1.32 emit TestWriteTypesJen_FastDecodersReadAsTheExactOnes fails on amd64 and 386 (vet of the generated package) not applicable

Are the new tests real?

  • decode_fast_semantics_test.go compares the fast and exact decoders on mutations. It asserts that decodeFast takes each seed and each null field, so the comparison is not empty, and reverts A and B make it fail. Its compareType does not compare the json.Marshal output, but fast_test.go and my harness do.

  • emit/fast_test.go generates a synthetic schema with the forms that real schemas lack:

    • recursion through a pointer
    • aliases of a struct and of a raw message
    • integer, number, bool and string union consts
    • integer alternatives of each format, tried in order
    • a Patch whose null reads as absent

    It compares value, error and encoding on amd64 and 386. TakeWhatTheyImplement checks that the fast path actually runs. Both test real behavior.

Gates: at 8de46c8 and at R158, all pass:

  • regenerating gives no diff
  • make check and make test
  • go test -race ./..., in the root and in cmd/generate
  • GOARCH=386 go test ./..., in both modules

Notes

  • stablecheck no longer guards fast decoders. The skip is needed: with it reverted, TestCompare_AllowsAdditions fails. From now on, the differential tests are the only check that a schema bump leaves decodeFast equal to the exact decoder for stable types. Keep FuzzFastDecode_* and emit/fast_test.go in the schema-bump routine.
  • Fix C (an alias of a raw alias) changes nothing in the generated code for schema 1.32, and only emit/fast_test.go covers it.
  • I did not rerun G1, G2 or rust-diff. The known 1.31.0 G1 row (PromptSuggestion in fastTypes) is not checked here.

Generated with xum • Model: anthropic:claude-opus-5-5 • Thinking: high

Keeps the verified tree of 8de46c8 plus main's changes since f51de42, which do not overlap it.

---
_Generated with [`xum`](https://github.com/coder/xum) • Model: `anthropic:claude-opus-5-5` • Thinking: `high`_
@ThomasK33
ThomasK33 merged commit 61d643b into main Nov 21, 2026
5 checks passed
@ThomasK33
ThomasK33 deleted the perf/fast-decoders branch November 21, 2026 10:50
ThomasK33 added a commit that referenced this pull request Nov 21, 2026
## Why

Part of #141 (duplicate JSON members). An object that held the same member twice decoded in Go with the last value winning, while the Rust SDK rejects it with `duplicate field`. A peer could slip a second `sessionId` or `type` past one reader and not the other. v0.21.0 rejects it as Rust does, and an inbound request that does so gets `-32602`.

## What changed

- `duplicate.go`: `rejectDuplicateMembers(b, v, props...)` fails when the object repeats one of the type's own properties; a key counts by its unescaped name and matches exactly. Each generated `UnmarshalJSON` calls it after encoding/json has decoded `b` (the exact path); the fast decoders of #156 already decline every repeat, so a duplicate always reaches it.
- Error, like the missing-member error of #134: `json: cannot unmarshal duplicate member into Go struct field SessionNotification.sessionId of type acp.SessionId`.
- Still last-wins, as in Rust: an unknown member, a key of a map (`_meta`'s keys, elicitation `content`), an `additionalProperties` member, the discriminator of a catch-all variant (Rust reads it into a map).
- Inside a hinted (lenient) value, a repeat makes the value its default or drops the item, as in Rust; inside a union variant the union tries its next variant.
- `ElicitationAcceptAction` gets an `UnmarshalJSON`. stablecheck keeps the receiver's own property names in call arguments; the emitter's `ranges_test` no longer relies on repeating a key.
- `MIGRATION_v0.21.md`: a "Duplicate members" section. `rust-diff` cases: 52 `dup/...` cases.

## Tradeoffs

- Go stays stricter than Rust in two rare places that Rust reads through a map: an agent auth method without `type`, and the scope of an elicitation whose `mode` the schema does not name.
- Not covered: the JSON-RPC envelope that `connection.go` decodes itself, and keys that differ only in case (encoding/json matches them; Rust treats the second as unknown).

## Blast Radius

Breaking for a peer that sends repeated properties: requests fail with `-32602`, notifications are logged and dropped, responses fail the call with `-32603`. Inputs without a repeat decode as before.

## Verification

- Failing tests first (93f6ca4: 8 fail on the base), then the fix (d7908fa).
- `rust-diff`: RUST PASS on 73 committed cases. On the probe cases: before 4 same, 4 differs, 11 go-only; after 7 same, 11 both-reject, 1 differs (keys in another case).
- `make check`, `make test`, `go test -race ./...`: pass. G2 `failures.txt` equal to main. G3: 15 of 15. Corpus outcomes equal to #156; [benchmark against #156](#157 (comment)).

---
_Generated with [`xum`](https://github.com/coder/xum) • Model: `anthropic:claude-opus-5-5` • Thinking: `xhigh`_
ThomasK33 added a commit that referenced this pull request Nov 21, 2026
…158)

## Why

Part of #125 (Decoding item 3). After #156 the fast decoders spent most of their time in the scanner skipping strings byte by byte, and every decoded slice grew by doubling. This is the last step of the hill-climb on the recorded traffic of #148; with it the stack reads that traffic 75.8% faster than main with 83.5% fewer allocations.

## What changed

- `jsonscan.go`: `skipString` finds the next quote a word at a time (the first 16 bytes) and with `bytes.IndexByte` after that, and counts the backslashes before it. Same results as the byte loop on every input, JSON or not.
- `decode_fast.go`: `fastSlice` and `fastItems` keep the items' spans in a 64-slot stack buffer and allocate the slice once at its length. Values equal; capacity may differ, as it already could.
- `decode_fast_test.go`: the leaf fuzz comparator allows whitespace between a key and its colon (`{"" :"","" :{}}` failed it although `Meta` rightly declines the repeated key).

## Blast Radius

Every fast decode. No API change.

## Verification

- `BenchmarkInbound/corpus` against #157: CPU 21.6 ms to 19.0 ms (-12.1%, p=0.000, 10 runs), allocs -2.3%; stream bursts -4%, pipe inbound -11.5%.
- The whole stack against main (12 alternating runs, `-cpu 1`): CPU median 78.1 ms (range 76.9 to 85.1) to 18.9 ms (18.7 to 19.3), -75.8%; allocs 307.7k to 50.7k, -83.5%; pipe pair 14.2k to 29.9k msgs/s, inbound 21.2k to 93.9k. Every corpus message decodes as on main. [Runs, the limiter and the hill-climb log](#158 (comment)).
- `TestJSONScan_Corpus` and the byte-loop reference test at every offset; `FuzzJSONScan` 2.29M execs; `FuzzFastDecode_Slices` and the message fuzz target 4.37M execs; `FuzzFastDecode_Leaves` 60 s.
- `make check`, `make test`, `go test -race ./...`: pass. G2 `failures.txt` equal to main. `rust-diff`: RUST PASS (73 cases). G3: 15 of 15.

---
_Generated with [`xum`](https://github.com/coder/xum) • Model: `anthropic:claude-opus-5-5` • Thinking: `xhigh`_
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant