Repository navigation
[schema] add MessagePack codec - #1685
Merged
Merged
Conversation
Adds a from-the-ground-up MessagePack codec to kyo-schema with no
third-party dependencies, cross-compiled to JVM, JS, and Native. The
format internals live in the kyo.internal.msgpack package, mirroring how
the YAML codec keeps its machinery isolated.
MsgPack is a compact, self-describing binary format, so the reader is a
Codec.IntrospectingReader: Structure.Value and open-shaped wire protocols
round-trip through it (the capability Protobuf lacks). The wire shape is
configurable via MsgPack.Config:
- KeyEncoding: case-class field and sealed-variant keys are written as
UTF-8 names by default (self-describing, interoperable) or as compact
MurmurHash3 fieldId integers. Dynamic Map keys and the Result/Either
discriminator keys always stay strings, since a hash is not reversible.
- TemporalEncoding: Instant/Duration default to a lossless [seconds,
nanos] pair, or the MessagePack timestamp extension. The reader
auto-detects the wire shape, so bytes decode regardless of reader
config.
The codec writer buffers object bodies to emit correct count-prefixed map
headers, because the derivation omits absent Option/Maybe fields and the
static field count would otherwise overcount. The reader is count-driven
and enforces maxDepth/maxCollectionSize on every path, including the skip
path used for unknown fields and captureValue.
Shared change: FocusMacro now emits fieldBytes (not field) for case-class
product fields, so a codec can distinguish recoverable schema-field keys
from dynamic Map/sum keys. This matches the existing design intent (the
JSON writer's fieldBytes ASCII fast path, the sealed-variant write path)
and is verified against the full kyo-schema suite across Json, Yaml, Ion,
Protobuf, and Structure codecs.
Docs: a MessagePack section with doctest-verified examples is added to
kyo-schema/README.md, which the docs site renders.
….duration support
Splits the temporal config so Instant and Duration are independent, and adds
a Duration compatibility mode plus schemas for scala.concurrent.duration.
MsgPack.Config now has:
- instantEncoding: Primitive ([seconds, nanos] array) or Extension (the
spec timestamp ext -1, replacing the previous combined temporalEncoding).
- durationEncoding: Lossless ([seconds, nanos] array, full java.time.Duration
range, default) or Compat (a string of total nanoseconds, wire-compatible
with upickle/weePickle, limited to the Long nanosecond range like them).
MessagePack defines no Duration type and no cross-library convention exists, so
this is a free choice; the previous kyo-specific Duration extension (ext type 1)
is removed in favor of these two clear options. The reader auto-detects the wire
shape (array, string, or bare integer of nanos), so bytes decode regardless of
the reader's config.
Adds module-wide schemas for scala.concurrent.duration.FiniteDuration (round-
trips by total nanoseconds via the duration primitive, honoring durationEncoding)
and scala.concurrent.duration.Duration (always the upickle string form, so it can
carry Inf/MinusInf/Undefined, which have no lossless numeric representation).
Updates the README MessagePack section and adds tests for both encodings, the
upickle nanos-string wire form, and the scala duration types including infinities.
DamianReeves
force-pushed
the
feat/schema-msgpack
branch
from
June 19, 2026 20:18
2de6258 to
22fb669
Compare
fwbrasil
approved these changes
Jun 19, 2026
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Summary
Adds a MessagePack codec to
kyo-schema, the fourth serialization format alongsideJson,Yaml,Ion, andProtobuf. It is hand-rolled from the ground up with no third-party dependencies and cross-compiles to JVM, JS, and Native. Format internals live in a dedicatedkyo.internal.msgpackpackage, mirroring how the YAML codec keeps its machinery isolated.MessagePack fills the gap between
Protobuf(compact but schema-required) andJson(self-describing but text): a compact, self-describing binary format that interoperates with standard MessagePack tooling.Why
kyo-schemaderives serialization fromSchema[A]and dispatches to a pluggableCodecat the call site; the self-describing binary option was missing. Because every MessagePack value carries a type tag, the reader implementsCodec.IntrospectingReader(introduced in #1682), soStructure.Valueand open-shaped wire protocols (JSON-RPC-style envelopes) round-trip through MsgPack: the capability a non-self-describing binary format like Protobuf cannot offer.Usage
Case classes encode as a MessagePack map keyed by field name, collections as arrays,
Option/Maybeas the value ornil, andSpan[Byte]as a binary blob.MsgPack.decodeaccepts the samemaxDepth/maxCollectionSizesafety limits asJson.decode.Configurable key encoding
KeyEncoding.StringName(default) is self-describing and interoperable.KeyEncoding.FieldIdis more compact, using the same stable MurmurHash3 IDs as Protobuf:Dynamic
Mapkeys and theResult/Eitherdiscriminators always stay strings underFieldId, since a hash is not reversible.Configurable temporal encoding
Instantdefaults to a lossless[seconds, nanos]array;InstantEncoding.Extensionwrites the spec-defined MessagePack timestamp extension (type -1), which standard decoders in other languages read as a timestamp:Durationhas no MessagePack standard (see the compatibility note below), soDurationEncodinglets you choose, and schemas are provided for bothjava.time.Durationandscala.concurrent.duration.{Duration, FiniteDuration}:Lossless(default): a[seconds, nanos]array keeping the fulljava.time.Durationrange.Compat: a string of total nanoseconds, wire-compatible with upickle/weePickle (limited to theLongnanosecond range, like those libraries).scala.concurrent.duration.Duration(the possibly-infinite type) always uses the string form so it can carryInf/MinusInf/Undefined;FiniteDurationandjava.time.Durationfollow theDurationEncodingsetting. The reader auto-detects the wire shape (array, string, or bare integer of nanos), so bytes decode regardless of the reader's config.Open / type-safe wire protocols
Because MessagePack is self-describing, the reader is a
Codec.IntrospectingReaderand can materialize an arbitrary payload into aStructure.Valuewithout a schema:This makes MsgPack a binary transport for open-shaped envelopes, the role JSON plays for JSON-RPC.
Design notes
Option/Maybefields, so the static field count can exceed the entries actually written; the writer counts real entries and emits the true map header onobjectEnd(mirrorsProtobufWriter's buffer stack).maxDepthandmaxCollectionSizeare enforced on the typed read path and on theskippath used for unknown fields andcaptureValue, so malformed input cannot exhaust depth or memory.FocusMacro. Case-class product fields now emitfieldBytes(notfield), so a codec can distinguish recoverable schema-field keys from dynamicMap/sum keys. This matches existing design intent (the JSON writer'sfieldBytesASCII fast path; the sealed-variant write path already usedfieldBytes) and is verified against the fullkyo-schemasuite with no regressions.scala.concurrent.durationschemas.Schema[FiniteDuration]andSchema[Duration]are added inSchema.scala, so all codecs (not just MsgPack) gain support; the abstractDurationuses the upickle string form for infinities.build.sbtchange. No change toSchemaorCodec:MsgPack <: Codecplus agivenmakesschema.encode[MsgPack](v)/schema.decode[MsgPack](bytes)work for free.Spec compatibility
Audited byte-for-byte against the official MessagePack spec: format bytes, big-endian encoding, smallest-format integer selection with correct sign-extension, IEEE-754 floats,
str/binseparation, the timestamp extension (32/64/96 including the 34/30-bit packing), map/array pair counts, and ext header layout all conform. Standard decoders (Python/JS/Go) read Kyo's output correctly.Duration interop: MessagePack defines no Duration type, and a survey of the Scala ecosystem found no de-facto convention. The libraries that do encode a Duration (upickle/upack, weePickle) use a string of total nanoseconds for
scala.concurrent.duration, and none encodejava.time.Durationat all.DurationEncoding.Compatmatches that string form exactly for interop;Losslessis the kyo-specific full-range default. This is the "no standard exists" case, not a divergence from one.Tests
MsgPackTest(52 tests) covers: primitive round-trips across every integer size class, wire-byte sanity, nested/recursive/sum/enum round-trips,Option/Maybe/Map/Span[Byte]/BigInt/BigDecimal, bothKeyEncodingmodes and bothInstantEncoding/DurationEncodingmodes (including cross-config decode and the upickle nanos-string wire form),scala.concurrent.durationFiniteDurationandDuration(finite andInf/MinusInf/Undefined), introspection (Structure.ValueandreadStructure), size-class boundaries (fix -> 16 -> 32 for str/bin/array/map plus empty containers and a 17-field object hitting themap16header), and error paths (truncation, range, parse, missing field, and depth/collection limits on the skip path).Verification
kyo-schemaJVM/test: full module green, no regressionsMsgPackTest: 52 passed on JVM and JSkyo-schemaNative/Test/compile: compileskyo-schemaJVM/doctest: all README blocks compile (the new MessagePack examples included)scalafmtCheckAll: clean🤖 Generated with Claude Code