Skip to content

[schema] add MessagePack codec - #1685

Merged
fwbrasil merged 2 commits into
getkyo:mainfrom
DamianReeves:feat/schema-msgpack
Jun 19, 2026
Merged

fwbrasil merged 2 commits into
getkyo:mainfrom
DamianReeves:feat/schema-msgpack

Conversation

@DamianReeves

@DamianReeves DamianReeves commented Jun 19, 2026 •

Copy link
Copy Markdown
Collaborator

Summary

Adds a MessagePack codec to kyo-schema, the fourth serialization format alongside Json, Yaml, Ion, and Protobuf. 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 dedicated kyo.internal.msgpack package, mirroring how the YAML codec keeps its machinery isolated.

MessagePack fills the gap between Protobuf (compact but schema-required) and Json (self-describing but text): a compact, self-describing binary format that interoperates with standard MessagePack tooling.

Why

kyo-schema derives serialization from Schema[A] and dispatches to a pluggable Codec at the call site; the self-describing binary option was missing. Because every MessagePack value carries a type tag, the reader implements Codec.IntrospectingReader (introduced in #1682), so Structure.Value and 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

import kyo.*

case class Address(city: String, zip: String) derives Schema
case class User(id: Int, name: String, address: Address) derives Schema, CanEqual

val alice = User(1, "Alice", Address("Portland", "97201"))

val bytes: Span[Byte] = MsgPack.encode(alice)

MsgPack.decode[User](bytes)
// Result.Success(User(1, "Alice", Address("Portland", "97201")))

Case classes encode as a MessagePack map keyed by field name, collections as arrays, Option/Maybe as the value or nil, and Span[Byte] as a binary blob. MsgPack.decode accepts the same maxDepth / maxCollectionSize safety limits as Json.decode.

Configurable key encoding

KeyEncoding.StringName (default) is self-describing and interoperable. KeyEncoding.FieldId is more compact, using the same stable MurmurHash3 IDs as Protobuf:

given MsgPack = MsgPack(MsgPack.Config(keyEncoding = MsgPack.KeyEncoding.FieldId))

MsgPack.decode[User](MsgPack.encode(alice))
// Result.Success(alice)  -- compact integer keys on the wire

Dynamic Map keys and the Result/Either discriminators always stay strings under FieldId, since a hash is not reversible.

Configurable temporal encoding

Instant defaults to a lossless [seconds, nanos] array; InstantEncoding.Extension writes the spec-defined MessagePack timestamp extension (type -1), which standard decoders in other languages read as a timestamp:

given MsgPack = MsgPack(MsgPack.Config(instantEncoding = MsgPack.InstantEncoding.Extension))

Duration has no MessagePack standard (see the compatibility note below), so DurationEncoding lets you choose, and schemas are provided for both java.time.Duration and scala.concurrent.duration.{Duration, FiniteDuration}:

  • Lossless (default): a [seconds, nanos] array keeping the full java.time.Duration range.
  • Compat: a string of total nanoseconds, wire-compatible with upickle/weePickle (limited to the Long nanosecond range, like those libraries).
import scala.concurrent.duration.{Duration, FiniteDuration, DurationInt}

case class Timeout(connect: FiniteDuration, idle: Duration) derives Schema

given MsgPack = MsgPack(MsgPack.Config(durationEncoding = MsgPack.DurationEncoding.Compat))

MsgPack.decode[Timeout](MsgPack.encode(Timeout(5.seconds, Duration.Inf)))
// Result.Success(Timeout(5 seconds, Duration.Inf))

scala.concurrent.duration.Duration (the possibly-infinite type) always uses the string form so it can carry Inf/MinusInf/Undefined; FiniteDuration and java.time.Duration follow the DurationEncoding setting. 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.IntrospectingReader and can materialize an arbitrary payload into a Structure.Value without a schema:

val bytes: Span[Byte] = MsgPack.encode(alice)

summon[Schema[Structure.Value]].decode[MsgPack](bytes)
// Result.Success(Structure.Value.Record(...))

This makes MsgPack a binary transport for open-shaped envelopes, the role JSON plays for JSON-RPC.

Design notes

  • Single writer, buffered objects. Arrays and maps are written with an exact count upfront. Object bodies are buffered because the derivation omits absent Option/Maybe fields, so the static field count can exceed the entries actually written; the writer counts real entries and emits the true map header on objectEnd (mirrors ProtobufWriter's buffer stack).
  • Count-driven reader with limits on every path. maxDepth and maxCollectionSize are enforced on the typed read path and on the skip path used for unknown fields and captureValue, so malformed input cannot exhaust depth or memory.
  • Shared change in FocusMacro. Case-class product fields now emit fieldBytes (not field), so a codec can distinguish recoverable schema-field keys from dynamic Map/sum keys. This matches existing design intent (the JSON writer's fieldBytes ASCII fast path; the sealed-variant write path already used fieldBytes) and is verified against the full kyo-schema suite with no regressions.
  • Module-wide scala.concurrent.duration schemas. Schema[FiniteDuration] and Schema[Duration] are added in Schema.scala, so all codecs (not just MsgPack) gain support; the abstract Duration uses the upickle string form for infinities.
  • No build.sbt change. No change to Schema or Codec: MsgPack <: Codec plus a given makes schema.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/bin separation, 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 encode java.time.Duration at all. DurationEncoding.Compat matches that string form exactly for interop; Lossless is 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, both KeyEncoding modes and both InstantEncoding/DurationEncoding modes (including cross-config decode and the upickle nanos-string wire form), scala.concurrent.duration FiniteDuration and Duration (finite and Inf/MinusInf/Undefined), introspection (Structure.Value and readStructure), size-class boundaries (fix -> 16 -> 32 for str/bin/array/map plus empty containers and a 17-field object hitting the map16 header), and error paths (truncation, range, parse, missing field, and depth/collection limits on the skip path).

Verification

  • kyo-schemaJVM/test: full module green, no regressions
  • MsgPackTest: 52 passed on JVM and JS
  • kyo-schemaNative/Test/compile: compiles
  • kyo-schemaJVM/doctest: all README blocks compile (the new MessagePack examples included)
  • scalafmtCheckAll: clean

🤖 Generated with Claude Code

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
DamianReeves force-pushed the feat/schema-msgpack branch from 2de6258 to 22fb669 Compare June 19, 2026 20:18
@fwbrasil
fwbrasil merged commit 1d989ea into getkyo:main Jun 19, 2026
8 of 10 checks passed
@DamianReeves
DamianReeves deleted the feat/schema-msgpack branch June 19, 2026 23:00
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.

2 participants