The Postcard Schema Specification

Version and Stability

This document is a draft of version 0.1 of the Postcard Schema Specification, which describes how the postcard-schema crate identifies schemas. It is not yet stable.

It builds on the Postcard Wire Specification, which defines how messages are encoded. This specification does not change the wire format.

Conventions

The key words "MUST", "MUST NOT", "REQUIRED", "SHALL", "SHALL NOT", "SHOULD", "SHOULD NOT", "RECOMMENDED", "NOT RECOMMENDED", "MAY", and "OPTIONAL" in this document are to be interpreted as described in BCP 14 (RFC 2119, RFC 8174) when, and only when, they appear in all capitals, as shown here.

Each requirement of this specification is labelled with a tracey identifier, such as schema[key.hash.fnv1a-128]. The postcard-schema crate refers to requirements by these identifiers, in comments.

Terms such as aggregate, sequence, tagged union, and varint(N) have the meanings defined in the Postcard Wire Specification.

Scope

This version of the specification only covers Keys: the 8-byte hash of a list of strings and schemas, chosen by an application; and Schema Tables: how schemas are sent.

Schemas

A schema in postcard-schema describes a type in the terms of the Serde Data Model: it records the serde calls that the type's Serialize implementation makes.

Each kind of schema is encoded as a postcard type, as described by the serde binding of the Postcard Wire Specification:

KindEncoded as
Bool, I8 to I128, U8 to U128the atom of the same name
F32, F64, Charthe atom of the same name
String { .. }string
ByteArray { .. }bytes
Unitunit
Option(T)an option of T
Seq { element, .. }a sequence of element
Tuple(T, ...)an aggregate of the Ts
Map { key, val, .. }a sequence of aggregates of key and val
Struct { name, data }data, as below
Enum { name, variants }a tagged union, with each variant's data as below

The data of a struct or variant is one of:

DataEncoded as
Unitunit
Newtype(T)T
Tuple(T, ...)an aggregate of the Ts
Struct(name: T, ...)an aggregate of the Ts

Names (of structs, enums, fields, and variants) and metadata like maximum lengths do not affect how the values themselves are encoded on the wire.

References

Document NameFull NameVersion
Postcard Wire SpecificationThe Postcard Wire Specification1.1
Serde Data ModelThe Serde Book: Serde data modelserde v1.0.229
FNVThe FNV Non-Cryptographic Hash Algorithmdraft-eastlake-fnv
MurmurHash3MurmurHash3, fmix64
BCP 14Key words for use in RFCs to Indicate Requirement LevelsRFC 2119, RFC 8174

License

The Postcard Schema Specification (this document) is licensed under the terms of the CC-BY-SA 4.0 license. The full license text is in spec/tracey/LICENSE-CC-BY-SA in the postcard repository.

Keys

As postcard is not a self-describing format, it is often useful for two entities (e.g. a client and server) to be able to quickly cross-check that they have a common understanding of message schemas, protocol versions, or the meaning of a method.

This chapter describes postcard-schema "keys": an 8-byte hash of a list of items (strings and schemas) that express information relevant to an application. Each application chooses its items, and the options that control which parts of each item are considered during hashing.

Keys borrow the idea of content addressing from tools such as Git and IPFS, and apply it to types and APIs: a key is derived from what it identifies, so a change that affects the key input (see What Changes a Key) produces a different key. Unlike those tools, keys use a short, non-cryptographic hash, and they hash a type's postcard structure, rather than the value of a specific piece of data.

Design Considerations

  1. Keys should be "misuse resistant", and are not a security boundary. Keys should never be used as a reason to skip input validation steps, or as an acceptable justification for unsafe code. A key can always be falsified by a malicious attacker.
  2. The process of generating keys must be deterministic across platforms, so that clients and servers built at different times, or built on or for different targets, agree on the key produced from the same input.
  3. Keys do not allow for Semantic Versioning (SemVer). SemVer lets an API change compatibly, for example by adding an enum variant, but hashing the schema causes any such change to produce a different key.

