Skip to content

⚡ perf: cut allocations and lookups in the decoder, encoder and cache - #104

Merged
ReneWerner87 merged 14 commits into
mainfrom
ccr-a6278878-8daap1
Oct 27, 2026
Merged

ReneWerner87 merged 14 commits into
mainfrom
ccr-a6278878-8daap1

Conversation

@gaby

@gaby gaby commented Oct 25, 2026 •

Copy link
Copy Markdown
Member

Summary

An audit of the decoder, encoder and cache for allocations and per-call overhead, using the helpers in gofiber/utils/v2 where 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

  • fix(cache): bound the path cache. The cache is keyed by the path as the client sent it, and a path with a slice index has many spellings of one meaning (ITEMS.0001.value is items.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 spill sync.Map had 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.
  • fix(cache): keep only the declared spelling of a path, and bound what the kept paths weigh (from the security sweep). The entry caps above still let a client fill the cache with spellings of its own, after which no later path is cached, 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, so a padded fill pinned 190 MB per decoder and root type. 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), so the struct rather than the client decides how many paths there are, and each kept entry is charged its key and the arrays behind its parts against an 8 MiB budget per root type. Every other spelling decodes as before and is parsed each time. The same deep fill now stops at about a thousand entries and 11 MB; of 25,600 spellings of one path exactly one is kept. A cache hit is unchanged; a miss pays 2.5% more instructions for the checks.
  • perf(decoder): reserve a path's parts once its first segment names a field. A key that names no field (utm.source, filter.a.b) now allocates nothing before it is rejected.
  • perf(decoder): share a map field's path and pool its entries' values. The parsed path of a map field named by its bare alias is built once per field, and the key/value reflect.Value pair an entry is built in comes from a per-field sync.Pool and is zeroed on the way back. A decode that panics never returns its pair.
  • perf(decoder): unmarshal slice elements in place. Slices of non-pointer encoding.TextUnmarshaler elements are made first and each element is unmarshaled where it lives, instead of a reflect.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 unless ZeroEmpty is set, and the result is a non-nil slice. Pointer elements stay on the old path.
  • fix(decoder): size an unmarshaler slice by the values accepted, not the values sent (from the Codex security review). The in-place slice reserved 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.
  • perf(decoder): split comma lists with utils.CutByte. Replaces strings.SplitSeq in the two slice decoders. A modest change.
  • perf(cache): skip the converter map for types nobody registered. A bitmask next to the registry map, indexed by the type slot the type cache already uses, answers "no converter" with a shift and a test; a type that shares a slot with a registered one falls through to the map, so the answer is always the map's.
  • perf(encoder): find plans through a slot cache; size the scratch to what uses it. The same direct-mapped slot idea for the encoder's plan lookup (reconfiguration clears it with the cache), and the shared scratch array is sized to the values that can use it instead of to every field.
  • Tests: a test for the pointer-element unmarshaler error branch Codecov flagged, and the allocation test above now pins which error a failing slice returns.

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.

Benchmark Before After
UnknownKeysDecode 693.5 ns, 552 B, 5 allocs 349.9 ns (-49.6%), 24 B, 1 alloc
MapFieldDecode 1.744 µs, 1358 B, 20 allocs 1.129 µs (-35.3%), 640 B, 8 allocs
MapFieldManyEntriesDecode (16 entries) 8.313 µs, 5.9 KiB, 88 allocs 4.958 µs (-40.4%), 2.2 KiB, 24 allocs
UnmarshalerSliceDecode (with the fix above) 1.048 µs, 144 B, 15 allocs 739.6 ns (-29.4%), 104 B, 9 allocs
CommaListNamedDecode 2.118 µs 1.937 µs (-8.5%)
converter() of an unregistered type 9.2 ns 1.9 ns (-79%)
Encode: OmitEmptyStruct / FloatField / TimeDuration 124.2 / 237.1 / 223.8 ns 114.3 / 219.9 / 204.3 ns (-8.0% / -7.2% / -8.7%)
EncodeFreshDst / EncodeMostlyStringsFreshDst (bytes per op) 176 / 232 128 / 136

