Skip to main content

DynamicSchema

DynamicSchema is a type-erased schema container that wraps a Reflect.Unbound[_] tree — all the structural information from a Schema[A] (field names, case names, type identities, validations, annotations) with no Scala functions attached. The two fundamental uses are validating DynamicValue instances at runtime, and transporting schemas across process boundaries.

final case class DynamicSchema(reflect: Reflect.Unbound[_])

DynamicSchema:

  • Holds the full structural shape of a type without capturing constructors or deconstructors
  • Can validate any DynamicValue against its structure using DynamicSchema#check and DynamicSchema#conforms
  • Can be converted to a DynamicValue and back, and stored or sent as Avro bytes (see Storing a DynamicSchema)
  • Can be rehydrated into a fully operational Schema[A] by supplying runtime bindings via DynamicSchema#rebind

Motivation​

A Schema[A] carries both structure (field names, type identities, validations) and behaviour (constructors and deconstructors as Scala closures). Closures cannot cross process boundaries. DynamicSchema is the structural half — a schema stripped of all Scala functions:

Schema[OrderPlaced] ←── compile-time type, closures attached
│
│ Schema[A]#toDynamicSchema
▼
DynamicSchema ←── no closures, stored in a registry
(Reflect.Unbound[_]) or sent over the wire as Avro bytes
│
│ DynamicSchema.toDynamicValue / DynamicSchema.fromDynamicValue
▼
DynamicValue ←── in-memory form that a codec writes
│
│ DynamicSchema.fromDynamicValue (on the consumer side)
▼
DynamicSchema ←── reconstructed from storage
│
│ DynamicSchema#rebind[OrderPlaced](resolver)
▼
Schema[OrderPlaced] ←── operational again, can encode and decode

This pattern enables schema registries: the Checkout Service registers its event schema on startup; the Fulfillment Service fetches it and rebinds it against its own type definitions, guaranteeing it uses the exact schema that was in effect when the event was encoded. See BindingResolver for the complete rebinding API.

Creating a DynamicSchema​

There are two ways to obtain a DynamicSchema: strip bindings from an existing typed schema, or reconstruct one from a serialized blob.

Schema[A]#toDynamicSchema​

Schema[A]#toDynamicSchema strips all runtime bindings from a typed schema, returning the structural skeleton as a DynamicSchema. The method is defined on Schema:

trait Schema[A] {
def toDynamicSchema: DynamicSchema
}

This is the standard entry point. The structural information — field names, case names, type IDs, Validation constraints, Modifier annotations, docs, and stored examples and default values — is preserved. The default values of case class fields (edition: Int = 1) are not:

import zio.blocks.schema._

case class Address(street: String, city: String)
case class Person(name: String, age: Int, address: Address)

object Address { implicit val schema: Schema[Address] = Schema.derived[Address] }
object Person { implicit val schema: Schema[Person] = Schema.derived[Person] }

val dynamic: DynamicSchema = Schema[Person].toDynamicSchema

We can inspect the schema's structure by printing it:

dynamic
// res1: DynamicSchema = DynamicSchema(
// Record(
// fields = IndexedSeq(
// Term(
// name = "name",
// value = Primitive(
// primitiveType = String(None),
// typeId = String,
// primitiveBinding = zio.blocks.schema.binding.NoBinding$$anon$1@58e219ce,
// doc = Doc(blocks = IndexedSeq(), metadata = Map()),
// modifiers = List(),
// storedDefaultValue = None,
// storedExamples = List()
// ),
// doc = Doc(blocks = IndexedSeq(), metadata = Map()),
// modifiers = List()
// ),
// Term(
// name = "age",
// value = Primitive(
// primitiveType = Int(None),
// typeId = Int,
// primitiveBinding = zio.blocks.schema.binding.NoBinding$$anon$1@58e219ce,
// doc = Doc(blocks = IndexedSeq(), metadata = Map()),
// modifiers = List(),
// storedDefaultValue = None,
// storedExamples = List()
// ),
// doc = Doc(blocks = IndexedSeq(), metadata = Map()),
// modifiers = List()
// ),
// Term(
// name = "address",
// value = Record(
// fields = IndexedSeq(
// Term(
// name = "street",
// value = Primitive(
// primitiveType = String(None),
// typeId = String,
// primitiveBinding = zio.blocks.schema.binding.NoBinding$$anon$1@58e219ce,
// doc = Doc(blocks = IndexedSeq(), metadata = Map()),
// modifiers = List(),
// storedDefaultValue = None,
// storedExamples = List()
// ),
// ...

