Keyboard shortcuts

Press ← or → to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Columnar serde layer

The opt-in serde feature (it implies framed) adds framing::serde: any serde::Serialize value, or a stream of rows, is shredded into typed columns and stored as resources of a framed container. Each resource is one ordinary OpenZL frame with one input per column, compressed with the compressor’s configured graph (compress_generic by default). The column layout is mopenzl’s own; the frames inside are the reference’s frames for those inputs. The #[columns] attribute (crate mopenzl-macros) gives fields a number instead of a name and routes their columns to a graph of their own (Field numbers and codecs).

Ownership and API

graph TD
    Pub["framing::serde (public): SerdeCompress, SerdeDecompress, BlockSize, SerdeError, RowWriter, RowReader, columns"]
    Macro["mopenzl-macros (proc macro): #[columns] expansion in its private core"] -->|re-exported as| Pub
    Pub --> Private["framing::serde::__private (hidden): column(marker, value, serializer)"]
    Pub --> Core["private framing::serde::core: Kind, Shape, Form, MARKER, NUMBERED"]
    Core --> Enc["core::encode: Shredder (sites, nodes, columns, codecs, journal) + RowSerializer, NumberProbe, descriptor writer (compression)"]
    Core --> Route["core::route: Routes, the routed graph of a block with codecs (compression)"]
    Core --> Dec["core::decode: Schema parser, Block + RowDeserializer (decompression)"]
    Route --> Graph["graph: CompressorGraph::column_graph, routed + Router (crate-private)"]
    Pub --> FC[FramedCompressor / FramedEncoderSession / FramedWriter]
    Pub --> FD[FramedDecompressor / FramedDecoderSession / FramedReader]
    Enc --> Input["input::Numbers, Records, Strings"]
    Dec --> Typed[TypedOutput]
    FC --> Raw[Compressor graph engine]
    FD --> RawD[Decompressor typed decoder]

The public surface is two sealed extension traits, implemented only for the framed codecs, so the methods appear after use mopenzl::framing::serde::{SerdeCompress, SerdeDecompress}:

TraitMethodGate
SerdeCompresscompress_value(&T) -> Vec<u8>: one row, one resourcecompression
compress_rows(IntoIterator<Item: Serialize>, BlockSize) -> Vec<u8>compression
rows_writer(W: Write, BlockSize) -> RowWriter (write, flush, finish)compression, std
SerdeDecompressdecompress_value::<T>(&[u8]) -> T: exactly one rowdecompression
decompress_rows::<T>(&[u8]) -> Vec<T>decompression
rows_reader::<R, T>(R: Read) -> RowReader, an iterator of Result<T>decompression, std

columns is an attribute macro re-exported from mopenzl-macros, a proc-macro crate of this workspace that the serde feature pulls in. It expands to paths under mopenzl::framing::serde::__private (or #[columns(crate = "...")]), a hidden module holding serde’s Serialize/Serializer and column.

BlockSize is a Copy newtype over a byte count (Default 1 MiB, From<usize>, Into<usize>). SerdeError is #[non_exhaustive] and implements serde::ser::Error and serde::de::Error, so the private serializer and deserializer use it directly; framed failures keep their source through SerdeError::Framed(#[from] FramedError).

Sites, nodes and columns

A value is walked as a tree of sites and nodes. A site is a place in the value: the root of every row, a struct field (keyed by name), a tuple element (by position), an Option’s value, a sequence’s elements, the values of one named map key, a map’s other keys or their values, a variant’s body (keyed by variant name and form). A node is one Shape a site took. The first visit of a site with a shape creates the node and, for shapes that have one, its column; later visits with that shape (the same field of the next row, the next element of the same sequence) append to the node’s column.

A site that took several shapes (an untagged enum, a serde_json::Value), or a struct or tuple field that some visits left out (skip_serializing_if, skip_field), gets a state column: one byte per visit of the site, 0 for absent and k for its k-th node. The column is created on the first need and backfilled with 1 for every earlier visit, which all took the first node; a field that first appears after n visits of its struct starts with n zeros. A site that always takes one shape and is never absent has no state column and costs nothing beyond its node’s column.

classDiagram
    class Shredder {
      sites: Vec~Site~
      nodes: Vec~Node~
      columns: Vec~Column~
      journal: Vec~Mark~
      row(value)
      flush(emit)
    }
    class Site {
      alts: Vec~u32~
      state: u32
      stamp: u64
    }
    class Node {
      shape: Shape
      column: u32
      keys: u32
      children: Vec~Child~
      entries: u64
      visits: u64
      stamp: u64
    }
    class Child {
      name: Cow~str~
      form: Form
      site: u32
    }
    class Shape {
      <<enum>>
      Unit
      Scalar(Kind)
      Option
      Seq
      Map
      Enum
      Tuple
      Struct
    }
    class Kind {
      <<enum>>
      Bool U8..U128 I8..I128 F32 F64 Char
      Str Bytes
      Len Some Tag State
    }
    Shredder "1" *-- "many" Site
    Shredder "1" *-- "many" Node
    Site --> Node : alts, one per shape
    Node "1" *-- "many" Child
    Child --> Site
    Node --> Shape
    Shape --> Kind
Rust / serde callShapeColumn (Kind)OpenZL inputChildren
boolScalarBoolnumeric, width 1 (0/1)
u8..u64, i8..i64ScalarU* / I*numeric, the type’s width; signed values in two’s complement
u128, i128ScalarU128 / I128struct, width 16
f32, f64ScalarF32 / F64numeric, the bit pattern
charScalarCharnumeric, width 4
str, collect_strScalarStrstring
serialize_bytesScalarBytesstring
OptionOptionSome (0/1)numeric, width 1the value, visited when 1
seq (Vec<T>, slices, sets)SeqLennumeric, narrowedthe elements
mapMapLen, and Tag for key positionsnumeric, narrowedother keys, their values, then one per named key
enum variantsEnumTagnumeric, narrowedone per variant seen, by name and form; unit variants have no body site
tuple, tuple struct, tuple variant bodyTuplenoneelements by position
struct, struct variant bodyStructnonefields by name, in first-visit order
(), unit structUnitnone
newtype structthe inner value’stransparent
a place’s shape and presenceStatenumeric, width 1

Len and Tag values are buffered as u64 and narrowed when the block is emitted to the smallest of 1, 2, 4 or 8 bytes that holds the block’s largest value. Tag is the variant’s position among the variants the node has seen in this block, not serde’s variant index. At most 23 shapes exist (16 scalar kinds and 7 others), so a state always fits a byte.

Maps as records

A map key is a name when it serializes as a string, a unit variant, or a newtype around either (KeyProbe finds out by serializing the key once into a probe that accepts only those calls and has no other effect). A named key becomes a child of the map node, like a struct field, and its values get their own site: the "status" values of every serde_json::Value object land in one column. Every entry records its key in the node’s key column, 0 for a key that is not a name (stored as a value at child 0, with its value at child 1) and k for the named key at child k + 1, so the order of entries and repeated keys survive exactly. The key column is created with the first named key, with a 0 for every earlier entry; a map that never sees a name (BTreeMap<u8, _>) has none and stores keys and values as before.

flowchart TD
    K["serialize_key(key)"] --> B["map_sites: children 0 and 1 on the first entry"]
    B --> P{"key.serialize(KeyProbe): a name?"}
    P -- "string / unit variant / newtype of one" --> N{"named child exists?"}
    N -- yes --> NI["entry(node, k): key column += k; value site = child k + 1"]
    N -- "no, fewer than 256 names" --> NC["create child and site"] --> NI
    N -- "no, 256 names" --> G
    P -- "anything else" --> G["entry(node, 0); key stored at child 0; value site = child 1"]

A node names at most MAX_KEYS (256) keys per block, so a map keyed by identifiers cannot create a column per identifier: later new keys are stored at child 0 like non-names. Keys longer than 65535 bytes are never named. Lookup tries the child after the last one found, then scans the names, so maps that repeat their keys in the same order (BTreeMap, structs written through flatten) find each key at the first compare.

The decoder hands a named key to the key’s Deserialize through Name: a string to deserialize_any and string types, a unit variant to deserialize_enum, the inner value to newtypes and options.

For Vec<Row> with Row { id: u32, name: String, score: Option<f64> } the block’s columns are, in first-visit order: id (U32), name (Str), score flags (Some) and score values (F64, only the Some rows). Marking score with skip_serializing_if = "Option::is_none" replaces the flags with a State column for the field (0 for skipped rows). With compress_value(&rows) the vector itself is a Seq at the root, so its length is one more column in front.

Field numbers and codecs

#[columns] runs before #[derive(Serialize, Deserialize)] and rewrites the fields that carry #[column(id = N, codec = "graph")]:

#[column]Field getsEffect
id = N (named fields only, unique per struct or variant)#[serde(alias = "#N")] and the markerstored by number; read back as key #N
codec = "graph"the markerits scalar columns are compressed by that graph
either, with with = "m"deserialize_with = "m::deserialize"; m::serialize runs inside the markerthe field’s own format is kept

The marker is a generated serialize_with function, __mopenzl_columns_<item>_<n>, that calls serializer.serialize_newtype_struct(name, value) with the name "\0mopenzl:", then id=N and codec=NAME separated by ;. Every serializer but the columnar one passes a newtype through, so JSON and other formats see the type as before (and accept the extra alias #N). A type that does not derive Serialize only gets the aliases; a generic type gets #[serde(bound(serialize = "<field type>: Serialize"))] for the marked field, since serde infers no bound for a serialize_with field, unless the field states its own bound.

A field with its own with or serialize_with keeps it: the helper wraps the value in a type __MopenzlColumns<Item><n> whose Serialize calls the user’s function, and the columnar serializer meets that function inside the marker newtype. The wrapper is declared next to the item, so it can name the item’s parameters, but Rust rejects unused ones; it takes only the parameters (lifetimes, types, consts) the field’s type mentions, without their defaults, and the predicates that mention some of those and no other parameter: inline bounds, the where clause, and the serializing part of the item’s and the field’s #[serde(bound)]. A predicate that ties a field parameter to another one is dropped, so a bound the user’s function needs must be stated on the field’s own parameters. A marked field cannot be skipped or flattened; that, a tuple field number, a repeated number and unknown keys are compile errors.

flowchart TD
    F["marked field: ty, own serializer?"] --> O{"with / serialize_with?"}
    O -- no --> P["helper&lt;V: Serialize&gt;: column(marker, value)"]
    O -- yes --> M["mentions(ty): parameters of the item it names"]
    M --> G["wrapper params: those, defaults dropped"]
    G --> W["predicates: inline, where, #[serde(bound)] of item and field<br/>kept if they name only wrapper params"]
    W --> S["struct __MopenzlColumns&lt;Item&gt;&lt;n&gt;&lt;'__a, params&gt;(&'__a ty)<br/>impl Serialize: user(self.0)"]
    S --> H["helper&lt;params, S&gt;: column(marker, &wrapper(value))"]
sequenceDiagram
    participant D as derived Serialize
    participant F as Fields (struct visit)
    participant P as NumberProbe
    participant S as Shredder
    participant R as RowSerializer
    D->>F: serialize_field("at", &value)
    F->>S: field(node, Name(hint, "at"), number)
    alt a child keyed "at" exists
        S-->>F: its site
    else first visit of "at" in this block
        S->>P: value.serialize(NumberProbe)
        P-->>S: N from "\0mopenzl:id=N...", or no number
        S->>S: reuse the child numbered N, or add child {name "at", id N}
        S-->>F: site
    end
    F->>R: value.serialize(RowSerializer at site, codec)
    R->>R: serialize_newtype_struct("\0mopenzl:...codec=g") sets codec = Shredder::codec("g")
    R->>S: enter(site, Scalar(kind), codec): a new scalar column remembers the codec

Numbers. The probe stops at the value’s first serializer call, so a field without a marker costs one failed call, once per field per block: a field is found by its key name afterwards, and only a key missing from the node is probed. A numbered child keeps its key name for those lookups and writes u16::MAX and its number instead of the name in the descriptor (Descriptor). The decoder names it #N, which the field accepts through its alias, so numbered structs are read by derived types in every path, including untagged and internally tagged enums, #[serde(flatten)] and deserialize_any (serde_json::Value sees "#N" keys). Fields stored by name still match by name, so adding numbers to a type keeps reading its earlier rows, and a renamed field keeps reading by its number. Struct names never carry markers.

Codecs. The codec applies to the scalar columns created below the marked field (numbers, strings, bytes, at any depth), not to lengths, presence flags, variant positions, map keys columns or states. A column keeps the codec of the visit that created it. Shredder::codecs lists the block’s codecs in first-use order and is truncated by a failed row like the rest of the journal. flush tags each marked column’s input with integer metadata CODEC_SLOT = k + 1 for codec k (the metadata is not written to the frame) and hands Emitted { descriptor, inputs, codecs, columns } to the caller.

flowchart TD
    B["queue_block: Emitted"] --> E{"block.codecs empty?"}
    E -- yes --> N["resource graph: None (the compressor's own graph; frame unchanged)"]
    E -- no --> C{"same codecs as the cached graph?"}
    C -- no --> L["column_graph(name) on the compressor's graph: newest custom graph of that name, else standard graph (with or without !zl.)"]
    L --> M{"found and single-input?"}
    M -- no --> X["SerdeError::Codec"]
    M -- yes --> G["CompressorGraph::routed: registry copy (new owner if standard), start = Router"]
    C -- yes --> T
    G --> T{"every marked column: graph accepts its type, or serial with conversion"}
    T -- no --> X
    T -- yes --> Q["resource graph: Some(routed)"]

The router is a crate-private function graph: an input with slot k goes alone to its graph; one the graph does not accept as is is first turned into serial bytes (convert_num_to_serial_le, convert_struct_to_serial, or separate_string_components, whose lengths join the rest), which needs the conversion codec feature. All other inputs go together, with the original runtime parameters, to the compressor’s start graph, which is exactly what that graph receives without codecs. Routes caches the routed graph while consecutive blocks use the same codec list, and RowWriter keeps one Routes for its stream. Frames record their codecs, so the decoder needs nothing; the C library decodes them (tested).

Encoding

sequenceDiagram
    participant U as caller
    participant T as SerdeCompress
    participant S as Shredder
    participant R as RowSerializer
    participant F as FramedEncoderSession / FramedWriter
    U->>T: compress_rows(rows, block)
    T->>F: start, drain header
    loop every row
        alt block holds rows and bytes >= block
            T->>S: flush(emit)
            S->>S: narrow Len/Tag, build descriptor + Inputs
            S->>F: resource(Typed(inputs), metadata SD)
            S->>S: clear sites, nodes and columns (spare buffers kept)
        end
        T->>S: row(&row)
        S->>R: value.serialize(RowSerializer at the root site)
        R->>S: enter(site, shape): node, state byte if needed
        R->>S: field(node, name) / slot(node, i) / variant(node, name, form)
        R->>S: append to the node's column
        R->>S: end of struct: record absent fields
    end
    T->>S: flush last block
    T->>F: Finish: directory + footer
flowchart TD
    E["enter(site, shape)"] --> F{"no state column, one node, same shape?"}
    F -- yes --> V["node.visits += 1 (fast path)"]
    F -- no --> N{"node for shape exists?"}
    N -- no --> C["create node and its column"]
    N -- yes --> S
    C --> S{"several nodes or a state column?"}
    S -- yes --> R["record(site, alt + 1); create the state column with earlier visits as 1"]
    S -- no --> V
    R --> V

Struct fields are looked up by name, first at the position the field has in the type (derived types write fields in the same order every time) and compared by address before content, since derived names are static strings. A field written twice in one visit is SerdeError::Shape; a field is recognized as written in this visit through a stamp that numbers every struct and tuple visit and never repeats. At the end of a visit every child not stamped with it is recorded absent, unless the visit wrote as many fields as the node has.

The block is closed before a row once it holds at least block raw bytes (column bytes, 4 per string, 1 per length, tag, flag or state), so compress_rows and RowWriter cut identical blocks and write identical bytes. A block without columns (rows of ()) is stored as one empty serial input, because a frame needs at least one input.

A failing row is rolled back: Shredder::row journals, once per row (by epoch), the column lengths, site states and node lengths and visits it touches, and on error restores them and drops the sites, nodes and columns the row created. RowWriter::write therefore leaves the block as it was. A block whose resource cannot be queued (for example a sink error) is kept, because flush clears it only after the emission succeeds.

Sites, nodes and columns are reset for every block, so each resource is self-contained: its schema and column numbering come from its own first visits and any resource can be decoded alone, for example through the container’s index.

Descriptor

Each resource carries one metadata field with code SD, all integers little-endian:

BytesField
1layout version, 2
8row count
4column count
4site count (site 0 is the root)
4node count
per sitestate column (u32::MAX for none), node count (1 byte), node ids (4 each)
per nodeshape code (1), scalar kind (1), column (4, u32::MAX for none), for maps only the key column (4, u32::MAX for none), child count (4), then per child: name length (2) and UTF-8 name, or u16::MAX and a field number (4) for a numbered struct field; form (1: unit, newtype, tuple, struct), site (4, u32::MAX for unit variants)

The parser checks, before allocating anything larger than the descriptor: every column has exactly one owner (a node of its kind or a site’s state) and is claimed once; every node is referenced by at most one site and every site but the root by at most one child, so the part reachable from the root is a tree no larger than the descriptor; a site without a state column has at most one node; children fit their shape (none for scalars and units, one for options and sequences, none or at least two for maps); forms other than unit appear only in enums, and unit variants have no site; field numbers appear only in structs; no bytes are left over. A numbered child is named #N in the parsed schema, so the rest of the decoder handles it as a name.

Decoding

stateDiagram-v2
    [*] --> Resource: next framed resource
    Resource --> Block: Schema::parse, column types, charge rows
    Block --> Row: rows > 0
    Row --> Row: pick(root), T::deserialize(RowDeserializer at node)
    Row --> Finish: rows == 0
    Finish --> Resource: every column read to its end
    Resource --> [*]: directory, footer and EOF validated
    Block --> Failed: layout, limit or type error
    Row --> Failed
    Finish --> Failed

The decoder walks the stored schema; the target type only chooses how the stored values are handed over. pick(site) reads the site’s state byte, if it has a state column, and returns its node or absent. A RowDeserializer stands on a node and answers every call from the node’s shape:

flowchart TD
    D["deserialize_* on a node"] --> K{"call"}
    K -- "deserialize_struct, Struct node, names = fields, no state columns" --> P["visit_seq over the fields (positional fast path)"]
    K -- "deserialize_enum, Enum node" --> EA["visit_enum: variant by name, body by form"]
    K -- "deserialize_enum, Str node" --> ES["visit_enum: unit variant named by the string"]
    K -- "deserialize_option" --> O{"shape"}
    O -- Option --> OA["flag: visit_none / visit_some"]
    O -- Unit --> ON[visit_none]
    O -- other --> OS["visit_some(self)"]
    K -- "deserialize_newtype_struct" --> NT["visit_newtype_struct(self)"]
    K -- "everything else" --> ANY["deserialize_any"]
    ANY --> A{"shape"}
    A -- Scalar --> AS["visit_<stored kind>"]
    A -- Unit --> AU[visit_unit]
    A -- "Seq / Tuple" --> AQ["visit_seq (absent tuple elements skipped)"]
    A -- "Map" --> AM["visit_map: named keys as Name, others from child 0"]
    A -- "Struct" --> AF["visit_map: present fields keyed by name"]
    A -- "Enum" --> AE["unit variant: visit_str(name); else visit_map {name: body}"]

Scalars are handed to the visitor as their stored kind (visit_u32 for a U32 column, whatever was asked), so serde’s primitive visitors decide the conversion: integers widen and narrow with a range check, integers read as floats, and floats are never read as integers. Field and variant names are handed over as strings, because derived FIELDS and VARIANTS lists include aliases and their indices are not the derive’s field indices. The positional fast path is chosen once per node and field list (cached by the list’s address) and skips names entirely; a child that is always present with one shape has its node precomputed, so the fast path reads no state.

A struct read through visit_map must hand over every present field (the derive does, ignoring unknown ones through deserialize_ignored_any, which walks and consumes the stored value); sequences, maps, tuples and variant maps must be read to their end; key and value calls must alternate. Otherwise the row fails with SerdeError::Layout, since unread values would shift every later row. After the last row of a block every column must have been read to its end. Stored values are checked: flags and bools are 0 or 1, states name an existing node, chars are scalar values, strings are UTF-8, a variant position names a stored variant.

decompress_rows and decompress_value drive a FramedDecoderSession and deserialize each resource as it arrives, so one decoded resource is in memory at a time besides the rows. RowReader does the same over a FramedReader; it yields an error once and then ends, except after a transport error, which may be retried.

Limits and invariants

  • Element budget. The rows, struct and tuple fields, and sequence and map elements of one container may not exceed the decoder’s FramingConfig::max_output_bytes, so that a forged length of zero-sized elements (Vec<()>) or a wide forged struct cannot spin. Legitimate data hits the byte limit first except for zero-sized values.
  • Depth. Both sides refuse nesting deeper than 128 levels.
  • Names are at most 65534 bytes (65535 marks a field number); strings at most u32::MAX bytes (the frame’s string lengths).
  • Schema size. The reachable schema is a tree of at most the descriptor’s size, and each struct visit costs its field count, so a forged descriptor cannot multiply work.
  • Byte identity. For the same columns, each resource’s frame equals the reference’s ZL_CCtx_compress with compress_generic; the framed_serde test and benchmark check this. A block with codec columns uses the routed graph, which the reference’s default graph does not express; its frames are checked by decoding them with the C library.

Errors

VariantRaised by
CustomSerialize/Deserialize implementations and serde’s derived visitors (unknown variant, wrong length)
Custom (conversions)a stored value the requested type does not accept: out of range, float read as integer, unknown or missing field
Unsupporteddepth, oversize field and variant names and strings, a map value before its key
Shapea struct field written twice in one visit
Layoutdescriptor, column type, stored value, consumption or access-order mismatch on decode
Limitthe element budget
ValueCountdecompress_value on a container without exactly one row
Codeca #[column(codec)] the compressor has no graph of, one taking several inputs, or one that does not take a column’s type
Framedcontainer, codec or transport failure, with its source

Measurements

cargo bench --features serde --bench framed_serde on an Apple M-series laptop, default level, 1 MiB blocks. Sizes compare the columnar container with the same rows in a row-major bincode-like layout compressed as one serial input by the C library:

CorpusRow-major → serial OpenZLColumns → container
logs, 100k rows6.68 MB → 1.17 MB (5.69x)0.70 MB (9.51x)
samples, 200k rows4.20 MB → 1.06 MB (3.96x)0.37 MB (11.50x)
JSON logs (serde_json::Value), 100k rows; row-major is the JSON text13.90 MB → 1.59 MB (8.76x)0.92 MB (15.12x)

Storing map keys as records took the JSON logs from 9.92x (16.3 MB of raw columns, every key a string in every row) to 15.12x (8.5 MB).

The named schema costs about 200 bytes per block (9.54x and 11.53x with the positional layout of the first version).

CorpusRust rows → containerRust container → rows
logs, 100k40.2 ms (38.1 ms positional)18.4 ms (17.5 ms positional)
samples, 200k22.8 ms (20.9 ms positional)6.1 ms (7.4 ms positional)
JSON logs, 100k65.5 ms (86.5 ms keys as values)53.9 ms (61.1 ms keys as values)

The columns alone compress in 29.0 ms (Rust) and 23.5 ms (C) and decompress in 2.8 ms and 2.5 ms for the logs (46.6, 40.3, 4.6 and 4.1 ms for the JSON logs); the rest is shredding and rebuilding rows, for Value mostly allocating its maps and strings. Shredding pays for name lookup, per-node visit counts and their journal; rebuilding pays for variant names handed over as strings and for UTF-8 validation and allocation of String fields.

Known gaps

  • Map key cap. A map node names at most 256 keys per block; beyond that, new keys and their values fall back to the shared key and value places. The cap is fixed, not configurable.
  • Recursive types get new columns for every recursion level a block reaches, and are limited to 128 levels.
  • Zero-copy reads. Rows are DeserializeOwned; borrowed &str fields cannot point into decoded columns.
  • Codecs per column. A codec graph receives one column at a time; a graph over several columns (for example clustering a field’s columns together) cannot be named by #[column]. Codecs are given by name only; their parameters come from the graph registered under that name.
  • What can be numbered. Named fields of structs and struct variants take numbers; enum variants and tuple fields keep names and positions.