Skip to content

Proposal: arrays and maps of unknown length (streaming), using 0xc1 as an escape byte - #347

Open
mlsomers wants to merge 1 commit into
msgpack:masterfrom
mlsomers:unknown-length-containers
Open

mlsomers wants to merge 1 commit into
msgpack:masterfrom
mlsomers:unknown-length-containers

Conversation

@mlsomers

Copy link
Copy Markdown
Contributor

Summary

This proposal adds arrays and maps whose length is not known when the serializer starts writing them. It uses the one byte the spec has never assigned, 0xc1, as an escape byte that is always followed by one code byte:

Sequence Meaning
c1 90 start of an array of unknown length
c1 80 start of a map of unknown length
c1 a0 / c1 c4 (optional) start of a str / bin made of definite chunks
c1 c0 end of the innermost open object of unknown length
any other code reserved; deserializers MUST report an error

Each start code is the header of the empty object of that family (90 = empty fixarray, 80 = empty fixmap, a0 = empty fixstr, c4 = bin 8), and the end code is nil. So a hex dump stays readable: c1 90 01 02 03 c1 c0 is [1, 2, 3].

The change to spec.md adds the "escape format family" section, renames the 0xc1 row in the overview from "(never used)" to "escape", extends the conversion tables, the limitation list and the profile paragraph, and adds an implementation guideline.

Motivation

Today every array, map, str and bin header stores its length up front. A serializer whose data arrives over time has to buffer everything (or run a second query for the count) before it can write the first byte:

  • database result sets and other row streams (IAsyncEnumerable, generators, iterators) sent as an HTTP response that the client parses while it arrives
  • transcoding JSON to MessagePack on the fly: the length of a JSON array is only known at its ]
  • logs, events and telemetry where the array is followed by a trailer: {"rows": [ …streamed… ], "total": n}

Several users said they stayed with JSON for this reason (see #197). The workarounds in use today are a sequence of top-level objects (msgpack-python Unpacker, msgpackr packIter, MessagePack-CSharp MessagePackStreamReader) or a protocol of chunks. Neither can express a streamed array inside a map, and neither is the same across libraries.

Prior art

Design choices

Why 0xc1, as a pair. 0xc1 is the only first byte left. Using it as a prefix with a code byte, instead of as a single marker, keeps 253 codes free for future proposals such as those in #268 and #318. #270 also pairs 0xc1 with a second byte; this proposal changes the codes so that they read as what they mean, and uses one end code for every kind.

Unaware deserializers fail early and safely. Existing deserializers reject 0xc1 (it is "never used"), so data written with these formats fails at the first byte of the first escape sequence. Nothing is allocated for it, and nothing is read as other data. The spec text says that an unknown code is an error and never "incomplete data": a streaming decoder must not wait for more bytes on it.

Alternatives considered

  1. array 32 / map 32 with the maximum length 0xffffffff, terminated by 0xc1 (Question/suggestion regarding the length of arrays and maps #197): dd ff ff ff ff 01 a1 61 91 c3 c1. It needs no new header and has a 1-byte terminator. A seekable writer could also patch the real count in afterwards and leave out the terminator. However:

    • 0xffffffff is a valid count, so the same bytes mean two different things.
    • An unaware deserializer believes the header. It may allocate 2^32 slots, or wait for more data, and only fails at the terminator (if ever).
    • The bare 0xc1 is then taken, leaving no escape for future extensions.

    The patching approach is mentioned in the implementation guideline as something serializers can do without any spec change.

  2. Reserved extension types as start/end markers (Proposal for structure extensions #243): no new first byte. However, unaware deserializers read the markers as ordinary ext values, so a streamed array inside a known-length array silently changes the structure. Also, ext -2 is wanted by several proposals.

  3. Chunks of known-length arrays, ended by an empty array: works today, but it is a convention of the application, not something a generic deserializer or a tool can recognize.

  4. A sequence of top-level objects: works today, but only at the top level.

Backward compatibility

  • Existing data, serializers and deserializers are unaffected: no existing byte sequence changes meaning.
  • Serializers SHOULD use these formats only when the length is not known when the object starts, and only when the receiver is known to support them (an option, a media-type parameter, a protocol version). The implementation guideline suggests deserializers first, serializers behind an option.
  • Deterministic profiles (hashing, signing) use only formats of known length, as with CBOR.

Security considerations

  • Deserializers must not allocate from an unknown count. They grow as elements arrive and should offer limits on elements and nesting depth, as they should for definite containers.
  • The existing limits ((2^32)-1 elements or bytes) still apply.
  • An end sequence outside an open object of unknown length, or at the position of a map value, is an error, so a truncated or spliced stream is detected.

Examples

[1, "a", [true]]                  c1 90  01  a1 61  91 c3  c1 c0
{"a": 1}                          c1 80  a1 61  01  c1 c0
[[1]], both of unknown length     c1 90  c1 90  01  c1 c0  c1 c0
{"rows": [1, 2], "total": 2}      82  a4 72 6f 77 73  c1 90  01  02  c1 c0  a5 74 6f 74 61 6c  02
"abc" in two chunks               c1 a0  a2 61 62  a1 63  c1 c0

Open questions

  • Should str and bin of unknown length stay in (as an optional part, as written now), or be left for a later proposal?
  • The code values: 90 / 80 / a0 / c4 / c0 were picked to be readable in a hex dump. Other values would work equally well if the maintainers prefer them.

I maintain LsMsgPack (.NET) and plan to implement this behind an option once the format is agreed.

🤖 Generated with Claude Code

Every array, map, str and bin header stores its length up front, so a
serializer that streams (database rows, async sequences, transcoding
JSON on the fly) must buffer its output or know the count beforehand.

0xc1, never used so far, becomes an escape byte that is always followed
by one code byte: c1 90 starts an array of unknown length, c1 80 a map,
c1 c0 ends the innermost one. Optionally c1 a0 / c1 c4 start a str / bin
made of definite chunks. All other codes stay reserved, so 0xc1 remains
available for future extensions. Existing deserializers reject 0xc1 and
therefore fail at the first escape sequence instead of misreading data.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@mlsomers

Copy link
Copy Markdown
Contributor Author

Even though the PR was pushed by Claude, that does not mean that I did not put effort into it.
I know it looks a bit lazy having Claude push this, but to be honest Claude did a better job than I could have (keeping track of previous proposals, giving credit etc).

@Daniel-Svensson

Copy link
Copy Markdown

@misnomer, unfortunately this repo
seems to be abandoned, but the idea is good and I was about to try and writeup some similar spec and converter for arrays to support streaming results.

I was about to suggest you may open a pr on https://github.com/AArnott/msgpack-website but i did not find the spec there which I suspect is intentional.

As for the next best maybe a common format can be agreed upon for by modern .net serializer?
Maybe you can open up a discussion on Nerdbank.MessagePack to get input from @AArnott i find his library well designed

@AArnott

AArnott commented Nov 2, 2026

Copy link
Copy Markdown

It's true my fork of this site was only scoped for the content at https://msgpack.io
However looking over the PRs on this repo suggests there's a need for a 'living' msgpack spec. I am not opposed to tracking the spec in my fork. But I'd love to learn more about the gatekeepers of the msgpack org if I can. I created my fork because I didn't think folks would come back, but forking the spec itself is a more significant move than just forking a web site.

I'd certainly be willing to add extensions to my Nerdbank.MessagePack library, as it already has some. Hopefully we can agree on the extension type codes. :)

@ludocode

ludocode commented Nov 2, 2026

Copy link
Copy Markdown

This is not a good idea at all. This places all the complexity on readers just to make the writers slightly easier to implement.

Variable-length maps and arrays require the reader to dynamically allocate these as they parse. They cannot simply allocate the proper size up front. Messages may be read many more times than they are written; for example imagine a video game that uses MessagePack to store its game data (I've worked on such a game.) You should not have to pay the cost of complexity each time you read it. There is also the security argument: the more complexity exists in the reader, the greater the danger of security vulnerabilities. (Not that writers are immune from security vulnerabilites, but the risk and attack surface is much lower.)

The complexity needed for writing sizes up front is very low. Even in low-level libraries it should not be necessary for callers to supply the sizes up front; the library should be able to track it itself. My C implementation MPack has support for dynamically sizing maps and arrays during encoding. It still encodes all other types on-the-fly into auxiliary buffers so the performance and memory impact is minimal. If your library doesn't support this or you really don't want the overhead of it, I don't think it's that much of a burden to calculate the size up front. MPack in debug mode verifies that the declared sizes are correct so shouldn't affect correctness of the data either.

It doesn't make sense to optimize for writing rather than reading. Unavoidable complexity belongs in the writer so that the reader can remain small, efficient and secure. But worst of all would be having BOTH fixed and variable-length encodings in a single format. This requires all readers to support both encodings; it's the worst of all worlds. If this is really what you want, go use CBOR instead. Your proposal even says you're following the CBOR model so why even bother to change MessagePack to work like CBOR? MessagePack needs to remain simple. I don't think we should have a living spec. MessagePack should be considered done, the same way JSON is done.

Lastly, this proposal is extremely verbose. Please do not publish LLM output. Do you realize your proposal is a metaphor for the feature it proposes? You've saved yourself a minor amount of effort writing this by using an LLM, and in exchange you've burdened everyone who reads this with having to wade through slop.

@AArnott

AArnott commented Nov 2, 2026

Copy link
Copy Markdown

I haven't studied this spec yet, but I am interested in this feature, and sharing encodings for other data types that are not specified for sharing yet.
Here are some responses to @ludocode's concerns. These are just my thoughts. This isn't my repo. :)

There is also the security argument: the more complexity exists in the reader, the greater the danger of security vulnerabilities.
... Unavoidable complexity belongs in the writer so that the reader can remain small, efficient and secure

True, but security concerns already lead readers to dynamically resize and re-allocate on deserialization. We've had multiple CVEs in various msgpack serializers already related to their eagerness to allocate memory for a collection's alleged size when in fact the msgpack data stream isn't long enough to justify it, giving it a DoS attack vector. So in fairness, a secure reader already treats (large) collections as dynamically growing on deserialization, so this proposal wouldn't change that.

For my own msgpack serializer library, adding this support would likely simplify the writer without adversely impacting the reader at all, since the reader already has to deal with expanding collections for security reasons.

And it isn't like there's no precedent for this. CBOR and JSON both support collections without a length prefix. So I don't think it's unreasonable to expect a reader to be able to handle it.

imagine a video game that uses MessagePack to store its game data

True. Having this extension doesn't mean that game data has to use the extension. In fact I would imagine (having not studied this proposal in detail yet) a serializer would only choose this extension encoding when it doesn't know the size of the collection up-front (e.g. a data type defined as an enumerable rather than an array). For game data, I wouldn't expect collections without a known size to be in a data model.

Messages may be read many more times than they are written;

Yes. Also if the msgpack is written as a backup, it might be written many more times than it is read. Just sayin...

MessagePack should be considered done, the same way JSON is done.

JSON is a far less precise format, and as such isn't "outdated" by the introduction of Half (16-bit floats) and decimal (non-lossy decimal point numbers), Guid, Int128, UInt128, etc. Adding to the spec allows greater interoperability between implementations that otherwise don't have a good place in which to collaborate and share encodings.

@ludocode

ludocode commented Nov 3, 2026 •

Copy link
Copy Markdown

True, but security concerns already lead readers to dynamically resize and re-allocate on deserialization. We've had multiple CVEs in various msgpack serializers already related to their eagerness to allocate memory for a collection's alleged size when in fact the msgpack data stream isn't long enough to justify it, giving it a DoS attack vector. So in fairness, a secure reader already treats (large) collections as dynamically growing on deserialization, so this proposal wouldn't change that.

Dynamically growing is not the only way to solve this problem.

MPack's tree parser keeps track of the number of possible nodes left in the message, which is essentially the number of bytes left minus the number of allocated nodes that have not yet been filled. As soon as the message tries to allocate more nodes than it can contain, the message is rejected.

MPack also allows declaring node and byte limits per message, and limits are required when attaching MPack to a stream. This way parsing can begin from a stream even when the message size is not known up-front; the allocation size is still always bounded.

JSON is a far less precise format, and as such isn't "outdated" by the introduction of Half (16-bit floats) and decimal (non-lossy decimal point numbers), Guid, Int128, UInt128, etc. Adding to the spec allows greater interoperability between implementations that otherwise don't have a good place in which to collaborate and share encodings.

I don't think any of those things belong in MessagePack. A half-float in particular would require at least two extra bytes to declare its type. The overhead of that is huge. If you're using half-floats you care about size and you probably want an array of them so it makes way more sense to just stuff the whole array in a bin type. The rest of those types would be adding too much complexity to decoders in order to support things that are rarely used, and all of them can trivially be stored in bins so there is little downside in not having them in the spec. The only types that belong in the spec are those things that are commonly used by most apps, which is exactly what MessagePack defines.

@mlsomers

mlsomers commented Nov 3, 2026

Copy link
Copy Markdown
Contributor Author

@ludocode as AArnott says, having the option in the specs does not obligate anyone to use it. I needed this and have actually already implemented it for my cross-platform data-table replication add-on. I could run Count(*) queries in a transaction, but that requires snapshot/locking an entire table during transmission. It is a niche feature that may also find other applications, so the streaming part is part is in my core lib. There are scenarios when sensors need to stream a burst of measurements. I have some currently using raw UDP packets (lossy) and consider upgrading them to use a MsgPack stream over Http (if benchmarks are in favor).

Json has no requirement to specify the length of an array up front, so it supports streaming from the bat. I fully agree that having the length up front is usually far more preferable (one can specify the length of a list in the constructor and allocate exactly what's needed up front, preventing dynamic resizing), but there are cases where the mandatory requirement gets in the way.

@AArnott you have my vote for carrying the specs standard.

As a side note / rabbit hole: Having known the extremely detailed xsd standard, I have never considered json to be "done". When implementing Rest clients, it is not unusual that decimal fields get generated as integers, or even strings as integers just because the swagger example held a number. That never happened with soap or wsdl (based on xsd). It has slowly become better with Json Schema on which OpenApi and Json:api are built, but generating a working client the way wsdl allowed is still not a mainstream feature to this day. There have been attempts to keep xsd and wsdl using json (JSONx) for transport (replacing soap) but the community never accepted it. If MsgPack were ever to become mainstream for API's, I think we should never try to make MsgPack specific XSD/JSON Schema, WSDL/OpenAPI or SOAP/JSON:API equivilents but rather a general one that can work on any underlying format.

@slavslavov

Copy link
Copy Markdown

I agree with @ludocode that this implementation will add performance penalty on read. Looks like the case for this proposal is not performance but comfort. And serialising an array of unknown size can be done in many ways adhering to the current spec, depending on the performance you are after. One is to serialise your data in a buffer, track the number of elements, then add the signature and move the buffer. Another is to write the signature for array 32 with 0 elements and remember the position of that signature, then add your unknown elements, go back to the remembered position and write the actual size. In both ways when you read it you will know the size on advance and you can skip an element instead of parsing a huge buffer to find out where the array ends.

@AArnott, this is not about Extensions, this is about amending the spec

@tagomoris

Copy link
Copy Markdown
Member

As a maintainer, I strongly disagree to accept this proposal.

  1. Unknown length array/map etc will introduce huge complexity and security risk
  2. Unknown length series of objects can be done in many implementations even with the current spec (usually called MessagePack Streaming serialization/deserialization)

You can create an array, unpack msgpack objects from stream one-by-one, and just put them into the array. Array size can be controlled much more easily&safely in apps than deserializers.

@mlsomers

mlsomers commented Nov 3, 2026

Copy link
Copy Markdown
Contributor Author

Ah, @tagomoris at least good to see a sign of life from an original maintainer! So the spec is not abandoned after all. And I guess a standard for serializing complex objects would also make it too complicated? I wanted to replace that proposal with my currently default Indexed schema, but did not bother since the previous proposal got hardly any attention. Not that it would really change much, any lib can add extra stuff outside the specs while staying compliant with the basic specs. But having at least one compatible configuration with others would be easier if there was a standard.

@methane

methane commented Nov 4, 2026

Copy link
Copy Markdown
Member

MessagePack is a mature format, and I oppose fundamental changes of this kind. I believe only changes that improve security and interoperability, such as restricting map keys to strings, are worth considering.

@AArnott

AArnott commented Nov 4, 2026

Copy link
Copy Markdown

such as restricting map keys to strings, are worth considering.

That would be a severe breaking change. I would strongly oppose such a change as that.

@methane

methane commented Nov 5, 2026

Copy link
Copy Markdown
Member

Of course, this is just an example, not an actual proposal. If I were to seriously propose such a change, I would start by restricting the default behavior and introduce changes gradually over a long period of time.

msgpack-python has long defaulted to accepting only string keys when decoding maps. This is because it is extremely difficult to protect against HashDoS attacks while supporting arbitrary key types. Even today, I believe that only string keys should be used outside of private, trusted environments.

@AArnott

AArnott commented Nov 5, 2026

Copy link
Copy Markdown

This is because it is extremely difficult to protect against HashDoS attacks while supporting arbitrary key types

True. However nerdbank.messagepack for .NET has done it. We can securely hash arbitrary key types, with the only caveat applying to the oddball type that has multiple distinct memory representations for the same logical value (where Equal(other) would return true, such as positive and negative 0), and we've covered all the ones that we know about.

@methane

methane commented Nov 5, 2026 •

Copy link
Copy Markdown
Member

MessagePack is a simple, cross-platform serialization format, like JSON. Please keep this in mind when making any proposals.

Do you think this feature would be relatively easy to implement in all major libraries, not just your own? If not, it is not a suitable addition to MessagePack.

I consider allowing arbitrary values as map keys to be a design mistake in MessagePack from the perspectives of simplicity, interoperability, and security, as many libraries have failed to adequately protect against hash DoS attacks.

While it would be difficult to prohibit this entirely at this point, it is still possible to officially recommend disallowing it by default.

@methane

methane commented Nov 5, 2026

Copy link
Copy Markdown
Member

Let's look at JSON as an example. JSON eventually disallowed UTF-16 and UTF-32. This was a breaking change, but it improved JSON's simplicity and security. JSON also evolved to allow arbitrary values at the top level, rather than just objects. This was an improvement that increased convenience without compromising simplicity or security.

I believe improvements to MessagePack should follow the same principles.

@mlsomers

mlsomers commented Nov 5, 2026

Copy link
Copy Markdown
Contributor Author

@methane "Let's look at JSON", already done here we established that JSON does not impose the need of knowing the length of an array up front and therefore is compatible with streaming huge datasets.

Seems like everyone wants the spec to stay small and simple, fair, keeps the libs lightweight. Maybe we should put a system on top of the basic spec, so that special requirements do not require all libs to implement them. Libs can then add the additions on their supported list like "This lib supports the full MsgPack spec + Streaming + ComplexOjects + AddOn". Addons could also be in additional dependent packages. Keeping the basic lib small, but still having an interop standard for cases beyond the basic spec.

@methane

methane commented Nov 5, 2026

Copy link
Copy Markdown
Member

@methane "Let's look at JSON", already done

What I meant was how the JSON specification has evolved over time. My intent should be clear if you read my reply. Please don't deliberately misinterpret what I'm saying.

Maybe we should put a system on top of the basic spec,

The JSON ecosystem provides a useful model here as well. Additional functionality can be built on top of JSON as a separate specification, as with JSON Schema. Alternatively, if the JSON specification itself has limitations, it can be extended under a different name, as with JSONC or JSON5. The JSON ecosystem has not tried to turn JSON itself into a collection of optional features, which would only create confusion and fragmentation.

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.

7 participants