DynamicSchema.fromDynamicValue​

DynamicSchema.fromDynamicValue reconstructs a DynamicSchema from a previously serialized DynamicValue blob. This is the consumer-side entry point when schemas are loaded from a registry or database:

object DynamicSchema {
def fromDynamicValue(dv: DynamicValue): DynamicSchema
}

Example showing the full store/retrieve round-trip:

import zio.blocks.schema._

case class Product(id: Long, name: String, price: Double)
object Product { implicit val schema: Schema[Product] = Schema.derived[Product] }

val original: DynamicSchema = Schema[Product].toDynamicSchema
val blob: DynamicValue = DynamicSchema.toDynamicValue(original)
val restored: DynamicSchema = DynamicSchema.fromDynamicValue(blob)

We inspect the restored schema's type name to confirm the round-trip preserved it:

restored.typeId.name
// res3: String = "Product"

Serializing a DynamicSchema​

A DynamicSchema turns into a DynamicValue in memory, and a codec turns it into bytes for storage or transmission. The format matters: only Avro reads a stored schema back intact in 0.0.56.

DynamicSchema.toDynamicValue​

DynamicSchema.toDynamicValue converts a DynamicSchema to a DynamicValue. The result contains only field names, type names, validations, and annotations — no Scala closures:

object DynamicSchema {
def toDynamicValue(ds: DynamicSchema): DynamicValue
}

The following example converts a simple case class schema to its DynamicValue form:

import zio.blocks.schema._

case class Tag(name: String)
object Tag { implicit val schema: Schema[Tag] = Schema.derived[Tag] }

val ds: DynamicSchema = Schema[Tag].toDynamicSchema
val blob: DynamicValue = DynamicSchema.toDynamicValue(ds)

We inspect the blob's value type to confirm the record structure was preserved:

blob.valueType
// res5: DynamicValueType = <function1>

Storing a DynamicSchema​

DynamicSchema.schema is the Schema[DynamicSchema] that every format derives a codec from, and it is found implicitly as Schema[DynamicSchema]. In 0.0.56, only the Avro codec from the zio-blocks-schema-avro module round-trips a DynamicSchema. The JSON, YAML, TOON and MessagePack codecs write each tagged node of the schema as a plain record and narrow its numbers, and DynamicSchema.fromDynamicValue falls back to an accept-anything Reflect.Dynamic node instead of reporting an error, so the schema they read back accepts any value. This is a known bug. The same happens when the DynamicValue form goes through Json.

The following example writes a schema with both codecs and checks a value with the wrong field type against each copy:

import zio.blocks.chunk.Chunk
import zio.blocks.schema._
import zio.blocks.schema.avro.AvroFormat
import zio.blocks.schema.json.JsonFormat

case class Tag(name: String, weight: Int)
object Tag { implicit val schema: Schema[Tag] = Schema.derived[Tag] }

val ds: DynamicSchema = Schema[Tag].toDynamicSchema
val wrongType = DynamicValue.Record(Chunk(
"name" -> DynamicValue.int(7),
"weight" -> DynamicValue.int(1)
))

val avroCodec = Schema[DynamicSchema].derive(AvroFormat)
val jsonCodec = Schema[DynamicSchema].derive(JsonFormat)

val fromAvro = avroCodec.decode(avroCodec.encode(ds))
val fromJson = jsonCodec.decode(jsonCodec.encode(ds))

The copy read from Avro equals the original and rejects the value, while the copy read from JSON decodes without an error, is a Dynamic node, and accepts it:

fromAvro.map(_ == ds)
// res7: Either[SchemaError, Boolean] = Right(true)
fromAvro.map(_.conforms(wrongType))
// res8: Either[SchemaError, Boolean] = Right(false)
fromJson.map(_.reflect.isDynamic)
// res9: Either[SchemaError, Boolean] = Right(true)
fromJson.map(_.conforms(wrongType))
// res10: Either[SchemaError, Boolean] = Right(true)

Store Avro bytes, and after loading a schema, reject one whose root is Dynamic (DynamicSchema#reflect and Reflect#isDynamic), so a later change of format can't silently turn the registry into one that accepts anything. Also in 0.0.56, the schema of a recursive type can't be stored: DynamicSchema.toDynamicValue and the codecs follow the recursion until they throw a StackOverflowError. How to Build a Schema Registry with DynamicSchema builds a registry that stores Avro files.

Validating DynamicValues​

DynamicSchema can check whether a DynamicValue conforms to its structure. Validation is recursive: field counts and names, variant case names, collection element types, and primitive type + validation constraints are all checked.

DynamicSchema#check​

DynamicSchema#check returns None if the value is valid, or Some(SchemaError) describing the first validation failure:

final case class DynamicSchema(reflect: Reflect.Unbound[_]) {
def check(value: DynamicValue): Option[SchemaError]
}

The following example shows all three outcomes — a valid value, a missing field, and a type mismatch:

import zio.blocks.chunk.Chunk
import zio.blocks.schema._

case class Point(x: Int, y: Int)
object Point { implicit val schema: Schema[Point] = Schema.derived[Point] }

val dynSchema = Schema[Point].toDynamicSchema

val valid = DynamicValue.Record(Chunk(
"x" -> DynamicValue.int(3),
"y" -> DynamicValue.int(7)
))

val missing = DynamicValue.Record(Chunk(
"x" -> DynamicValue.int(3)
// "y" missing
))

val wrongType = DynamicValue.Record(Chunk(
"x" -> DynamicValue.int(3),
"y" -> DynamicValue.string("not an int")
))

We evaluate all three cases to observe the outcomes:

dynSchema.check(valid)
// res12: Option[SchemaError] = None
dynSchema.check(missing)
// res13: Option[SchemaError] = Some(
// SchemaError(
// List(MissingField(source = DynamicOptic(ArraySeq()), fieldName = "y"))
// )
// )
dynSchema.check(wrongType)
// res14: Option[SchemaError] = Some(
// SchemaError(
// List(
// ExpectationMismatch(
// source = DynamicOptic(ArraySeq(Field("y"))),
// expectation = "Expected Int, got String"
// )
// )
// )
// )

Validation rules:

  • Records: every field in the schema must be present; extra fields in the value are rejected.
  • Variants: the case name must be valid; the case payload is validated recursively.
  • Sequences: every element is validated against the element schema.
  • Maps: every key and every value is validated against their respective schemas.
  • Primitives: the PrimitiveType must match, and any Validation constraints (range, pattern, etc.) must pass.

DynamicSchema#conforms​

DynamicSchema#conforms is a convenience method that returns true when the value is valid:

final case class DynamicSchema(reflect: Reflect.Unbound[_]) {
def conforms(value: DynamicValue): Boolean
}

We pass a well-formed record to confirm the return value:

import zio.blocks.chunk.Chunk
import zio.blocks.schema._

case class Tag(name: String)
object Tag { implicit val schema: Schema[Tag] = Schema.derived[Tag] }

val dynSchema = Schema[Tag].toDynamicSchema
val value = DynamicValue.Record(Chunk("name" -> DynamicValue.string("scala")))
dynSchema.conforms(value)
// res16: Boolean = true

Rebinding to a Typed Schema​

DynamicSchema#rebind converts a structural DynamicSchema back into a fully operational Schema[A] by walking the Reflect.Unbound tree and attaching runtime bindings from a BindingResolver:

final case class DynamicSchema(reflect: Reflect.Unbound[_]) {
def rebind[A](resolver: BindingResolver): Schema[A]
}

The resolver must provide a binding for every concrete type referenced in the schema tree: record types, variant types, and wrapper types must be covered explicitly; primitives, sequences, and maps are covered by BindingResolver.defaults:

import zio.blocks.schema._
import zio.blocks.schema.binding._

case class OrderId(value: String)
case class LineItem(sku: String, quantity: Int)
case class Order(id: OrderId, items: List[LineItem])

object OrderId { implicit val schema: Schema[OrderId] = Schema.derived[OrderId] }
object LineItem { implicit val schema: Schema[LineItem] = Schema.derived[LineItem] }
object Order { implicit val schema: Schema[Order] = Schema.derived[Order] }

val blob: DynamicValue = DynamicSchema.toDynamicValue(Schema[Order].toDynamicSchema)
val dynamic: DynamicSchema = DynamicSchema.fromDynamicValue(blob)

val resolver: BindingResolver =
BindingResolver.empty
.bind(Binding.of[OrderId])
.bind(Binding.of[LineItem])
.bind(Binding.of[Order])
++ BindingResolver.defaults

val rebound: Schema[Order] = dynamic.rebind[Order](resolver)
val order = Order(OrderId("ORD-1"), List(LineItem("SKU-A", 2)))
val encoded = rebound.toDynamicValue(order)

We decode the encoded value to confirm the round-trip is lossless:

rebound.fromDynamicValue(encoded)
// res18: Either[SchemaError, Order] = Right(
// Order(
// id = OrderId("ORD-1"),
// items = List(LineItem(sku = "SKU-A", quantity = 2))
// )
// )
warning

If DynamicSchema#rebind cannot find a binding for any type in the unbound schema tree, it throws a RebindException at runtime. Ensure the resolver covers every concrete type — records, variants, wrappers, primitives, and standard collections — that appears in the schema. BindingResolver.defaults covers all standard primitives, java.time types, List, Vector, Set, Map and the other standard collections, but not Option.

Rebinding a schema with an Option field and only BindingResolver.defaults behind the record fails. Consider a book with two optional fields:

import zio.blocks.schema._
import zio.blocks.schema.binding._

case class Book(title: String, edition: Option[Int], subtitle: Option[String])
object Book { implicit val schema: Schema[Book] = Schema.derived[Book] }

val stored: DynamicSchema = Schema[Book].toDynamicSchema

The rebind fails on an Option case it can't bind and names its type and path:

try stored.rebind[Book](BindingResolver.empty.bind(Binding.of[Book]) ++ BindingResolver.defaults)
catch { case e: RebindException => e.getMessage }
// res20: Schema[Book] | String = "Missing Record binding for type scala.Some at path: .subtitle<Some>"

Each Option[A] needs three bindings: Binding.of[Option[A]] for the Option itself, a Some case for its element type, and Binding.Record.none, which serves every element type; leaving out the last one fails the same way, naming scala.None. Binding.Record.some[A] builds the Some case for a reference type such as String, and Binding.Record.someInt, Binding.Record.someLong, Binding.Record.someDouble and their siblings build it for primitives:

val withOptions: BindingResolver =
BindingResolver.empty
.bind(Binding.of[Book])
.bind(Binding.of[Option[Int]])
.bind(Binding.Record.someInt)
.bind(Binding.of[Option[String]])
.bind(Binding.Record.some[String])
.bind(Binding.Record.none)
++ BindingResolver.defaults

val reboundBook: Schema[Book] = stored.rebind[Book](withOptions)

The rebound schema converts a Book both ways:

reboundBook.fromDynamicValue(reboundBook.toDynamicValue(Book("Zionomicon", Some(1), None)))
// res21: Either[SchemaError, Book] = Right(
// Book(title = "Zionomicon", edition = Some(1), subtitle = None)
// )

See BindingResolver for the full resolver API including BindingResolver.reflection for automatic binding via reflection.

Structural Navigation​

DynamicSchema#get navigates into the schema tree using a DynamicOptic path, returning the nested Reflect.Unbound[_] at that location:

final case class DynamicSchema(reflect: Reflect.Unbound[_]) {
def get(optic: DynamicOptic): Option[Reflect.Unbound[_]]
}

The following example navigates to a field nested two levels deep:

import zio.blocks.schema._

case class Address(street: String, city: String)
case class Person(name: String, age: Int, address: Address)

object Address { implicit val schema: Schema[Address] = Schema.derived[Address] }
object Person { implicit val schema: Schema[Person] = Schema.derived[Person] }

val dynSchema = Schema[Person].toDynamicSchema
val streetSchema: Option[Reflect.Unbound[_]] =
dynSchema.get(DynamicOptic.root.field("address").field("street"))

We map over the result to read the type name at that path:

streetSchema.map(_.typeId.name)
// res23: Option[String] = Some("String")

See DynamicOptic for the full path DSL.

Metadata Access and Updates​

DynamicSchema provides read and write access to the metadata stored in the Reflect tree.

DynamicSchema#typeId​

Returns the TypeId of the root type:

import zio.blocks.schema._

case class Event(id: Long, kind: String)
object Event { implicit val schema: Schema[Event] = Schema.derived[Event] }

val dynSchema = Schema[Event].toDynamicSchema
dynSchema.typeId.name
// res25: String = "Event"
dynSchema.typeId.fullName
// res26: String = "repl.MdocSession.MdocApp24.Event"

DynamicSchema#doc​

Reads and writes the documentation annotation on the schema. The zero-argument form reads the current Doc; the single-argument form returns a copy with updated documentation:

final case class DynamicSchema(reflect: Reflect.Unbound[_]) {
def doc: Doc
def doc(value: String): DynamicSchema
}

We attach a description and read it back to confirm it was applied:

import zio.blocks.schema._

case class Event(id: Long, kind: String)
object Event { implicit val schema: Schema[Event] = Schema.derived[Event] }

val updated: DynamicSchema = Schema[Event].toDynamicSchema.doc("An event in the event log")
updated.doc
// res28: Doc = Doc(
// blocks = IndexedSeq(Paragraph(IndexedSeq(Text("An event in the event log")))),
// metadata = Map()
// )

DynamicSchema#modifiers and DynamicSchema#modifier​

DynamicSchema#modifiers returns the Modifier.Reflect annotations attached to the root node. DynamicSchema#modifier returns a copy with an additional modifier appended:

final case class DynamicSchema(reflect: Reflect.Unbound[_]) {
def modifiers: Seq[Modifier.Reflect]
def modifier(m: Modifier.Reflect): DynamicSchema
}

DynamicSchema#getDefaultValue and DynamicSchema#defaultValue​

DynamicSchema#getDefaultValue returns the stored default DynamicValue, if one is set. DynamicSchema#defaultValue returns a copy with the given default:

final case class DynamicSchema(reflect: Reflect.Unbound[_]) {
def getDefaultValue: Option[DynamicValue]
def defaultValue(value: DynamicValue): DynamicSchema
}

We attach a default value and then retrieve it:

import zio.blocks.schema._

case class Config(retries: Int)
object Config { implicit val schema: Schema[Config] = Schema.derived[Config] }

val withDefault: DynamicSchema =
Schema[Config].toDynamicSchema
.defaultValue(DynamicValue.Record(
zio.blocks.chunk.Chunk("retries" -> DynamicValue.int(3))
))
withDefault.getDefaultValue
// res30: Option[DynamicValue] = Some(
// Record(IndexedSeq(("retries", Primitive(Int(3)))))
// )

DynamicSchema#examples​

The zero-argument form returns stored examples as a Seq[DynamicValue]. The multi-argument form returns a copy with the given examples set:

final case class DynamicSchema(reflect: Reflect.Unbound[_]) {
def examples: Seq[DynamicValue]
def examples(value: DynamicValue, values: DynamicValue*): DynamicSchema
}

Converting to a Typed Schema​

DynamicSchema#toSchema returns a Schema[DynamicValue] — it stays fully in the dynamic world and requires no bindings. Use it when you have received a DynamicSchema over the wire and need a codec-compatible schema that enforces structural conformance without binding any Scala types.

After transporting a DynamicSchema, you may not have the Scala types that DynamicSchema#rebind requires. For example, when the consumer is a validation gateway or format converter that handles arbitrary event shapes, any codec pipeline that accepts Schema[DynamicValue] can use the result directly. The conversion runs DynamicSchema#check, which compares primitive types exactly, so DynamicSchema#toSchema suits input whose DynamicValues carry the exact primitive types, such as values made by Schema#toDynamicValue or read with Schema[DynamicValue].derive(AvroFormat).

JSON input is a poor fit. The JSON codec of Schema[DynamicValue] reads a string as a String, a whole number as an Int or a Long, every other number as a BigDecimal, and an Option as a bare value or null, so a valid JSON event is rejected when it has a field of another primitive type (such as Double, Float, BigInt, Instant or UUID), a Long field holding a value that fits in an Int, a BigDecimal field holding a whole number, or an Option field. For JSON input, rebind the schema and decode with the rebound schema's JSON codec.

warning

Use DynamicSchema#rebind instead when you have a BindingResolver and need a fully operational Schema[A] for typed encoding and decoding.

DynamicSchema#toSchema is defined as:

final case class DynamicSchema(reflect: Reflect.Unbound[_]) {
def toSchema: Schema[DynamicValue]
}

The following example shows a schema-validation gateway: we receive a DynamicSchema from a registry, convert it to a Schema[DynamicValue], and use the result to validate an incoming payload, rejecting it on structural mismatch:

import zio.blocks.schema._

case class OrderEvent(orderId: String, amount: Double)
object OrderEvent { implicit val schema: Schema[OrderEvent] = Schema.derived[OrderEvent] }

val blob: DynamicValue = DynamicSchema.toDynamicValue(Schema[OrderEvent].toDynamicSchema)
val received: DynamicSchema = DynamicSchema.fromDynamicValue(blob)
val gatewaySchema: Schema[DynamicValue] = received.toSchema

val incoming: DynamicValue = DynamicValue.Record(
zio.blocks.chunk.Chunk(
"orderId" -> DynamicValue.string("ORD-42"),
"amount" -> DynamicValue.double(99.95)
)
)

We validate the payload and observe the result:

gatewaySchema.fromDynamicValue(incoming)
// res32: Either[SchemaError, DynamicValue] = Right(
// Record(
// IndexedSeq(
// ("orderId", Primitive(String("ORD-42"))),
// ("amount", Primitive(Double(99.95)))
// )
// )
// )

The same order sent as JSON is rejected, because the JSON codec reads 99.95 as a BigDecimal while the schema expects a Double:

gatewaySchema.jsonCodec.decode("""{"orderId":"ORD-42","amount":99.95}""").left.map(_.getMessage)
// res33: Either[String, DynamicValue] = Left(
// "Expected Double, got BigDecimal at: .amount at: .wrapped"
// )

Integration​

DynamicSchema connects to several other ZIO Blocks types, each serving a distinct role in the dynamic layer.

With DynamicValue​

DynamicSchema and DynamicValue are the two halves of ZIO Blocks' dynamic layer. DynamicValue holds runtime data without compile-time types; DynamicSchema holds structural metadata without runtime bindings. Together they enable fully type-erased validation and serialization pipelines. See DynamicValue.

With BindingResolver​

The primary consumer of DynamicSchema in a type-safe context is DynamicSchema#rebind, which requires a BindingResolver to reattach runtime bindings. See BindingResolver for the complete rebinding API, including BindingResolver.reflection for automatic binding discovery.

With DynamicOptic​

DynamicSchema#get accepts a DynamicOptic path to navigate the structural tree. This allows you to inspect nested schemas, extract type information, or validate sub-trees independently. See DynamicOptic.

With Schema​

Schema[A]#toDynamicSchema is defined on Schema and is the standard way to obtain a DynamicSchema. See Schema.

See also: How to Build a Schema Registry with DynamicSchema, a guide that stores versioned schemas as data and checks incoming events against them.

Running the Examples​

All code from this guide is available as runnable examples in the schema-examples module.

1. Clone the repository and navigate to the project:

git clone https://github.com/zio/zio-blocks.git
cd zio-blocks

2. Run individual examples with sbt:

Validate DynamicValues against a DynamicSchema (source)

cd schema-examples && sbt "runMain dynamicschema.DynamicSchemaValidationExample"

Serialize and deserialize a DynamicSchema (source)

cd schema-examples && sbt "runMain dynamicschema.DynamicSchemaSerializationExample"

Rebind a restored DynamicSchema to a typed Schema (source)

cd schema-examples && sbt "runMain dynamicschema.DynamicSchemaRebindExample"

Complete schema registry pipeline (source)

cd schema-examples && sbt "runMain dynamicschema.DynamicSchemaRegistryExample"