How Keys Work

postcard-schema defines how items and options are converted to bytes to be hashed, called the key input, and how the key input is hashed into the key.

For example, an RPC framework may choose to use the following as the items of its application-specific keys:

  • the method name, e.g. "get_temperature_value"
  • the schema of the request type
  • the schema of the response type

This would allow the client and server of the RPC framework to use these keys both to uniquely identify the method being called, and to ensure they have a common understanding of the request and response types being exchanged.

text
   the application chooses             postcard-schema defines
  ┌────────────────────────────┐      ┌─────────────────────────────┐
  │ options                    │      │ the key input:              │
  │ items, in order:           │─────▶│   how items become bytes    │─────▶  8-byte key
  │   "get_temperature_value"  │      │ the hash:                   │
  │   schema of the request    │      │   how those bytes are mixed │
  │   schema of the response   │      └─────────────────────────────┘
  └────────────────────────────┘

What the Application Chooses

hash.rs:222 tests.rs:254 +1

A key MUST be computed from a set of options and an ordered list of zero or more items.

This specification does not define the use of any particular items. Both sides of an application need to choose the same items, in the same order, with the same options.

hash.rs:114 tests.rs:255

An item MUST be either a string or a schema.

hash.rs:63 tests.rs:177

There MUST be exactly two options:

  • The names option: include the names of fields and variants. Enabled by default.
  • The maximum lengths option: include the maximum length of strings, byte arrays, sequences, and maps. Disabled by default.

What Changes a Key

A schema is part of the key input by its postcard type, such as an aggregate, a sequence, or a tagged union, not by how the type is written in Rust. A change to a type changes the key only if it changes that postcard type, or a name or maximum length that the options include. Some different postcard types share an encoding on the wire (see Wire Compatibility), but still produce different keys. For example:

ChangeChanges the key?
adding, removing, reordering, or changing itemsyes
the name of a field or variantonly with the names option
the maximum length of a string, byte array, sequence or maponly with the maximum lengths option
the name of a struct or enumno
a newtype struct -> its field, a unit struct -> (), a tuple struct -> tupleno
Vec<u8> -> a byte array, a map -> a sequence of (key, value) tuplesno
a struct with named fields -> a tuple of the same typesonly without the names option
u16 -> u32, Option<T> -> an enum with variants None and Some(T)yes

Key Input

The key input is a header followed by the items, each preceded by an item tag:

text
●──[ domain ]──[ options ]──[ count ]──┬───────────────────────────────────────┬──▶
   |----------- header -------------|  │   ┌──( 0x00 )──[   string    ]───┐    │
                                       └─▶─┤  | tag  |  |---- item ---|   ├──┐ │
                                         ▲ └──( 0x01 )──[    type     ]───┘  │ │
                                         │                                   │ │
                                         └───────────── count times ◀────────┴─┘
                                           |----------- items ------------|
hash.rs:31 +5 tests.rs:178 +2

The key input MUST be the postcard encoding of a KeyInput, as given by the Serde binding of the Postcard Wire Specification:

rust
struct KeyInput {
    domain: [u8; 22],
    options: u64,
    items: Vec<Item>,
}

enum Item {
    String(String),               // 0x00
    Schema(Type),                 // 0x01
}

enum Type {
    Bool,                         // 0x00
    I8,                           // 0x01
    U8,                           // 0x02
    I16,                          // 0x03
    I32,                          // 0x04
    I64,                          // 0x05
    I128,                         // 0x06
    U16,                          // 0x07
    U32,                          // 0x08
    U64,                          // 0x09
    U128,                         // 0x0A
    F32,                          // 0x0B
    F64,                          // 0x0C
    Char,                         // 0x0D
    String(MaxLen),               // 0x0E
    Unit,                         // 0x0F
    Option(Box<Type>),            // 0x10
    Sequence(MaxLen, Box<Type>),  // 0x11
    Aggregate(Vec<Element>),      // 0x12
    TaggedUnion(Vec<Element>),    // 0x13
}

struct Element {
    name: Name,
    ty: Type,
}

The comments give each variant's discriminant, which postcard writes as one byte: the item tag, or the type's tag. Name and MaxLen depend on the options, as below.

Postcard gives every KeyInput value a different encoding, so different items or options never produce the same key input.

hash.rs:13 tests.rs:179

The domain MUST be the array of 22 ASCII bytes postcard-schema/key/v3.

This array is not length prefixed.

hash.rs:94 tests.rs:180 +1

The options MUST be written as a varint(u64), with bit 0 (0x01) set if the names option is enabled, bit 1 (0x02) set if the maximum lengths option is enabled, and all other bits clear.

Options added in future will each use a new bit and be disabled by default, so existing keys keep their values.

hash.rs:27 tests.rs:181 +1

The items MUST be the application's items, in order: a string as Item::String, and a schema as Item::Schema with its Type.

hash.rs:183 tests.rs:182 +3

When the names option is enabled, Name MUST be Option<String>: the name of a named element, or None for an unnamed one. When it is disabled, Name MUST be ().

hash.rs:171 tests.rs:226 +3

When the maximum lengths option is enabled, MaxLen MUST be Option<u64>: the maximum length, or None if there is none. When it is disabled, MaxLen MUST be ().

Postcard writes () as no bytes, so a disabled option adds nothing to the key input.

A maximum length counts bytes for a string or a byte array, elements for a sequence, and entries for a map.

Normalization

Each kind of schema is written as the Type of its own postcard type (see Schemas), except for the kinds below, which are written as another Type. No other equivalences, such as those in Wire Compatibility, are applied.

hash.rs:237 tests.rs:293 +1

A ByteArray MUST be written as a Type::Sequence of Type::U8, with the byte array's maximum length.

hash.rs:238 tests.rs:225 +2

A Map MUST be written as a Type::Sequence, with the map's maximum length, of Type::Aggregates of two unnamed elements, the key type and then the value type.

hash.rs:239 tests.rs:295

A Tuple MUST be written as a Type::Aggregate of unnamed elements.

hash.rs:297 tests.rs:183 +1

A Struct MUST be written as its Data: Data::Unit as Type::Unit, Data::Newtype(T) as T, Data::Tuple as a Type::Aggregate of unnamed elements, and Data::Struct as a Type::Aggregate of elements named after its fields.

hash.rs:240 tests.rs:204 +1

An Enum MUST be written as a Type::TaggedUnion with one element per variant, in order, named after the variant, whose type is the variant's Data written as for a Struct. A variant is identified by its position; no discriminant is written.

Hash

hash.rs:136 tests.rs:133

The key input MUST be hashed with 128-bit FNV-1a, with offset basis 0x6c62272e07bb014262b821756295c58d and prime 0x0000000001000000000000000000013B.

hash.rs:200 tests.rs:148

The 128-bit hash MUST be folded to 64 bits by XORing its upper 64 bits with its lower 64 bits.

hash.rs:201 tests.rs:149

The folded value k MUST then be mixed with the fmix64 function of MurmurHash3, using wrapping 64-bit arithmetic.

As pseudocode:

text
k ^= k >> 33
k *= 0xff51afd7ed558ccd
k ^= k >> 33
k *= 0xc4ceb9fe1a85ec53
k ^= k >> 33

fmix64 spreads every input bit across the whole key, to reduce the chance of collisions when a key is shortened to a prefix, or folded by XOR.

hash.rs:202 tests.rs:150

The key MUST be the mixed value as 8 bytes, least significant byte first.

Examples

An application that keys on a path and one schema, with the default options: the path ping, and this struct:

rust
struct Ping {
    seq: u32,
    data: Vec<u8>,
}

Key input:

text
70 6f 73 74 63 61 72 64 2d 73 63 68 65 6d 61    domain: "postcard-schema/key/v3"
2f 6b 65 79 2f 76 33
01                                              options: names
02                                              2 items
00 04 70 69 6e 67                               a string, length 4: "ping"
01                                              a schema
12 02                                           an aggregate of 2 elements
01 03 73 65 71 08                               "seq": u32
01 04 64 61 74 61 11 02                         "data": a sequence of u8

Key:

text
key: 94 a1 8b 70 c2 aa 4b 3f

The same application, for the path cmd and this enum:

rust
enum Cmd {
    Stop,
    Go(u8),
}

Key input:

text
70 6f 73 74 63 61 72 64 2d 73 63 68 65 6d 61    domain: "postcard-schema/key/v3"
2f 6b 65 79 2f 76 33
01                                              options: names
02                                              2 items
00 03 63 6d 64                                  a string, length 3: "cmd"
01                                              a schema
13 02                                           a tagged union of 2 variants
01 04 53 74 6f 70 0f                            "Stop": unit
01 02 47 6f 02                                  "Go": u8

Key:

text
key: 22 11 ad 35 85 38 eb 76

One item, the schema of a BTreeMap<String, u8>, with the maximum lengths option enabled and the names option disabled:

Key input:

text
70 6f 73 74 63 61 72 64 2d 73 63 68 65 6d 61    domain: "postcard-schema/key/v3"
2f 6b 65 79 2f 76 33
02                                              options: maximum lengths
01                                              1 item
01                                              a schema
11 00                                           a sequence, no maximum length
12 02                                           of aggregates of 2 elements
0e 00                                           a string, no maximum length
02                                              u8

Key:

text
key: c1 19 b9 32 34 91 d6 a0

An RPC framework that keys on a method name and the schemas of its request and response, with both options enabled: the method get_temperature_value, and these types:

rust
struct Read {
    channel: u8,
}

type Response = Vec<MaxLenString<16>>;

Key input:

text
70 6f 73 74 63 61 72 64 2d 73 63 68 65 6d 61    domain: "postcard-schema/key/v3"
2f 6b 65 79 2f 76 33
03                                              options: names, maximum lengths
03                                              3 items
00 15                                           a string, length 21:
67 65 74 5f 74 65 6d 70 65 72 61 74 75 72 65    "get_temperature_value"
5f 76 61 6c 75 65
01                                              a schema
12 01                                           an aggregate of 1 element
01 07 63 68 61 6e 6e 65 6c 02                   "channel": u8
01                                              a schema
11 00                                           a sequence, no maximum length
0e 01 10                                        of strings, maximum length 16

Key:

text
key: 90 13 41 cc 15 df a3 cb

Versions

This specification defines version 3 of keys. Earlier versions were defined only by their implementations:

VersionUsed byDifferences from version 3
1early postcard-rpcFNV-1a 64; type names are hashed, so String and &str differ
2postcard-schema 0.1 to 0.2, postcard-schema-ngFNV-1a 64; no lengths or counts; only ByteArray is normalized
3postcard-schema 0.5, this specification

Schema Tables

A schema table is a compact format for sending or storing schemas. It holds one or more schemas in three parts:

  • nodes: a list of nodes, each describing one type
  • roots: a list of node indices, naming the "top level" types
  • names: one string holding every name, which nodes refer to by byte range

Nodes refer to each other by index. Variants, fields, and the elements of tuples aren't nodes: each is stored inside the node it belongs to.

A schema table is an ordinary postcard type, not a recursive one, so a message can hold one as a field, and its schema is a finite schema like any other.

Keys are computed from schemas, rather than the bytes of a table. Tables of the same schemas give the same keys, whatever their node order or how much they are deduplicated.

Encoding

encode.rs:87 +1 tests.rs:274 +3

A schema table MUST be the postcard encoding of a SchemaTable, as given by the Serde binding of the Postcard Wire Specification:

rust
struct SchemaTable {
    /// Always 1; see below.
    version: u32,
    /// Roots are the "entry point" types that were used to build this table.
    /// Each `u32` is an index into the `nodes` list.
    roots: Vec<u32>,
    /// Nodes are each a type, as one of the variants in the `Node` enum type.
    nodes: Vec<Node>,
    /// Every name in the table, as one UTF-8 string, which nodes refer to by
    /// `NameRef`.
    names: String,
}

/// A name: the bytes `offset..offset+len` of `names`. Used for the names of
/// types, variants and fields.
struct NameRef {
    offset: u32,
    len: u32,
}

enum Node {                                                 // Discriminant
    Bool,                                                   // 0x00
    I8,                                                     // 0x01
    U8,                                                     // 0x02
    I16,                                                    // 0x03
    I32,                                                    // 0x04
    I64,                                                    // 0x05
    I128,                                                   // 0x06
    U16,                                                    // 0x07
    U32,                                                    // 0x08
    U64,                                                    // 0x09
    U128,                                                   // 0x0A
    F32,                                                    // 0x0B
    F64,                                                    // 0x0C
    Char,                                                   // 0x0D
    String { max_len: Option<u64> },                        // 0x0E
    ByteArray { max_len: Option<u64> },                     // 0x0F
    Option(u32),                                            // 0x10
    Unit,                                                   // 0x11
    Seq { element: u32, max_len: Option<u64> },             // 0x12
    Tuple(Vec<u32>),                                        // 0x13
    Map { key: u32, val: u32, max_len: Option<u64> },       // 0x14
    Struct { name: NameRef, data: Data },                   // 0x15
    Enum { name: NameRef, variants: Vec<Variant> },         // 0x16
    Array { element: u32, len: u64 },                       // 0x17
}

/// The `Data` of a struct or enum
enum Data {                                                 // Discriminant
    /// A Unit Struct or Unit Variant
    Unit,                                                   // 0x00
    /// A Newtype Struct or Newtype Variant. The `u32` is the index of the inner
    /// type in the `nodes` list.
    Newtype(u32),                                           // 0x01
    /// A Tuple Struct or Tuple Variant. Each `u32` is the index of an
    /// element's type in the `nodes` list.
    Tuple(Vec<u32>),                                        // 0x02
    /// A (regular) Struct or Struct Variant. Its fields, in order.
    Struct(Vec<Field>),                                     // 0x03
}

/// A variant of an enum
struct Variant {
    name: NameRef,
    data: Data,
}

/// A field of a struct or struct variant. `ty` is the index of its type
/// in the `nodes` list.
struct Field {
    name: NameRef,
    ty: u32,
}
decode.rs:129 tests.rs:561

The version MUST be 1. A decoder MUST reject a table with any other version.

The version is the first field, so a decoder could check it before decoding the rest of the table. The postcard-schema crate decodes the whole table first, so a later version with a different layout may fail to decode rather than being rejected by its version.

Meaning

decode.rs:226 tests.rs:452 +1

Each root MUST be decoded as the schema of the node it refers to, and the roots MUST be decoded in order. The schema of a node is given by the tables below, where T is the schema of the node that a node index refers to, and the Ts of a list of node indices are the schemas of its nodes, in order.

NodeSchema
Bool to Char, Unitthe kind of the same name
String { max_len }String { max_len }
ByteArray { max_len }ByteArray { max_len }
Option(n)Option(T)
Seq { element, max_len }Seq { element: T, max_len }
Tuple(indices)Tuple(T, ...)
Map { key, val, max_len }Map { key: T, val: T, max_len }
Struct { name, data }Struct { name, data }, with data as below
Enum { name, variants }Enum { name, variants }, with each variant as below
Array { element, len }Tuple(T, ...), with len copies of T
DataSchema data
UnitUnit
Newtype(n)Newtype(T)
Tuple(indices)Tuple(T, ...)
Struct(fields)Struct(field, ...)
a Varianta variant name with data as above
a Fielda field name, whose type is the schema of ty

A max_len of None means there is no maximum length. A name is the string that its NameRef refers to.

