Skip to content

[schema] A type-safe foundation for wire protocols - #1682

Merged
fwbrasil merged 4 commits into
mainfrom
pr1-kyo-schema
Jun 19, 2026
Merged

fwbrasil merged 4 commits into
mainfrom
pr1-kyo-schema

Conversation

@fwbrasil

@fwbrasil fwbrasil commented Jun 18, 2026 •

Copy link
Copy Markdown
Collaborator

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

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.
fwbrasil and others added 3 commits June 18, 2026 17:17
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
fwbrasil merged commit 15d4e50 into main Jun 19, 2026
9 of 10 checks passed
@fwbrasil
fwbrasil deleted the pr1-kyo-schema branch June 19, 2026 13:50
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)
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.

1 participant