Repository navigation
⚡ perf: cut allocations and lookups in the decoder, encoder and cache - #104
Conversation
The parsed-path cache is keyed by the path as the client sent it, and a path with a slice index has far more spellings than one meaning: the letters of an alias fold, and an index parses the same with any amount of zero padding, so "ITEMS.0001.value" is "items.1.value". Every spelling got an entry of its own, kept for the life of the decoder, and past maxFastPaths the entries went to a sync.Map with no limit at all. Sending one logical path spelled with 0..4999 zeros of padding left 5000 entries and 12.5 MB of key text in the cache. Case variants and the 1001 admissible indexes multiply that, so a client could grow the process at will with ordinary-looking requests. Two bounds now stop it, both parsed again every time past them, as a map entry's path already is: - maxCachedPathLen (256): a key longer than any real path is not kept. - maxSpillPaths (16384): the spill stops taking paths. That holds sixteen paths of the full maxParserIndex+1 keys each, far more than a struct has. The same 5000 spellings now leave 244 entries and 32.8 KB, every one of them still decoding correctly. Requests that fit the bounds, which is every request a real client sends, are unaffected: both checks sit on the path that stores a new entry. Co-Authored-By: Claude Sonnet 5.5 <[email protected]> Claude-Session: https://claude.ai/code/session_01WXqjhK35VDX6EkzSFWzPoH
…field
parsePathInfo sized and allocated its parts and hops from the key's
separator count before looking at the first segment. A key that names no
field, the commonest failure and a client's to send as often as it likes,
therefore paid two allocations to be rejected one segment in.
The reservation now waits for the first segment to resolve to a field. A
key whose first segment names none (utm.source, filter.a.b) allocates
nothing; the cap on the reservation, and what a valid path costs, are as
they were.
Measured with 14 interleaved rounds per side, pinned to one core, benchstat:
UnknownKeysDecode 693.5n -> 349.9n -49.6% (p=0.000)
552 B -> 24 B -95.7%
5 allocs -> 1 -80.0%
(its one remaining allocation is the benchmark's own destination struct).
The instructions executed per call, counted under cachegrind, which does not
depend on how the binary is laid out, fall by 39%.
Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01WXqjhK35VDX6EkzSFWzPoH
Each entry of a map field cost five allocations on top of its work:
- the parser built a path for it, two allocations, because a map entry's
path is not cached (its key is the client's to choose) and so was parsed
again for every key;
- reflect.New built a value to decode into;
- the key was cloned, since it may alias the caller's buffer, and then
boxed by reflect.ValueOf, and converted to the map's key type.
A map field named by its bare alias, which is the usual way, has the same
parsed path whatever follows the alias. structInfo now builds that path
once per field (fieldInfo.mapRoot) and parsePathInfo hands it out after
the cache misses; the part carries no offset, so decodeMapEntry finds the
key after the first separator itself. Fields reached through a nested
struct or a slice element still take the parser, as before.
The value and key an entry is built in are a pair of reflect.Values that
the map copies from, so one pair serves entry after entry: they come from
a per-field sync.Pool and are zeroed on the way back, so nothing of one
entry or of the request's data stays in the pool. The key is cloned and
nothing else about its handling changes. A decode that panics never
returns its pair.
Measured with 14 interleaved rounds per side, pinned to one core, benchstat:
MapFieldDecode 1.744µ -> 1.129µ -35.3% (p=0.000)
1358 B -> 640 B -52.9%
20 allocs -> 8 -60.0%
MapFieldManyEntriesDecode 8.313µ -> 4.958µ -40.4% (p=0.000)
(16 entries) 5.9 KiB -> 2.2 KiB -63.3%
88 allocs -> 24 -72.7%
Instructions executed per call under cachegrind: -42% and -47%.
Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01WXqjhK35VDX6EkzSFWzPoH
A slice whose elements implement encoding.TextUnmarshaler went through
decodeBoxedSlice, which gave every element a reflect.New of its own to
unmarshal into, parked it in a pooled []reflect.Value, and copied it into
the finished slice with Index(i).Set: an allocation, a pool round trip,
and a copy per element, plus a defer.
When the elements are not pointers, the slice can be made first and each
element unmarshaled where it will live, through the address of its slot.
decodeUnmarshalerSlice does that. It keeps what decodeBoxedSlice did: the
slice is built detached and assigned only if every value unmarshaled (an
error leaves the field as it was), an empty value is skipped unless
ZeroEmpty is set, the error names the index of the value and the slice's
type, and the result is a non-nil slice even when nothing is left of it.
Pointer elements need a value of their own each, so they stay on the old
path, which no longer has a branch for the other case.
The tests that pin this pass on the old code as well.
Measured with 14 interleaved rounds per side, pinned to one core, benchstat:
UnmarshalerSliceDecode 1.043µ -> 660.0n -36.7% (p=0.000)
144 B -> 104 B -27.8%
15 allocs -> 9 -40.0%
Instructions executed per call under cachegrind: -27%.
Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01WXqjhK35VDX6EkzSFWzPoH
The two slice decoders that split ?ids=1,2,3 walked a value with
strings.SplitSeq, a closure per call that calls back into the loop body
and looks the one-byte separator up through Index for every item.
utils.CutByte is IndexByte and a reslice, and a loop on it is the same
loop without the iterator: an item, empty or not, goes through the same
steps as before, and a value with no comma still takes the path it did.
Measured with 14 interleaved rounds per side, pinned to one core, benchstat:
CommaListNamedDecode 2.118µ -> 1.937µ -8.5% (p=0.004)
Over 30 rounds of its own CommaListDecode (the native element types) the
change measured -8.7% (p=0.000); in the full run above, where it was one of
forty-six benchmarks, -1.6% (n.s.). The instructions executed per call under
cachegrind are the steadier figure: -3.0% and -6.4%. A modest change.
Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01WXqjhK35VDX6EkzSFWzPoH
Decode asks the registry for the converter of a field's type for every key
that is not a plain scalar, up to twice for a slice, and the answer is
nearly always none. With any converter registered at all the question was a
lookup in a map keyed by reflect.Type, which hashes the type as an
interface; a decoder with one custom converter paid for it on every
pointer, slice and struct field of every request.
The registry now carries a bitmask next to its map: the bit typeSlot(t) is
set for each registered type, the same index the type cache already uses.
A type whose bit is clear has no converter, and the answer is a shift and
a test. A type that shares a slot with a registered one falls through to
the map as before, so the answer is the map's in every case.
converter() of an unregistered type 9.2n -> 1.9n -79% (p=0.000, n=15)
On a decode that touches six non-scalar fields with one unrelated converter
registered, the instructions executed per call under cachegrind drop 11.3%,
from 8159 to 7236, where without the converter they were 7229 and are 7189:
registering a converter no longer slows the rest of the struct down.
Wall-clock on that benchmark: 955n -> 881n (-7.7%, p=0.035, n=14).
Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01WXqjhK35VDX6EkzSFWzPoH
…hat uses it
Two things in Encode's per-struct overhead:
encCache is a sync.Map keyed by reflect.Type, so every struct encoded, and
every struct nested in it, hashed the type as an interface to find its
plan. The decoder's metadata lookup went through the same thing until
cache.slots put a direct-mapped array in front of it. The encoder now has
the same: encSlots is indexed by the address of the type's descriptor, its
entries are encCache's own, generation included, and a slot stays with the
first live type to claim it. Reconfiguration clears them with the cache.
structInfo now returns the plan itself, which also carries the scratch
count below.
The shared scratch array, for the short numbers and "null"s of a fresh
map, was sized to every field of the struct, string fields included, which
never use it. The plan now counts the values that can go in it.
Measured with 40 interleaved rounds per side, pinned to one core, benchstat:
OmitEmptyStructEncode 124.2n -> 114.3n -8.0% (p=0.008)
FloatFieldEncode 237.1n -> 219.9n -7.2% (p=0.003)
TimeDurationEncoding 223.8n -> 204.3n -8.7% (p=0.000)
SizedIntegerEncode 395.9n -> 384.4n -2.9% (p=0.285, n.s.)
EncodeFreshDst 176 B -> 128 B -27.3% (p=0.000)
EncodeMostlyStringsFreshDst 232 B -> 136 B -41.4% (p=0.000)
The instructions executed per call under cachegrind, which do not depend on
the layout of the binary, are 3% to 10% lower across the eight encode
benchmarks. Allocation counts are unchanged.
Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01WXqjhK35VDX6EkzSFWzPoH
|
Important
This repository does not receive automatic reviews because it has fewer than 10 stars.
|
| Layer / File(s) | Summary |
|---|---|
Converter registry lookup cache.go, cache_test.go |
Converter registration publishes an immutable registry containing a converter map and a type-slot bitset. Lookup checks the bitset before accessing the map. Tests cover slot collisions, concurrent access, and misses. |
Parsed-path cache limits cache.go, cache_test.go |
Path parsing delays buffer allocation until a field resolves. The parsed-path cache limits cached path length and spill entries, tracks occupancy, and resets spill state when cleared. |
Map-entry path reuse and decoding cache.go, decoder.go, decoder_test.go |
Map fields receive reusable root paths and pooled entry values. Tests cover key forms, embedded fields, independent values, errors, and concurrent decoding. |
Unmarshaler and comma-list decoding decoder.go, decoder_test.go |
Text-unmarshaler slice elements are decoded into a detached, growing slice. Comma-separated builtin slices use utils.CutByte. Tests and benchmarks cover these decoding paths. |
Encoder plan caching
| Layer / File(s) | Summary |
|---|---|
Plan caching and encoding encoder.go, encoder_test.go |
The encoder adds direct-mapped plan slots and resets them when configuration changes. Plans record generation, fresh-key status, and scratch capacity. Tests cover collisions, reconfiguration, concurrent lookups, and encoding output. |
Priority:
Estimated code review effort: 4 (Complex) | ~45 minutes
Change: Refactor
Possibly related PRs
- gofiber/schema#100: Both PRs change dotted map-field decoding; this PR updates its path reuse and entry-value handling.
- gofiber/fiber#4788: The PR uses gofiber/schema map-field decoding, which this PR updates.
Suggested reviewers: claude
Merge Risk: 
Minimal · up to 1b498
-
No identified issue blocks merging after normal checks.
Pre-merge checks: 
5
Finishing Touches
-
📝 Generate docstrings
-
- Commit to this branch
- Create a new PR
🧪 Generate unit tests (beta)
-
- Commit to this branch
- Create a new PR
-
- Autofix · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts
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.
A rabbit checks the paths at night
And keeps each map entry right
The slices grow, the plans align
Cache bits mark a type in line
Then hops away; the tests all shine
Comment @coderabbitai help to get the list of available commands.
Codex Review SummaryThis comment shows the latest Codex review activity on this pull request.
Security findingsAdvisory findings (1)
ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings. |
Codecov Report✅ All modified and coverable lines are covered by tests. Additional details and impacted files@@ Coverage Diff @@
## main #104 +/- ##
==========================================
+ Coverage 99.47% 99.50% +0.02%
==========================================
Files 6 6
Lines 1723 1827 +104
==========================================
+ Hits 1714 1818 +104
Misses 5 5
Partials 4 4
Flags with carried forward coverage won't be shown. Click here to find out more. ☔ View full report in Codecov by Harness. 🚀 New features to boost your workflow:
|
decodeBoxedSlice's branch for pointer elements returns a ConversionError of its own, and no test reached it: Codecov showed the block as the one new uncovered stretch of this change. The test decodes a slice of pointers whose second value does not unmarshal, and checks the error names the index of the value and the type of the slice and that the field is left as it was. The test also passes on the code before this change. Co-Authored-By: Claude Sonnet 5.5 <[email protected]> Claude-Session: https://claude.ai/code/session_01WXqjhK35VDX6EkzSFWzPoH
There was a problem hiding this comment.
🛡️ Codex Security Review · Automatically triggered
Here are some automated security review suggestions for this pull request.
Reviewed commit: 99d920879a
ℹ️ About Codex security reviews in GitHub
This is an experimental Codex feature. Security reviews are triggered when:
- You comment "@codex security review"
- A regular code review gets triggered (for example, "@codex review" or when a PR is opened), and you’re opted in so security review runs alongside code review
Once complete, Codex will leave suggestions, or a comment if no findings are found.
…he values sent decodeUnmarshalerSlice reserved the whole slice, len(values) elements, before it looked at a value. The client chooses how many values to send, so a request of empty values, or one whose first value fails, reserved a slot apiece that decodeBoxedSlice, the path this one replaced, never did. An element is small for the builtin kinds, but a type with a converter of its own can be any size: 2048 empty values for a 64 KiB element reserved 128 MiB. Nothing is allocated now until a value needs a slot. The first slice holds at most 4 KiB of elements (all of them, for a list that fits) and the slice doubles, up to the number of values, as values are accepted, so what a request claims stays proportional to what it gets accepted. The results, the errors and the ZeroEmpty handling are as they were. The same 2048 values now allocate under a megabyte, empty or failing, which a test checks from the allocator's totals; the other tests cover the growth (past the first slice, past two doublings, with empty values skipped and kept) and a zero-size element. The cost, on UnmarshalerSliceDecode (six values, one slice, the same bytes and allocation count): 6217 -> 6465 instructions per call under cachegrind (+4.0%), with only decoder.go differing between the two binaries. Over 20 interleaved rounds the wall clock went 695.1n -> 715.2n, which is not significant (p=0.25). Reported by the Codex security review of the pull request. Co-Authored-By: Claude Sonnet 5.5 <[email protected]> Claude-Session: https://claude.ai/code/session_01WXqjhK35VDX6EkzSFWzPoH
|
@codex review |
|
Codex Review: Didn't find any major issues. More of your lovely PRs please. Reviewed commit: ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
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". |
… the kept paths weigh
The path cache is keyed by the path as the client sent it, and the bounds
added earlier in this branch counted entries: 512 fast and 16384 spilled, of
up to 256 bytes each. Two gaps remained. A client can still fill a struct
type's cache with spellings of its own ("ITEMS.0001.value" for "items.1.value")
and, once it is full, every path that was not already in it is parsed on each
request for the life of the decoder. And an entry weighs more than its key: a
type that contains itself through a slice has paths of any depth, and a
256-byte path of sixty segments parses into sixty parts and hops. Filling such
a cache with padded spellings pinned 190 MB per decoder and root type, measured
on the heap after a GC, where a flat type pinned 8 MB.
The cache now keeps a path only when it is spelled as the struct declares it:
each alias as declared or in lower case, each index without padding or sign.
The other spellings decode as they did and are parsed each time they come, as
the path of a map entry is. That leaves the struct, not the client, to decide
how many paths the cache can hold. And each kept entry is charged what it
weighs, its key and the arrays behind its parts and hops, against a budget of
8 MiB per root type, next to the entry caps. The same deep fill, spelled
canonically, now stops at about a thousand entries and 11 MB.
A client that spells an alias in a case other than the declared one or lower
case pays the parse on every request. ParsePathCacheMissMixedCase, which parses
"Items.0.Value" against lowercase tags, executes 37% fewer instructions, as the
path is no longer cloned and stored; ParsePathCacheMiss executes 2.5% more, for
the spelling checks and the weight; a cache hit is unchanged.
Tests: the spellings test now checks that of 25,600 spellings of one path
exactly the declared one is kept and all of them decode; a table pins which
spellings are kept; a self-referential type fills the cache by weight, well
under the entry caps, with every path decoding and later paths parsed but not
kept; the long-key test uses a declared spelling.
Co-Authored-By: Claude Fable 5.1 <[email protected]>
Claude-Session: https://claude.ai/code/session_01WXqjhK35VDX6EkzSFWzPoH
TestDecodeUnmarshalerSliceClaimsWhatItAccepts checked only that the request whose values all fail returned an error, so a change that stopped the values from reaching the unmarshaler at all, with any other error, would have passed it. It now requires the first value's ConversionError, with its index and the slice type. Co-Authored-By: Claude Fable 5.1 <[email protected]> Claude-Session: https://claude.ai/code/session_01WXqjhK35VDX6EkzSFWzPoH
Comments only: the code of cache.go, decoder.go and encoder.go is the same with the comments stripped. The branch added 125 comment lines next to its code; it now adds 71. Each kept comment says what is not plain from the code, in one or two lines. Co-Authored-By: Claude Fable 5.1 <[email protected]> Claude-Session: https://claude.ai/code/session_01WXqjhK35VDX6EkzSFWzPoH
The branch adds 21 comment lines to cache.go, decoder.go and encoder.go, down from 71. The code is the same with comments stripped. Co-Authored-By: Claude Sonnet 5.5 <[email protected]> Claude-Session: https://claude.ai/code/session_01WXqjhK35VDX6EkzSFWzPoH
The docs of the Test and Benchmark functions lose half of their added lines (82 to 39) and the other test comments 70% (40 to 11). The code is the same with comments stripped. Co-Authored-By: Claude Sonnet 5.5 <[email protected]> Claude-Session: https://claude.ai/code/session_01WXqjhK35VDX6EkzSFWzPoH
Match main's comment density after gofiber#104: one-line doc comments for the required-check helpers, and no comments that restate the code. The code is unchanged apart from a gofmt fix.
Summary
An audit of the decoder, encoder and cache for allocations and per-call overhead, using the helpers in
gofiber/utils/v2where they fit. Seven changes, two fixes for findings made on this PR (one by the Codex security review, one by a security sweep of the branch), and two test commits. No exported identifier is added or removed, and each change keeps the existing behavior. One of them (fix(cache)) closes a memory-growth path: the parsed-path cache could be grown without limit by a client that spells the same path many ways.Changes
ITEMS.0001.valueisitems.1.value: aliases fold case, and an index parses the same with any zero padding). Every spelling got an entry kept for the life of the decoder, and the spillsync.Maphad no limit. One logical path spelled with 0..4999 zeros of padding left 5000 entries and 12.5 MB of key text. Keys longer than 256 bytes are no longer kept, and the spill stops taking paths at 16384; past either bound a path is parsed again each time, as a map entry's path already is.utm.source,filter.a.b) now allocates nothing before it is rejected.reflect.Valuepair an entry is built in comes from a per-fieldsync.Pooland is zeroed on the way back. A decode that panics never returns its pair.encoding.TextUnmarshalerelements are made first and each element is unmarshaled where it lives, instead of areflect.New, a pool round trip and a copy per element. Kept: the field is left as it was on error, the error names the index and the slice type, empty values are skipped unlessZeroEmptyis set, and the result is a non-nil slice. Pointer elements stay on the old path.len(values)slots up front, which the client chooses, so a request of empty values (or whose first value fails) reserved a slot apiece, which the path it replaced never did: 2048 empty values for a 64 KiB element reserved 128 MiB. Nothing is allocated now until a value needs a slot; the first slice holds at most 4 KiB of elements and doubles as values are accepted. Tests measure the allocator totals and the growth. About 4% more instructions on the benchmark, same bytes and allocation count.utils.CutByte. Replacesstrings.SplitSeqin the two slice decoders. A modest change.Measurements
Interleaved base/head rounds pinned to one core, compared with
benchstat(14 to 16 rounds per side, 40 for the encoder); the full figures are in each commit message. Instruction counts under cachegrind, which do not depend on binary layout, are quoted there where wall-clock is noisy.converter()of an unregistered typeThe larger wins are for map fields, unknown keys, unmarshaler slices, and decoders that have a converter registered. The comma-list and encoder changes are modest (about 3-10%).
Testing
cache_test.go,decoder_test.go,encoder_test.go). The tests that pin the unmarshaler-slice behavior also pass on the old code; the test that measures what a request reserves fails on the code before its fix (134 MB allocated), and the deep-path test fills the cache by weight well under the entry caps.go test ./... -race -count=1 -shuffle=onpasses on Go 1.26.10 and 1.27.0;go vetand golangci-lint v2.14.0 (the version CI pins) report nothing.🤖 Generated with Claude Code
https://claude.ai/code/session_01WXqjhK35VDX6EkzSFWzPoH