The 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

  • Each change comes with tests and benchmarks (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=on passes on Go 1.26.10 and 1.27.0; go vet and golangci-lint v2.14.0 (the version CI pins) report nothing.

🤖 Generated with Claude Code

https://claude.ai/code/session_01WXqjhK35VDX6EkzSFWzPoH

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
@gaby
gaby requested a review from a team as a code owner October 25, 2026 15:31
@gaby
gaby requested review from ReneWerner87, efectn and sixcolors and removed request for a team October 25, 2026 15:31
@coderabbitai

coderabbitai Bot commented Oct 25, 2026 •

Copy link
Copy Markdown

Review in Change Stack →

Important

  • 🔍 Trigger review

This repository does not receive automatic reviews because it has fewer than 10 stars.

Run configuration
  • Source mode: Auto
  • Repository: Unavailable
  • Branch: Unavailable
  • File: No configuration file from this repository applied
  • Commit: Unavailable
  • Layers: Organization UI
  • Review profile: CHILL
  • Plan: Advanced
  • Run ID: b49041b4-a093-4fa6-9822-39cdb7f99227

No actionable comments were generated in the recent review.

Recent review info
Run configuration
  • Source mode: Auto
  • Repository: Unavailable
  • Branch: Unavailable
  • File: No configuration file from this repository applied
  • Commit: Unavailable
  • Layers: Organization UI
  • Review profile: CHILL
  • Plan: Advanced
  • Run ID: 8d8c58a9-0114-469f-98c3-4e811037630a
Commits

Reviewing files that changed from the base of the PR and between a267c81 and 1b4987e.

Files selected for processing: 6
  • cache.go
  • cache_test.go
  • decoder.go
  • decoder_test.go
  • encoder.go
  • encoder_test.go

Included review availability: This review used your included allowance. Your plan provides up to 1 included review per hour; 0 remain after this review.

Recent review details
Additional context used
Learnings: 1
Learning: 2026-07-18T00:21:21.433Z
Learnt from: gaby
Repo: gofiber/schema PR: 76
File: encoder.go:0-0
Timestamp: 2026-07-18T00:21:21.433Z
Learning: In the Go `schema` package, encoder and decoder metadata caches must generation-tag cached entries and validate each cache hit against the current configuration generation. A stale cache entry may be stored after a concurrent reconfiguration, but it must never be served. Regression tests should deterministically inject stale-generation entries after reconfiguration.

Applied to files:

  • encoder.go
  • encoder_test.go
ast-grep (0.45.3)
cache.go

[warning] 110-110: Narrowing a non-constant integer to a smaller fixed-width type (int8/int16/int32, uint8/uint16/uint32) can silently overflow or wrap, yielding negative or truncated values that are dangerous in size, length, or index logic. Validate the source value is within the target type's range before converting (e.g. bounds-check, or use a checked helper), and avoid narrowing untrusted or len()/parsed values.
Context: uint8(64 - typeCacheSlots)
Note: [CWE-190] Integer Overflow or Wraparound.

(integer-overflow-narrowing-conversion-go)

Additional comments: 6
encoder.go: 1

44-50: LGTM!

Also applies to: 58-58, 61-65, 140-140, 149-159, 167-184, 219-259, 351-352, 363-363, 381-381

encoder_test.go: 1

7-7: LGTM!

Also applies to: 10-10, 280-280, 1373-1396, 1398-1426, 1428-1462, 1464-1489, 1491-1511, 1513-1549

cache.go: 1

56-60: LGTM!

Also applies to: 96-123, 165-175, 184-185, 195-201, 296-298, 309-323, 333-343, 390-392, 402-402, 576-582, 813-813, 843-846, 872-874, 1037-1043, 1080-1082

cache_test.go: 1

569-864: LGTM!

decoder.go: 1

908-912: LGTM!

Also applies to: 978-991, 999-1030, 1034-1036, 1052-1053, 1064-1064, 1119-1189, 1246-1248, 1306-1308

decoder_test.go: 1

15-15: LGTM!

Also applies to: 5843-6526

Walkthrough

The changes update converter and path caching, map-entry decoding, text-unmarshaler slice decoding, comma-list parsing, and encoder plan caching.

Changes: Decoder and cache paths

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: Low

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: Passed 5
Check name Status Explanation
Description Check Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check Passed The title clearly and concisely describes the main changes: performance improvements that reduce allocations and lookups across the decoder, encoder, and cache.
Docstring Coverage Passed Docstring coverage is 92.00% which is sufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 50 functions across 6 files.
Linked Issues check Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check Passed Check skipped because no linked issues were found for this pull request.
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.

❤️ Share

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.

@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Oct 25, 2026 •

Copy link
Copy Markdown

Codex Review Summary

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

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-10-25T16:08:39.564021Z 1b4987e Manual request
🔒 Security Review ✅ Completed 2026-10-25T15:39:28.414114Z 99d9208 PR opened

Security findings

Advisory findings (1)

ℹ️ 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.

@codecov

codecov Bot commented Oct 25, 2026 •

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 99.50%. Comparing base (a267c81) to head (2ecf8b1).

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              
Flag Coverage Δ
unittests 99.50% <100.00%> (+0.02%) ⬆️

Flags with carried forward coverage won't be shown. Click here to find out more.

☔ View full report in Codecov by Harness.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.

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

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🛡️ 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.

Comment thread decoder.go Resolved
…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
@gaby gaby changed the title perf: cut allocations and lookups in the decoder, encoder and cache; bound the path cache ⚡ perf: cut allocations and lookups in the decoder, encoder and cache; bound the path cache Oct 25, 2026
@gaby gaby changed the title ⚡ perf: cut allocations and lookups in the decoder, encoder and cache; bound the path cache ⚡ perf: cut allocations and lookups in the decoder, encoder and cache Oct 25, 2026
@gaby

gaby commented Oct 25, 2026

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. More of your lovely PRs please.

Reviewed commit: 1b4987e17d

ℹ️ 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".

… 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
@ReneWerner87
ReneWerner87 merged commit 6b0810c into main Oct 27, 2026
20 checks passed
@ReneWerner87
ReneWerner87 deleted the ccr-a6278878-8daap1 branch October 27, 2026 20:48
IslamElsayed added a commit to IslamElsayed/schema that referenced this pull request Oct 28, 2026
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.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants