Repository navigation
[schema] A type-safe foundation for wire protocols - #1682
Merged
Merged
Conversation
## Problem Protocols like JSON-RPC could not be built type-safe on the old derivation. A JSON-RPC message is a typed envelope (id, method, error) around params / result / data whose type depends on the method; kyo-jsonrpc, and kyo-mcp / kyo-lsp / the CDP client above it, all live on that shape. Two things made it unsafe: the open part had to be handled by reaching into raw JSON, the exact runtime-failing code a typed schema exists to remove; and a type's wire codec and its structure were derived by two separate macros that could silently disagree, so the JSON Schema a type advertised could not be trusted to match the bytes it wrote. ## Solution Protocol code now stays in types end to end. Structure.Value is the first-class open value (Record / Array / Str / Integer / Null / ...), and every Schema converts to and from it via fromStructureValue / toStructureValue. The envelope is one derived Schema[JsonRpcEnvelope] whose open slots are Structure.Value, and each method decodes its own params with its own derived Schema. Codec.IntrospectingReader makes "can read an open value" a type-level capability: JSON and YAML extend it, a binary codec without per-value type tags (Protobuf) does not, so decoding a Structure.Value through one is a compile error, not a runtime surprise. Structure.Type.Open is the structure those open-shaped schemas report. Structure and codec are co-derived from one macro. FocusMacro walks the case fields or sealed children once and emits both, and Schema.init captures the structure by-name, so the two are produced at one site and cannot drift; the JSON Schema a type advertises (for example MCP tools/list inputSchema) is the exact shape it reads and writes. The standalone StructureMacro is deleted. The codec body is static per field: the macro emits summonInline[Schema[ft]] per field and a kyo.internal.writeField / kyo.internal.readField call against the inline bridges in kyo-schema's internal package, kept out of the user-facing kyo namespace (primitives stay unboxed there, everything else goes through the field schema). There is no runtime Array[Schema[Any]] walk, and recursion closes by forward-reference to the in-flight derived$Schema, so the macro carries no per-type cases. Constant-sized per-method bytecode keeps a class with many derives Schema under the JVM class-file limit. SerializationMacro.scala and StructureMacro.scala (about 1450 lines together) are gone. Hand-written codecs stay ergonomic: Schema.init and Schema.initFocused default their structure argument to Structure.Type.Open, so a custom codec is just Schema.init(writeFn = ..., readFn = ...); an explicit structure is passed only when a precise wire shape matters. ## Notes Structure.Field holds its field type as a () => Structure.Type thunk so recursive structures are not forced eagerly; read it only through def fieldType, never the case-class productElement / unapply / copy that expose the raw thunk. The kyo.internal writeField / readField bridges are the single place JVM primitives are special-cased; moving that back into the emitted bodies reintroduces per-field branching and blows the class-file limit on wide types.
Problem: deriving Schema for a type whose recursion cycle passes through a container element with no source-side `derives Schema` failed to compile with "No given instance of type Schema[Chunk[...]]". The cycle runs through the container given and through intermediate types that carry no derives of their own, so Scala's implicit search diverges before it reaches the companion that anchors the cycle. kyo-tasty's Symbol.Class, holding Chunk[Java.Annotation], is the real case. Solution: the 13 container and wrapper givens (list, vector, set, chunk, seq, span, maybe, option, stringMap, result, either, stringDict, dict) take their inner Schema as a by-name using parameter captured into a lazy val. A by-name context parameter is Scala 3's mechanism for recursive given resolution: it breaks the divergence so the strict sub-search reaches the anchoring companion, and the lazy val defers forcing to serialize time so the runtime knot ties without re-entering construction. The givens stay non-inline and their bodies are otherwise unchanged. Notes: SchemaCustomContainerNestedTest gains the mutual-recursion-through- container regression guard. SchemaStructureTest's stale abstract-gate test, which asserted a compile failure that the Schema.init structure default no longer produces, becomes the positive structure-default test.
Problem: the static product codec summoned each field's Schema independently in writeBody, readBody, and structureExpr (3N summons for N fields). A nested type without source-side `derives` inline-expands its whole codec at every summon and reconstructs it on every serialize call. On kyo-tasty's 41-type recursive AST this exhausted the 12G compile heap, and at runtime a no-derives field rebuilt its nested Schema on each call. Solution: emitProductSchemaStatic hoists each distinct field-schema resolution into one lazy val per codec, shared by write, read, and structure. summonInline fires once per distinct field type instead of 3N times, and the lazy val memoizes the nested Schema per instance, so a no-derives field behaves at runtime like a derives field. lazy preserves recursion: the in-flight derived$Schema still resolves but is forced at serialize/structure time, not at construction; parentSelf and self-recursive fields keep the existing tied-knot. Measured on an 8-field type whose nested type has no derives: per-call Schema constructions 618 to 9, generated classes 51 to 13, decompiled codec 7878 to 762 lines. kyo-tasty now compiles within 12G (was OOM); 4430 kyo-schema tests pass on JVM, JS/Native/Wasm green.
fwbrasil
pushed a commit
that referenced
this pull request
Jun 19, 2026
## 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 ```scala 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: ```scala 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: ```scala 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). ```scala 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: ```scala 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](https://claude.com/claude-code)
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.
Problem
Protocols like JSON-RPC could not be built type-safe on the old derivation. A JSON-RPC message is a typed envelope (id, method, error) around params / result / data whose type depends on the method; kyo-jsonrpc, and kyo-mcp / kyo-lsp / the CDP client above it, all live on that shape. Two things made it unsafe: the open part had to be handled by reaching into raw JSON, the exact runtime-failing code a typed schema exists to remove; and a type's wire codec and its structure were derived by two separate macros that could silently disagree, so the JSON Schema a type advertised could not be trusted to match the bytes it wrote.
Solution
Protocol code now stays in types end to end.
Structure.Value is the first-class open value (Record / Array / Str / Integer / Null / ...), and every Schema converts to and from it via fromStructureValue / toStructureValue. The envelope is one derived Schema[JsonRpcEnvelope] whose open slots are Structure.Value, and each method decodes its own params with its own derived Schema. Codec.IntrospectingReader makes "can read an open value" a type-level capability: JSON and YAML extend it, a binary codec without per-value type tags (Protobuf) does not, so decoding a Structure.Value through one is a compile error, not a runtime surprise. Structure.Type.Open is the structure those open-shaped schemas report.
Structure and codec are co-derived from one macro. FocusMacro walks the case fields or sealed children once and emits both, and Schema.init captures the structure by-name, so the two are produced at one site and cannot drift; the JSON Schema a type advertises (for example MCP tools/list inputSchema) is the exact shape it reads and writes. The standalone StructureMacro is deleted.
The codec body is static per field: the macro emits summonInline[Schema[ft]] per field and a kyo.internal.writeField / kyo.internal.readField call against the inline bridges in kyo-schema's internal package, kept out of the user-facing kyo namespace (primitives stay unboxed there, everything else goes through the field schema). There is no runtime Array[Schema[Any]] walk, and recursion closes by forward-reference to the in-flight derived$Schema, so the macro carries no per-type cases. Constant-sized per-method bytecode keeps a class with many derives Schema under the JVM class-file limit. SerializationMacro.scala and StructureMacro.scala (about 1450 lines together) are gone.
Hand-written codecs stay ergonomic: Schema.init and Schema.initFocused default their structure argument to Structure.Type.Open, so a custom codec is just Schema.init(writeFn = ..., readFn = ...); an explicit structure is passed only when a precise wire shape matters.
Notes
Structure.Field holds its field type as a () => Structure.Type thunk so recursive structures are not forced eagerly; read it only through def fieldType, never the case-class productElement / unapply / copy that expose the raw thunk. The kyo.internal writeField / readField bridges are the single place JVM primitives are special-cased; moving that back into the emitted bodies reintroduces per-field branching and blows the class-file limit on wide types.