decode.rs:434 +1 tests.rs:122 +1

An Array MUST be decoded as a Tuple of len copies of the schema of its element. An encoder SHOULD write a Tuple node of two or more node indices that are all the same as an Array. The Tuple data of a struct or variant has no Array form.

An Array only makes the table smaller: [u8; 32] and a tuple of 32 u8s are the same schema, as serde writes both as a tuple.

Validity

decode.rs:133 tests.rs:571

Every root MUST be the index of a node.

decode.rs:143 tests.rs:581 +1

Every node index in a node, including those in its tuple elements, its variants and its fields, MUST be less than the index of that node.

Each node therefore comes after all of its children, and following children always moves towards the start of nodes. A table can't contain a cycle, and decoding one always ends.

Variants and fields are stored inside their node, so every node index refers to a type.

decode.rs:150 tests.rs:652

Every NameRef MUST be within names, and MUST start and end on the boundary of a UTF-8 character.

decode.rs:139 tests.rs:582 +1

A decoder MUST reject a table that does not meet every requirement of this section, including in nodes that no root refers to.

Checking every node makes validity a property of the table alone. Each index and each name is checked once, so checking a table takes time linear in its size.

decode.rs:161 tests.rs:782

A decoder MAY reject a table with a maximum length, or an Array length, that it can't represent.

decode.rs:75 tests.rs:821 +8

A decoder MUST limit the total size of the schemas it decodes a table into, and MUST reject a table that would exceed that limit.

Nodes can be shared, so a few nodes can describe a very large schema. A table of a U8 and 64 Tuples, each of two of the node before it, is 65 nodes, but its last node describes 264 U8s.

An encoder would write each of those Tuples as an Array of two, but a decoder must accept either.

Each copy in an Array counts towards the limit, so an Array with a very large len is two nodes that describe a very large schema. A decoder should check the limit before making the copies.

Names count towards the size as well, since one long name can be used by many nodes. The postcard-schema crate has three limits: the number of types, variants and fields it produces, counting an Array once and each of its copies; the bytes of names it produces, counting a name each time it is used; and the depth of nested types, so that code that walks the decoded schemas can't run out of stack.

decode.rs:140 tests.rs:740

A decoder MUST accept every table that meets the requirements of this section and is within its limits, whatever its node order, including tables with repeated nodes or names, and nodes that no root refers to.

owned.rs:349 +1 tests.rs:43 +3

An encoder SHOULD write each node, each root, and each name once, and SHOULD NOT write nodes that no root refers to.

A table only holds types. How an application uses them, such as the request and response of a method, belongs in the application's own data, which can refer to the types by node index.

A NameRef MAY refer to part of a longer name. The postcard-schema crate reuses the first match, so the name y can be found inside the name xy.

Example

The schema table of struct Point { xy: u8, y: u8 }, as written by the postcard-schema crate:

text
01                                  version: 1
01 01                               roots: [1]
02                                  nodes: 2 nodes
   02                                 0: U8
   15 00 05                           1: Struct { name: "Point" (0, 5),
      03 02                                data: Struct(2 fields:
         05 02 00                            "xy" (5, 2) of type 0,
         06 01 00                            "y" (6, 1) of type 0) }
07 50 6F 69 6E 74 78 79             names: "Pointxy"

Glossary

These words have specific meanings throughout this specification.

Item

One of the strings or schemas that a key is computed from, in order. The application chooses the items. In the postcard-schema crate, an item is a key::Item. See What the Application Chooses.

Key

The 8-byte result of hashing the key input. See Keys.

Key Input

The bytes hashed into a key: a header (the domain, the options and the item count), then the items. See Key Input.

Options

The settings that decide whether the names of fields and variants, and maximum lengths, are part of the key input. The application chooses the options. See What the Application Chooses.

Schema Table

One or more schemas, stored as a list of types and one string of names, with each type and name stored once. It's how schemas are sent. See Schema Tables.