Skip to content

CborWriter: keep map key check state out of the stack frame - #138602

Open
sichanyoo wants to merge 1 commit into
dotnet:mainfrom
sichanyoo:cbor-writer-key-state-out-of-frame
Open

sichanyoo wants to merge 1 commit into
dotnet:mainfrom
sichanyoo:cbor-writer-key-state-out-of-frame

Conversation

@sichanyoo

Copy link
Copy Markdown
Contributor

Contributes to #137111 (change 3). Follows #137943.

Description

Every map, array and indefinite-length string pushes a StackFrame on open and pops it on close. Besides the context the writer needs in every mode, the frame carries three fields used only by the duplicate and sorted key checks: KeysRequireSorting, KeyValuePairEncodingRanges and KeyEncodingRanges. Lax mode never sets them, since #137772 skips the key bookkeeping there. It still copies them into and out of every frame, and resets the three live fields on every push.

This PR moves those three fields into a separate KeyFrame, kept on its own Stack<KeyFrame>. It is pushed and popped only when _tracksMapKeys is set, which is every mode except Lax. In Lax, the second stack is never created and the three fields are never copied or reset.

StackFrame keeps the other six fields and no longer holds any references. Stack<StackFrame> is unchanged otherwise. There are no public API changes.

The issue described this change with "a separate array". That wording assumed change 1 (an array-based frame stack) went first. Change 1 turned out not to help on top of #137943, so I dropped it, and this PR uses a Stack<KeyFrame> to match the existing frame stack.

Why the behavior is the same

  • Lax: the three fields are always false/null. They are only set by HandleMapKeyWritten, HandleMapValueWritten and CompleteMapWrite (directly or through GetKeyEncodingRanges/GetKeyValueEncodingRanges), and all three run only when _tracksMapKeys is set. Saving, resetting and restoring values that never change has no effect, so skipping it changes nothing.
  • Strict, Canonical and Ctap2Canonical: the same values are saved, reset and restored at the same points as before. The only difference is where they're saved. PushDataItem and PopDataItem push and pop both stacks together, and Reset() clears both, so the two stay in step.

Benchmarks

BenchmarkDotNet 0.15.2, .NET 10.0.12, Arm64 RyuJIT, Apple M1 Pro, macOS 26.7.3. main and this branch were built from source in the same benchmark project (namespace changed, nothing else) and run as separate processes in 5 interleaved rounds, alternating which went first. Each column is the best mean of the 5 rounds. The writer is CborConformanceMode.Lax (Strict for DocStrict and ListStrict) with convertIndefiniteLengthEncodings: true, created once and reused through Reset(). The benchmarks are the same as in #137772 and #137943, plus ListStrict.

Benchmark main this PR this PR vs main
Text: 64 short strings in an array, per string 10.3 ns 10.1 ns 1.03x faster
Pairs: 32 short string pairs in a map, per string 10.2 ns 10.1 ns 1.02x faster
Map1Indef: 64 maps {"S": v}, indefinite length, per map 33.1 ns 28.1 ns 1.18x faster
Map1Def: same, definite length, per map 29.5 ns 25.7 ns 1.15x faster
Doc: nested document (below) 1,145 ns 1,070 ns 1.07x faster
DocStrict: Doc with unique keys, Strict mode 1,914 ns 1,939 ns 1.01x slower
ListStrict: 20 unique keys, each k: {"L": [{"S": v}, {"S": v}]}, Strict mode 3,738 ns 3,764 ns 1.01x slower

In Lax, this PR was faster than main in every round except one Text round, which tied. In Strict, where every nested container now pushes two stacks instead of one, it's about 1% slower (by median: DocStrict 1,943 vs 1,959 ns, ListStrict 3,772 vs 3,813 ns). Allocations are unchanged: 0 B for Text, Pairs, Map1 and ListStrict, and 128 B for Doc and DocStrict (the benchmark's own key strings).

Doc is {"TableName": "my-table", "Item": {...}}, where Item has 20 short-key entries like k: {"S": v} or k: {"N": v} plus "nested": {"M": {...}} with 4 more k: {"S": v} entries: 28 maps, all started with WriteStartMap(null), and 77 short strings (389 bytes), then Encode(Span<byte>) into a preallocated buffer. ListStrict starts every map and array with a null length (indefinite length).

Testing

  • System.Formats.Cbor.Tests (net10.0 configuration, including the FsCheck property tests): 2,652 passed, 2 skipped, 0 failed, the same as main. The 2 skipped tests are the RemoteExecutor culture tests, which I couldn't run locally.
  • Differential comparison against main, as described in CborWriter: reduce per-call overhead of map and array bookkeeping #137111. Boundary test: 1,512 documents with container sizes and string lengths around 24 and 256, in every conformance mode with conversion on and off. Fuzz: random sequences of the write APIs with misuse mixed in, 10,000 cases per configuration over all four conformance modes, conversion and AllowMultipleRootLevelValues on and off, with both a reused writer and a new writer per case. That is 121,581,530 calls per comparison. After every call, success or exception (type and message), CurrentDepth, BytesWritten and IsWriteCompleted matched, and so did the final Encode() bytes: 0 differences.

@github-actions github-actions Bot added the needs-area-label An area label is needed to ensure this gets routed to the appropriate area owners label Dec 1, 2026
@dotnet-policy-service dotnet-policy-service Bot added the community-contribution Indicates that the PR has been added by a community member label Dec 1, 2026
@vcsjones vcsjones added area-System.Formats.Cbor and removed needs-area-label An area label is needed to ensure this gets routed to the appropriate area owners labels Dec 1, 2026
@dotnet-policy-service

Copy link
Copy Markdown
Contributor

Tagging subscribers to this area: @dotnet/area-system-formats-cbor, @bartonjs, @vcsjones
See info in area-owners.md if you want to be subscribed.

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

area-System.Formats.Cbor community-contribution Indicates that the PR has been added by a community member

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants